Skip to content

Latest commit

 

History

History
406 lines (320 loc) · 21.3 KB

API.md

File metadata and controls

406 lines (320 loc) · 21.3 KB

API Reference: @en32/debuggy

All functions start with an early-return guard: in production they do nothing and debuggy(...)(value) returns value unchanged.

debuggy(label, ...)

debuggy(label: string): Passthrough
debuggy(label: string, options: DebuggyOptions): Passthrough
debuggy(label: string, template: string | TemplateFn, options?: DebuggyOptions): Passthrough

interface Passthrough {
  (): void;                  // label only
  <V>(value: V): V;          // log the value and pass it through
}

The second argument is told apart at runtime: string = registered template name, function = inline template, object = options.

Evaluation order for debuggy(label)(expr):

  1. debuggy(label) runs: mode guard, label parse (cached), tag filter, option and template resolution, stack capture, scope lookup, timer start.
  2. expr is evaluated.
  3. The returned function receives the value and applies the Promise/thenable policy.

The duration therefore includes the evaluation of expr. If the returned function is used more than once, the first use is measured from step 1 and later uses from their own call.

Return value

Input Returns
No argument (debuggy(label)()) undefined (label-only entry, see below)
Non-thenable the same value
Native Promise a derived Promise
Thenable, thenable: "skip" the same object
Thenable, thenable: "wrap" a Proxy over the object (or the same object if wrapping is impossible)
Thenable, thenable: "observe" the same object
Production / tag filtered out the same value

Label-only calls

debuggy(label)() logs the label, call site and scope without a value. The returned function tells the two forms apart by the number of arguments, so debuggy(label)(undefined) is a normal entry whose result is undefined.

Output / API Label-only behavior
pretty, compact no status, time or result
json no result, resultType, resultCount; status and durationMs stay
logger (DebuggyEntry) no result, resultType, resultCount
%t %j %J %o %O %s empty text
%c, %k -
TemplateContext hasResult === false, result === undefined

The status is "sync" and the measured duration is not meaningful. In production the call does nothing and returns undefined.

Labels

[TAG1][TAG2] title with %placeholders and <hy>styles<0>
Part Meaning
[TAG] leading tag blocks, used by the filter
%t %j %J %o %O %s result renderers
%x %v %p %D ... meta placeholders (replace the layout), see the README; %D is YYYY-MM-DD hh:mm:ss in local time, %T is ISO UTC
<codes> style markup, e.g. <hy>, <r>, <0>
%q marker: keep the entry out of the log file (prints nothing)
%%, << literal % and <

Style codes (StyleCode): 0 reset, h bold, d dim, u underline; foreground k r g y b m c w; background K R G Y B M C W.

%q is a marker like style markup: it is removed from the title, never counts as a placeholder (the layout and template precedence do not change) and has no effect on the terminal or on logger. It only skips the log file (see Log file); %%q is a literal %q. Tags can also come from the tags option (see Tags option).

Style markup is parsed once per label (cached) and only in the title. It is removed, and no escape code is written, when colors are disabled. It never counts as a placeholder, so it does not change template precedence. A text that starts with < but is not a valid style tag (Array<string>) is literal.

Filter

Function Description
debuggy.enable(tags?) Replace the filter. No argument = "*". "" / [] = disable
debuggy.enable.add(tags) Add patterns (union, no duplicates). Empty input is a no-op
debuggy.disable() Empty filter: no tag is active
debuggy.reset() Restore the filter from DEBUGGY (or * when unset)
debuggy.enabled(tag) Whether a single tag is currently active

tags is a string (comma, | or whitespace separated) or an array. Pattern syntax:

Pattern Meaning
SQL exact tag (case-insensitive)
HTTP:* wildcard
* everything, including untagged labels
-SQL exclusion, always wins; exclusion-only = *,-X

A label with several tags is active when any tag matches and none is excluded. Filter changes are not applied in production and never switch the mode on.

Scopes

Function Description
debuggy.scope(name, fn) Runs fn in a named scope and returns its result
scope<R>(name: string, fn: () => R): R

The name is kept in an AsyncLocalStorage (Node.js and Bun), so it follows async continuations and does not depend on stack parsing. It is read synchronously inside debuggy(label). The innermost scope wins. Entries report it as ctx.scope / entry.scope, and %n prefers it over the stack-derived function name. In production scope() calls fn and nothing else.

Templates

Function Description
debuggy.template.add(name, fn) Register (overwrites an existing name)
debuggy.template.set(name) Set the default template (resolved lazily)
debuggy.template.clear() Clear the default template
debuggy.template.remove(name) Remove a template
debuggy.template.has(name) Whether a template is registered

An unknown template name produces a single warning on stderr and is then ignored (the label's placeholders apply).

Template precedence

  1. Template argument (debuggy(label, template)).
  2. Placeholders in the label.
  3. options.template (per call > create() > configure()).
  4. Global default template (template.set).
  5. Built-in layout.

The registry and template.set are global per process. options.template (a registered name or an inline function) gives one instance its own default template without affecting other instances.

Ready-made templates (@en32/debuggy/templates)

Export Type
Minimal, Timing, Table, Json, Label, Location, Expression, ErrorsOnly, Classic, Hash, Banner, Warning, Danger, Debug, Info TemplateFn
highlight(style, layout?) (style: string, layout?: "hash" | "classic") => TemplateFn; style = letters of a <...> markup, e.g. "Yk"
level(name) (name: string) => TemplateFn, prefixes the title with name:
compose(...templates) (...templates: TemplateFn[]) => TemplateFn
templates Record<string, TemplateFn>, lower-case registration names

Label writes the title and call site on one line and never prints the value. Each one writes through ctx.write() and escapes dynamic text before applying style markup. For label-only entries (hasResult === false), the templates that print a value (and Minimal, Classic, Hash and their variants) skip the value and the duration. Timing reads slowMs, ErrorsOnly reads stack, and Expression needs source reading. Templates only run in development mode, like everything else.

TemplateContext

Field Notes
label, tags, title label is the original string; title has placeholders and style markup removed
styledTitle title with style markup applied; plain text when colors are off
at, file, line, column call site
fn name of the nearest caller frame, e.g. UserService.list; <anonymous> when the caller has no name
scope innermost debuggy.scope() name, if any
expr, variable lazy; read the source on first access
status "sync" | "resolved" | "rejected" | "thenable"
durationMs, timestamp
result, error
hasResult false when called as debuggy(label)()
type, count lazy; same as %k / %c
memoryDeltaBytes only when memory capture is active
options resolved, frozen options
fmt.table / fmt.json / fmt.inspect built-in renderers
fmt.escapeStyle(text) escapes < so dynamic text is not read as markup
style(markup) applies style markup; markup is removed when colors are off
write(...lines) writes to stderr with the colored tag prefix; does not parse style markup

Templates run when the value settles.

Configuration

debuggy.configure(options: Partial<GlobalOptions>): void   // GlobalOptions has no `tags`
debuggy.create<T extends string = string, Req extends boolean = false>(
  defaults?: DebuggyOptions,
): TypedDebuggy<T, Req>

create() returns a new function with its own default options and type-level tag list. The filter and the template registry stay global per process; the template option gives the instance its own default template. In production it returns the root debuggy.

DebuggyOptions

See the options table in the README.

Tags option

tags?: string | readonly string[]   // DebuggyOptions; create() and per call, not configure()

Adds tags to every label of an instance or of one call, so labels need no [TAG] blocks:

const sql = debuggy.create({ tags: "SQL" });
const http = debuggy.create({ tags: "HTTP|GET", file: "logs/HTTP.log" });
const api = debuggy.create({ tags: ["API, V2", "UI|FORM"] });

sql("users")(query());                         // [SQL] users
debuggy("save", { tags: "AUDIT" })(write());   // [AUDIT] save
Aspect Behavior
Separators comma, | or whitespace, in a string or in each array element
Valid tags A-Z a-z 0-9 _ . : -; an invalid tag is ignored with one warning
Effective tags instance tags, then call tags, then label tags; duplicates are dropped
Chained create tags accumulate: create({ tags: "DB" }).create({ tags: "SLOW" }) is DB, SLOW
Used by the filter, the output prefix, entry.tags, ctx.tags, {tag} log files
Filter an instance with tags is active when any effective tag matches the filter, not only when it contains *
configure() not available (GlobalOptions omits tags)
Production no-op like every other option

Types: create({ tags }) returns a function that does not require tags in the labels, even with requireTag or create<T, true>() inferred from the call. When T is a union, every value of tags (also inside "A|B" strings) must be a member of T. A tags option on a single call does not relax the label requirement.

Log file (file)

interface LogFileOptions {
  path: string;       // relative to process.cwd() or absolute; supports {date} and {tag}
  append?: boolean;   // default true; false truncates once per process
  console?: boolean;  // default true; also write to stderr
  stamp?: boolean;    // default true; prefix the first line with YYYY-MM-DD hh:mm:ss
}

// DebuggyOptions
file?: string | false | LogFileOptions;

A string is shorthand for { path }; false disables an inherited file. The environment variable DEBUGGY_FILE sets a default path. The option follows the usual precedence (per call > create() > configure() > environment).

The file mirrors the text that goes to stderr: layouts and ctx.write() of templates, without colors. Behavior:

Aspect Behavior
Production no-op: no file is created or opened
{date} replaced by YYYY-MM-DD (local time) of the entry; a new day uses a new file
{tag} one file per tag of the entry (see below); no tag is default; unsafe characters become _
%q an entry whose label has %q is never written to the file; stderr still gets it, also with console: false
Stamp local time of the entry, first line only; not added to json lines
Writes synchronous; one descriptor per resolved path; missing directories created
Failure one warning on stderr; later entries only go to stderr; an entry is never lost with console: false
logger with logger and no template there is no text output, so the file stays empty
Internal messages warnings and internal errors go to stderr only

Not included: rotation by size, retention, asynchronous streams.

One file per tag

{tag} writes an entry to one file per effective tag, with the same text and stamp in each file; stderr receives it once.

debuggy.configure({ file: "logs/{tag}-{date}.log" });

debuggy("[SQL] users")(query());          // logs/SQL-2026-11-29.log
debuggy("[SQL][SLOW] users")(query());    // logs/SQL-2026-11-29.log and logs/SLOW-2026-11-29.log
debuggy("[HTTP:users] show")(handler());  // logs/HTTP_users-2026-11-29.log
debuggy("plain label")(1);                // logs/default-2026-11-29.log
path [SQL] on 2026-11-29 [HTTP:users] on 2026-11-30
logs/{tag}.log logs/SQL.log logs/HTTP_users.log
logs/{tag}-{date}.log logs/SQL-2026-11-29.log logs/HTTP_users-2026-11-30.log
logs/{date}/{tag}.log logs/2026-11-29/SQL.log logs/2026-11-30/HTTP_users.log

{tag} and {date} are resolved for each entry, in any order and in directory names. Other ways to split files, without {tag}:

// One instance per file
const sql = debuggy.create({ file: "logs/SQL.log" });
const http = debuggy.create({ file: "logs/HTTP.log" });

sql("[SQL] users")(query());
http("[HTTP] show")(handler());

// The same, with the tags declared once and no tag in the label
const sql2 = debuggy.create({ tags: "SQL", file: "logs/SQL.log" });
const http2 = debuggy.create({ tags: "HTTP", file: "logs/HTTP.log" });

sql2("users")(query());
http2("show")(handler());

Notes: a character outside A-Z a-z 0-9 _ . - in a tag becomes _ (HTTP:users is HTTP_users) and a tag made only of dots becomes _; tags that give the same name (HTTP:users, HTTP_users, and SQL / sql on case-insensitive file systems) share one file. SLOW from slowMs is a marker, not a tag. One descriptor stays open per resolved path.

logger and DebuggyEntry

interface DebuggyEntry {
  label: string; tags: string[]; title: string;
  expression?: string; variable?: string;      // lazy getters
  file?: string; line?: number; column?: number; function?: string;
  scope?: string;                              // innermost debuggy.scope()
  status: Status; durationMs: number;
  result?: unknown; resultType?: string; resultCount?: number;
  error?: unknown; timestamp?: string; memoryDeltaBytes?: number;
}

When logger is set it is called for every entry and the built-in stderr output is suppressed. A template, if one applies, still runs.

Output formats

Format Output
pretty tree layout (default)
compact one line: [TAG] title at=… in=… status 1.2ms result=…
json one JSON object per line (NDJSON)

A label with meta placeholders replaces the pretty and compact layouts. Every rendered result or error text is limited by maxLength (default 2000, 0 = unlimited); a value in a json line that is longer than that becomes truncated text and the line gets resultTruncated or errorTruncated: true. logger entries always carry the raw value. pretty and compact apply the title's style markup when colors are enabled. json always emits the structured entry, never contains escape codes, and keeps the original label string. A template, when used, controls its own output.

Source extraction (source)

Value Behavior
"auto" read lazily, only when %x/%v/ctx.expr/entry.expression is used
true read eagerly and show expr / var in the default layout
false never read; %x, %v, ctx.expr are empty / undefined

The call-site text must have the curried shape name(...)(...). The position from the stack is verified against the source; when it does not match, the same line is searched for the nearest curried call. If none is found, nothing is extracted and one warning per file is written to stderr (bundled code without source maps, stale files after hot reload).

Global registration (@en32/debuggy/global)

import "@en32/debuggy/global";

Side-effect-only entry. It assigns the default debuggy instance to globalThis.debuggy and declares var debuggy: typeof debuggy in the global scope, so the identifier type-checks in every file of the program without an import. It has no exports. In production the instance is the same no-op as the regular import. The module is listed in sideEffects, so bundlers keep it.

Types

Type Purpose
TagRegistry augmentable global tag list
DebuggyConfig augmentable global config (requireTag)
TypedDebuggy<T, Req> type of debuggy / create() results
ValidateLabel, ValidateList literal label / filter validation
ValidateTagList, SplitTags tags option validation / "A|B, C" split into a tuple
TemplateFn, TemplateContext template types
Passthrough function returned by debuggy(label): (): void and <V>(value: V): V
StyleCode letters allowed inside <...> style markup
DebuggyOptions, ResolvedOptions, GlobalOptions options
LogFileOptions file option (log file)
DebuggyEntry logger entry

@en32/debuggy/types exposes the same declarations and can also be used as the target of declare module augmentation.