-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug.ts
More file actions
480 lines (440 loc) · 13.2 KB
/
debug.ts
File metadata and controls
480 lines (440 loc) · 13.2 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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
/**
* @fileoverview Debug logging utilities with lazy loading and environment-based control.
* Provides Socket CLI specific debug functionality and logging formatters.
*/
import { getDebug } from './env/debug'
import { getSocketDebug } from './env/socket'
import isUnicodeSupported from './external/@socketregistry/is-unicode-supported'
import debugJs from './external/debug'
import { getDefaultLogger } from './logger'
import { hasOwn } from './objects'
import { getDefaultSpinner } from './spinner'
import { applyLinePrefix } from './strings'
// IMPORTANT: Do not use destructuring here - use direct assignment instead.
// tsgo has a bug that incorrectly transpiles destructured exports, resulting in
// `exports.SomeName = void 0;` which causes runtime errors.
// See: https://github.com/SocketDev/socket-packageurl-js/issues/3
const ReflectApply = Reflect.apply
const logger = getDefaultLogger()
// Type definitions
interface DebugOptions {
namespaces?: string
spinner?: { isSpinning: boolean; stop(): void; start(): void }
[key: string]: unknown
}
type NamespacesOrOptions = string | DebugOptions
interface InspectOptions {
depth?: number | null
colors?: boolean
[key: string]: unknown
}
export type { DebugOptions, NamespacesOrOptions, InspectOptions }
const debugByNamespace = new Map()
let _util: typeof import('node:util') | undefined
let pointingTriangle: string | undefined
/**
* Custom log function for debug output.
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function customLog(...args: unknown[]) {
const util = getUtil()
/* c8 ignore start - External debug library inspection options */
const inspectOpts = debugJs.inspectOpts
? {
...debugJs.inspectOpts,
showHidden:
debugJs.inspectOpts.showHidden === null
? undefined
: debugJs.inspectOpts.showHidden,
depth:
debugJs.inspectOpts.depth === null ||
typeof debugJs.inspectOpts.depth === 'boolean'
? undefined
: debugJs.inspectOpts.depth,
}
: {}
/* c8 ignore stop */
ReflectApply(logger.info, logger, [
util.formatWithOptions(inspectOpts, ...args),
])
}
/**
* Extract options from namespaces parameter.
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function extractOptions(namespaces: NamespacesOrOptions): DebugOptions {
return namespaces !== null && typeof namespaces === 'object'
? ({ __proto__: null, ...namespaces } as DebugOptions)
: ({ __proto__: null, namespaces } as DebugOptions)
}
/**
* Extract caller information from the stack trace.
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function getCallerInfo(stackOffset: number = 3): string {
let name = ''
const captureStackTrace = Error.captureStackTrace
if (typeof captureStackTrace === 'function') {
const obj: { stack?: unknown } = {}
captureStackTrace(obj, getCallerInfo)
const stack = obj.stack
if (typeof stack === 'string') {
let lineCount = 0
let lineStart = 0
for (let i = 0, { length } = stack; i < length; i += 1) {
if (stack[i] === '\n') {
lineCount += 1
if (lineCount < stackOffset) {
// Store the start index of the next line.
lineStart = i + 1
} else {
// Extract the full line and trim it.
const line = stack.slice(lineStart, i).trimStart()
// Match the function name portion (e.g., "async runFix").
const match = /(?<=^at\s+).*?(?=\s+\(|$)/.exec(line)?.[0]
if (match) {
name = match
// Strip known V8 invocation prefixes to get the name.
.replace(/^(?:async|bound|get|new|set)\s+/, '')
if (name.startsWith('Object.')) {
// Strip leading 'Object.' if not an own property of Object.
const afterDot = name.slice(7 /*'Object.'.length*/)
if (!hasOwn(Object, afterDot)) {
name = afterDot
}
}
}
break
}
}
}
}
}
return name
}
/**
* Get or create a debug instance for a namespace.
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function getDebugJsInstance(namespace: string) {
let inst = debugByNamespace.get(namespace)
if (inst) {
return inst
}
if (
!getDebug() &&
getSocketDebug() &&
(namespace === 'error' || namespace === 'notice')
) {
/* c8 ignore next - External debug library call */
debugJs.enable(namespace)
}
/* c8 ignore next - External debug library call */
inst = debugJs(namespace)
inst.log = customLog
debugByNamespace.set(namespace, inst)
return inst
}
/**
* Lazily load the util module.
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function getUtil() {
if (_util === undefined) {
// Use non-'node:' prefixed require to avoid Webpack errors.
_util = /*@__PURE__*/ require('node:util')
}
return _util as typeof import('node:util')
}
/**
* Check if debug is enabled for given namespaces.
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function isEnabled(namespaces: string | undefined) {
// Check if debugging is enabled at all
if (!getSocketDebug()) {
return false
}
if (typeof namespaces !== 'string' || !namespaces || namespaces === '*') {
return true
}
// Namespace splitting logic is based the 'debug' package implementation:
// https://github.com/debug-js/debug/blob/4.4.1/src/common.js#L169-L173.
const split = namespaces
.trim()
.replace(/\s+/g, ',')
.split(',')
.filter(Boolean)
const names = []
const skips = []
for (const ns of split) {
if (ns.startsWith('-')) {
skips.push(ns.slice(1))
} else {
names.push(ns)
}
}
if (names.length && !names.some(ns => getDebugJsInstance(ns).enabled)) {
return false
}
return skips.every(ns => !getDebugJsInstance(ns).enabled)
}
/**
* Debug output with caller info (wrapper for debugNs with default namespace).
*/
export function debug(...args: unknown[]): void {
debugNs('*', ...args)
}
/**
* Cache debug function with caller info.
*
* @example
* ```typescript
* debugCache('hit', 'socket-sdk:scans:abc123')
* debugCache('miss', 'socket-sdk:scans:xyz', { ttl: 60000 })
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function debugCache(
operation: string,
key: string,
meta?: unknown | undefined,
): void {
if (!getSocketDebug()) {
return
}
// Get caller info with stack offset of 3 (caller -> debugCache -> getCallerInfo).
const callerName = getCallerInfo(3) || 'cache'
if (pointingTriangle === undefined) {
const supported = isUnicodeSupported()
pointingTriangle = supported ? '▸' : '>'
}
const prefix = `[CACHE] ${callerName} ${pointingTriangle} ${operation}: ${key}`
const args = meta !== undefined ? [prefix, meta] : [prefix]
console.log(...args)
}
/**
* Debug output for cache operations with caller info.
* First argument is the operation type (hit/miss/set/clear).
* Second argument is the cache key or message.
* Optional third argument is metadata object.
*/
export function debugCacheNs(
namespacesOrOpts: NamespacesOrOptions,
operation: string,
key: string,
meta?: unknown | undefined,
) {
const options = extractOptions(namespacesOrOpts)
const { namespaces } = options
if (!isEnabled(namespaces as string)) {
return
}
// Get caller info with stack offset of 4 (caller -> debugCacheNs -> getCallerInfo).
const callerName = getCallerInfo(4) || 'cache'
if (pointingTriangle === undefined) {
const supported = isUnicodeSupported()
pointingTriangle = supported ? '▸' : '>'
}
const prefix = `[CACHE] ${callerName} ${pointingTriangle} ${operation}: ${key}`
const logArgs = meta !== undefined ? [prefix, meta] : [prefix]
const spinnerInstance = options.spinner || getDefaultSpinner()
const wasSpinning = spinnerInstance?.isSpinning
spinnerInstance?.stop()
ReflectApply(logger.info, logger, logArgs)
if (wasSpinning) {
spinnerInstance?.start()
}
}
/**
* Debug output for object inspection (wrapper for debugDirNs with default namespace).
*/
export function debugDir(
obj: unknown,
inspectOpts?: InspectOptions | undefined,
): void {
debugDirNs('*', obj, inspectOpts)
}
/**
* Debug output for object inspection with caller info.
*/
export function debugDirNs(
namespacesOrOpts: NamespacesOrOptions,
obj: unknown,
inspectOpts?: InspectOptions | undefined,
) {
const options = extractOptions(namespacesOrOpts)
const { namespaces } = options
if (!isEnabled(namespaces as string)) {
return
}
// Get caller info with stack offset of 4 (caller -> debugDirNs -> getCallerInfo).
const callerName = getCallerInfo(4) || 'anonymous'
if (pointingTriangle === undefined) {
const supported = isUnicodeSupported()
pointingTriangle = supported ? '▸' : '>'
}
let opts: InspectOptions | undefined = inspectOpts
if (opts === undefined) {
/* c8 ignore next - External debug library inspection options */
const debugOpts = debugJs.inspectOpts
if (debugOpts) {
opts = {
...debugOpts,
showHidden:
debugOpts.showHidden === null ? undefined : debugOpts.showHidden,
depth:
debugOpts.depth === null || typeof debugOpts.depth === 'boolean'
? null
: debugOpts.depth,
} as InspectOptions
}
}
const spinnerInstance = options.spinner || getDefaultSpinner()
const wasSpinning = spinnerInstance?.isSpinning
spinnerInstance?.stop()
logger.info(`[DEBUG] ${callerName} ${pointingTriangle} object inspection:`)
logger.dir(obj, inspectOpts)
if (wasSpinning) {
spinnerInstance?.start()
}
}
/**
* Debug logging function (wrapper for debugLogNs with default namespace).
*/
export function debugLog(...args: unknown[]): void {
debugLogNs('*', ...args)
}
/**
* Debug logging function with caller info.
*/
export function debugLogNs(
namespacesOrOpts: NamespacesOrOptions,
...args: unknown[]
) {
const options = extractOptions(namespacesOrOpts)
const { namespaces } = options
if (!isEnabled(namespaces as string)) {
return
}
// Get caller info with stack offset of 4 (caller -> debugLogNs -> getCallerInfo).
const callerName = getCallerInfo(4) || 'anonymous'
if (pointingTriangle === undefined) {
const supported = isUnicodeSupported()
pointingTriangle = supported ? '▸' : '>'
}
const text = args.at(0)
const logArgs =
typeof text === 'string'
? [
applyLinePrefix(
`${callerName ? `${callerName} ${pointingTriangle} ` : ''}${text}`,
{ prefix: '[DEBUG] ' },
),
...args.slice(1),
]
: [`[DEBUG] ${callerName} ${pointingTriangle}`, ...args]
const spinnerInstance = options.spinner || getDefaultSpinner()
const wasSpinning = spinnerInstance?.isSpinning
spinnerInstance?.stop()
ReflectApply(logger.info, logger, logArgs)
if (wasSpinning) {
spinnerInstance?.start()
}
}
/**
* Create a Node.js util.debuglog compatible function.
* Returns a function that conditionally writes debug messages to stderr.
*/
/*@__NO_SIDE_EFFECTS__*/
export function debuglog(section: string) {
const util = getUtil()
return util.debuglog(section)
}
/**
* Debug output with caller info.
*/
export function debugNs(
namespacesOrOpts: NamespacesOrOptions,
...args: unknown[]
) {
const options = extractOptions(namespacesOrOpts)
const { namespaces } = options
if (!isEnabled(namespaces as string)) {
return
}
// Get caller info with stack offset of 4 (caller -> debugNs -> getCallerInfo).
const name = getCallerInfo(4) || 'anonymous'
if (pointingTriangle === undefined) {
const supported = isUnicodeSupported()
pointingTriangle = supported ? '▸' : '>'
}
const text = args.at(0)
const logArgs =
typeof text === 'string'
? [
applyLinePrefix(
`${name ? `${name} ${pointingTriangle} ` : ''}${text}`,
{ prefix: '[DEBUG] ' },
),
...args.slice(1),
]
: args
const spinnerInstance = options.spinner || getDefaultSpinner()
const wasSpinning = spinnerInstance?.isSpinning
spinnerInstance?.stop()
ReflectApply(logger.info, logger, logArgs)
if (wasSpinning) {
spinnerInstance?.start()
}
}
/**
* Create timing functions for measuring code execution time.
* Returns an object with start() and end() methods, plus a callable function.
*/
/*@__NO_SIDE_EFFECTS__*/
export function debugtime(label: string) {
const util = getUtil()
// Node.js util doesn't have debugtime - create a custom implementation
let startTime: number | undefined
const impl = () => {
if (startTime === undefined) {
startTime = Date.now()
} else {
const duration = Date.now() - startTime
util.debuglog('time')(`${label}: ${duration}ms`)
startTime = undefined
}
}
impl.start = () => {
startTime = Date.now()
}
impl.end = () => {
if (startTime !== undefined) {
const duration = Date.now() - startTime
util.debuglog('time')(`${label}: ${duration}ms`)
startTime = undefined
}
}
return impl
}
/**
* Check if debug mode is enabled.
*/
/*@__NO_SIDE_EFFECTS__*/
export function isDebug(): boolean {
return !!getSocketDebug()
}
/**
* Check if debug mode is enabled.
*/
/*@__NO_SIDE_EFFECTS__*/
export function isDebugNs(namespaces: string | undefined): boolean {
return !!getSocketDebug() && isEnabled(namespaces)
}