Repository navigation
Expand file tree
/
Copy pathindex.d.ts
More file actions
629 lines (577 loc) · 18.8 KB
/
Copy pathindex.d.ts
File metadata and controls
629 lines (577 loc) · 18.8 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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
/**
* Scribbles - A log and tracing lib for Node
* TypeScript definitions
*/
// =============================================================================
// Configuration Types
// =============================================================================
/**
* Pretty printing options for value serialization
*/
interface PrettyOptions {
/** Preferred indentation string (default: " ") */
indent?: string;
/** Will inline values up to this length (default: terminal width in dev, Infinity in prod) */
inlineCharacterLimit?: number;
/** Set to true to get single-quoted strings (default: false) */
singleQuotes?: boolean;
/** How many nested steps in the object/array tree to walk */
depth?: number;
/** Filter function to include/exclude properties */
filter?: (obj: object, key: string) => boolean;
/** Transform function to modify stringified property values */
transform?: (obj: object, key: string, value: string) => string;
/** Use ASCII brackets (⎡⎜⎣) for group indentation (default: false) */
groupBrackets?: boolean;
/**
* When true with `colors`, emit ANSI syntax roles for the `{value}` column
* (keys, brackets, type names, primitives, etc.). `colorScheme[level]` is
* applied only to the plain template prefix before `{value}` so inner token
* colors are not wrapped by a single outer SGR. Default: true (set false for
* whole-line level color only, no per-token roles).
*/
syntaxHighlight?: boolean;
/**
* Overrides for syntax roles (shallow-merged over defaults; base map switches
* with `colorblindMode`). Role keys include: bracket, comma, colon, typeName,
* key, string, number, boolean, nullish, symbol, regex, function, arrayIndex,
* circular, truncation, identifierLabel, disambiguationPrefix, fallback, transformOutput.
* Values are color names accepted by `colors.js` / {@link ScribblesConfig.colorScheme} keys.
*/
syntaxColorScheme?: { [role: string]: string };
/**
* When false with colors + syntax highlight, use a single `colorScheme[level]`
* wash on the plain prefix instead of semantic `38;2` prose. Default: true.
*/
prosePrefix?: boolean;
/**
* Anchor `#RRGGBB` for prose dimming; literals and tokens interpolate toward black
* from this color by semantic tier. Default: `#DDDDDD`.
*/
proseColor?: string;
/** Multiplier for all default and `proseFieldDarken` factors. Default: 1. */
proseImportanceScale?: number;
/** Per-token darken overrides (0–1 scale before `proseImportanceScale`). */
proseFieldDarken?: { [token: string]: number };
/** Subtract from `{message}` darken when non-empty (lift toward anchor). Default: 0. */
proseMessageLift?: number;
/** Extra darken added to wrapper delimiters vs inner reference. Default: 0.05. */
proseWrapperExtraDarken?: number;
/** Darken for empty wrapper/message regions. Default: 0.75. */
proseEmptyRegionDarken?: number;
/** Darken for lines after the first (e.g. stack). Default: 0.65. */
proseContinuationDarken?: number;
}
/**
* Git environment variable mapping
*/
interface GitEnvConfig {
/** Environment variable name for git short hash */
hash?: string;
/** Environment variable name for git repository name */
repo?: string;
/** Environment variable name for git branch */
branch?: string;
}
/**
* StdOut configuration - can be a function, object with level methods, or null to disable
*/
type StdOutConfig =
| ((msg: string) => void)
| { [level: string]: (msg: string) => void }
| { log: (msg: string) => void }
| null;
/**
* Which destination failed, as reported to `onSinkError`.
*/
type SinkName = 'stdOut' | 'dataOut';
/**
* Configuration options for scribbles
*/
interface ScribblesConfig {
/** Environment mode (default: process.env.NODE_ENV || 'dev') */
mode?: string;
/** Log format template string with placeholders */
format?: string;
/** Time format using Moment.js format tokens (default: "YYYY-MM-DDTHH:mm:ss.SSS") */
time?: string;
/** Array of log levels from highest to lowest priority */
levels?: string[];
/** Minimum log level to output (default: "debug"). Must be one of `levels`, otherwise `config()` throws; a bad `LOG_LEVEL` environment variable makes `require` throw. */
logLevel?: string;
/** Log level that triggers trace flushing */
traceTrigger?: string;
/** Output destination for formatted log strings */
stdOut?: StdOutConfig;
/** Callback to receive structured log data objects */
dataOut?: (data: LogEntry) => void;
/**
* Called when `stdOut` (or the formatting of its line) or `dataOut` throws. The error never
* reaches the code that logged. `sink` says which destination failed and `entry` is the log
* entry that was not delivered. If the hook throws, that is ignored. Without a hook the first
* failure of each destination function is written once to `console.error`.
*/
onSinkError?: (error: unknown, sink: SinkName, entry: LogEntry) => void;
/** Custom stringify function for values */
stringify?: (value: unknown, pretty: PrettyOptions) => string;
/** Headers to forward in trace context (string, RegExp, array, or null to disable) */
headers?: string | RegExp | (string | RegExp)[] | null;
/** Header name mapping from input to output */
headersMapping?: { [outputKey: string]: string | string[] };
/** Environment variable mapping for git info */
gitEnv?: GitEnvConfig;
/** Pretty printing options */
pretty?: PrettyOptions;
/** Global object to attach log functions to ("console", "global", or custom object) */
global?: "console" | "global" | { [key: string]: unknown };
/** Enable colored log output (default: true in dev mode) */
colors?: boolean;
/** Use colorblind-friendly color scheme (default: false) */
colorblindMode?: boolean;
}
// =============================================================================
// Log Entry Types
// =============================================================================
/**
* Git information in log entry
*/
interface GitInfo {
repo: string;
branch: string;
hash: string;
}
/**
* Trace context information
*/
interface TraceInfo {
traceId?: string;
/** Caller's span id, when `traceId` was passed as a full W3C traceparent */
parentId?: string;
spanId?: string;
span64?: string;
spanLabel?: string;
tracestate?: Array<{ key: string; value: string }>;
}
/**
* Log entry metadata
*/
interface LogInfo {
time: Date;
mode: string;
hostname: string;
instance: string;
logLevel: string;
}
/**
* Source context information
*/
interface ContextInfo {
fileName: string;
lineNumber: number;
method?: string;
/** Current group nesting level (0 when not in a group) */
groupLevel?: number;
/** Joined labels of all parent groups */
groupLabel?: string;
}
/**
* Log input data
*/
interface InputInfo {
message?: string;
originalMessage?: string;
value?: unknown;
stackTrace?: string[];
from?: string[];
}
/**
* CPU status information
*/
interface CpuStatus {
cores: number;
model: string;
speed: number;
percUsed: number;
percFree: number;
}
/**
* System status information
*/
interface SysStatus {
startedAt: Date;
arch: string;
platform: string;
totalMem: number;
freeMem: number;
usedMem: number;
}
/**
* Process status information
*/
interface ProcessStatus {
percUsedCpu: number;
percFreeMem: number;
usedMem: number;
startedAt: Date;
pTitle?: string;
pid?: number;
ppid?: number;
user?: string;
vNode?: string;
}
/**
* Network status information
*/
interface NetworkStatus {
port: number | null;
connections: number;
}
/**
* Full status information returned by scribbles.status()
*/
interface StatusInfo {
state: 'up' | 'blocking';
cpu: CpuStatus;
sys: SysStatus;
process: ProcessStatus;
network: NetworkStatus;
}
/**
* Structured log entry object passed to dataOut callback
*/
interface LogEntry {
/** Scribbles version */
v: string;
/** Git repository information */
git: GitInfo;
/** Trace context */
trace: TraceInfo;
/** Log metadata */
info: LogInfo;
/** Source file context */
context: ContextInfo;
/** Log input data */
input: InputInfo;
/** Status information (only present for status logs) */
status?: StatusInfo;
/** Convert log entry to formatted string */
toString(): string;
}
// =============================================================================
// Trace Types
// =============================================================================
/**
* Options for trace function
*/
interface TraceOptions {
/** Custom trace ID or W3C traceparent string */
traceId?: string;
/** Tracestate as string or parsed array */
tracestate?: string | Array<{ key: string; value: string }>;
/** Label for this span */
spanLabel?: string;
/** Headers to include in trace context */
headers?: { [key: string]: string };
}
/**
* W3C trace context headers
*/
interface TraceHeaders {
'x-git-hash'?: string;
traceparent: string;
tracestate: string;
[key: string]: string | undefined;
}
// =============================================================================
// Logging Function Types
// =============================================================================
/**
* Log function with optional .at() method for source location override
*/
interface LogFunction {
/**
* Log a message
* @param message - Message string
*/
(message: string): LogEntry;
/**
* Log a value
* @param value - Any value to log
*/
(value: unknown): LogEntry;
/**
* Log an error
* @param error - Error object
*/
(error: Error): LogEntry;
/**
* Log a message with a value
* @param message - Message string
* @param value - Any value to log
*/
(message: string, value: unknown): LogEntry;
/**
* Log a message with an error
* @param message - Message string
* @param error - Error object
*/
(message: string, error: Error): LogEntry;
/**
* Log a value with an error
* @param value - Any value to log
* @param error - Error object
*/
(value: unknown, error: Error): LogEntry;
/**
* Log an error with a value
* @param error - Error object
* @param value - Any value to log
*/
(error: Error, value: unknown): LogEntry;
/**
* Log a message with value and error
* @param message - Message string
* @param value - Any value to log
* @param error - Error object
*/
(message: string, value: unknown, error: Error): LogEntry;
/**
* Log a message with error and value
* @param message - Message string
* @param error - Error object
* @param value - Any value to log
*/
(message: string, error: Error, value: unknown): LogEntry;
/**
* Log with explicit source location
*/
at: (from: { file: string; line: number; col?: number }, ...args: unknown[]) => LogEntry;
}
/**
* Timer log entry with timing information
*/
interface TimerLogEntry extends LogEntry {
input: InputInfo & {
value: {
tag: string;
elapsed: number;
increment: number;
};
};
}
// =============================================================================
// Express Middleware Types
// =============================================================================
/**
* Express-compatible request object (minimal interface for middleware)
*/
interface ExpressRequest {
headers: { [key: string]: string | string[] | undefined };
socket?: { remoteAddress?: string };
connection?: {
remoteAddress?: string;
socket?: { remoteAddress?: string };
};
ip?: string;
}
/**
* Express-compatible response object (minimal interface for middleware)
*/
interface ExpressResponse {
[key: string]: unknown;
}
/**
* Express-compatible next function
*/
type ExpressNextFunction = () => void;
// =============================================================================
// Main Scribbles Interface
// =============================================================================
/**
* Identifiers of the trace context a callback runs in
*/
interface TraceContext {
traceId: string;
spanId: string;
}
/**
* Callback run inside a trace context. Receives the span id string
* first and the `{ traceId, spanId }` context second.
*/
type TraceCallback<T> = (spanId: string, context: TraceContext) => T;
/**
* Trace function with headers method
*/
interface TraceFunction {
/**
* Create a trace context and execute callback
* @param callback - Function to execute within trace context
* @returns whatever the callback returns (a returned promise is returned as-is)
*/
<T>(callback: TraceCallback<T>): T;
/**
* Create a labeled trace context
* @param label - Span label
* @param callback - Function to execute within trace context
* @returns whatever the callback returns (a returned promise is returned as-is)
*/
<T>(label: string, callback: TraceCallback<T>): T;
/**
* Create a trace context with options
* @param options - Trace options
* @param callback - Function to execute within trace context
* @returns whatever the callback returns (a returned promise is returned as-is)
*/
<T>(options: TraceOptions, callback: TraceCallback<T>): T;
/**
* Get W3C trace context headers (must be called inside a trace).
* Outside a trace there is nothing to propagate: the result is a copy of
* `customHeaders` with no `traceparent`, `tracestate` or `x-git-hash`.
* `x-git-hash` is also omitted when the git hash is empty.
* @param customHeaders - Optional custom headers to merge
*/
headers: (customHeaders?: { [key: string]: string }) => TraceHeaders;
}
/**
* Middleware collection
*/
interface Middleware {
/**
* Express middleware that creates trace context from incoming request
*/
express: (req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction) => void;
}
/**
* Return shape for `register.status()` — describes whether the
* runtime-specific source-transform hook is active.
*/
interface RegisterStatus {
/** Detected runtime of the current process. */
runtime: 'node-cjs' | 'node-esm' | 'bun-cjs' | 'bun-esm' | 'unknown';
/** True iff the CJS `Module._extensions` hook is installed. */
cjsInstalled: boolean;
/** True iff the ESM preload (`scribbles/register`) has executed. */
esmPreloaded: boolean;
/**
* Shorthand for "the right mechanism for the current runtime is
* wired". For CJS-only runtimes the CJS hook is sufficient; for
* ESM-ish runtimes the preload is the load-bearing piece.
*/
transformActive: boolean;
/**
* Human-readable remediation text. Present iff `transformActive`
* is false — otherwise omitted.
*/
instructions?: string;
}
/**
* Register API — installs the source-transform hook for the current
* runtime and exposes introspection helpers for CI / health-check use.
*
* Exposed as both a callable function (idempotent installer) and an
* object carrying `.status()` / `.assert()` methods. Also self-
* references under `.register` so `const { register } = require('scribbles')`
* and `import { register } from 'scribbles'` both yield the same value.
*/
interface Register {
/**
* Install the source-transform hook for the current runtime. Safe
* to call multiple times — only the first call has any effect.
*/
(): void;
/** Inspect whether the transform is active (see RegisterStatus). */
status: () => RegisterStatus;
/**
* Fail-fast CI / boot check. Throws a `SCRIBBLES_NOT_REGISTERED`
* error with remediation instructions when the transform is not
* active (e.g. an ESM entrypoint booted without `--import
* scribbles/register` / `bunfig.toml` preload).
*/
assert: () => void;
/** Self-reference so `const { register } = ...` is well-typed. */
register: Register;
}
/**
* Group function collection for console.group-style logging
*/
interface GroupFunction {
/**
* Start a labeled console group
* @param label - Optional group label
* @returns Group ID for targeted closing
*/
start: (label?: string) => number;
/**
* Start a collapsed console group
* @param label - Optional group label
* @returns Group ID for targeted closing
*/
collapsed: (label?: string) => number;
/**
* End a console group.
* - `end()` — LIFO; caption defaults to the same label passed to `start` / `collapsed` (or `"Group"`).
* - `end("caption")` — LIFO; caption is the string shown on the `groupEnd` line.
* - `end(id)` — Close from id (and nested groups); caption defaults to that group's stored label.
* - `end(id, "caption")` — Same close; caption is the string shown (pass `""` for an empty caption).
*/
end: (groupIdOrEndLabel?: number | string, endLabel?: string) => LogEntry;
}
/**
* Main scribbles interface
*/
interface Scribbles {
// Default log levels
error: LogFunction;
warn: LogFunction;
log: LogFunction;
info: LogFunction;
debug: LogFunction;
// Dynamic log levels (added via config.levels)
[level: string]: LogFunction | unknown;
/**
* Configure scribbles options
*/
config: (options: ScribblesConfig) => void;
/**
* Create a trace context
*/
trace: TraceFunction;
/**
* Framework middleware
*/
middleware: Middleware;
/**
* Start or log an intermediate timer value
* @param tag - Timer identifier
* @param message - Optional message
*/
timer: (tag: string, message?: string) => TimerLogEntry;
/**
* End a timer and log final value
* @param tag - Timer identifier
* @param message - Optional message
* @throws Error if timer tag does not exist
*/
timerEnd: (tag: string, message?: string) => TimerLogEntry;
/**
* Log system status with performance metrics
* @param message - Optional message
*/
status: LogFunction;
/**
* Console grouping functions for organizing related log messages
*/
group: GroupFunction;
/**
* Runtime-registration API (v2.0.0+).
*
* In CJS the `scribbles.register` property is a back-compat shim
* over the canonical `const { register } = require('scribbles')`
* named export. In ESM the hard cut applies: `scribbles.register`
* is `undefined` and users must do
* `import { register } from 'scribbles'`.
*/
register: Register;
}
declare const scribbles: Scribbles;
export = scribbles;