@socketsecurity/lib 2.10.3 → 3.0.0
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 +38 -0
- package/README.md +231 -40
- package/dist/constants/platform.js +1 -1
- package/dist/constants/platform.js.map +3 -3
- package/dist/cover/code.js +1 -1
- package/dist/cover/code.js.map +3 -3
- package/dist/debug.js +2 -2
- package/dist/debug.js.map +3 -3
- package/dist/dlx-binary.d.ts +29 -6
- package/dist/dlx-binary.js +7 -7
- package/dist/dlx-binary.js.map +3 -3
- package/dist/dlx-package.d.ts +16 -1
- 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/env/rewire.js +1 -1
- package/dist/env/rewire.js.map +3 -3
- 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/yoctocolors-cjs.d.ts +14 -0
- package/dist/fs.d.ts +82 -27
- package/dist/fs.js +7 -7
- package/dist/fs.js.map +3 -3
- package/dist/git.js +1 -1
- package/dist/git.js.map +3 -3
- package/dist/http-request.js +1 -1
- package/dist/http-request.js.map +3 -3
- package/dist/ipc.js +1 -1
- package/dist/ipc.js.map +3 -3
- package/dist/links/index.d.ts +65 -0
- package/dist/links/index.js +3 -0
- package/dist/links/index.js.map +7 -0
- package/dist/logger.d.ts +21 -18
- package/dist/logger.js +1 -1
- package/dist/logger.js.map +3 -3
- package/dist/packages/isolation.js +1 -1
- package/dist/packages/isolation.js.map +3 -3
- package/dist/paths.js +1 -1
- package/dist/paths.js.map +2 -2
- package/dist/process-lock.js +2 -2
- package/dist/process-lock.js.map +3 -3
- package/dist/promises.d.ts +6 -21
- package/dist/promises.js +1 -1
- package/dist/promises.js.map +2 -2
- package/dist/prompts/index.d.ts +115 -0
- package/dist/prompts/index.js +3 -0
- package/dist/prompts/index.js.map +7 -0
- package/dist/spinner.d.ts +33 -23
- package/dist/spinner.js +1 -1
- package/dist/spinner.js.map +3 -3
- package/dist/stdio/mask.d.ts +2 -2
- package/dist/stdio/mask.js +4 -4
- package/dist/stdio/mask.js.map +3 -3
- package/dist/stdio/stdout.js +1 -1
- package/dist/stdio/stdout.js.map +3 -3
- package/dist/themes/context.d.ts +80 -0
- package/dist/themes/context.js +3 -0
- package/dist/themes/context.js.map +7 -0
- package/dist/themes/index.d.ts +53 -0
- package/dist/themes/index.js +3 -0
- package/dist/themes/index.js.map +7 -0
- package/dist/themes/themes.d.ts +49 -0
- package/dist/themes/themes.js +3 -0
- package/dist/themes/themes.js.map +7 -0
- package/dist/themes/types.d.ts +92 -0
- package/dist/themes/types.js +3 -0
- package/dist/themes/types.js.map +7 -0
- package/dist/themes/utils.d.ts +78 -0
- package/dist/themes/utils.js +3 -0
- package/dist/themes/utils.js.map +7 -0
- package/package.json +40 -8
- package/dist/download-lock.d.ts +0 -49
- package/dist/download-lock.js +0 -10
- package/dist/download-lock.js.map +0 -7
package/dist/process-lock.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/process-lock.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @fileoverview Process locking utilities with stale detection and exit cleanup.\n * Provides cross-platform inter-process synchronization using directory-based locks.\n * Aligned with npm's npx locking strategy (5-second stale timeout, periodic touching).\n *\n * ## Why directories instead of files?\n *\n * This implementation uses `mkdir()` to create lock directories (not files) because:\n *\n * 1. **Atomic guarantee**: `mkdir()` is guaranteed atomic across ALL filesystems,\n * including NFS. Only ONE process can successfully create the directory. If it\n * exists, `mkdir()` fails with EEXIST instantly with no race conditions.\n *\n * 2. **File-based locking issues**:\n * - `writeFile()` with `flag: 'wx'` - atomicity can fail on NFS\n * - `open()` with `O_EXCL` - not guaranteed atomic on older NFS\n * - Traditional lockfiles - can have race conditions on network filesystems\n *\n * 3. **Simplicity**: No need to write/read file content, track PIDs, or manage\n * file descriptors. Just create/delete directory and check mtime.\n *\n * 4. **Historical precedent**: Well-known Unix locking pattern used by package\n * managers for decades. Git uses similar approach for `.git/index.lock`.\n *\n * ## The mtime trick\n *\n * We periodically update the lock directory's mtime (modification time) by\n * \"touching\" it to signal \"I'm still actively working\". This prevents other\n * processes from treating the lock as stale and removing it.\n *\n * **The lock directory remains empty** - it's just a sentinel that signals\n * \"locked\". The mtime is the only data needed to track lock freshness.\n *\n * ## npm npx compatibility\n *\n * This implementation matches npm npx's concurrency.lock approach:\n * - Lock created via `mkdir(path.join(installDir, 'concurrency.lock'))`\n * - 5-second stale timeout (if mtime is older than 5s, lock is stale)\n * - 2-second touching interval (updates mtime every 2s to keep lock fresh)\n * - Automatic cleanup on process exit\n */\n\nimport { existsSync, mkdirSync, statSync, utimesSync } from 'node:fs'\n\nimport { safeDeleteSync } from './fs'\nimport { logger } from './logger'\nimport { pRetry } from './promises'\nimport { onExit } from './signal-exit'\n\n/**\n * Lock acquisition options.\n */\nexport interface ProcessLockOptions {\n /**\n * Maximum number of retry attempts.\n * @default 3\n */\n retries?: number | undefined\n\n /**\n * Base delay between retries in milliseconds.\n * @default 100\n */\n baseDelayMs?: number | undefined\n\n /**\n * Maximum delay between retries in milliseconds.\n * @default 1000\n */\n maxDelayMs?: number | undefined\n\n /**\n * Stale lock timeout in milliseconds.\n * Locks older than this are considered abandoned and can be reclaimed.\n * Aligned with npm's npx locking strategy (5 seconds).\n * @default 5000 (5 seconds)\n */\n staleMs?: number | undefined\n\n /**\n * Interval for touching lock file to keep it fresh in milliseconds.\n * Set to 0 to disable periodic touching.\n * @default 2000 (2 seconds)\n */\n touchIntervalMs?: number | undefined\n}\n\n/**\n * Process lock manager with stale detection and exit cleanup.\n * Provides cross-platform inter-process synchronization using file-system\n * based locks.\n */\nclass ProcessLockManager {\n private activeLocks = new Set<string>()\n private touchTimers = new Map<string, NodeJS.Timeout>()\n private exitHandlerRegistered = false\n\n /**\n * Ensure process exit handler is registered for cleanup.\n * Registers a handler that cleans up all active locks when the process exits.\n */\n private ensureExitHandler() {\n if (this.exitHandlerRegistered) {\n return\n }\n\n onExit(() => {\n // Clear all touch timers.\n for (const timer of this.touchTimers.values()) {\n clearInterval(timer)\n }\n this.touchTimers.clear()\n\n // Clean up all active locks.\n for (const lockPath of this.activeLocks) {\n try {\n if (existsSync(lockPath)) {\n safeDeleteSync(lockPath, { recursive: true })\n }\n } catch {\n // Ignore cleanup errors during exit.\n }\n }\n })\n\n this.exitHandlerRegistered = true\n }\n\n /**\n * Touch a lock file to update its mtime.\n * This prevents the lock from being detected as stale during long operations.\n *\n * @param lockPath - Path to the lock directory\n */\n private touchLock(lockPath: string): void {\n try {\n if (existsSync(lockPath)) {\n const now = new Date()\n utimesSync(lockPath, now, now)\n }\n } catch (error) {\n logger.warn(\n `Failed to touch lock ${lockPath}: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n\n /**\n * Start periodic touching of a lock file.\n * Aligned with npm npx strategy to prevent false stale detection.\n *\n * @param lockPath - Path to the lock directory\n * @param intervalMs - Touch interval in milliseconds\n */\n private startTouchTimer(lockPath: string, intervalMs: number): void {\n if (intervalMs <= 0 || this.touchTimers.has(lockPath)) {\n return\n }\n\n const timer = setInterval(() => {\n this.touchLock(lockPath)\n }, intervalMs)\n\n // Prevent timer from keeping process alive.\n timer.unref()\n\n this.touchTimers.set(lockPath, timer)\n }\n\n /**\n * Stop periodic touching of a lock file.\n *\n * @param lockPath - Path to the lock directory\n */\n private stopTouchTimer(lockPath: string): void {\n const timer = this.touchTimers.get(lockPath)\n if (timer) {\n clearInterval(timer)\n this.touchTimers.delete(lockPath)\n }\n }\n\n /**\n * Check if a lock is stale based on mtime.\n * Uses second-level granularity to avoid APFS floating-point precision issues.\n * Aligned with npm's npx locking strategy.\n *\n * @param lockPath - Path to the lock directory\n * @param staleMs - Stale timeout in milliseconds\n * @returns True if lock exists and is stale\n */\n private isStale(lockPath: string, staleMs: number): boolean {\n try {\n if (!existsSync(lockPath)) {\n return false\n }\n\n const stats = statSync(lockPath)\n // Use second-level granularity to avoid APFS issues.\n const ageSeconds = Math.floor((Date.now() - stats.mtime.getTime()) / 1000)\n const staleSeconds = Math.floor(staleMs / 1000)\n return ageSeconds > staleSeconds\n } catch {\n return false\n }\n }\n\n /**\n * Acquire a lock using mkdir for atomic operation.\n * Handles stale locks and includes exit cleanup.\n *\n * This method attempts to create a lock directory atomically. If the lock\n * already exists, it checks if it's stale and removes it before retrying.\n * Uses exponential backoff with jitter for retry attempts.\n *\n * @param lockPath - Path to the lock directory\n * @param options - Lock acquisition options\n * @returns Release function to unlock\n * @throws Error if lock cannot be acquired after all retries\n *\n * @example\n * ```typescript\n * const release = await processLock.acquire('/tmp/my-lock')\n * try {\n * // Critical section\n * } finally {\n * release()\n * }\n * ```\n */\n async acquire(\n lockPath: string,\n options: ProcessLockOptions = {},\n ): Promise<() => void> {\n const {\n baseDelayMs = 100,\n maxDelayMs = 1000,\n retries = 3,\n staleMs = 5000,\n touchIntervalMs = 2000,\n } = options\n\n // Ensure exit handler is registered before any lock acquisition.\n this.ensureExitHandler()\n\n return await pRetry(\n async () => {\n try {\n // Check for stale lock and remove if necessary.\n if (existsSync(lockPath) && this.isStale(lockPath, staleMs)) {\n logger.log(`Removing stale lock: ${lockPath}`)\n try {\n safeDeleteSync(lockPath, { recursive: true })\n } catch {\n // Ignore errors removing stale lock - will retry.\n }\n }\n\n // Check if lock already exists before creating.\n if (existsSync(lockPath)) {\n throw new Error(`Lock already exists: ${lockPath}`)\n }\n\n // Atomic lock acquisition via mkdir with recursive to create parent dirs.\n mkdirSync(lockPath, { recursive: true })\n\n // Track lock for cleanup.\n this.activeLocks.add(lockPath)\n\n // Start periodic touching to prevent stale detection.\n this.startTouchTimer(lockPath, touchIntervalMs)\n\n // Return release function.\n return () => this.release(lockPath)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n\n // Handle lock contention - lock already exists.\n if (code === 'EEXIST') {\n if (this.isStale(lockPath, staleMs)) {\n throw new Error(`Stale lock detected: ${lockPath}`)\n }\n throw new Error(`Lock already exists: ${lockPath}`)\n }\n\n // Handle permission errors - not retryable.\n if (code === 'EACCES' || code === 'EPERM') {\n throw new Error(\n `Permission denied creating lock: ${lockPath}. ` +\n 'Check directory permissions or run with appropriate access.',\n { cause: error },\n )\n }\n\n // Handle read-only filesystem - not retryable.\n if (code === 'EROFS') {\n throw new Error(\n `Cannot create lock on read-only filesystem: ${lockPath}`,\n { cause: error },\n )\n }\n\n // Handle parent path issues - not retryable.\n if (code === 'ENOTDIR') {\n const parentDir = lockPath.slice(0, lockPath.lastIndexOf('/'))\n throw new Error(\n `Cannot create lock directory: ${lockPath}\\n` +\n 'A path component is a file when it should be a directory.\\n' +\n `Parent path: ${parentDir}\\n` +\n 'To resolve:\\n' +\n ` 1. Check if \"${parentDir}\" contains a file instead of a directory\\n` +\n ' 2. Remove any conflicting files in the path\\n' +\n ' 3. Ensure the full parent directory structure exists',\n { cause: error },\n )\n }\n\n if (code === 'ENOENT') {\n const parentDir = lockPath.slice(0, lockPath.lastIndexOf('/'))\n throw new Error(\n `Cannot create lock directory: ${lockPath}\\n` +\n `Parent directory does not exist: ${parentDir}\\n` +\n 'To resolve:\\n' +\n ` 1. Ensure the parent directory \"${parentDir}\" exists\\n` +\n ` 2. Create the directory structure: mkdir -p \"${parentDir}\"\\n` +\n ' 3. Check filesystem permissions allow directory creation',\n { cause: error },\n )\n }\n\n // Re-throw other errors with context.\n throw new Error(`Failed to acquire lock: ${lockPath}`, {\n cause: error,\n })\n }\n },\n {\n retries,\n baseDelayMs,\n maxDelayMs,\n jitter: true,\n },\n )\n }\n\n /**\n * Release a lock and remove from tracking.\n * Stops periodic touching and removes the lock directory.\n *\n * @param lockPath - Path to the lock directory\n *\n * @example\n * ```typescript\n * processLock.release('/tmp/my-lock')\n * ```\n */\n release(lockPath: string): void {\n // Stop periodic touching.\n this.stopTouchTimer(lockPath)\n\n try {\n if (existsSync(lockPath)) {\n safeDeleteSync(lockPath, { recursive: true })\n }\n this.activeLocks.delete(lockPath)\n } catch (error) {\n logger.warn(\n `Failed to release lock ${lockPath}: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n\n /**\n * Execute a function with exclusive lock protection.\n * Automatically handles lock acquisition, execution, and cleanup.\n *\n * This is the recommended way to use process locks, as it guarantees\n * cleanup even if the callback throws an error.\n *\n * @param lockPath - Path to the lock directory\n * @param fn - Function to execute while holding the lock\n * @param options - Lock acquisition options\n * @returns Result of the callback function\n * @throws Error from callback or lock acquisition failure\n *\n * @example\n * ```typescript\n * const result = await processLock.withLock('/tmp/my-lock', async () => {\n * // Critical section\n * return someValue\n * })\n * ```\n */\n async withLock<T>(\n lockPath: string,\n fn: () => Promise<T>,\n options?: ProcessLockOptions,\n ): Promise<T> {\n const release = await this.acquire(lockPath, options)\n try {\n return await fn()\n } finally {\n release()\n }\n }\n}\n\n// Export singleton instance.\nexport const processLock = new ProcessLockManager()\n"],
|
|
5
|
-
"mappings": ";4ZAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iBAAAE,IAAA,eAAAC,EAAAH,GA0CA,IAAAI,EAA4D,
|
|
6
|
-
"names": ["process_lock_exports", "__export", "processLock", "__toCommonJS", "
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview Process locking utilities with stale detection and exit cleanup.\n * Provides cross-platform inter-process synchronization using directory-based locks.\n * Aligned with npm's npx locking strategy (5-second stale timeout, periodic touching).\n *\n * ## Why directories instead of files?\n *\n * This implementation uses `mkdir()` to create lock directories (not files) because:\n *\n * 1. **Atomic guarantee**: `mkdir()` is guaranteed atomic across ALL filesystems,\n * including NFS. Only ONE process can successfully create the directory. If it\n * exists, `mkdir()` fails with EEXIST instantly with no race conditions.\n *\n * 2. **File-based locking issues**:\n * - `writeFile()` with `flag: 'wx'` - atomicity can fail on NFS\n * - `open()` with `O_EXCL` - not guaranteed atomic on older NFS\n * - Traditional lockfiles - can have race conditions on network filesystems\n *\n * 3. **Simplicity**: No need to write/read file content, track PIDs, or manage\n * file descriptors. Just create/delete directory and check mtime.\n *\n * 4. **Historical precedent**: Well-known Unix locking pattern used by package\n * managers for decades. Git uses similar approach for `.git/index.lock`.\n *\n * ## The mtime trick\n *\n * We periodically update the lock directory's mtime (modification time) by\n * \"touching\" it to signal \"I'm still actively working\". This prevents other\n * processes from treating the lock as stale and removing it.\n *\n * **The lock directory remains empty** - it's just a sentinel that signals\n * \"locked\". The mtime is the only data needed to track lock freshness.\n *\n * ## npm npx compatibility\n *\n * This implementation matches npm npx's concurrency.lock approach:\n * - Lock created via `mkdir(path.join(installDir, 'concurrency.lock'))`\n * - 5-second stale timeout (if mtime is older than 5s, lock is stale)\n * - 2-second touching interval (updates mtime every 2s to keep lock fresh)\n * - Automatic cleanup on process exit\n */\n\nimport { existsSync, mkdirSync, statSync, utimesSync } from 'fs'\n\nimport { safeDeleteSync } from './fs'\nimport { getDefaultLogger } from './logger'\nimport { pRetry } from './promises'\nimport { onExit } from './signal-exit'\n\nconst logger = getDefaultLogger()\n\n/**\n * Lock acquisition options.\n */\nexport interface ProcessLockOptions {\n /**\n * Maximum number of retry attempts.\n * @default 3\n */\n retries?: number | undefined\n\n /**\n * Base delay between retries in milliseconds.\n * @default 100\n */\n baseDelayMs?: number | undefined\n\n /**\n * Maximum delay between retries in milliseconds.\n * @default 1000\n */\n maxDelayMs?: number | undefined\n\n /**\n * Stale lock timeout in milliseconds.\n * Locks older than this are considered abandoned and can be reclaimed.\n * Aligned with npm's npx locking strategy (5 seconds).\n * @default 5000 (5 seconds)\n */\n staleMs?: number | undefined\n\n /**\n * Interval for touching lock file to keep it fresh in milliseconds.\n * Set to 0 to disable periodic touching.\n * @default 2000 (2 seconds)\n */\n touchIntervalMs?: number | undefined\n}\n\n/**\n * Process lock manager with stale detection and exit cleanup.\n * Provides cross-platform inter-process synchronization using file-system\n * based locks.\n */\nclass ProcessLockManager {\n private activeLocks = new Set<string>()\n private touchTimers = new Map<string, NodeJS.Timeout>()\n private exitHandlerRegistered = false\n\n /**\n * Ensure process exit handler is registered for cleanup.\n * Registers a handler that cleans up all active locks when the process exits.\n */\n private ensureExitHandler() {\n if (this.exitHandlerRegistered) {\n return\n }\n\n onExit(() => {\n // Clear all touch timers.\n for (const timer of this.touchTimers.values()) {\n clearInterval(timer)\n }\n this.touchTimers.clear()\n\n // Clean up all active locks.\n for (const lockPath of this.activeLocks) {\n try {\n if (existsSync(lockPath)) {\n safeDeleteSync(lockPath, { recursive: true })\n }\n } catch {\n // Ignore cleanup errors during exit.\n }\n }\n })\n\n this.exitHandlerRegistered = true\n }\n\n /**\n * Touch a lock file to update its mtime.\n * This prevents the lock from being detected as stale during long operations.\n *\n * @param lockPath - Path to the lock directory\n */\n private touchLock(lockPath: string): void {\n try {\n if (existsSync(lockPath)) {\n const now = new Date()\n utimesSync(lockPath, now, now)\n }\n } catch (error) {\n logger.warn(\n `Failed to touch lock ${lockPath}: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n\n /**\n * Start periodic touching of a lock file.\n * Aligned with npm npx strategy to prevent false stale detection.\n *\n * @param lockPath - Path to the lock directory\n * @param intervalMs - Touch interval in milliseconds\n */\n private startTouchTimer(lockPath: string, intervalMs: number): void {\n if (intervalMs <= 0 || this.touchTimers.has(lockPath)) {\n return\n }\n\n const timer = setInterval(() => {\n this.touchLock(lockPath)\n }, intervalMs)\n\n // Prevent timer from keeping process alive.\n timer.unref()\n\n this.touchTimers.set(lockPath, timer)\n }\n\n /**\n * Stop periodic touching of a lock file.\n *\n * @param lockPath - Path to the lock directory\n */\n private stopTouchTimer(lockPath: string): void {\n const timer = this.touchTimers.get(lockPath)\n if (timer) {\n clearInterval(timer)\n this.touchTimers.delete(lockPath)\n }\n }\n\n /**\n * Check if a lock is stale based on mtime.\n * Uses second-level granularity to avoid APFS floating-point precision issues.\n * Aligned with npm's npx locking strategy.\n *\n * @param lockPath - Path to the lock directory\n * @param staleMs - Stale timeout in milliseconds\n * @returns True if lock exists and is stale\n */\n private isStale(lockPath: string, staleMs: number): boolean {\n try {\n if (!existsSync(lockPath)) {\n return false\n }\n\n const stats = statSync(lockPath)\n // Use second-level granularity to avoid APFS issues.\n const ageSeconds = Math.floor((Date.now() - stats.mtime.getTime()) / 1000)\n const staleSeconds = Math.floor(staleMs / 1000)\n return ageSeconds > staleSeconds\n } catch {\n return false\n }\n }\n\n /**\n * Acquire a lock using mkdir for atomic operation.\n * Handles stale locks and includes exit cleanup.\n *\n * This method attempts to create a lock directory atomically. If the lock\n * already exists, it checks if it's stale and removes it before retrying.\n * Uses exponential backoff with jitter for retry attempts.\n *\n * @param lockPath - Path to the lock directory\n * @param options - Lock acquisition options\n * @returns Release function to unlock\n * @throws Error if lock cannot be acquired after all retries\n *\n * @example\n * ```typescript\n * const release = await processLock.acquire('/tmp/my-lock')\n * try {\n * // Critical section\n * } finally {\n * release()\n * }\n * ```\n */\n async acquire(\n lockPath: string,\n options: ProcessLockOptions = {},\n ): Promise<() => void> {\n const {\n baseDelayMs = 100,\n maxDelayMs = 1000,\n retries = 3,\n staleMs = 5000,\n touchIntervalMs = 2000,\n } = options\n\n // Ensure exit handler is registered before any lock acquisition.\n this.ensureExitHandler()\n\n return await pRetry(\n async () => {\n try {\n // Check for stale lock and remove if necessary.\n if (existsSync(lockPath) && this.isStale(lockPath, staleMs)) {\n logger.log(`Removing stale lock: ${lockPath}`)\n try {\n safeDeleteSync(lockPath, { recursive: true })\n } catch {\n // Ignore errors removing stale lock - will retry.\n }\n }\n\n // Check if lock already exists before creating.\n if (existsSync(lockPath)) {\n throw new Error(`Lock already exists: ${lockPath}`)\n }\n\n // Atomic lock acquisition via mkdir with recursive to create parent dirs.\n mkdirSync(lockPath, { recursive: true })\n\n // Track lock for cleanup.\n this.activeLocks.add(lockPath)\n\n // Start periodic touching to prevent stale detection.\n this.startTouchTimer(lockPath, touchIntervalMs)\n\n // Return release function.\n return () => this.release(lockPath)\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n\n // Handle lock contention - lock already exists.\n if (code === 'EEXIST') {\n if (this.isStale(lockPath, staleMs)) {\n throw new Error(`Stale lock detected: ${lockPath}`)\n }\n throw new Error(`Lock already exists: ${lockPath}`)\n }\n\n // Handle permission errors - not retryable.\n if (code === 'EACCES' || code === 'EPERM') {\n throw new Error(\n `Permission denied creating lock: ${lockPath}. ` +\n 'Check directory permissions or run with appropriate access.',\n { cause: error },\n )\n }\n\n // Handle read-only filesystem - not retryable.\n if (code === 'EROFS') {\n throw new Error(\n `Cannot create lock on read-only filesystem: ${lockPath}`,\n { cause: error },\n )\n }\n\n // Handle parent path issues - not retryable.\n if (code === 'ENOTDIR') {\n const parentDir = lockPath.slice(0, lockPath.lastIndexOf('/'))\n throw new Error(\n `Cannot create lock directory: ${lockPath}\\n` +\n 'A path component is a file when it should be a directory.\\n' +\n `Parent path: ${parentDir}\\n` +\n 'To resolve:\\n' +\n ` 1. Check if \"${parentDir}\" contains a file instead of a directory\\n` +\n ' 2. Remove any conflicting files in the path\\n' +\n ' 3. Ensure the full parent directory structure exists',\n { cause: error },\n )\n }\n\n if (code === 'ENOENT') {\n const parentDir = lockPath.slice(0, lockPath.lastIndexOf('/'))\n throw new Error(\n `Cannot create lock directory: ${lockPath}\\n` +\n `Parent directory does not exist: ${parentDir}\\n` +\n 'To resolve:\\n' +\n ` 1. Ensure the parent directory \"${parentDir}\" exists\\n` +\n ` 2. Create the directory structure: mkdir -p \"${parentDir}\"\\n` +\n ' 3. Check filesystem permissions allow directory creation',\n { cause: error },\n )\n }\n\n // Re-throw other errors with context.\n throw new Error(`Failed to acquire lock: ${lockPath}`, {\n cause: error,\n })\n }\n },\n {\n retries,\n baseDelayMs,\n maxDelayMs,\n jitter: true,\n },\n )\n }\n\n /**\n * Release a lock and remove from tracking.\n * Stops periodic touching and removes the lock directory.\n *\n * @param lockPath - Path to the lock directory\n *\n * @example\n * ```typescript\n * processLock.release('/tmp/my-lock')\n * ```\n */\n release(lockPath: string): void {\n // Stop periodic touching.\n this.stopTouchTimer(lockPath)\n\n try {\n if (existsSync(lockPath)) {\n safeDeleteSync(lockPath, { recursive: true })\n }\n this.activeLocks.delete(lockPath)\n } catch (error) {\n logger.warn(\n `Failed to release lock ${lockPath}: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n\n /**\n * Execute a function with exclusive lock protection.\n * Automatically handles lock acquisition, execution, and cleanup.\n *\n * This is the recommended way to use process locks, as it guarantees\n * cleanup even if the callback throws an error.\n *\n * @param lockPath - Path to the lock directory\n * @param fn - Function to execute while holding the lock\n * @param options - Lock acquisition options\n * @returns Result of the callback function\n * @throws Error from callback or lock acquisition failure\n *\n * @example\n * ```typescript\n * const result = await processLock.withLock('/tmp/my-lock', async () => {\n * // Critical section\n * return someValue\n * })\n * ```\n */\n async withLock<T>(\n lockPath: string,\n fn: () => Promise<T>,\n options?: ProcessLockOptions,\n ): Promise<T> {\n const release = await this.acquire(lockPath, options)\n try {\n return await fn()\n } finally {\n release()\n }\n }\n}\n\n// Export singleton instance.\nexport const processLock = new ProcessLockManager()\n"],
|
|
5
|
+
"mappings": ";4ZAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iBAAAE,IAAA,eAAAC,EAAAH,GA0CA,IAAAI,EAA4D,cAE5DA,EAA+B,gBAC/BC,EAAiC,oBACjCC,EAAuB,sBACvBC,EAAuB,yBAEvB,MAAMC,KAAS,oBAAiB,EA6ChC,MAAMC,CAAmB,CACf,YAAc,IAAI,IAClB,YAAc,IAAI,IAClB,sBAAwB,GAMxB,mBAAoB,CACtB,KAAK,2BAIT,UAAO,IAAM,CAEX,UAAWC,KAAS,KAAK,YAAY,OAAO,EAC1C,cAAcA,CAAK,EAErB,KAAK,YAAY,MAAM,EAGvB,UAAWC,KAAY,KAAK,YAC1B,GAAI,IACE,cAAWA,CAAQ,MACrB,kBAAeA,EAAU,CAAE,UAAW,EAAK,CAAC,CAEhD,MAAQ,CAER,CAEJ,CAAC,EAED,KAAK,sBAAwB,GAC/B,CAQQ,UAAUA,EAAwB,CACxC,GAAI,CACF,MAAI,cAAWA,CAAQ,EAAG,CACxB,MAAMC,EAAM,IAAI,QAChB,cAAWD,EAAUC,EAAKA,CAAG,CAC/B,CACF,OAASC,EAAO,CACdL,EAAO,KACL,wBAAwBG,CAAQ,KAAKE,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EAC7F,CACF,CACF,CASQ,gBAAgBF,EAAkBG,EAA0B,CAClE,GAAIA,GAAc,GAAK,KAAK,YAAY,IAAIH,CAAQ,EAClD,OAGF,MAAMD,EAAQ,YAAY,IAAM,CAC9B,KAAK,UAAUC,CAAQ,CACzB,EAAGG,CAAU,EAGbJ,EAAM,MAAM,EAEZ,KAAK,YAAY,IAAIC,EAAUD,CAAK,CACtC,CAOQ,eAAeC,EAAwB,CAC7C,MAAMD,EAAQ,KAAK,YAAY,IAAIC,CAAQ,EACvCD,IACF,cAAcA,CAAK,EACnB,KAAK,YAAY,OAAOC,CAAQ,EAEpC,CAWQ,QAAQA,EAAkBI,EAA0B,CAC1D,GAAI,CACF,GAAI,IAAC,cAAWJ,CAAQ,EACtB,MAAO,GAGT,MAAMK,KAAQ,YAASL,CAAQ,EAEzBM,EAAa,KAAK,OAAO,KAAK,IAAI,EAAID,EAAM,MAAM,QAAQ,GAAK,GAAI,EACnEE,EAAe,KAAK,MAAMH,EAAU,GAAI,EAC9C,OAAOE,EAAaC,CACtB,MAAQ,CACN,MAAO,EACT,CACF,CAyBA,MAAM,QACJP,EACAQ,EAA8B,CAAC,EACV,CACrB,KAAM,CACJ,YAAAC,EAAc,IACd,WAAAC,EAAa,IACb,QAAAC,EAAU,EACV,QAAAP,EAAU,IACV,gBAAAQ,EAAkB,GACpB,EAAIJ,EAGJ,YAAK,kBAAkB,EAEhB,QAAM,UACX,SAAY,CACV,GAAI,CAEF,MAAI,cAAWR,CAAQ,GAAK,KAAK,QAAQA,EAAUI,CAAO,EAAG,CAC3DP,EAAO,IAAI,wBAAwBG,CAAQ,EAAE,EAC7C,GAAI,IACF,kBAAeA,EAAU,CAAE,UAAW,EAAK,CAAC,CAC9C,MAAQ,CAER,CACF,CAGA,MAAI,cAAWA,CAAQ,EACrB,MAAM,IAAI,MAAM,wBAAwBA,CAAQ,EAAE,EAIpD,sBAAUA,EAAU,CAAE,UAAW,EAAK,CAAC,EAGvC,KAAK,YAAY,IAAIA,CAAQ,EAG7B,KAAK,gBAAgBA,EAAUY,CAAe,EAGvC,IAAM,KAAK,QAAQZ,CAAQ,CACpC,OAASE,EAAO,CACd,MAAMW,EAAQX,EAAgC,KAG9C,GAAIW,IAAS,SACX,MAAI,KAAK,QAAQb,EAAUI,CAAO,EAC1B,IAAI,MAAM,wBAAwBJ,CAAQ,EAAE,EAE9C,IAAI,MAAM,wBAAwBA,CAAQ,EAAE,EAIpD,GAAIa,IAAS,UAAYA,IAAS,QAChC,MAAM,IAAI,MACR,oCAAoCb,CAAQ,gEAE5C,CAAE,MAAOE,CAAM,CACjB,EAIF,GAAIW,IAAS,QACX,MAAM,IAAI,MACR,+CAA+Cb,CAAQ,GACvD,CAAE,MAAOE,CAAM,CACjB,EAIF,GAAIW,IAAS,UAAW,CACtB,MAAMC,EAAYd,EAAS,MAAM,EAAGA,EAAS,YAAY,GAAG,CAAC,EAC7D,MAAM,IAAI,MACR,iCAAiCA,CAAQ;AAAA;AAAA,eAEvBc,CAAS;AAAA;AAAA,iBAEPA,CAAS;AAAA;AAAA,wDAG7B,CAAE,MAAOZ,CAAM,CACjB,CACF,CAEA,GAAIW,IAAS,SAAU,CACrB,MAAMC,EAAYd,EAAS,MAAM,EAAGA,EAAS,YAAY,GAAG,CAAC,EAC7D,MAAM,IAAI,MACR,iCAAiCA,CAAQ;AAAA,mCACHc,CAAS;AAAA;AAAA,oCAERA,CAAS;AAAA,iDACIA,CAAS;AAAA,4DAE7D,CAAE,MAAOZ,CAAM,CACjB,CACF,CAGA,MAAM,IAAI,MAAM,2BAA2BF,CAAQ,GAAI,CACrD,MAAOE,CACT,CAAC,CACH,CACF,EACA,CACE,QAAAS,EACA,YAAAF,EACA,WAAAC,EACA,OAAQ,EACV,CACF,CACF,CAaA,QAAQV,EAAwB,CAE9B,KAAK,eAAeA,CAAQ,EAE5B,GAAI,IACE,cAAWA,CAAQ,MACrB,kBAAeA,EAAU,CAAE,UAAW,EAAK,CAAC,EAE9C,KAAK,YAAY,OAAOA,CAAQ,CAClC,OAASE,EAAO,CACdL,EAAO,KACL,0BAA0BG,CAAQ,KAAKE,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EAC/F,CACF,CACF,CAuBA,MAAM,SACJF,EACAe,EACAP,EACY,CACZ,MAAMQ,EAAU,MAAM,KAAK,QAAQhB,EAAUQ,CAAO,EACpD,GAAI,CACF,OAAO,MAAMO,EAAG,CAClB,QAAE,CACAC,EAAQ,CACV,CACF,CACF,CAGO,MAAMzB,EAAc,IAAIO",
|
|
6
|
+
"names": ["process_lock_exports", "__export", "processLock", "__toCommonJS", "import_fs", "import_logger", "import_promises", "import_signal_exit", "logger", "ProcessLockManager", "timer", "lockPath", "now", "error", "intervalMs", "staleMs", "stats", "ageSeconds", "staleSeconds", "options", "baseDelayMs", "maxDelayMs", "retries", "touchIntervalMs", "code", "parentDir", "fn", "release"]
|
|
7
7
|
}
|
package/dist/promises.d.ts
CHANGED
|
@@ -30,13 +30,8 @@ export interface RetryOptions {
|
|
|
30
30
|
* @default 200
|
|
31
31
|
*/
|
|
32
32
|
baseDelayMs?: number | undefined;
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
*
|
|
36
|
-
* @deprecated Use `backoffFactor` instead
|
|
37
|
-
* @default 2
|
|
38
|
-
*/
|
|
39
|
-
factor?: number | undefined;
|
|
33
|
+
// REMOVED: Deprecated `factor` option
|
|
34
|
+
// Migration: Use `backoffFactor` instead
|
|
40
35
|
/**
|
|
41
36
|
* Whether to apply randomness to spread out retries and avoid thundering herd.
|
|
42
37
|
* When `true`, adds random delay between 0 and current delay value.
|
|
@@ -54,20 +49,10 @@ export interface RetryOptions {
|
|
|
54
49
|
* @default 10000
|
|
55
50
|
*/
|
|
56
51
|
maxDelayMs?: number | undefined;
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
* @default 10000
|
|
62
|
-
*/
|
|
63
|
-
maxTimeout?: number | undefined;
|
|
64
|
-
/**
|
|
65
|
-
* Legacy alias for `baseDelayMs`. Use `baseDelayMs` instead.
|
|
66
|
-
*
|
|
67
|
-
* @deprecated Use `baseDelayMs` instead
|
|
68
|
-
* @default 200
|
|
69
|
-
*/
|
|
70
|
-
minTimeout?: number | undefined;
|
|
52
|
+
// REMOVED: Deprecated `maxTimeout` option
|
|
53
|
+
// Migration: Use `maxDelayMs` instead
|
|
54
|
+
// REMOVED: Deprecated `minTimeout` option
|
|
55
|
+
// Migration: Use `baseDelayMs` instead
|
|
71
56
|
/**
|
|
72
57
|
* Callback invoked on each retry attempt.
|
|
73
58
|
* Can observe errors, customize delays, or cancel retries.
|
package/dist/promises.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/* Socket Lib - Built with esbuild */
|
|
2
|
-
var
|
|
2
|
+
var T=Object.defineProperty;var F=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var z=Object.prototype.hasOwnProperty;var I=(e,n)=>{for(var r in n)T(e,r,{get:n[r],enumerable:!0})},v=(e,n,r,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of S(n))!z.call(e,o)&&o!==r&&T(e,o,{get:()=>n[o],enumerable:!(t=F(n,o))||t.enumerable});return e};var A=e=>v(T({},"__esModule",{value:!0}),e);var K={};I(K,{normalizeIterationOptions:()=>w,normalizeRetryOptions:()=>y,pEach:()=>j,pEachChunk:()=>q,pFilter:()=>N,pFilterChunk:()=>D,pRetry:()=>R,resolveRetryOptions:()=>_});module.exports=A(K);var O=require("#constants/core"),M=require("#constants/process"),h=require("./arrays");const P=(0,M.getAbortSignal)();let k;function E(){return k===void 0&&(k=require("node:timers/promises")),k}function w(e){const n=typeof e=="number"?{concurrency:e}:e,{concurrency:r=1,retries:t,signal:o=P}={__proto__:null,...n};return{__proto__:null,concurrency:Math.max(1,r),retries:y({signal:o,..._(t)}),signal:o}}function y(e){const n=_(e),{args:r=[],backoffFactor:t=2,baseDelayMs:o=200,jitter:u=!0,maxDelayMs:i=1e4,onRetry:s,onRetryCancelOnFalse:c=!1,onRetryRethrow:d=!1,retries:f=0,signal:a=P}=n;return{args:r,backoffFactor:t,baseDelayMs:o,jitter:u,maxDelayMs:i,onRetry:s,onRetryCancelOnFalse:c,onRetryRethrow:d,retries:f,signal:a}}function _(e){const n={__proto__:null,retries:0,baseDelayMs:200,maxDelayMs:1e4,backoffFactor:2};return typeof e=="number"?{...n,retries:e}:e?{...n,...e}:n}async function j(e,n,r){const t=w(r),{concurrency:o,retries:u,signal:i}=t,s=(0,h.arrayChunk)(e,o);for(const c of s){if(i?.aborted)return;await Promise.all(c.map(d=>R((...f)=>n(f[0]),{...u,args:[d],signal:i})))}}async function N(e,n,r){const t=w(r);return(await D((0,h.arrayChunk)(e,t.concurrency),n,t.retries)).flat()}async function q(e,n,r){const{chunkSize:t=100,...o}=r||{},u=(0,h.arrayChunk)(e,t),i=y(o),{signal:s}=i;for(const c of u){if(s?.aborted)return;await R((...d)=>n(d[0]),{...i,args:[c]})}}async function D(e,n,r){const t=y(r),{signal:o}=t,{length:u}=e,i=Array(u);for(let s=0;s<u;s+=1)if(o?.aborted)i[s]=[];else{const c=e[s],d=await Promise.all(c.map(f=>R((...a)=>n(a[0]),{...t,args:[f]})));i[s]=c.filter((f,a)=>d[a])}return i}async function R(e,n){const{args:r,backoffFactor:t,baseDelayMs:o,jitter:u,maxDelayMs:i,onRetry:s,onRetryCancelOnFalse:c,onRetryRethrow:d,retries:f,signal:a}=y(n);if(a?.aborted)return;if(f===0)return await e(...r||[],{signal:a});const C=E();let g=f,p=o,b=O.UNDEFINED_TOKEN;for(;g-->=0;){if(a?.aborted)return;try{return await e(...r||[],{signal:a})}catch(x){if(b===O.UNDEFINED_TOKEN&&(b=x),g<0)break;let m=p;if(u&&(m+=Math.floor(Math.random()*p)),m=Math.min(m,i),typeof s=="function")try{const l=s(f-g,x,m);if(l===!1&&c)break;typeof l=="number"&&l>=0&&(m=Math.min(l,i))}catch(l){if(d)throw l}try{await C.setTimeout(m,void 0,{signal:a})}catch{return}if(a?.aborted)return;p=Math.min(p*t,i)}}if(b!==O.UNDEFINED_TOKEN)throw b}0&&(module.exports={normalizeIterationOptions,normalizeRetryOptions,pEach,pEachChunk,pFilter,pFilterChunk,pRetry,resolveRetryOptions});
|
|
3
3
|
//# sourceMappingURL=promises.js.map
|
package/dist/promises.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/promises.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @fileoverview Promise utilities including chunked iteration and timers.\n * Provides async control flow helpers and promise-based timing functions.\n */\n\nimport { UNDEFINED_TOKEN } from '#constants/core'\nimport { getAbortSignal } from '#constants/process'\n\nimport { arrayChunk } from './arrays'\n\nconst abortSignal = getAbortSignal()\n\n/**\n * Configuration options for retry behavior with exponential backoff.\n *\n * Controls how failed operations are retried, including timing, backoff strategy,\n * and callback hooks for observing or modifying retry behavior.\n */\nexport interface RetryOptions {\n /**\n * Arguments to pass to the callback function on each attempt.\n *\n * @default []\n */\n args?: unknown[] | undefined\n\n /**\n * Multiplier for exponential backoff (e.g., 2 doubles delay each retry).\n * Each retry waits `baseDelayMs * (backoffFactor ** attemptNumber)`.\n *\n * @default 2\n * @example\n * // With backoffFactor: 2, baseDelayMs: 100\n * // Retry 1: 100ms\n * // Retry 2: 200ms\n * // Retry 3: 400ms\n */\n backoffFactor?: number | undefined\n\n /**\n * Initial delay before the first retry (in milliseconds).\n * This is the base value for exponential backoff calculations.\n *\n * @default 200\n */\n baseDelayMs?: number | undefined\n\n /**\n * Legacy alias for `backoffFactor`. Use `backoffFactor` instead.\n *\n * @deprecated Use `backoffFactor` instead\n * @default 2\n */\n factor?: number | undefined\n\n /**\n * Whether to apply randomness to spread out retries and avoid thundering herd.\n * When `true`, adds random delay between 0 and current delay value.\n *\n * @default true\n * @example\n * // With jitter: true, delay: 100ms\n * // Actual wait: 100ms + random(0-100ms) = 100-200ms\n */\n jitter?: boolean | undefined\n\n /**\n * Upper limit for any backoff delay (in milliseconds).\n * Prevents exponential backoff from growing unbounded.\n *\n * @default 10000\n */\n maxDelayMs?: number | undefined\n\n /**\n * Legacy alias for `maxDelayMs`. Use `maxDelayMs` instead.\n *\n * @deprecated Use `maxDelayMs` instead\n * @default 10000\n */\n maxTimeout?: number | undefined\n\n /**\n * Legacy alias for `baseDelayMs`. Use `baseDelayMs` instead.\n *\n * @deprecated Use `baseDelayMs` instead\n * @default 200\n */\n minTimeout?: number | undefined\n\n /**\n * Callback invoked on each retry attempt.\n * Can observe errors, customize delays, or cancel retries.\n *\n * @param attempt - The current attempt number (1-based: 1, 2, 3, ...)\n * @param error - The error that triggered this retry\n * @param delay - The calculated delay in milliseconds before next retry\n * @returns `false` to cancel retries (if `onRetryCancelOnFalse` is `true`),\n * a number to override the delay, or `undefined` to use calculated delay\n *\n * @example\n * // Log each retry\n * onRetry: (attempt, error, delay) => {\n * console.log(`Retry ${attempt} after ${delay}ms: ${error}`)\n * }\n *\n * @example\n * // Cancel retries for specific errors\n * onRetry: (attempt, error) => {\n * if (error instanceof ValidationError) return false\n * }\n *\n * @example\n * // Use custom delay\n * onRetry: (attempt) => attempt * 1000 // 1s, 2s, 3s, ...\n */\n onRetry?:\n | ((\n attempt: number,\n error: unknown,\n delay: number,\n ) => boolean | number | undefined)\n | undefined\n\n /**\n * Whether `onRetry` can cancel retries by returning `false`.\n * When `true`, returning `false` from `onRetry` stops retry attempts.\n *\n * @default false\n */\n onRetryCancelOnFalse?: boolean | undefined\n\n /**\n * Whether errors thrown by `onRetry` should propagate.\n * When `true`, exceptions in `onRetry` terminate the retry loop.\n * When `false`, exceptions in `onRetry` are silently caught.\n *\n * @default false\n */\n onRetryRethrow?: boolean | undefined\n\n /**\n * Number of retry attempts (0 = no retries, only initial attempt).\n * The callback is executed `retries + 1` times total (initial + retries).\n *\n * @default 0\n * @example\n * // retries: 0 -> 1 total attempt (no retries)\n * // retries: 3 -> 4 total attempts (1 initial + 3 retries)\n */\n retries?: number | undefined\n\n /**\n * AbortSignal to support cancellation of retry operations.\n * When aborted, immediately stops retrying and returns `undefined`.\n *\n * @default process abort signal\n * @example\n * const controller = new AbortController()\n * pRetry(fn, { signal: controller.signal })\n * // Later: controller.abort() to cancel\n */\n signal?: AbortSignal | undefined\n}\n\n/**\n * Configuration options for iteration functions with concurrency control.\n *\n * Controls how array operations are parallelized and retried.\n */\nexport interface IterationOptions {\n /**\n * The number of concurrent executions performed at one time.\n * Higher values increase parallelism but may overwhelm resources.\n *\n * @default 1\n * @example\n * // Process 5 items at a time\n * await pEach(items, processItem, { concurrency: 5 })\n */\n concurrency?: number | undefined\n\n /**\n * Retry configuration as a number (retry count) or full options object.\n * Applied to each individual item's callback execution.\n *\n * @default 0 (no retries)\n * @example\n * // Simple: retry each item up to 3 times\n * await pEach(items, fetchItem, { retries: 3 })\n *\n * @example\n * // Advanced: custom backoff for each item\n * await pEach(items, fetchItem, {\n * retries: {\n * retries: 3,\n * baseDelayMs: 1000,\n * backoffFactor: 2\n * }\n * })\n */\n retries?: number | RetryOptions | undefined\n\n /**\n * AbortSignal to support cancellation of the entire iteration.\n * When aborted, stops processing remaining items.\n *\n * @default process abort signal\n */\n signal?: AbortSignal | undefined\n}\n\nlet _timers: typeof import('node:timers/promises') | undefined\n/**\n * Get the timers/promises module.\n * Uses lazy loading to avoid Webpack bundling issues.\n *\n * @private\n * @returns The Node.js timers/promises module\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getTimers() {\n if (_timers === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _timers = /*@__PURE__*/ require('node:timers/promises')\n }\n return _timers as typeof import('node:timers/promises')\n}\n\n/**\n * Normalize options for iteration functions.\n *\n * Converts various option formats into a consistent structure with defaults applied.\n * Handles number shorthand for concurrency and ensures minimum values.\n *\n * @param options - Concurrency as number, or full options object, or undefined\n * @returns Normalized options with concurrency, retries, and signal\n *\n * @example\n * // Number shorthand for concurrency\n * normalizeIterationOptions(5)\n * // => { concurrency: 5, retries: {...}, signal: AbortSignal }\n *\n * @example\n * // Full options\n * normalizeIterationOptions({ concurrency: 3, retries: 2 })\n * // => { concurrency: 3, retries: {...}, signal: AbortSignal }\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function normalizeIterationOptions(\n options?: number | IterationOptions | undefined,\n): { concurrency: number; retries: RetryOptions; signal: AbortSignal } {\n // Handle number as concurrency shorthand\n const opts = typeof options === 'number' ? { concurrency: options } : options\n\n const {\n // The number of concurrent executions performed at one time.\n concurrency = 1,\n // Retries as a number or options object.\n retries,\n // AbortSignal used to support cancellation.\n signal = abortSignal,\n } = { __proto__: null, ...opts } as IterationOptions\n\n // Ensure concurrency is at least 1\n const normalizedConcurrency = Math.max(1, concurrency)\n const retryOpts = resolveRetryOptions(retries)\n return {\n __proto__: null,\n concurrency: normalizedConcurrency,\n retries: normalizeRetryOptions({ signal, ...retryOpts }),\n signal,\n } as { concurrency: number; retries: RetryOptions; signal: AbortSignal }\n}\n\n/**\n * Normalize options for retry functionality.\n *\n * Converts various retry option formats into a complete configuration with all defaults.\n * Handles legacy property names (`factor`, `minTimeout`, `maxTimeout`) and merges them\n * with modern equivalents.\n *\n * @param options - Retry count as number, or full options object, or undefined\n * @returns Normalized retry options with all properties set\n *\n * @example\n * // Number shorthand\n * normalizeRetryOptions(3)\n * // => { retries: 3, baseDelayMs: 200, backoffFactor: 2, ... }\n *\n * @example\n * // Full options with defaults filled in\n * normalizeRetryOptions({ retries: 5, baseDelayMs: 500 })\n * // => { retries: 5, baseDelayMs: 500, backoffFactor: 2, jitter: true, ... }\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function normalizeRetryOptions(\n options?: number | RetryOptions | undefined,\n): RetryOptions {\n const resolved = resolveRetryOptions(options)\n const {\n // Arguments to pass to the callback function.\n args = [],\n // Multiplier for exponential backoff (e.g., 2 doubles delay each retry).\n backoffFactor = resolved.factor || 2,\n // Initial delay before the first retry (in milliseconds).\n baseDelayMs = resolved.minTimeout || 200,\n // Whether to apply randomness to spread out retries.\n jitter = true,\n // Upper limit for any backoff delay (in milliseconds).\n maxDelayMs = resolved.maxTimeout || 10_000,\n // Optional callback invoked on each retry attempt:\n // (attempt: number, error: unknown, delay: number) => void\n onRetry,\n // Whether onRetry can cancel retries by returning `false`.\n onRetryCancelOnFalse = false,\n // Whether onRetry will rethrow errors.\n onRetryRethrow = false,\n // Number of retry attempts (0 = no retries, only initial attempt).\n retries = resolved.retries || 0,\n // AbortSignal used to support cancellation.\n signal = abortSignal,\n } = resolved\n return {\n args,\n backoffFactor,\n baseDelayMs,\n jitter,\n maxDelayMs,\n minTimeout: baseDelayMs,\n maxTimeout: maxDelayMs,\n onRetry,\n onRetryCancelOnFalse,\n onRetryRethrow,\n retries,\n signal,\n } as RetryOptions\n}\n\n/**\n * Resolve retry options from various input formats.\n *\n * Converts shorthand and partial options into a base configuration that can be\n * further normalized. This is an internal helper for option processing.\n *\n * @param options - Retry count as number, or partial options object, or undefined\n * @returns Resolved retry options with defaults for basic properties\n *\n * @example\n * resolveRetryOptions(3)\n * // => { retries: 3, minTimeout: 200, maxTimeout: 10000, factor: 2 }\n *\n * @example\n * resolveRetryOptions({ retries: 5, maxTimeout: 5000 })\n * // => { retries: 5, minTimeout: 200, maxTimeout: 5000, factor: 2 }\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function resolveRetryOptions(\n options?: number | RetryOptions | undefined,\n): RetryOptions {\n const defaults = {\n __proto__: null,\n retries: 0,\n minTimeout: 200,\n maxTimeout: 10_000,\n factor: 2,\n }\n\n if (typeof options === 'number') {\n return { ...defaults, retries: options }\n }\n\n return options ? { ...defaults, ...options } : defaults\n}\n\n/**\n * Execute an async function for each array element with concurrency control.\n *\n * Processes array items in parallel batches (chunks) with configurable concurrency.\n * Each item's callback can be retried independently on failure. Similar to\n * `Promise.all(array.map(fn))` but with controlled parallelism.\n *\n * @template T - The type of array elements\n * @param array - The array to iterate over\n * @param callbackFn - Async function to execute for each item\n * @param options - Concurrency as number, or full iteration options, or undefined\n * @returns Promise that resolves when all items are processed\n *\n * @example\n * // Process items serially (concurrency: 1)\n * await pEach(urls, async (url) => {\n * await fetch(url)\n * })\n *\n * @example\n * // Process 5 items at a time\n * await pEach(files, async (file) => {\n * await processFile(file)\n * }, 5)\n *\n * @example\n * // With retries and cancellation\n * const controller = new AbortController()\n * await pEach(tasks, async (task) => {\n * await executeTask(task)\n * }, {\n * concurrency: 3,\n * retries: 2,\n * signal: controller.signal\n * })\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function pEach<T>(\n array: T[],\n callbackFn: (item: T) => Promise<unknown>,\n options?: number | IterationOptions | undefined,\n): Promise<void> {\n const iterOpts = normalizeIterationOptions(options)\n const { concurrency, retries, signal } = iterOpts\n\n // Process items with concurrency control.\n const chunks = arrayChunk(array, concurrency)\n for (const chunk of chunks) {\n if (signal?.aborted) {\n return\n }\n // Process each item in the chunk concurrently.\n // eslint-disable-next-line no-await-in-loop\n await Promise.all(\n chunk.map((item: T) =>\n pRetry((...args: unknown[]) => callbackFn(args[0] as T), {\n ...retries,\n args: [item],\n signal,\n }),\n ),\n )\n }\n}\n\n/**\n * Filter an array asynchronously with concurrency control.\n *\n * Tests each element with an async predicate function, processing items in parallel\n * batches. Returns a new array with only items that pass the test. Similar to\n * `array.filter()` but for async predicates with controlled concurrency.\n *\n * @template T - The type of array elements\n * @param array - The array to filter\n * @param callbackFn - Async predicate function returning true to keep item\n * @param options - Concurrency as number, or full iteration options, or undefined\n * @returns Promise resolving to filtered array\n *\n * @example\n * // Filter serially\n * const activeUsers = await pFilter(users, async (user) => {\n * return await isUserActive(user.id)\n * })\n *\n * @example\n * // Filter with concurrency\n * const validFiles = await pFilter(filePaths, async (path) => {\n * try {\n * await fs.access(path)\n * return true\n * } catch {\n * return false\n * }\n * }, 10)\n *\n * @example\n * // With retries for flaky checks\n * const reachable = await pFilter(endpoints, async (url) => {\n * const response = await fetch(url)\n * return response.ok\n * }, {\n * concurrency: 5,\n * retries: 2\n * })\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function pFilter<T>(\n array: T[],\n callbackFn: (item: T) => Promise<boolean>,\n options?: number | IterationOptions | undefined,\n): Promise<T[]> {\n const iterOpts = normalizeIterationOptions(options)\n return (\n await pFilterChunk(\n arrayChunk(array, iterOpts.concurrency),\n callbackFn,\n iterOpts.retries,\n )\n ).flat()\n}\n\n/**\n * Process array in chunks with an async callback.\n *\n * Divides the array into fixed-size chunks and processes each chunk sequentially\n * with the callback. Useful for batch operations like bulk database inserts or\n * API calls with payload size limits.\n *\n * @template T - The type of array elements\n * @param array - The array to process in chunks\n * @param callbackFn - Async function to execute for each chunk\n * @param options - Chunk size and retry options\n * @returns Promise that resolves when all chunks are processed\n *\n * @example\n * // Insert records in batches of 100\n * await pEachChunk(records, async (chunk) => {\n * await db.batchInsert(chunk)\n * }, { chunkSize: 100 })\n *\n * @example\n * // Upload files in batches with retries\n * await pEachChunk(files, async (batch) => {\n * await uploadBatch(batch)\n * }, {\n * chunkSize: 50,\n * retries: 3,\n * baseDelayMs: 1000\n * })\n *\n * @example\n * // Process with cancellation support\n * const controller = new AbortController()\n * await pEachChunk(items, async (chunk) => {\n * await processChunk(chunk)\n * }, {\n * chunkSize: 25,\n * signal: controller.signal\n * })\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function pEachChunk<T>(\n array: T[],\n callbackFn: (chunk: T[]) => Promise<unknown>,\n options?: (RetryOptions & { chunkSize?: number | undefined }) | undefined,\n): Promise<void> {\n const { chunkSize = 100, ...retryOpts } = options || {}\n const chunks = arrayChunk(array, chunkSize)\n const normalizedRetryOpts = normalizeRetryOptions(retryOpts)\n const { signal } = normalizedRetryOpts\n for (const chunk of chunks) {\n if (signal?.aborted) {\n return\n }\n // eslint-disable-next-line no-await-in-loop\n await pRetry((...args: unknown[]) => callbackFn(args[0] as T[]), {\n ...normalizedRetryOpts,\n args: [chunk],\n })\n }\n}\n\n/**\n * Filter chunked arrays with an async predicate.\n *\n * Internal helper for `pFilter`. Processes pre-chunked arrays, applying the\n * predicate to each element within each chunk with retry support.\n *\n * @template T - The type of array elements\n * @param chunks - Pre-chunked array (array of arrays)\n * @param callbackFn - Async predicate function\n * @param options - Retry count as number, or full retry options, or undefined\n * @returns Promise resolving to array of filtered chunks\n *\n * @example\n * const chunks = [[1, 2], [3, 4], [5, 6]]\n * const filtered = await pFilterChunk(chunks, async (n) => n % 2 === 0)\n * // => [[2], [4], [6]]\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function pFilterChunk<T>(\n chunks: T[][],\n callbackFn: (value: T) => Promise<boolean>,\n options?: number | RetryOptions | undefined,\n): Promise<T[][]> {\n const retryOpts = normalizeRetryOptions(options)\n const { signal } = retryOpts\n const { length } = chunks\n const filteredChunks = Array(length)\n for (let i = 0; i < length; i += 1) {\n // Process each chunk, filtering based on the callback function.\n if (signal?.aborted) {\n filteredChunks[i] = []\n } else {\n const chunk = chunks[i] as T[]\n // eslint-disable-next-line no-await-in-loop\n const predicateResults = await Promise.all(\n chunk.map(value =>\n pRetry((...args: unknown[]) => callbackFn(args[0] as T), {\n ...retryOpts,\n args: [value],\n }),\n ),\n )\n filteredChunks[i] = chunk.filter((_v, i) => predicateResults[i])\n }\n }\n return filteredChunks\n}\n\n/**\n * Retry an async function with exponential backoff.\n *\n * Attempts to execute a function multiple times with increasing delays between attempts.\n * Implements exponential backoff with optional jitter to prevent thundering herd problems.\n * Supports custom retry logic via `onRetry` callback.\n *\n * The delay calculation follows: `min(baseDelayMs * (backoffFactor ** attempt), maxDelayMs)`\n * With jitter: adds random value between 0 and calculated delay.\n *\n * @template T - The return type of the callback function\n * @param callbackFn - Async function to retry\n * @param options - Retry count as number, or full retry options, or undefined\n * @returns Promise resolving to callback result, or `undefined` if aborted\n *\n * @throws {Error} The last error if all retry attempts fail\n *\n * @example\n * // Simple retry: 3 attempts with default backoff\n * const data = await pRetry(async () => {\n * return await fetchData()\n * }, 3)\n *\n * @example\n * // Custom backoff strategy\n * const result = await pRetry(async () => {\n * return await unreliableOperation()\n * }, {\n * retries: 5,\n * baseDelayMs: 1000, // Start at 1 second\n * backoffFactor: 2, // Double each time\n * maxDelayMs: 30000, // Cap at 30 seconds\n * jitter: true // Add randomness\n * })\n * // Delays: ~1s, ~2s, ~4s, ~8s, ~16s (each \u00B1 random jitter)\n *\n * @example\n * // With custom retry logic\n * const data = await pRetry(async () => {\n * return await apiCall()\n * }, {\n * retries: 3,\n * onRetry: (attempt, error, delay) => {\n * console.log(`Attempt ${attempt} failed: ${error}`)\n * console.log(`Waiting ${delay}ms before retry...`)\n *\n * // Cancel retries for client errors (4xx)\n * if (error.statusCode >= 400 && error.statusCode < 500) {\n * return false\n * }\n *\n * // Use longer delay for rate limit errors\n * if (error.statusCode === 429) {\n * return 60000 // Wait 1 minute\n * }\n * },\n * onRetryCancelOnFalse: true\n * })\n *\n * @example\n * // With cancellation support\n * const controller = new AbortController()\n * setTimeout(() => controller.abort(), 5000) // Cancel after 5s\n *\n * const result = await pRetry(async ({ signal }) => {\n * return await longRunningTask(signal)\n * }, {\n * retries: 10,\n * signal: controller.signal\n * })\n * // Returns undefined if aborted\n *\n * @example\n * // Pass arguments to callback\n * const result = await pRetry(\n * async (url, options) => {\n * return await fetch(url, options)\n * },\n * {\n * retries: 3,\n * args: ['https://api.example.com', { method: 'POST' }]\n * }\n * )\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function pRetry<T>(\n callbackFn: (...args: unknown[]) => Promise<T>,\n options?: number | RetryOptions | undefined,\n): Promise<T | undefined> {\n const {\n args,\n backoffFactor,\n baseDelayMs,\n jitter,\n maxDelayMs,\n onRetry,\n onRetryCancelOnFalse,\n onRetryRethrow,\n retries,\n signal,\n } = normalizeRetryOptions(options)\n if (signal?.aborted) {\n return undefined\n }\n if (retries === 0) {\n return await callbackFn(...(args || []), { signal })\n }\n\n const timers = getTimers()\n\n let attempts = retries as number\n let delay = baseDelayMs as number\n let error: unknown = UNDEFINED_TOKEN\n\n while (attempts-- >= 0) {\n // Check abort before attempt.\n if (signal?.aborted) {\n return undefined\n }\n\n try {\n // eslint-disable-next-line no-await-in-loop\n return await callbackFn(...(args || []), { signal })\n } catch (e) {\n if (error === UNDEFINED_TOKEN) {\n error = e\n }\n if (attempts < 0) {\n break\n }\n let waitTime = delay\n if (jitter) {\n // Add randomness: Pick a value between 0 and `delay`.\n waitTime += Math.floor(Math.random() * delay)\n }\n // Clamp wait time to max delay.\n waitTime = Math.min(waitTime, maxDelayMs as number)\n if (typeof onRetry === 'function') {\n try {\n const result = onRetry((retries as number) - attempts, e, waitTime)\n if (result === false && onRetryCancelOnFalse) {\n break\n }\n // If onRetry returns a number, use it as the custom delay.\n if (typeof result === 'number' && result >= 0) {\n waitTime = Math.min(result, maxDelayMs as number)\n }\n } catch (e) {\n if (onRetryRethrow) {\n throw e\n }\n }\n }\n\n try {\n // eslint-disable-next-line no-await-in-loop\n await timers.setTimeout(waitTime, undefined, { signal })\n } catch {\n // setTimeout was aborted.\n return undefined\n }\n\n // Check abort again after delay.\n if (signal?.aborted) {\n return undefined\n }\n\n // Exponentially increase the delay for the next attempt, capping at maxDelayMs.\n delay = Math.min(delay * (backoffFactor as number), maxDelayMs as number)\n }\n }\n if (error !== UNDEFINED_TOKEN) {\n throw error\n }\n return undefined\n}\n"],
|
|
5
|
-
"mappings": ";4ZAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,+BAAAE,EAAA,0BAAAC,EAAA,UAAAC,EAAA,eAAAC,EAAA,YAAAC,EAAA,iBAAAC,EAAA,WAAAC,EAAA,wBAAAC,IAAA,eAAAC,EAAAV,GAKA,IAAAW,EAAgC,2BAChCC,EAA+B,8BAE/BC,EAA2B,oBAE3B,MAAMC,KAAc,kBAAe,
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview Promise utilities including chunked iteration and timers.\n * Provides async control flow helpers and promise-based timing functions.\n */\n\nimport { UNDEFINED_TOKEN } from '#constants/core'\nimport { getAbortSignal } from '#constants/process'\n\nimport { arrayChunk } from './arrays'\n\nconst abortSignal = getAbortSignal()\n\n/**\n * Configuration options for retry behavior with exponential backoff.\n *\n * Controls how failed operations are retried, including timing, backoff strategy,\n * and callback hooks for observing or modifying retry behavior.\n */\nexport interface RetryOptions {\n /**\n * Arguments to pass to the callback function on each attempt.\n *\n * @default []\n */\n args?: unknown[] | undefined\n\n /**\n * Multiplier for exponential backoff (e.g., 2 doubles delay each retry).\n * Each retry waits `baseDelayMs * (backoffFactor ** attemptNumber)`.\n *\n * @default 2\n * @example\n * // With backoffFactor: 2, baseDelayMs: 100\n * // Retry 1: 100ms\n * // Retry 2: 200ms\n * // Retry 3: 400ms\n */\n backoffFactor?: number | undefined\n\n /**\n * Initial delay before the first retry (in milliseconds).\n * This is the base value for exponential backoff calculations.\n *\n * @default 200\n */\n baseDelayMs?: number | undefined\n\n // REMOVED: Deprecated `factor` option\n // Migration: Use `backoffFactor` instead\n\n /**\n * Whether to apply randomness to spread out retries and avoid thundering herd.\n * When `true`, adds random delay between 0 and current delay value.\n *\n * @default true\n * @example\n * // With jitter: true, delay: 100ms\n * // Actual wait: 100ms + random(0-100ms) = 100-200ms\n */\n jitter?: boolean | undefined\n\n /**\n * Upper limit for any backoff delay (in milliseconds).\n * Prevents exponential backoff from growing unbounded.\n *\n * @default 10000\n */\n maxDelayMs?: number | undefined\n\n // REMOVED: Deprecated `maxTimeout` option\n // Migration: Use `maxDelayMs` instead\n\n // REMOVED: Deprecated `minTimeout` option\n // Migration: Use `baseDelayMs` instead\n\n /**\n * Callback invoked on each retry attempt.\n * Can observe errors, customize delays, or cancel retries.\n *\n * @param attempt - The current attempt number (1-based: 1, 2, 3, ...)\n * @param error - The error that triggered this retry\n * @param delay - The calculated delay in milliseconds before next retry\n * @returns `false` to cancel retries (if `onRetryCancelOnFalse` is `true`),\n * a number to override the delay, or `undefined` to use calculated delay\n *\n * @example\n * // Log each retry\n * onRetry: (attempt, error, delay) => {\n * console.log(`Retry ${attempt} after ${delay}ms: ${error}`)\n * }\n *\n * @example\n * // Cancel retries for specific errors\n * onRetry: (attempt, error) => {\n * if (error instanceof ValidationError) return false\n * }\n *\n * @example\n * // Use custom delay\n * onRetry: (attempt) => attempt * 1000 // 1s, 2s, 3s, ...\n */\n onRetry?:\n | ((\n attempt: number,\n error: unknown,\n delay: number,\n ) => boolean | number | undefined)\n | undefined\n\n /**\n * Whether `onRetry` can cancel retries by returning `false`.\n * When `true`, returning `false` from `onRetry` stops retry attempts.\n *\n * @default false\n */\n onRetryCancelOnFalse?: boolean | undefined\n\n /**\n * Whether errors thrown by `onRetry` should propagate.\n * When `true`, exceptions in `onRetry` terminate the retry loop.\n * When `false`, exceptions in `onRetry` are silently caught.\n *\n * @default false\n */\n onRetryRethrow?: boolean | undefined\n\n /**\n * Number of retry attempts (0 = no retries, only initial attempt).\n * The callback is executed `retries + 1` times total (initial + retries).\n *\n * @default 0\n * @example\n * // retries: 0 -> 1 total attempt (no retries)\n * // retries: 3 -> 4 total attempts (1 initial + 3 retries)\n */\n retries?: number | undefined\n\n /**\n * AbortSignal to support cancellation of retry operations.\n * When aborted, immediately stops retrying and returns `undefined`.\n *\n * @default process abort signal\n * @example\n * const controller = new AbortController()\n * pRetry(fn, { signal: controller.signal })\n * // Later: controller.abort() to cancel\n */\n signal?: AbortSignal | undefined\n}\n\n/**\n * Configuration options for iteration functions with concurrency control.\n *\n * Controls how array operations are parallelized and retried.\n */\nexport interface IterationOptions {\n /**\n * The number of concurrent executions performed at one time.\n * Higher values increase parallelism but may overwhelm resources.\n *\n * @default 1\n * @example\n * // Process 5 items at a time\n * await pEach(items, processItem, { concurrency: 5 })\n */\n concurrency?: number | undefined\n\n /**\n * Retry configuration as a number (retry count) or full options object.\n * Applied to each individual item's callback execution.\n *\n * @default 0 (no retries)\n * @example\n * // Simple: retry each item up to 3 times\n * await pEach(items, fetchItem, { retries: 3 })\n *\n * @example\n * // Advanced: custom backoff for each item\n * await pEach(items, fetchItem, {\n * retries: {\n * retries: 3,\n * baseDelayMs: 1000,\n * backoffFactor: 2\n * }\n * })\n */\n retries?: number | RetryOptions | undefined\n\n /**\n * AbortSignal to support cancellation of the entire iteration.\n * When aborted, stops processing remaining items.\n *\n * @default process abort signal\n */\n signal?: AbortSignal | undefined\n}\n\nlet _timers: typeof import('node:timers/promises') | undefined\n/**\n * Get the timers/promises module.\n * Uses lazy loading to avoid Webpack bundling issues.\n *\n * @private\n * @returns The Node.js timers/promises module\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getTimers() {\n if (_timers === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _timers = /*@__PURE__*/ require('node:timers/promises')\n }\n return _timers as typeof import('node:timers/promises')\n}\n\n/**\n * Normalize options for iteration functions.\n *\n * Converts various option formats into a consistent structure with defaults applied.\n * Handles number shorthand for concurrency and ensures minimum values.\n *\n * @param options - Concurrency as number, or full options object, or undefined\n * @returns Normalized options with concurrency, retries, and signal\n *\n * @example\n * // Number shorthand for concurrency\n * normalizeIterationOptions(5)\n * // => { concurrency: 5, retries: {...}, signal: AbortSignal }\n *\n * @example\n * // Full options\n * normalizeIterationOptions({ concurrency: 3, retries: 2 })\n * // => { concurrency: 3, retries: {...}, signal: AbortSignal }\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function normalizeIterationOptions(\n options?: number | IterationOptions | undefined,\n): { concurrency: number; retries: RetryOptions; signal: AbortSignal } {\n // Handle number as concurrency shorthand\n const opts = typeof options === 'number' ? { concurrency: options } : options\n\n const {\n // The number of concurrent executions performed at one time.\n concurrency = 1,\n // Retries as a number or options object.\n retries,\n // AbortSignal used to support cancellation.\n signal = abortSignal,\n } = { __proto__: null, ...opts } as IterationOptions\n\n // Ensure concurrency is at least 1\n const normalizedConcurrency = Math.max(1, concurrency)\n const retryOpts = resolveRetryOptions(retries)\n return {\n __proto__: null,\n concurrency: normalizedConcurrency,\n retries: normalizeRetryOptions({ signal, ...retryOpts }),\n signal,\n } as { concurrency: number; retries: RetryOptions; signal: AbortSignal }\n}\n\n/**\n * Normalize options for retry functionality.\n *\n * Converts various retry option formats into a complete configuration with all defaults.\n * Handles legacy property names (`factor`, `minTimeout`, `maxTimeout`) and merges them\n * with modern equivalents.\n *\n * @param options - Retry count as number, or full options object, or undefined\n * @returns Normalized retry options with all properties set\n *\n * @example\n * // Number shorthand\n * normalizeRetryOptions(3)\n * // => { retries: 3, baseDelayMs: 200, backoffFactor: 2, ... }\n *\n * @example\n * // Full options with defaults filled in\n * normalizeRetryOptions({ retries: 5, baseDelayMs: 500 })\n * // => { retries: 5, baseDelayMs: 500, backoffFactor: 2, jitter: true, ... }\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function normalizeRetryOptions(\n options?: number | RetryOptions | undefined,\n): RetryOptions {\n const resolved = resolveRetryOptions(options)\n const {\n // Arguments to pass to the callback function.\n args = [],\n // Multiplier for exponential backoff (e.g., 2 doubles delay each retry).\n backoffFactor = 2,\n // Initial delay before the first retry (in milliseconds).\n baseDelayMs = 200,\n // Whether to apply randomness to spread out retries.\n jitter = true,\n // Upper limit for any backoff delay (in milliseconds).\n maxDelayMs = 10_000,\n // Optional callback invoked on each retry attempt:\n // (attempt: number, error: unknown, delay: number) => void\n onRetry,\n // Whether onRetry can cancel retries by returning `false`.\n onRetryCancelOnFalse = false,\n // Whether onRetry will rethrow errors.\n onRetryRethrow = false,\n // Number of retry attempts (0 = no retries, only initial attempt).\n retries = 0,\n // AbortSignal used to support cancellation.\n signal = abortSignal,\n } = resolved\n return {\n args,\n backoffFactor,\n baseDelayMs,\n jitter,\n maxDelayMs,\n onRetry,\n onRetryCancelOnFalse,\n onRetryRethrow,\n retries,\n signal,\n } as RetryOptions\n}\n\n/**\n * Resolve retry options from various input formats.\n *\n * Converts shorthand and partial options into a base configuration that can be\n * further normalized. This is an internal helper for option processing.\n *\n * @param options - Retry count as number, or partial options object, or undefined\n * @returns Resolved retry options with defaults for basic properties\n *\n * @example\n * resolveRetryOptions(3)\n * // => { retries: 3, minTimeout: 200, maxTimeout: 10000, factor: 2 }\n *\n * @example\n * resolveRetryOptions({ retries: 5, maxTimeout: 5000 })\n * // => { retries: 5, minTimeout: 200, maxTimeout: 5000, factor: 2 }\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function resolveRetryOptions(\n options?: number | RetryOptions | undefined,\n): RetryOptions {\n const defaults = {\n __proto__: null,\n retries: 0,\n baseDelayMs: 200,\n maxDelayMs: 10_000,\n backoffFactor: 2,\n }\n\n if (typeof options === 'number') {\n return { ...defaults, retries: options }\n }\n\n return options ? { ...defaults, ...options } : defaults\n}\n\n/**\n * Execute an async function for each array element with concurrency control.\n *\n * Processes array items in parallel batches (chunks) with configurable concurrency.\n * Each item's callback can be retried independently on failure. Similar to\n * `Promise.all(array.map(fn))` but with controlled parallelism.\n *\n * @template T - The type of array elements\n * @param array - The array to iterate over\n * @param callbackFn - Async function to execute for each item\n * @param options - Concurrency as number, or full iteration options, or undefined\n * @returns Promise that resolves when all items are processed\n *\n * @example\n * // Process items serially (concurrency: 1)\n * await pEach(urls, async (url) => {\n * await fetch(url)\n * })\n *\n * @example\n * // Process 5 items at a time\n * await pEach(files, async (file) => {\n * await processFile(file)\n * }, 5)\n *\n * @example\n * // With retries and cancellation\n * const controller = new AbortController()\n * await pEach(tasks, async (task) => {\n * await executeTask(task)\n * }, {\n * concurrency: 3,\n * retries: 2,\n * signal: controller.signal\n * })\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function pEach<T>(\n array: T[],\n callbackFn: (item: T) => Promise<unknown>,\n options?: number | IterationOptions | undefined,\n): Promise<void> {\n const iterOpts = normalizeIterationOptions(options)\n const { concurrency, retries, signal } = iterOpts\n\n // Process items with concurrency control.\n const chunks = arrayChunk(array, concurrency)\n for (const chunk of chunks) {\n if (signal?.aborted) {\n return\n }\n // Process each item in the chunk concurrently.\n // eslint-disable-next-line no-await-in-loop\n await Promise.all(\n chunk.map((item: T) =>\n pRetry((...args: unknown[]) => callbackFn(args[0] as T), {\n ...retries,\n args: [item],\n signal,\n }),\n ),\n )\n }\n}\n\n/**\n * Filter an array asynchronously with concurrency control.\n *\n * Tests each element with an async predicate function, processing items in parallel\n * batches. Returns a new array with only items that pass the test. Similar to\n * `array.filter()` but for async predicates with controlled concurrency.\n *\n * @template T - The type of array elements\n * @param array - The array to filter\n * @param callbackFn - Async predicate function returning true to keep item\n * @param options - Concurrency as number, or full iteration options, or undefined\n * @returns Promise resolving to filtered array\n *\n * @example\n * // Filter serially\n * const activeUsers = await pFilter(users, async (user) => {\n * return await isUserActive(user.id)\n * })\n *\n * @example\n * // Filter with concurrency\n * const validFiles = await pFilter(filePaths, async (path) => {\n * try {\n * await fs.access(path)\n * return true\n * } catch {\n * return false\n * }\n * }, 10)\n *\n * @example\n * // With retries for flaky checks\n * const reachable = await pFilter(endpoints, async (url) => {\n * const response = await fetch(url)\n * return response.ok\n * }, {\n * concurrency: 5,\n * retries: 2\n * })\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function pFilter<T>(\n array: T[],\n callbackFn: (item: T) => Promise<boolean>,\n options?: number | IterationOptions | undefined,\n): Promise<T[]> {\n const iterOpts = normalizeIterationOptions(options)\n return (\n await pFilterChunk(\n arrayChunk(array, iterOpts.concurrency),\n callbackFn,\n iterOpts.retries,\n )\n ).flat()\n}\n\n/**\n * Process array in chunks with an async callback.\n *\n * Divides the array into fixed-size chunks and processes each chunk sequentially\n * with the callback. Useful for batch operations like bulk database inserts or\n * API calls with payload size limits.\n *\n * @template T - The type of array elements\n * @param array - The array to process in chunks\n * @param callbackFn - Async function to execute for each chunk\n * @param options - Chunk size and retry options\n * @returns Promise that resolves when all chunks are processed\n *\n * @example\n * // Insert records in batches of 100\n * await pEachChunk(records, async (chunk) => {\n * await db.batchInsert(chunk)\n * }, { chunkSize: 100 })\n *\n * @example\n * // Upload files in batches with retries\n * await pEachChunk(files, async (batch) => {\n * await uploadBatch(batch)\n * }, {\n * chunkSize: 50,\n * retries: 3,\n * baseDelayMs: 1000\n * })\n *\n * @example\n * // Process with cancellation support\n * const controller = new AbortController()\n * await pEachChunk(items, async (chunk) => {\n * await processChunk(chunk)\n * }, {\n * chunkSize: 25,\n * signal: controller.signal\n * })\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function pEachChunk<T>(\n array: T[],\n callbackFn: (chunk: T[]) => Promise<unknown>,\n options?: (RetryOptions & { chunkSize?: number | undefined }) | undefined,\n): Promise<void> {\n const { chunkSize = 100, ...retryOpts } = options || {}\n const chunks = arrayChunk(array, chunkSize)\n const normalizedRetryOpts = normalizeRetryOptions(retryOpts)\n const { signal } = normalizedRetryOpts\n for (const chunk of chunks) {\n if (signal?.aborted) {\n return\n }\n // eslint-disable-next-line no-await-in-loop\n await pRetry((...args: unknown[]) => callbackFn(args[0] as T[]), {\n ...normalizedRetryOpts,\n args: [chunk],\n })\n }\n}\n\n/**\n * Filter chunked arrays with an async predicate.\n *\n * Internal helper for `pFilter`. Processes pre-chunked arrays, applying the\n * predicate to each element within each chunk with retry support.\n *\n * @template T - The type of array elements\n * @param chunks - Pre-chunked array (array of arrays)\n * @param callbackFn - Async predicate function\n * @param options - Retry count as number, or full retry options, or undefined\n * @returns Promise resolving to array of filtered chunks\n *\n * @example\n * const chunks = [[1, 2], [3, 4], [5, 6]]\n * const filtered = await pFilterChunk(chunks, async (n) => n % 2 === 0)\n * // => [[2], [4], [6]]\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function pFilterChunk<T>(\n chunks: T[][],\n callbackFn: (value: T) => Promise<boolean>,\n options?: number | RetryOptions | undefined,\n): Promise<T[][]> {\n const retryOpts = normalizeRetryOptions(options)\n const { signal } = retryOpts\n const { length } = chunks\n const filteredChunks = Array(length)\n for (let i = 0; i < length; i += 1) {\n // Process each chunk, filtering based on the callback function.\n if (signal?.aborted) {\n filteredChunks[i] = []\n } else {\n const chunk = chunks[i] as T[]\n // eslint-disable-next-line no-await-in-loop\n const predicateResults = await Promise.all(\n chunk.map(value =>\n pRetry((...args: unknown[]) => callbackFn(args[0] as T), {\n ...retryOpts,\n args: [value],\n }),\n ),\n )\n filteredChunks[i] = chunk.filter((_v, i) => predicateResults[i])\n }\n }\n return filteredChunks\n}\n\n/**\n * Retry an async function with exponential backoff.\n *\n * Attempts to execute a function multiple times with increasing delays between attempts.\n * Implements exponential backoff with optional jitter to prevent thundering herd problems.\n * Supports custom retry logic via `onRetry` callback.\n *\n * The delay calculation follows: `min(baseDelayMs * (backoffFactor ** attempt), maxDelayMs)`\n * With jitter: adds random value between 0 and calculated delay.\n *\n * @template T - The return type of the callback function\n * @param callbackFn - Async function to retry\n * @param options - Retry count as number, or full retry options, or undefined\n * @returns Promise resolving to callback result, or `undefined` if aborted\n *\n * @throws {Error} The last error if all retry attempts fail\n *\n * @example\n * // Simple retry: 3 attempts with default backoff\n * const data = await pRetry(async () => {\n * return await fetchData()\n * }, 3)\n *\n * @example\n * // Custom backoff strategy\n * const result = await pRetry(async () => {\n * return await unreliableOperation()\n * }, {\n * retries: 5,\n * baseDelayMs: 1000, // Start at 1 second\n * backoffFactor: 2, // Double each time\n * maxDelayMs: 30000, // Cap at 30 seconds\n * jitter: true // Add randomness\n * })\n * // Delays: ~1s, ~2s, ~4s, ~8s, ~16s (each \u00B1 random jitter)\n *\n * @example\n * // With custom retry logic\n * const data = await pRetry(async () => {\n * return await apiCall()\n * }, {\n * retries: 3,\n * onRetry: (attempt, error, delay) => {\n * console.log(`Attempt ${attempt} failed: ${error}`)\n * console.log(`Waiting ${delay}ms before retry...`)\n *\n * // Cancel retries for client errors (4xx)\n * if (error.statusCode >= 400 && error.statusCode < 500) {\n * return false\n * }\n *\n * // Use longer delay for rate limit errors\n * if (error.statusCode === 429) {\n * return 60000 // Wait 1 minute\n * }\n * },\n * onRetryCancelOnFalse: true\n * })\n *\n * @example\n * // With cancellation support\n * const controller = new AbortController()\n * setTimeout(() => controller.abort(), 5000) // Cancel after 5s\n *\n * const result = await pRetry(async ({ signal }) => {\n * return await longRunningTask(signal)\n * }, {\n * retries: 10,\n * signal: controller.signal\n * })\n * // Returns undefined if aborted\n *\n * @example\n * // Pass arguments to callback\n * const result = await pRetry(\n * async (url, options) => {\n * return await fetch(url, options)\n * },\n * {\n * retries: 3,\n * args: ['https://api.example.com', { method: 'POST' }]\n * }\n * )\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function pRetry<T>(\n callbackFn: (...args: unknown[]) => Promise<T>,\n options?: number | RetryOptions | undefined,\n): Promise<T | undefined> {\n const {\n args,\n backoffFactor,\n baseDelayMs,\n jitter,\n maxDelayMs,\n onRetry,\n onRetryCancelOnFalse,\n onRetryRethrow,\n retries,\n signal,\n } = normalizeRetryOptions(options)\n if (signal?.aborted) {\n return undefined\n }\n if (retries === 0) {\n return await callbackFn(...(args || []), { signal })\n }\n\n const timers = getTimers()\n\n let attempts = retries as number\n let delay = baseDelayMs as number\n let error: unknown = UNDEFINED_TOKEN\n\n while (attempts-- >= 0) {\n // Check abort before attempt.\n if (signal?.aborted) {\n return undefined\n }\n\n try {\n // eslint-disable-next-line no-await-in-loop\n return await callbackFn(...(args || []), { signal })\n } catch (e) {\n if (error === UNDEFINED_TOKEN) {\n error = e\n }\n if (attempts < 0) {\n break\n }\n let waitTime = delay\n if (jitter) {\n // Add randomness: Pick a value between 0 and `delay`.\n waitTime += Math.floor(Math.random() * delay)\n }\n // Clamp wait time to max delay.\n waitTime = Math.min(waitTime, maxDelayMs as number)\n if (typeof onRetry === 'function') {\n try {\n const result = onRetry((retries as number) - attempts, e, waitTime)\n if (result === false && onRetryCancelOnFalse) {\n break\n }\n // If onRetry returns a number, use it as the custom delay.\n if (typeof result === 'number' && result >= 0) {\n waitTime = Math.min(result, maxDelayMs as number)\n }\n } catch (e) {\n if (onRetryRethrow) {\n throw e\n }\n }\n }\n\n try {\n // eslint-disable-next-line no-await-in-loop\n await timers.setTimeout(waitTime, undefined, { signal })\n } catch {\n // setTimeout was aborted.\n return undefined\n }\n\n // Check abort again after delay.\n if (signal?.aborted) {\n return undefined\n }\n\n // Exponentially increase the delay for the next attempt, capping at maxDelayMs.\n delay = Math.min(delay * (backoffFactor as number), maxDelayMs as number)\n }\n }\n if (error !== UNDEFINED_TOKEN) {\n throw error\n }\n return undefined\n}\n"],
|
|
5
|
+
"mappings": ";4ZAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,+BAAAE,EAAA,0BAAAC,EAAA,UAAAC,EAAA,eAAAC,EAAA,YAAAC,EAAA,iBAAAC,EAAA,WAAAC,EAAA,wBAAAC,IAAA,eAAAC,EAAAV,GAKA,IAAAW,EAAgC,2BAChCC,EAA+B,8BAE/BC,EAA2B,oBAE3B,MAAMC,KAAc,kBAAe,EA2LnC,IAAIC,EASJ,SAASC,GAAY,CACnB,OAAID,IAAY,SAGdA,EAAwB,QAAQ,sBAAsB,GAEjDA,CACT,CAsBO,SAASb,EACde,EACqE,CAErE,MAAMC,EAAO,OAAOD,GAAY,SAAW,CAAE,YAAaA,CAAQ,EAAIA,EAEhE,CAEJ,YAAAE,EAAc,EAEd,QAAAC,EAEA,OAAAC,EAASP,CACX,EAAI,CAAE,UAAW,KAAM,GAAGI,CAAK,EAK/B,MAAO,CACL,UAAW,KACX,YAJ4B,KAAK,IAAI,EAAGC,CAAW,EAKnD,QAAShB,EAAsB,CAAE,OAAAkB,EAAQ,GAJzBZ,EAAoBW,CAAO,CAIW,CAAC,EACvD,OAAAC,CACF,CACF,CAuBO,SAASlB,EACdc,EACc,CACd,MAAMK,EAAWb,EAAoBQ,CAAO,EACtC,CAEJ,KAAAM,EAAO,CAAC,EAER,cAAAC,EAAgB,EAEhB,YAAAC,EAAc,IAEd,OAAAC,EAAS,GAET,WAAAC,EAAa,IAGb,QAAAC,EAEA,qBAAAC,EAAuB,GAEvB,eAAAC,EAAiB,GAEjB,QAAAV,EAAU,EAEV,OAAAC,EAASP,CACX,EAAIQ,EACJ,MAAO,CACL,KAAAC,EACA,cAAAC,EACA,YAAAC,EACA,OAAAC,EACA,WAAAC,EACA,QAAAC,EACA,qBAAAC,EACA,eAAAC,EACA,QAAAV,EACA,OAAAC,CACF,CACF,CAoBO,SAASZ,EACdQ,EACc,CACd,MAAMc,EAAW,CACf,UAAW,KACX,QAAS,EACT,YAAa,IACb,WAAY,IACZ,cAAe,CACjB,EAEA,OAAI,OAAOd,GAAY,SACd,CAAE,GAAGc,EAAU,QAASd,CAAQ,EAGlCA,EAAU,CAAE,GAAGc,EAAU,GAAGd,CAAQ,EAAIc,CACjD,CAuCA,eAAsB3B,EACpB4B,EACAC,EACAhB,EACe,CACf,MAAMiB,EAAWhC,EAA0Be,CAAO,EAC5C,CAAE,YAAAE,EAAa,QAAAC,EAAS,OAAAC,CAAO,EAAIa,EAGnCC,KAAS,cAAWH,EAAOb,CAAW,EAC5C,UAAWiB,KAASD,EAAQ,CAC1B,GAAId,GAAQ,QACV,OAIF,MAAM,QAAQ,IACZe,EAAM,IAAKC,GACT7B,EAAO,IAAIe,IAAoBU,EAAWV,EAAK,CAAC,CAAM,EAAG,CACvD,GAAGH,EACH,KAAM,CAACiB,CAAI,EACX,OAAAhB,CACF,CAAC,CACH,CACF,CACF,CACF,CA2CA,eAAsBf,EACpB0B,EACAC,EACAhB,EACc,CACd,MAAMiB,EAAWhC,EAA0Be,CAAO,EAClD,OACE,MAAMV,KACJ,cAAWyB,EAAOE,EAAS,WAAW,EACtCD,EACAC,EAAS,OACX,GACA,KAAK,CACT,CA0CA,eAAsB7B,EACpB2B,EACAC,EACAhB,EACe,CACf,KAAM,CAAE,UAAAqB,EAAY,IAAK,GAAGC,CAAU,EAAItB,GAAW,CAAC,EAChDkB,KAAS,cAAWH,EAAOM,CAAS,EACpCE,EAAsBrC,EAAsBoC,CAAS,EACrD,CAAE,OAAAlB,CAAO,EAAImB,EACnB,UAAWJ,KAASD,EAAQ,CAC1B,GAAId,GAAQ,QACV,OAGF,MAAMb,EAAO,IAAIe,IAAoBU,EAAWV,EAAK,CAAC,CAAQ,EAAG,CAC/D,GAAGiB,EACH,KAAM,CAACJ,CAAK,CACd,CAAC,CACH,CACF,CAoBA,eAAsB7B,EACpB4B,EACAF,EACAhB,EACgB,CAChB,MAAMsB,EAAYpC,EAAsBc,CAAO,EACzC,CAAE,OAAAI,CAAO,EAAIkB,EACb,CAAE,OAAAE,CAAO,EAAIN,EACbO,EAAiB,MAAMD,CAAM,EACnC,QAASE,EAAI,EAAGA,EAAIF,EAAQE,GAAK,EAE/B,GAAItB,GAAQ,QACVqB,EAAeC,CAAC,EAAI,CAAC,MAChB,CACL,MAAMP,EAAQD,EAAOQ,CAAC,EAEhBC,EAAmB,MAAM,QAAQ,IACrCR,EAAM,IAAIS,GACRrC,EAAO,IAAIe,IAAoBU,EAAWV,EAAK,CAAC,CAAM,EAAG,CACvD,GAAGgB,EACH,KAAM,CAACM,CAAK,CACd,CAAC,CACH,CACF,EACAH,EAAeC,CAAC,EAAIP,EAAM,OAAO,CAACU,EAAIH,IAAMC,EAAiBD,CAAC,CAAC,CACjE,CAEF,OAAOD,CACT,CAuFA,eAAsBlC,EACpByB,EACAhB,EACwB,CACxB,KAAM,CACJ,KAAAM,EACA,cAAAC,EACA,YAAAC,EACA,OAAAC,EACA,WAAAC,EACA,QAAAC,EACA,qBAAAC,EACA,eAAAC,EACA,QAAAV,EACA,OAAAC,CACF,EAAIlB,EAAsBc,CAAO,EACjC,GAAII,GAAQ,QACV,OAEF,GAAID,IAAY,EACd,OAAO,MAAMa,EAAW,GAAIV,GAAQ,CAAC,EAAI,CAAE,OAAAF,CAAO,CAAC,EAGrD,MAAM0B,EAAS/B,EAAU,EAEzB,IAAIgC,EAAW5B,EACX6B,EAAQxB,EACRyB,EAAiB,kBAErB,KAAOF,KAAc,GAAG,CAEtB,GAAI3B,GAAQ,QACV,OAGF,GAAI,CAEF,OAAO,MAAMY,EAAW,GAAIV,GAAQ,CAAC,EAAI,CAAE,OAAAF,CAAO,CAAC,CACrD,OAAS8B,EAAG,CAIV,GAHID,IAAU,oBACZA,EAAQC,GAENH,EAAW,EACb,MAEF,IAAII,EAAWH,EAOf,GANIvB,IAEF0B,GAAY,KAAK,MAAM,KAAK,OAAO,EAAIH,CAAK,GAG9CG,EAAW,KAAK,IAAIA,EAAUzB,CAAoB,EAC9C,OAAOC,GAAY,WACrB,GAAI,CACF,MAAMyB,EAASzB,EAASR,EAAqB4B,EAAUG,EAAGC,CAAQ,EAClE,GAAIC,IAAW,IAASxB,EACtB,MAGE,OAAOwB,GAAW,UAAYA,GAAU,IAC1CD,EAAW,KAAK,IAAIC,EAAQ1B,CAAoB,EAEpD,OAASwB,EAAG,CACV,GAAIrB,EACF,MAAMqB,CAEV,CAGF,GAAI,CAEF,MAAMJ,EAAO,WAAWK,EAAU,OAAW,CAAE,OAAA/B,CAAO,CAAC,CACzD,MAAQ,CAEN,MACF,CAGA,GAAIA,GAAQ,QACV,OAIF4B,EAAQ,KAAK,IAAIA,EAASzB,EAA0BG,CAAoB,CAC1E,CACF,CACA,GAAIuB,IAAU,kBACZ,MAAMA,CAGV",
|
|
6
6
|
"names": ["promises_exports", "__export", "normalizeIterationOptions", "normalizeRetryOptions", "pEach", "pEachChunk", "pFilter", "pFilterChunk", "pRetry", "resolveRetryOptions", "__toCommonJS", "import_core", "import_process", "import_arrays", "abortSignal", "_timers", "getTimers", "options", "opts", "concurrency", "retries", "signal", "resolved", "args", "backoffFactor", "baseDelayMs", "jitter", "maxDelayMs", "onRetry", "onRetryCancelOnFalse", "onRetryRethrow", "defaults", "array", "callbackFn", "iterOpts", "chunks", "chunk", "item", "chunkSize", "retryOpts", "normalizedRetryOpts", "length", "filteredChunks", "i", "predicateResults", "value", "_v", "timers", "attempts", "delay", "error", "e", "waitTime", "result"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Themed interactive prompts for terminal input.
|
|
3
|
+
* Provides type definitions and utilities for themed prompt interactions.
|
|
4
|
+
*
|
|
5
|
+
* Note: This module provides the theme-aware API structure.
|
|
6
|
+
* Actual prompt implementations should be added based on project needs.
|
|
7
|
+
*/
|
|
8
|
+
import type { Theme } from '../themes/types';
|
|
9
|
+
import type { ThemeName } from '../themes/themes';
|
|
10
|
+
/**
|
|
11
|
+
* Base options for all prompts.
|
|
12
|
+
*/
|
|
13
|
+
export type PromptBaseOptions = {
|
|
14
|
+
/** Prompt message to display */
|
|
15
|
+
message: string;
|
|
16
|
+
/** Theme to use (overrides global) */
|
|
17
|
+
theme?: Theme | ThemeName | undefined;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Options for text input prompts.
|
|
21
|
+
*/
|
|
22
|
+
export type InputPromptOptions = PromptBaseOptions & {
|
|
23
|
+
/** Default value */
|
|
24
|
+
default?: string | undefined;
|
|
25
|
+
/** Validation function */
|
|
26
|
+
validate?: ((value: string) => boolean | string) | undefined;
|
|
27
|
+
/** Placeholder text */
|
|
28
|
+
placeholder?: string | undefined;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Options for confirmation prompts.
|
|
32
|
+
*/
|
|
33
|
+
export type ConfirmPromptOptions = PromptBaseOptions & {
|
|
34
|
+
/** Default value */
|
|
35
|
+
default?: boolean | undefined;
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Choice option for select prompts.
|
|
39
|
+
*/
|
|
40
|
+
export type Choice<T = string> = {
|
|
41
|
+
/** Display label */
|
|
42
|
+
label: string;
|
|
43
|
+
/** Value to return */
|
|
44
|
+
value: T;
|
|
45
|
+
/** Optional description */
|
|
46
|
+
description?: string | undefined;
|
|
47
|
+
/** Whether this choice is disabled */
|
|
48
|
+
disabled?: boolean | undefined;
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Options for selection prompts.
|
|
52
|
+
*/
|
|
53
|
+
export type SelectPromptOptions<T = string> = PromptBaseOptions & {
|
|
54
|
+
/** Array of choices */
|
|
55
|
+
choices: Array<Choice<T>>;
|
|
56
|
+
/** Default selected value */
|
|
57
|
+
default?: T | undefined;
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* Text input prompt (themed).
|
|
61
|
+
*
|
|
62
|
+
* @param options - Input prompt configuration
|
|
63
|
+
* @returns Promise resolving to user input
|
|
64
|
+
*
|
|
65
|
+
* @example
|
|
66
|
+
* ```ts
|
|
67
|
+
* import { input } from '@socketsecurity/lib/prompts'
|
|
68
|
+
*
|
|
69
|
+
* const name = await input({
|
|
70
|
+
* message: 'Enter your name:',
|
|
71
|
+
* default: 'User',
|
|
72
|
+
* validate: (v) => v.length > 0 || 'Name required'
|
|
73
|
+
* })
|
|
74
|
+
* ```
|
|
75
|
+
*/
|
|
76
|
+
export declare function input(_options: InputPromptOptions): Promise<string>;
|
|
77
|
+
/**
|
|
78
|
+
* Confirmation prompt (themed).
|
|
79
|
+
*
|
|
80
|
+
* @param options - Confirm prompt configuration
|
|
81
|
+
* @returns Promise resolving to boolean
|
|
82
|
+
*
|
|
83
|
+
* @example
|
|
84
|
+
* ```ts
|
|
85
|
+
* import { confirm } from '@socketsecurity/lib/prompts'
|
|
86
|
+
*
|
|
87
|
+
* const proceed = await confirm({
|
|
88
|
+
* message: 'Continue with installation?',
|
|
89
|
+
* default: true
|
|
90
|
+
* })
|
|
91
|
+
* ```
|
|
92
|
+
*/
|
|
93
|
+
export declare function confirm(_options: ConfirmPromptOptions): Promise<boolean>;
|
|
94
|
+
/**
|
|
95
|
+
* Selection prompt (themed).
|
|
96
|
+
*
|
|
97
|
+
* @template T - Type of choice values
|
|
98
|
+
* @param options - Select prompt configuration
|
|
99
|
+
* @returns Promise resolving to selected value
|
|
100
|
+
*
|
|
101
|
+
* @example
|
|
102
|
+
* ```ts
|
|
103
|
+
* import { select } from '@socketsecurity/lib/prompts'
|
|
104
|
+
*
|
|
105
|
+
* const choice = await select({
|
|
106
|
+
* message: 'Select environment:',
|
|
107
|
+
* choices: [
|
|
108
|
+
* { label: 'Development', value: 'dev' },
|
|
109
|
+
* { label: 'Staging', value: 'staging' },
|
|
110
|
+
* { label: 'Production', value: 'prod' }
|
|
111
|
+
* ]
|
|
112
|
+
* })
|
|
113
|
+
* ```
|
|
114
|
+
*/
|
|
115
|
+
export declare function select<T = string>(_options: SelectPromptOptions<T>): Promise<T>;
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/* Socket Lib - Built with esbuild */
|
|
2
|
+
var r=Object.defineProperty;var p=Object.getOwnPropertyDescriptor;var s=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var a=(e,t)=>{for(var o in t)r(e,o,{get:t[o],enumerable:!0})},d=(e,t,o,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of s(t))!m.call(e,n)&&n!==o&&r(e,n,{get:()=>t[n],enumerable:!(i=p(t,n))||i.enumerable});return e};var l=e=>d(r({},"__esModule",{value:!0}),e);var y={};a(y,{confirm:()=>u,input:()=>f,select:()=>c});module.exports=l(y);async function f(e){throw new Error("input() not yet implemented - add prompt library integration")}async function u(e){throw new Error("confirm() not yet implemented - add prompt library integration")}async function c(e){throw new Error("select() not yet implemented - add prompt library integration")}0&&(module.exports={confirm,input,select});
|
|
3
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/prompts/index.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview Themed interactive prompts for terminal input.\n * Provides type definitions and utilities for themed prompt interactions.\n *\n * Note: This module provides the theme-aware API structure.\n * Actual prompt implementations should be added based on project needs.\n */\n\nimport type { Theme } from '../themes/types'\nimport type { ThemeName } from '../themes/themes'\n\n/**\n * Base options for all prompts.\n */\nexport type PromptBaseOptions = {\n /** Prompt message to display */\n message: string\n /** Theme to use (overrides global) */\n theme?: Theme | ThemeName | undefined\n}\n\n/**\n * Options for text input prompts.\n */\nexport type InputPromptOptions = PromptBaseOptions & {\n /** Default value */\n default?: string | undefined\n /** Validation function */\n validate?: ((value: string) => boolean | string) | undefined\n /** Placeholder text */\n placeholder?: string | undefined\n}\n\n/**\n * Options for confirmation prompts.\n */\nexport type ConfirmPromptOptions = PromptBaseOptions & {\n /** Default value */\n default?: boolean | undefined\n}\n\n/**\n * Choice option for select prompts.\n */\nexport type Choice<T = string> = {\n /** Display label */\n label: string\n /** Value to return */\n value: T\n /** Optional description */\n description?: string | undefined\n /** Whether this choice is disabled */\n disabled?: boolean | undefined\n}\n\n/**\n * Options for selection prompts.\n */\nexport type SelectPromptOptions<T = string> = PromptBaseOptions & {\n /** Array of choices */\n choices: Array<Choice<T>>\n /** Default selected value */\n default?: T | undefined\n}\n\n/**\n * Text input prompt (themed).\n *\n * @param options - Input prompt configuration\n * @returns Promise resolving to user input\n *\n * @example\n * ```ts\n * import { input } from '@socketsecurity/lib/prompts'\n *\n * const name = await input({\n * message: 'Enter your name:',\n * default: 'User',\n * validate: (v) => v.length > 0 || 'Name required'\n * })\n * ```\n */\nexport async function input(_options: InputPromptOptions): Promise<string> {\n // Note: Implement actual prompt logic\n // For now, return a mock implementation\n throw new Error(\n 'input() not yet implemented - add prompt library integration',\n )\n}\n\n/**\n * Confirmation prompt (themed).\n *\n * @param options - Confirm prompt configuration\n * @returns Promise resolving to boolean\n *\n * @example\n * ```ts\n * import { confirm } from '@socketsecurity/lib/prompts'\n *\n * const proceed = await confirm({\n * message: 'Continue with installation?',\n * default: true\n * })\n * ```\n */\nexport async function confirm(\n _options: ConfirmPromptOptions,\n): Promise<boolean> {\n // Note: Implement actual prompt logic\n throw new Error(\n 'confirm() not yet implemented - add prompt library integration',\n )\n}\n\n/**\n * Selection prompt (themed).\n *\n * @template T - Type of choice values\n * @param options - Select prompt configuration\n * @returns Promise resolving to selected value\n *\n * @example\n * ```ts\n * import { select } from '@socketsecurity/lib/prompts'\n *\n * const choice = await select({\n * message: 'Select environment:',\n * choices: [\n * { label: 'Development', value: 'dev' },\n * { label: 'Staging', value: 'staging' },\n * { label: 'Production', value: 'prod' }\n * ]\n * })\n * ```\n */\nexport async function select<T = string>(\n _options: SelectPromptOptions<T>,\n): Promise<T> {\n // Note: Implement actual prompt logic\n throw new Error(\n 'select() not yet implemented - add prompt library integration',\n )\n}\n"],
|
|
5
|
+
"mappings": ";4ZAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,EAAA,UAAAC,EAAA,WAAAC,IAAA,eAAAC,EAAAL,GAkFA,eAAsBG,EAAMG,EAA+C,CAGzE,MAAM,IAAI,MACR,8DACF,CACF,CAkBA,eAAsBJ,EACpBI,EACkB,CAElB,MAAM,IAAI,MACR,gEACF,CACF,CAuBA,eAAsBF,EACpBE,EACY,CAEZ,MAAM,IAAI,MACR,+DACF,CACF",
|
|
6
|
+
"names": ["prompts_exports", "__export", "confirm", "input", "select", "__toCommonJS", "_options"]
|
|
7
|
+
}
|
package/dist/spinner.d.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* @fileoverview CLI spinner utilities for long-running operations.
|
|
3
3
|
* Provides animated progress indicators with CI environment detection.
|
|
4
4
|
*/
|
|
5
|
-
import type { Writable } from '
|
|
5
|
+
import type { Writable } from 'stream';
|
|
6
6
|
import type { ShimmerColorGradient, ShimmerConfig, ShimmerDirection, ShimmerState } from './effects/text-shimmer';
|
|
7
7
|
/**
|
|
8
8
|
* Named color values supported by the spinner.
|
|
@@ -29,6 +29,13 @@ export type ColorValue = ColorName | ColorRgb;
|
|
|
29
29
|
* Maps to log symbols: success (✓), fail (✗), info (ℹ), warn (⚠).
|
|
30
30
|
*/
|
|
31
31
|
export type SymbolType = 'fail' | 'info' | 'success' | 'warn';
|
|
32
|
+
/**
|
|
33
|
+
* Convert a color value to RGB tuple format.
|
|
34
|
+
* Named colors are looked up in the `colorToRgb` map, RGB tuples are returned as-is.
|
|
35
|
+
* @param color - Color name or RGB tuple
|
|
36
|
+
* @returns RGB tuple with values 0-255
|
|
37
|
+
*/
|
|
38
|
+
export declare function toRgb(color: ColorValue): ColorRgb;
|
|
32
39
|
/**
|
|
33
40
|
* Progress tracking information for display in spinner.
|
|
34
41
|
* Used by `progress()` and `progressStep()` methods to show animated progress bars.
|
|
@@ -80,6 +87,8 @@ export type Spinner = {
|
|
|
80
87
|
spinner: SpinnerStyle;
|
|
81
88
|
/** Whether spinner is currently animating */
|
|
82
89
|
get isSpinning(): boolean;
|
|
90
|
+
/** Get current shimmer state (enabled/disabled and configuration) */
|
|
91
|
+
get shimmerState(): ShimmerInfo | undefined;
|
|
83
92
|
/** Clear the current line without stopping the spinner */
|
|
84
93
|
clear(): Spinner;
|
|
85
94
|
/** Show debug message without stopping (only if debug mode enabled) */
|
|
@@ -131,10 +140,14 @@ export type Spinner = {
|
|
|
131
140
|
progress(current: number, total: number, unit?: string | undefined): Spinner;
|
|
132
141
|
/** Increment progress by specified amount (default: 1) */
|
|
133
142
|
progressStep(amount?: number): Spinner;
|
|
134
|
-
/**
|
|
135
|
-
|
|
136
|
-
/**
|
|
137
|
-
|
|
143
|
+
/** Enable shimmer effect (restores saved config or uses defaults) */
|
|
144
|
+
enableShimmer(): Spinner;
|
|
145
|
+
/** Disable shimmer effect (preserves config for later re-enable) */
|
|
146
|
+
disableShimmer(): Spinner;
|
|
147
|
+
/** Set complete shimmer configuration */
|
|
148
|
+
setShimmer(config: ShimmerConfig): Spinner;
|
|
149
|
+
/** Update partial shimmer configuration */
|
|
150
|
+
updateShimmer(config: Partial<ShimmerConfig>): Spinner;
|
|
138
151
|
/** Show warning (⚠) without stopping the spinner */
|
|
139
152
|
warn(text?: string | undefined, ...extras: unknown[]): Spinner;
|
|
140
153
|
/** Show warning (⚠) and stop the spinner, auto-clearing the line */
|
|
@@ -286,24 +299,9 @@ export declare function Spinner(options?: SpinnerOptions | undefined): Spinner;
|
|
|
286
299
|
* ```
|
|
287
300
|
*/
|
|
288
301
|
export declare function getDefaultSpinner(): ReturnType<typeof Spinner>;
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
* @deprecated Use `getDefaultSpinner()` function instead for better tree-shaking and to avoid circular dependencies.
|
|
293
|
-
*
|
|
294
|
-
* @example
|
|
295
|
-
* ```ts
|
|
296
|
-
* // Old (deprecated):
|
|
297
|
-
* import { spinner } from '@socketsecurity/lib/spinner'
|
|
298
|
-
* spinner.start('Loading…')
|
|
299
|
-
*
|
|
300
|
-
* // New (recommended):
|
|
301
|
-
* import { getDefaultSpinner } from '@socketsecurity/lib/spinner'
|
|
302
|
-
* const spinner = getDefaultSpinner()
|
|
303
|
-
* spinner.start('Loading…')
|
|
304
|
-
* ```
|
|
305
|
-
*/
|
|
306
|
-
export declare const spinner: Spinner;
|
|
302
|
+
// REMOVED: Deprecated `spinner` export
|
|
303
|
+
// Migration: Use getDefaultSpinner() instead
|
|
304
|
+
// See: getDefaultSpinner() function above
|
|
307
305
|
/**
|
|
308
306
|
* Configuration options for `withSpinner()` helper.
|
|
309
307
|
* @template T - Return type of the async operation
|
|
@@ -318,6 +316,12 @@ export type WithSpinnerOptions<T> = {
|
|
|
318
316
|
* If not provided, operation runs without spinner.
|
|
319
317
|
*/
|
|
320
318
|
spinner?: Spinner | undefined;
|
|
319
|
+
/**
|
|
320
|
+
* Optional spinner options to apply during the operation.
|
|
321
|
+
* These options will be pushed when the operation starts and popped when it completes.
|
|
322
|
+
* Supports color and shimmer configuration.
|
|
323
|
+
*/
|
|
324
|
+
withOptions?: Partial<Pick<SpinnerOptions, 'color' | 'shimmer'>> | undefined;
|
|
321
325
|
};
|
|
322
326
|
/**
|
|
323
327
|
* Execute an async operation with spinner lifecycle management.
|
|
@@ -416,6 +420,12 @@ export type WithSpinnerSyncOptions<T> = {
|
|
|
416
420
|
* If not provided, operation runs without spinner.
|
|
417
421
|
*/
|
|
418
422
|
spinner?: Spinner | undefined;
|
|
423
|
+
/**
|
|
424
|
+
* Optional spinner options to apply during the operation.
|
|
425
|
+
* These options will be pushed when the operation starts and popped when it completes.
|
|
426
|
+
* Supports color and shimmer configuration.
|
|
427
|
+
*/
|
|
428
|
+
withOptions?: Partial<Pick<SpinnerOptions, 'color' | 'shimmer'>> | undefined;
|
|
419
429
|
};
|
|
420
430
|
/**
|
|
421
431
|
* Execute a synchronous operation with spinner lifecycle management.
|
package/dist/spinner.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/* Socket Lib - Built with esbuild */
|
|
2
|
-
var
|
|
2
|
+
var Y=Object.create;var x=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var M=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty;var F=(r,s)=>{for(var u in s)x(r,u,{get:s[u],enumerable:!0})},I=(r,s,u,t)=>{if(s&&typeof s=="object"||typeof s=="function")for(let i of L(s))!z.call(r,i)&&i!==u&&x(r,i,{get:()=>s[i],enumerable:!(t=G(s,i))||t.enumerable});return r};var E=(r,s,u)=>(u=r!=null?Y(M(r)):{},I(s||!r||!r.__esModule?x(u,"default",{value:r,enumerable:!0}):u,r)),N=r=>I(x({},"__esModule",{value:!0}),r);var Z={};F(Z,{Spinner:()=>V,ciSpinner:()=>W,getCliSpinners:()=>v,getDefaultSpinner:()=>U,toRgb:()=>S,withSpinner:()=>J,withSpinnerRestore:()=>Q,withSpinnerSync:()=>X});module.exports=N(Z);var O=require("#env/ci"),P=require("./effects/pulse-frames"),p=require("./effects/text-shimmer"),T=E(require("./external/@socketregistry/yocto-spinner")),B=require("./objects"),_=require("./strings"),D=require("./themes/context"),$=require("./themes/utils");const j={__proto__:null,black:[0,0,0],blue:[0,0,255],blueBright:[100,149,237],cyan:[0,255,255],cyanBright:[0,255,255],gray:[128,128,128],green:[0,128,0],greenBright:[0,255,0],magenta:[255,0,255],magentaBright:[255,105,180],red:[255,0,0],redBright:[255,69,0],white:[255,255,255],whiteBright:[255,255,255],yellow:[255,255,0],yellowBright:[255,255,153]};function C(r){return Array.isArray(r)}function S(r){return C(r)?r:j[r]}const W={frames:[""],interval:2147483647};function b(r){return{__proto__:null,configurable:!0,value:r,writable:!0}}function R(r){return typeof r=="string"?r.trimStart():""}function H(r){const{current:s,total:u,unit:t}=r,i=Math.round(s/u*100),e=K(i),n=t?`${s}/${u} ${t}`:`${s}/${u}`;return`${e} ${i}% (${n})`}function K(r,s=20){const u=Math.round(r/100*s),t=s-u,i="\u2588".repeat(u)+"\u2591".repeat(t);return require("./external/yoctocolors-cjs").cyan(i)}let g;function v(r){return g===void 0&&(g={__proto__:null,...(0,T.default)({}).constructor.spinners,socket:(0,P.generateSocketSpinnerFrames)()}),typeof r=="string"&&g?(0,B.hasOwn)(g,r)?g[r]:void 0:g}let f,A;function V(r){if(f===void 0){const t=(0,T.default)({}).constructor;f=class extends t{#s="";#o="";#e;#n;#r;constructor(e){const n={__proto__:null,...e},o=(0,D.getTheme)();let a=o.colors.primary;if(o.effects?.spinner?.color){const d=(0,$.resolveColor)(o.effects.spinner.color,o.colors);d==="inherit"||Array.isArray(d[0])?a=o.colors.primary:a=d}const m=n.color??a;if(C(m)&&(m.length!==3||!m.every(d=>typeof d=="number"&&d>=0&&d<=255)))throw new TypeError("RGB color must be an array of 3 numbers between 0 and 255");const h=S(m);let c;if(n.shimmer){let d,l,y=.3333333333333333;if(typeof n.shimmer=="string")d=n.shimmer;else{const w={__proto__:null,...n.shimmer};d=w.dir??p.DIR_LTR,l=w.color??p.COLOR_INHERIT,y=w.speed??1/3}c={__proto__:null,color:l===void 0?p.COLOR_INHERIT:l,currentDir:p.DIR_LTR,mode:d,speed:y,step:0}}super({signal:require("#constants/process").getAbortSignal(),...n,color:h,onRenderFrame:(d,l,y)=>{const q=(0,_.stringWidth)(d)===1?" ":" ";return d?`${y(d)}${q}${l}`:l},onFrameUpdate:c?()=>{this.#s&&(super.text=this.#d())}:void 0}),this.#n=c,this.#r=c}get color(){const e=super.color;return C(e)?e:S(e)}set color(e){super.color=C(e)?e:S(e)}get shimmerState(){if(this.#n)return{color:this.#n.color,currentDir:this.#n.currentDir,mode:this.#n.mode,speed:this.#n.speed,step:this.#n.step}}#i(e,n){let o,a=n.at(0);typeof a=="string"?o=n.slice(1):(o=n,a="");const m=this.isSpinning,h=R(a);super[e](h);const{incLogCallCountSymbol:c,lastWasBlankSymbol:d,logger:l}=require("./logger.js");return e==="stop"?m&&h&&(l[d]((0,_.isBlankString)(h)),l[c]()):(l[d](!1),l[c]()),o.length&&(l.log(...o),l[d](!1)),this}#d(){let e=this.#s;if(this.#e){const n=H(this.#e);e=e?`${e} ${n}`:n}if(e&&this.#n){let n;this.#n.color===p.COLOR_INHERIT?n=this.color:Array.isArray(this.#n.color[0])?n=this.#n.color:n=S(this.#n.color),e=(0,p.applyShimmer)(e,this.#n,{color:n,direction:this.#n.mode})}return this.#o&&e&&(e=this.#o+e),e}#u(e,n){let o=n.at(0),a;typeof o=="string"?a=n.slice(1):(a=n,o="");const{LOG_SYMBOLS:m,logger:h}=require("./logger.js");return h.error(`${m[e]} ${o}`,...a),this}#t(){super.text=this.#d()}debug(e,...n){const{isDebug:o}=require("./debug.js");return o()?this.#u("info",[e,...n]):this}debugAndStop(e,...n){const{isDebug:o}=require("./debug.js");return o()?this.#i("info",[e,...n]):this}dedent(e){if(e===0)this.#o="";else{const n=e??2,o=Math.max(0,this.#o.length-n);this.#o=this.#o.slice(0,o)}return this.#t(),this}done(e,...n){return this.#u("success",[e,...n])}doneAndStop(e,...n){return this.#i("success",[e,...n])}fail(e,...n){return this.#u("fail",[e,...n])}failAndStop(e,...n){return this.#i("error",[e,...n])}indent(e){if(e===0)this.#o="";else{const n=e??2;this.#o+=" ".repeat(n)}return this.#t(),this}info(e,...n){return this.#u("info",[e,...n])}infoAndStop(e,...n){return this.#i("info",[e,...n])}log(...e){const{logger:n}=require("./logger.js");return n.log(...e),this}logAndStop(e,...n){return this.#i("stop",[e,...n])}progress=(e,n,o)=>(this.#e={__proto__:null,current:e,total:n,...o?{unit:o}:{}},this.#t(),this);progressStep(e=1){if(this.#e){const n=this.#e.current+e;this.#e={__proto__:null,current:Math.max(0,Math.min(n,this.#e.total)),total:this.#e.total,...this.#e.unit?{unit:this.#e.unit}:{}},this.#t()}return this}start(...e){if(e.length){const n=e.at(0),o=R(n);o?this.#s=o:(this.#s="",super.text="")}return this.#t(),this.#i("start",[])}step(e,...n){const{logger:o}=require("./logger.js");return typeof e=="string"&&(o.error(""),o.error(e,...n)),this}substep(e,...n){if(typeof e=="string"){const{logger:o}=require("./logger.js");o.error(` ${e}`,...n)}return this}stop(...e){this.#s="",this.#e=void 0,this.#n&&(this.#n.currentDir=p.DIR_LTR,this.#n.step=0);const n=this.#i("stop",e);return super.text="",n}success(e,...n){return this.#u("success",[e,...n])}successAndStop(e,...n){return this.#i("success",[e,...n])}text(e){return arguments.length===0?this.#s:(this.#s=e??"",this.#t(),this)}warn(e,...n){return this.#u("warn",[e,...n])}warnAndStop(e,...n){return this.#i("warning",[e,...n])}enableShimmer(){return this.#r?this.#n={...this.#r}:(this.#n={color:p.COLOR_INHERIT,currentDir:p.DIR_LTR,mode:p.DIR_LTR,speed:1/3,step:0},this.#r=this.#n),this.#t(),this}disableShimmer(){return this.#n=void 0,this.#t(),this}setShimmer(e){return this.#n={color:e.color,currentDir:p.DIR_LTR,mode:e.dir,speed:e.speed,step:0},this.#r=this.#n,this.#t(),this}updateShimmer(e){const n={__proto__:null,...e};return this.#n?(this.#n={...this.#n,...n.color!==void 0?{color:n.color}:{},...n.dir!==void 0?{mode:n.dir}:{},...n.speed!==void 0?{speed:n.speed}:{}},this.#r=this.#n):this.#r?(this.#n={...this.#r,...n.color!==void 0?{color:n.color}:{},...n.dir!==void 0?{mode:n.dir}:{},...n.speed!==void 0?{speed:n.speed}:{}},this.#r=this.#n):(this.#n={color:n.color??p.COLOR_INHERIT,currentDir:p.DIR_LTR,mode:n.dir??p.DIR_LTR,speed:n.speed??1/3,step:0},this.#r=this.#n),this.#t(),this}},Object.defineProperties(f.prototype,{error:b(f.prototype.fail),errorAndStop:b(f.prototype.failAndStop),warning:b(f.prototype.warn),warningAndStop:b(f.prototype.warnAndStop)}),A=(0,O.getCI)()?W:v("socket")}return new f({spinner:A,...r})}let k;function U(){return k===void 0&&(k=V()),k}async function J(r){const{message:s,operation:u,spinner:t,withOptions:i}={__proto__:null,...r};if(!t)return await u();const e=i?.color!==void 0?t.color:void 0,n=i?.shimmer!==void 0?t.shimmerState:void 0;i?.color!==void 0&&(t.color=S(i.color)),i?.shimmer!==void 0&&(typeof i.shimmer=="string"?t.updateShimmer({dir:i.shimmer}):t.setShimmer(i.shimmer)),t.start(s);try{return await u()}finally{t.stop(),e!==void 0&&(t.color=e),i?.shimmer!==void 0&&(n?t.setShimmer({color:n.color,dir:n.mode,speed:n.speed}):t.disableShimmer())}}async function Q(r){const{operation:s,spinner:u,wasSpinning:t}={__proto__:null,...r};try{return await s()}finally{u&&t&&u.start()}}function X(r){const{message:s,operation:u,spinner:t,withOptions:i}={__proto__:null,...r};if(!t)return u();const e=i?.color!==void 0?t.color:void 0,n=i?.shimmer!==void 0?t.shimmerState:void 0;i?.color!==void 0&&(t.color=S(i.color)),i?.shimmer!==void 0&&(typeof i.shimmer=="string"?t.updateShimmer({dir:i.shimmer}):t.setShimmer(i.shimmer)),t.start(s);try{return u()}finally{t.stop(),e!==void 0&&(t.color=e),i?.shimmer!==void 0&&(n?t.setShimmer({color:n.color,dir:n.mode,speed:n.speed}):t.disableShimmer())}}0&&(module.exports={Spinner,ciSpinner,getCliSpinners,getDefaultSpinner,toRgb,withSpinner,withSpinnerRestore,withSpinnerSync});
|
|
3
3
|
//# sourceMappingURL=spinner.js.map
|