-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwith.ts
More file actions
292 lines (274 loc) · 8.64 KB
/
Copy pathwith.ts
File metadata and controls
292 lines (274 loc) · 8.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/**
* @file Lifecycle wrappers around `Spinner` — `withSpinner` (async, push-pop
* options + auto-stop), `withSpinnerRestore` (conditionally restart a
* previously-spinning instance), and `withSpinnerSync` (sync sibling of
* `withSpinner`). Each wrapper guarantees `spinner.stop()` runs via
* `try/finally` even when the inner operation throws, then re-throws the
* original error so callers see the same failure surface as a plain `await`.
*/
import process from 'node:process'
import { toRgb } from '../colors/convert'
import type { ColorInherit, ColorValue } from '../colors/types'
import type { Palette, RGB } from '../effects/shimmer'
import type {
WithSpinnerOptions,
WithSpinnerRestoreOptions,
WithSpinnerSyncOptions,
} from './types'
/**
* Narrow a saved shimmer color (`'inherit' | ColorName | ColorRgb | Palette`)
* down to the `RGB | Palette | undefined` shape `ShimmerConfig.color` accepts.
* `'inherit'` becomes `undefined` so `setShimmer` falls back to its inherit
* default; named colors resolve to an RGB tuple; tuples and palettes pass
* through unchanged.
*/
export function toShimmerColor(
color: ColorInherit | ColorValue | Palette,
): RGB | Palette | undefined {
if (color === 'inherit') {
return undefined
}
if (typeof color === 'string') {
return toRgb(color)
}
// An RGB tuple has numeric channels; a palette is an array of tuples.
if (typeof color[0] === 'number') {
return color as RGB
}
return color as Palette
}
/**
* Execute an async operation with spinner lifecycle management. Ensures
* `spinner.stop()` is always called via try/finally, even if the operation
* throws. Provides safe cleanup and consistent spinner behavior.
*
* @example
* ;```ts
* import { Spinner } from '@socketsecurity/lib/spinner/spinner'
* import { withSpinner } from '@socketsecurity/lib/spinner/with'
*
* const spinner = Spinner()
*
* // With spinner instance
* const result = await withSpinner({
* message: 'Processing…',
* operation: async () => {
* return await processData()
* },
* spinner,
* })
*
* // Without spinner instance (no-op, just runs operation)
* const result = await withSpinner({
* message: 'Processing…',
* operation: async () => {
* return await processData()
* },
* })
* ```
*
* @template T - Return type of the operation.
*
* @param options - Configuration object.
* @param options.message - Message to display while spinner is running.
* @param options.operation - Async function to execute.
* @param options.spinner - Optional spinner instance (if not provided, no
* spinner is used)
*
* @returns Result of the operation
*
* @throws Re-throws any error from operation after stopping spinner
*/
export async function withSpinner<T>(
options: WithSpinnerOptions<T>,
): Promise<T> {
const { message, operation, spinner, withOptions } = {
__proto__: null,
...options,
} as WithSpinnerOptions<T>
if (!spinner) {
return await operation()
}
// Save current options if we're going to change them
const savedColor =
withOptions?.color !== undefined ? spinner.color : undefined
const savedShimmerState =
withOptions?.shimmer !== undefined ? spinner.shimmerState : undefined
// Apply temporary options
if (withOptions?.color !== undefined) {
spinner.color = toRgb(withOptions.color)
}
if (withOptions?.shimmer !== undefined) {
if (typeof withOptions.shimmer === 'string') {
spinner.updateShimmer({ dir: withOptions.shimmer })
} else {
spinner.setShimmer(withOptions.shimmer)
}
}
spinner.start(message)
try {
return await operation()
} finally {
const wasSpinning = spinner.isSpinning
spinner.stop()
// Clear any remaining spinner artifacts that yocto-spinner's clear() misses.
// Despite yocto-spinner calling clear(), ANSI-colored spinner frames can sometimes
// leave visual artifacts on the line. A final explicit clear ensures clean output.
// Only clear if spinner was actually running (which means it was already interactive).
// Each restore branch fires only when caller seeded the
// corresponding option; tests cover paths individually.
/* c8 ignore start */
if (wasSpinning) {
process.stderr.write('\r\x1B[2K') // socket-lint: allow process-stdio
}
if (savedColor !== undefined) {
spinner.color = savedColor
}
if (withOptions?.shimmer !== undefined) {
if (savedShimmerState) {
spinner.setShimmer({
color: toShimmerColor(savedShimmerState.color),
dir: savedShimmerState.direction,
speed: savedShimmerState.speed,
})
} else {
spinner.disableShimmer()
}
}
/* c8 ignore stop */
}
}
/**
* Execute an async operation with conditional spinner restart. Useful when you
* need to temporarily stop a spinner for an operation, then restore it to its
* previous state (if it was spinning).
*
* @example
* ;```ts
* import { getDefaultSpinner } from '@socketsecurity/lib/spinner/default'
* import { withSpinnerRestore } from '@socketsecurity/lib/spinner/with'
*
* const spinner = getDefaultSpinner()
* const wasSpinning = spinner.isSpinning
* spinner.stop()
*
* const result = await withSpinnerRestore({
* operation: async () => {
* // Do work without spinner
* return await someOperation()
* },
* spinner,
* wasSpinning,
* })
* // Spinner is automatically restarted if wasSpinning was true
* ```
*
* @template T - Return type of the operation.
*
* @param options - Configuration object.
* @param options.operation - Async function to execute.
* @param options.spinner - Optional spinner instance to manage.
* @param options.wasSpinning - Whether spinner was spinning before the
* operation.
*
* @returns Result of the operation
*
* @throws Re-throws any error from operation after restoring spinner state
*/
export async function withSpinnerRestore<T>(
options: WithSpinnerRestoreOptions<T>,
): Promise<T> {
const { operation, spinner, wasSpinning } = {
__proto__: null,
...options,
} as WithSpinnerRestoreOptions<T>
try {
return await operation()
} finally {
if (spinner && wasSpinning) {
spinner.start()
}
}
}
/**
* Execute a synchronous operation with spinner lifecycle management. Ensures
* `spinner.stop()` is always called via try/finally, even if the operation
* throws. Provides safe cleanup and consistent spinner behavior for sync
* operations.
*
* @example
* ;```ts
* import { Spinner } from '@socketsecurity/lib/spinner/spinner'
* import { withSpinnerSync } from '@socketsecurity/lib/spinner/with'
*
* const spinner = Spinner()
*
* const result = withSpinnerSync({
* message: 'Processing…',
* operation: () => {
* return processDataSync()
* },
* spinner,
* })
* ```
*
* @template T - Return type of the operation.
*
* @param options - Configuration object.
* @param options.message - Message to display while spinner is running.
* @param options.operation - Synchronous function to execute.
* @param options.spinner - Optional spinner instance (if not provided, no
* spinner is used)
*
* @returns Result of the operation
*
* @throws Re-throws any error from operation after stopping spinner
*/
export function withSpinnerSync<T>(options: WithSpinnerSyncOptions<T>): T {
const { message, operation, spinner, withOptions } = {
__proto__: null,
...options,
} as WithSpinnerSyncOptions<T>
if (!spinner) {
return operation()
}
// Save current options if we're going to change them
const savedColor =
withOptions?.color !== undefined ? spinner.color : undefined
const savedShimmerState =
withOptions?.shimmer !== undefined ? spinner.shimmerState : undefined
// Apply temporary options
if (withOptions?.color !== undefined) {
spinner.color = toRgb(withOptions.color)
}
if (withOptions?.shimmer !== undefined) {
if (typeof withOptions.shimmer === 'string') {
spinner.updateShimmer({ dir: withOptions.shimmer })
} else {
spinner.setShimmer(withOptions.shimmer)
}
}
spinner.start(message)
try {
return operation()
} finally {
spinner.stop()
// Restore previous options
/* c8 ignore start */
if (savedColor !== undefined) {
spinner.color = savedColor
}
if (withOptions?.shimmer !== undefined) {
if (savedShimmerState) {
spinner.setShimmer({
color: toShimmerColor(savedShimmerState.color),
dir: savedShimmerState.direction,
speed: savedShimmerState.speed,
})
} else {
spinner.disableShimmer()
}
}
/* c8 ignore stop */
}
}