Alea uint32
() => numberfract53
() => numberversion
stringseeds
Array<unknown>utility belt for JS
330 declarations
Alea uint32() => numberfract53() => numberversionstringseedsArray<unknown>ArrayElement<T> TAssignable<T, K> TKkeyof Tkeyof TAsyncStatus (to_error_label?: ((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefined, map_error_text?: ((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefined, handle_error?: (err: Error, origin: UncaughtExceptionOrigin) => void): void Attaches the 'uncoughtException' event to despawn all processes,
and enables custom error logging with to_error_label.
to_error_label?- Customize the error label or return null for the default origin.
((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefinedmap_error_text?- Customize the error text. Return '' to silence, or null for the default print_error(err).
((err: Error, origin: UncaughtExceptionOrigin) => string | null) | undefinedhandle_error(err: Error, origin: UncaughtExceptionOrigin) => void() =>
process.exit(1)void Benchmark class for measuring and comparing function performance.
constructortype new (config?: BenchmarkConfig): Benchmark
config{}addAdd a benchmark task.
type (name: string, fn: () => unknown): this
name- Task name or full task object
stringfn- Function to benchmark (if name is string). Return values are ignored.
() => unknownthisThis Benchmark instance for chaining
addtype (name: string, fn: () => unknown): this
namestringfn() => unknownthisaddtype (name: string, fn: () => unknown): this
namestringfn() => unknownthisremoveRemove a benchmark task by name.
type (name: string): this
name- Name of the task to remove
stringthisThis Benchmark instance for chaining
Error - if task with given name doesn't existskipMark a task to be skipped during benchmark runs.
type (name: string): this
name- Name of the task to skip
stringthisThis Benchmark instance for chaining
Error - if task with given name doesn't existonlyMark a task to run exclusively (along with other only tasks).
type (name: string): this
name- Name of the task to run exclusively
stringthisThis Benchmark instance for chaining
Error - if task with given name doesn't existrunRun all benchmark tasks.
type (): Promise<BenchmarkResult[]>
Promise<BenchmarkResult[]>Array of benchmark results
tableFormat results as an ASCII table with percentiles, min/max, and relative performance.
type (options?: BenchmarkFormatTableOptions | undefined): string
options?- Formatting options
BenchmarkFormatTableOptions | undefinedstringFormatted table string
markdownFormat results as a Markdown table.
type (options?: BenchmarkFormatTableOptions | undefined): string
options?- Formatting options (groups for organized output with optional baselines)
BenchmarkFormatTableOptions | undefinedstringFormatted markdown string
jsonFormat results as JSON.
type (options?: BenchmarkFormatJsonOptions | undefined): string
options?- Formatting options (pretty, include_timings)
BenchmarkFormatJsonOptions | undefinedstringJSON string
resultsGet the benchmark results. Returns a shallow copy to prevent external mutation.
type (): BenchmarkResult[]
BenchmarkResult[]Array of benchmark results
results_by_nameGet results as a map for convenient lookup by task name. Returns a new Map each call to prevent external mutation.
type (): Map<string, BenchmarkResult>
Map<string, BenchmarkResult>Map of task name to benchmark result
resetReset the benchmark results. Keeps tasks intact so benchmarks can be rerun.
type (): this
thisThis Benchmark instance for chaining
clearClear everything (results and tasks). Use this to start fresh with a new set of benchmarks.
type (): this
thisThis Benchmark instance for chaining
summaryGet a quick text summary of the fastest task.
type (): string
stringHuman-readable summary string
benchmark_baseline.ts view source
(results: BenchmarkResult[], options?: BenchmarkBaselineCompareOptions): Promise<BenchmarkBaselineComparisonResult> Compare benchmark results against the stored baseline.
results- Current benchmark results
BenchmarkResult[]options- Comparison options including regression threshold and staleness warning
{}Promise<BenchmarkBaselineComparisonResult> Comparison result with regressions, improvements, and unchanged tasks
benchmark_baseline.ts view source
(result: BenchmarkBaselineComparisonResult): string Format a baseline comparison result as a human-readable string.
result- Comparison result from benchmark_baseline_compare
string Formatted string summary
benchmark_baseline.ts view source
(result: BenchmarkBaselineComparisonResult, options?: { pretty?: boolean | undefined; }): string Format a baseline comparison result as JSON for programmatic consumption.
result- Comparison result from benchmark_baseline_compare
options- Formatting options
{ pretty?: boolean | undefined; }{}string JSON string
benchmark_baseline.ts view source
(options?: BenchmarkBaselineLoadOptions): Promise<{ version: number; timestamp: string; git_commit: string | null; git_branch: string | null; node_version: string; entries: { ...; }[]; } | null> Load the current baseline from disk.
options- Load options
{}Promise<{ version: number; timestamp: string; git_commit: string | null; git_branch: string | null; node_version: string; entries: { name: string; mean_ns: number; p50_ns: number; std_dev_ns: number; ... 7 more ...; sample_size: number; }[]; } | null> The baseline, or null if not found or invalid
benchmark_baseline.ts view source
(results: BenchmarkResult[], options?: BenchmarkBaselineSaveOptions): Promise<void> Save benchmark results as the current baseline.
results- Benchmark results to save
BenchmarkResult[]options- Save options
{}Promise<void> benchmark_format.ts view source
(results: BenchmarkResult[], options?: BenchmarkFormatJsonOptions | undefined): string Format results as JSON.
results- Array of benchmark results
BenchmarkResult[]options?- Formatting options
BenchmarkFormatJsonOptions | undefinedstring JSON string
benchmark_format.ts view source
(results: BenchmarkResult[], baseline?: string | undefined): string Format results as a Markdown table with key metrics. All times use the same unit for easy comparison.
results- Array of benchmark results
BenchmarkResult[]baseline?- Optional task name to use as baseline for comparison (defaults to fastest)
string | undefinedstring Formatted markdown table string
benchmark_format.ts view source
(results: BenchmarkResult[], groups: BenchmarkGroup[]): string Format results as grouped Markdown tables with headers between groups.
results- Array of benchmark results
BenchmarkResult[]groups- Array of group definitions
BenchmarkGroup[]string Formatted markdown string with group headers and tables
benchmark_format.ts view source
(n: number, decimals?: number) => string Format a number with fixed decimal places and thousands separators.
{@link format_number} in maths.ts for the underlying implementation.
benchmark_format.ts view source
(results: BenchmarkResult[], baseline?: string | undefined): string Format results as an ASCII table with percentiles, min/max, and relative performance. All times use the same unit for easy comparison.
results- Array of benchmark results
BenchmarkResult[]baseline?- Optional task name to use as baseline for comparison (defaults to fastest)
string | undefinedstring Formatted table string with enhanced metrics
benchmark_format.ts view source
(results: BenchmarkResult[], groups: BenchmarkGroup[]): string Format results as a grouped table with visual separators between groups.
results- Array of benchmark results
BenchmarkResult[]groups- Array of group definitions
BenchmarkGroup[]string Formatted table string with group separators
benchmark_stats.ts view source
(a: BenchmarkStatsComparable, b: BenchmarkStatsComparable, options?: BenchmarkCompareOptions | undefined): BenchmarkComparison Compare two benchmark results for statistical significance. Uses Welch's t-test (handles unequal variances) and Cohen's d effect size.
a- First benchmark stats (or any object with required properties)
b- Second benchmark stats (or any object with required properties)
options?- Comparison options
BenchmarkCompareOptions | undefinedBenchmarkComparison Comparison result with significance, effect size, and recommendation
(fn: () => unknown, iterations: number, async_hint?: boolean | undefined): Promise<boolean> Warmup function by running it multiple times. Detects whether the function is async based on return value.
fn- Function to warmup (sync or async)
() => unknowniterations- Number of warmup iterations
numberasync_hint?- If provided, use this instead of detecting
boolean | undefinedPromise<boolean> Whether the function is async
benchmark_baseline.ts view source
ZodObject<{ version: ZodNumber; timestamp: ZodString; git_commit: ZodNullable<ZodString>; git_branch: ZodNullable<ZodString>; node_version: ZodString; entries: ZodArray<...>; }, $strip> Schema for the complete baseline file.
benchmark_baseline.ts view source
BenchmarkBaselineCompareOptions Options for comparing against a baseline.
regression_thresholdMinimum speedup ratio to consider a regression. For example, 1.05 means only flag regressions that are 5% or more slower. Default: 1.0 (any statistically significant slowdown is a regression)
numberstaleness_warning_daysNumber of days after which to warn about stale baseline. Default: undefined (no staleness warning)
numberbenchmark_baseline.ts view source
BenchmarkBaselineComparisonResult Result of comparing current results against a baseline.
baseline_foundWhether a baseline was found
booleanbaseline_timestampTimestamp of the baseline
string | nullbaseline_commitGit commit of the baseline
string | nullbaseline_age_daysAge of the baseline in days
number | nullbaseline_staleWhether the baseline is considered stale based on staleness_warning_days option
booleancomparisonsIndividual task comparisons
Array<BenchmarkBaselineTaskComparison>regressionsTasks that regressed (slower with statistical significance), sorted by effect size (largest first)
Array<BenchmarkBaselineTaskComparison>improvementsTasks that improved (faster with statistical significance), sorted by effect size (largest first)
Array<BenchmarkBaselineTaskComparison>unchangedTasks with no significant change
Array<BenchmarkBaselineTaskComparison>new_tasksTasks in current run but not in baseline
Array<string>removed_tasksTasks in baseline but not in current run
Array<string>benchmark_baseline.ts view source
ZodObject<{ name: ZodString; mean_ns: ZodNumber; p50_ns: ZodNumber; std_dev_ns: ZodNumber; min_ns: ZodNumber; max_ns: ZodNumber; ... 5 more ...; sample_size: ZodNumber; }, $strip> Schema for a single benchmark entry in the baseline.
benchmark_baseline.ts view source
BenchmarkBaselineLoadOptions Options for loading a baseline.
pathDirectory to load baseline from (default: '.gro/benchmarks')
stringbenchmark_baseline.ts view source
BenchmarkBaselineSaveOptions Options for saving a baseline.
pathDirectory to store baselines (default: '.gro/benchmarks')
stringgit_commitGit commit hash (auto-detected if not provided)
string | nullgit_branchGit branch name (auto-detected if not provided)
string | nullbenchmark_baseline.ts view source
BenchmarkBaselineTaskComparison Comparison result for a single task.
namestringbaselinecurrentcomparisonbenchmark_stats.ts view source
BenchmarkCompareOptions Options for benchmark comparison.
alphaSignificance level for hypothesis testing (default: 0.05)
numberbenchmark_stats.ts view source
BenchmarkComparison Result from comparing two benchmark stats.
fasterWhich benchmark is faster ('a', 'b', or 'equal' if difference is negligible)
'a' | 'b' | 'equal'speedup_ratioHow much faster the winner is (e.g., 1.5 means 1.5x faster)
numbersignificantWhether the difference is statistically significant at the given alpha
booleanp_valueP-value from Welch's t-test (lower = more confident the difference is real)
numbereffect_sizeCohen's d effect size (magnitude of difference independent of sample size)
numbereffect_magnitudeInterpretation of effect size
ci_overlapWhether the 95% confidence intervals overlap
booleanrecommendationHuman-readable interpretation of the comparison
stringbenchmark_types.ts view source
BenchmarkConfig Configuration options for a benchmark suite.
duration_msTarget duration to run each benchmark task in milliseconds. The benchmark will run until this duration is reached or max_iterations is hit. Default: 1000ms
numberwarmup_iterationsNumber of warmup iterations before actual measurements. Warmup helps stabilize JIT compilation and caches. Default: 5
numbercooldown_msCooldown time between tasks in milliseconds. Helps prevent interference between benchmarks. Default: 100ms
numbermin_iterationsMinimum number of iterations to run. Default: 10
numbermax_iterationsMaximum number of iterations to run. Prevents infinite loops if function is extremely fast. Default: 100000
numbertimerCustom timer to use for measurements. Default: timer_default (auto-detects environment)
on_iterationCallback invoked after each iteration completes. Useful for triggering garbage collection, logging progress, early termination, or custom instrumentation.
Note: The callback time is NOT included in iteration measurements - it runs after the timing capture. However, frequent GC calls will slow overall benchmark execution time.
(task_name: string, iteration: number, abort: () => void) => voidon_task_completeCallback invoked after each task completes. Useful for logging progress during long benchmark runs.
(result: BenchmarkResult, index: number, total: number) => voidbenchmark_format.ts view source
BenchmarkFormatJsonOptions prettyWhether to pretty-print (default: true)
booleaninclude_timingsWhether to include raw timings array (default: false, can be large)
booleanbenchmark_types.ts view source
BenchmarkFormatTableOptions Options for table formatting.
groupsGroup results by category using filter functions.
Array<BenchmarkGroup>benchmark_types.ts view source
BenchmarkGroup A group definition for organizing benchmark results.
nameDisplay name for the group
stringdescriptionOptional description shown below the group name
stringfilterFilter function to determine which results belong to this group
(result: BenchmarkResult) => booleanbaselineTask name to use as baseline for the "vs" column. When specified, ratios are computed against this task instead of the fastest. If the baseline task is not found in the group, falls back to "vs Best" with a warning.
stringbenchmark_types.ts view source
BenchmarkResult Result from running a single benchmark task.
nameTask name
stringstatsStatistical analysis of the benchmark
iterationsNumber of iterations executed
numbertotal_time_msTotal time spent benchmarking (including warmup) in milliseconds
numbertimings_nsRaw timing data for each iteration in nanoseconds. Useful for custom statistical analysis, histogram generation, or exporting to external tools.
Array<number>benchmark_stats.ts view source
Complete statistical analysis of timing measurements. Includes outlier detection, descriptive statistics, and performance metrics. All timing values are in nanoseconds.
mean_nsMean (average) time in nanoseconds
type number
p50_ns50th percentile (median) time in nanoseconds
type number
std_dev_nsStandard deviation in nanoseconds
type number
min_nsMinimum time in nanoseconds
type number
max_nsMaximum time in nanoseconds
type number
p75_ns75th percentile in nanoseconds
type number
p90_ns90th percentile in nanoseconds
type number
p95_ns95th percentile in nanoseconds
type number
p99_ns99th percentile in nanoseconds
type number
cvCoefficient of variation (std_dev / mean)
type number
confidence_interval_ns95% confidence interval for the mean in nanoseconds
type [number, number]
outliers_nsArray of detected outlier values in nanoseconds
type Array<number>
outlier_ratioRatio of outliers to total samples
type number
sample_sizeNumber of samples after outlier removal
type number
raw_sample_sizeOriginal number of samples (before outlier removal)
type number
ops_per_secondOperations per second (NS_PER_SEC / mean_ns)
type number
failed_iterationsNumber of failed iterations (NaN, Infinity, or negative values)
type number
constructortype new (timings_ns: number[]): BenchmarkStats
timings_nsnumber[]toStringFormat stats as a human-readable string.
type (): string
stringbenchmark_stats.ts view source
BenchmarkStatsComparable Minimal stats interface for comparison. This allows comparing stats from different sources (e.g., loaded baselines).
mean_nsnumberstd_dev_nsnumbersample_sizenumberconfidence_interval_ns[number, number]benchmark_types.ts view source
BenchmarkTask A benchmark task to execute.
nameName of the task (for display)
stringfnFunction to benchmark (sync or async). Return values are ignored.
() => unknownsetupOptional setup function run before benchmarking this task. Not included in timing measurements.
() => void | Promise<void>teardownOptional teardown function run after benchmarking this task. Not included in timing measurements.
() => void | Promise<void>skipIf true, skip this task during benchmark runs. Useful for temporarily disabling tasks during development.
booleanonlyIf true, run only this task (and other tasks marked only).
Useful for focusing on specific tasks during development.
booleanasyncHint for whether the function is sync or async. If not provided, automatically detected during warmup. Setting this explicitly skips per-iteration promise checking for sync functions.
booleanBlue Brand<T> TBranded<TValue, TName> TValueTName(n: number, min: number, max: number): number Returns n bounded to min and max.
nnumberminnumbermaxnumbernumber ClassConstructor<TInstance, TArgs> TInstanceTArgsArray<any>Array<any>ClientIdCreator (a: [any, any], b: [any, any]): number Compares two map entries for sorting purposes.
If the key is a string, it uses localeCompare for comparison.
For other types, it uses >.
a[any, any]b[any, any]number ZodObject<{ name: ZodString; type: ZodString; optional: ZodOptional<ZodBoolean>; description: ZodOptional<ZodString>; default_value: ZodOptional<...>; bindable: ZodOptional<...>; }, $loose> Component prop information for Svelte components.
Kept distinct from ParameterInfo despite structural similarity.
Component props are named attributes with different semantics:
no positional order when passing (<Foo {a} {b} /> = <Foo {b} {a} />),
support two-way binding via $bindable rune.
(s: ((format: ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[], text: string, options?: StyleTextOptions | undefined) => string) | null | undefined): (format: ForegroundColors | ... 2 more ... | (ForegroundColors | ... 1 more ... | Modifiers)[], text: string, options?: StyleTextOptions | undefined) => string Configures the module-level styling function for colored output.
s((format: ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[], text: string, options?: StyleTextOptions | undefined) => string) | null | undefined(format: ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[], text: string, options?: StyleTextOptions | undefined) => string (str: string): number Returns the count of graphemes in a string, the individually rendered characters.
strstringnumber (iterator: Iterable<unknown>): number Useful for fast counting when .length is not available.
iteratorIterable<unknown>number Counter (name: string, count?: number | undefined, separator?: string): ClientIdCreator Creates a string id generator function, outputting ${name}_${count} by default.
namestringcount?number | undefinedseparatorstring'_'ClientIdCreator (initial?: number | undefined): Counter Creates a counter constructor function, starting at 0.
initial?number | undefinedCounter <T>(): Deferred<T> Creates a object with a promise and its resolve/reject handlers.
Deferred<T> (...seed: unknown[]): Alea Seeded pseudo-random number generator. DO NOT USE when security matters, use webcrypto APIs instead.
seedunknown[]Alea (decimals?: number): Stopwatch Tracks elapsed time in milliseconds.
decimalsnumber2Stopwatch CreateCounter (declaration: { [x: string]: unknown; name: string; kind: "function" | "type" | "variable" | "class" | "constructor" | "component" | "json" | "css"; doc_comment?: string | undefined; type_signature?: string | undefined; ... 17 more ...; alias_of?: { ...; } | undefined; }, module_path: string, library_name: string): string Generate TypeScript import statement for a declaration.
declaration{ [x: string]: unknown; name: string; kind: "function" | "type" | "variable" | "class" | "constructor" | "component" | "json" | "css"; doc_comment?: string | undefined; type_signature?: string | undefined; ... 17 more ...; alias_of?: { ...; } | undefined; }module_pathstringlibrary_namestringstring (declaration: { [x: string]: unknown; name: string; kind: "function" | "type" | "variable" | "class" | "constructor" | "component" | "json" | "css"; doc_comment?: string | undefined; type_signature?: string | undefined; ... 17 more ...; alias_of?: { ...; } | undefined; }): string Format declaration name with generic parameters for display.
declaration{ [x: string]: unknown; name: string; kind: "function" | "type" | "variable" | "class" | "constructor" | "component" | "json" | "css"; doc_comment?: string | undefined; type_signature?: string | undefined; ... 17 more ...; alias_of?: { ...; } | undefined; }string ZodObject<{ name: ZodString; kind: ZodEnum<{ function: "function"; type: "type"; variable: "variable"; class: "class"; constructor: "constructor"; component: "component"; json: "json"; css: "css"; }>; ... 19 more ...; alias_of: ZodOptional<...>; }, $loose> Metadata for an exported declaration (function, type, class, component, etc.).
Extracted from TypeScript source and JSDoc/TSDoc comments at build time.
ZodEnum<{ function: "function"; type: "type"; variable: "variable"; class: "class"; constructor: "constructor"; component: "component"; json: "json"; css: "css"; }> The kind of exported declaration.
(a: unknown, b: unknown): boolean Deep equality comparison that checks both structure and type.
Key behaviors:
- Compares by constructor to prevent type confusion (security: {} ≠ [], {} ≠ new Map(), new ClassA() ≠ new ClassB())
- Prevents asymmetry bugs: deep_equal(a, b) always equals deep_equal(b, a)
- Compares only enumerable own properties (ignores prototypes, symbols, non-enumerable)
- Special handling for: Date (timestamp), Number/Boolean (boxed primitives), Error (message/name)
- Promises always return false (cannot be meaningfully compared)
- Maps/Sets compare by reference for object keys/values
afirst value to compare
unknownbsecond value to compare
unknownboolean true if deeply equal, false otherwise
Deferred<T> Creates a deferred object with a promise and its resolve/reject handlers.
TpromisePromise<T>resolve(value: T) => voidreject(reason: any) => voidDefined<T> T(str: string): string Removes leading and trailing spaces from each line of a string.
strstringstring (serialized: string): Map<string, { key: string; url: string; params: any; value: any; etag: string | null; last_modified: string | null; }> Converts a serialized cache string to a FetchValueCache.
serializedstringMap<string, { key: string; url: string; params: any; value: any; etag: string | null; last_modified: string | null; }> (child: ChildProcess): Promise<SpawnResult> Kills a child process and returns a SpawnResult.
childChildProcessPromise<SpawnResult> (): Promise<SpawnResult[]> Kills all globally registered child processes.
Promise<SpawnResult[]> <T>(items: T[], fn: (item: T, index: number) => Promise<void>, concurrency: number): Promise<void> Runs an async function on each item with controlled concurrency. Like map_concurrent but doesn't collect results (more efficient for side effects).
itemsarray of items to process
T[]fnasync function to apply to each item
(item: T, index: number) => Promise<void>concurrencymaximum number of concurrent operations
numberPromise<void> benchmark_stats.ts view source
EffectMagnitude Effect size magnitude interpretation (Cohen's d).
any[] Record<string | number | symbol, undefined> & object Frozen empty object with no properties, good for options default values.
(source: string, ensured: string): string Adds the substring ensured to the end of the source string if it's not already present.
sourcestringensuredstringstring (source: string, ensured: string): string Adds the substring ensured to the start of the source string if it's not already present.
sourcestringensuredstringstring (str: string): string Escapes a string for literal matching in a RegExp.
strstringstring ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> <TValue = any, TParams = undefined>(url: string | URL, options?: FetchValueOptions<TValue, TParams> | undefined): Promise<Result<{ value: TValue; headers: Headers; }, { ...; }>> Specializes fetch with some slightly different behavior and additional features:
- throws on ratelimit errors to mitigate unintentional abuse
- optional parse function called on the return value
- optional cache (different from the browser cache,
the caller can serialize it so e.g. dev setups can avoid hitting the network)
- optional simplified API for authorization and data types
(you can still provide headers directly)
Unlike fetch, this throws on ratelimits (status code 429)
to halt whatever is happpening in its tracks to avoid accidental abuse,
but returns a Result in all other cases.
Handling ratelimit headers with more sophistication gets tricky because behavior
differs across services.
(e.g. Mastodon returns an ISO string for x-ratelimit-reset,
but GitHub returns Date.now()/1000,
and other services may do whatever, or even use a different header)
It's also stateless to avoid the complexity and bugs,
so we don't try to track x-ratelimit-remaining per domain.
If the value is cached, only the cached safe subset of the headers are returned.
(currently just etag and last-modified)
Otherwise the full res.headers are included.
urlstring | URLoptions?FetchValueOptions<TValue, TParams> | undefinedPromise<Result<{ value: TValue; headers: Headers; }, { status: number; message: string; }>> ZodMap<ZodString, ZodObject<{ key: ZodString; url: ZodString; params: ZodAny; value: ZodAny; etag: ZodNullable<ZodString>; last_modified: ZodNullable<...>; }, $strip>> ZodObject<{ key: ZodString; url: ZodString; params: ZodAny; value: ZodAny; etag: ZodNullable<ZodString>; last_modified: ZodNullable<ZodString>; }, $strip> ZodString FetchValueOptions<TValue, TParams> TValueTParamsundefinedrequestThe request.headers take precedence over the headers computed from other options.
RequestInitparamsTParamsparse(v: any) => TValuetokenstring | nullcacheFetchValueCache | nullreturn_early_from_cachebooleanlogfetchtypeof globalThis.fetchFileFilter A filter function for file paths only.
Flavor<T> TFlavored<TValue, TName> The Flavored and Branded type helpers add varying degrees of nominal typing to other types. This is especially useful with primitives like strings and numbers.
TValueTNamehttps://spin.atomicobject.com/typescript-flexible-nominal-typing/ * Flavored is a looser form of Branded that trades explicitness and a little safety in some cases for ergonomics. With Flavored you don't need to cast unflavored types: * ``ts type Email = Flavored<string, 'Email'>; const email1: Email = 'foo'; // ok type Address = Flavored<string, 'Address'>; const email2: Email = 'foo' as Address; // error! `` * Branded requires casting: * ``ts type PhoneNumber = Branded<string, 'PhoneNumber'>; const phone1: PhoneNumber = 'foo'; // error! const phone2: PhoneNumber = 'foo' as PhoneNumber; // ok `` * See also Zod's .brand schema helper:
(n: number, decimals?: number): string Format a number with fixed decimal places and thousands separators.
nnumberdecimalsnumber2string (url: string): string Formats a URL by removing 'https://', 'www.', and trailing slashes. Notably it does not remove 'http://', so the user can see that it's insecure.
urlstringstring (dir: string, should_remove?: ((name: string) => boolean) | undefined, options?: RmOptions | undefined): Promise<void> Empties a directory, recursively by default. If should_remove is provided, only entries where it returns true are removed.
dirstringshould_remove?((name: string) => boolean) | undefinedoptions?RmOptions | undefinedPromise<void> (path: string): Promise<boolean> Checks if a file or directory exists.
pathstringPromise<boolean> (dir: string, options?: FsSearchOptions): Promise<ResolvedPath[]> dirstringoptionsEMPTY_OBJECTPromise<ResolvedPath[]> FsSearchOptions filterOne or more filter functions, any of which can short-circuit the search by returning false.
PathFilter | Array<PathFilter>file_filterOne or more file filter functions. Every filter must pass for a file to be included.
FileFilter | Array<FileFilter>sortPass null or false to speed things up at the cost of volatile ordering.
boolean | null | ((a: ResolvedPath, b: ResolvedPath) => number)include_directoriesSet to true to include directories. Defaults to false.
booleancwdSets the cwd for dir unless it's an absolute path or null.
string | nullZodObject<{ name: ZodString; constraint: ZodOptional<ZodString>; default_type: ZodOptional<ZodString>; }, $loose> Generic type parameter information.
(options?: SpawnOptions | undefined): Promise<string | null> options?SpawnOptions | undefinedPromise<string | null> an error message if the git workspace has any unstaged or uncommitted changes, or null if it's clean
(options?: SpawnOptions | undefined): Promise<string | null> options?SpawnOptions | undefinedPromise<string | null> an error message if the git workspace has any unstaged changes or untracked files, or null if fully staged
(options?: SpawnOptions | undefined): Promise<boolean> Returns the global git config setting for pull.rebase.
options?SpawnOptions | undefinedPromise<boolean> (options?: SpawnOptions | undefined): Promise<GitWorkspaceStatus> Checks the git workspace status using a single git status --porcelain -z call.
The -z format provides more reliable parsing by using NUL separators and avoiding escaping.
options?SpawnOptions | undefinedPromise<GitWorkspaceStatus> status object with flags for unstaged changes, staged changes, and untracked files
(branch: GitBranch, options?: SpawnOptions | undefined): Promise<GitBranch | null> Calls git checkout and throws if anything goes wrong.
branchoptions?SpawnOptions | undefinedPromise<GitBranch | null> the previous branch name, if it changed
(origin: GitOrigin, branch: GitBranch, source_dir: string, target_dir: string, options?: SpawnOptions | undefined): Promise<void> Clones a branch locally to another directory and updates the origin to match the source.
originbranchsource_dirstringtarget_dirstringoptions?SpawnOptions | undefinedPromise<void> (options?: SpawnOptions | undefined): Promise<string> Returns the hash of the current branch's first commit or throws if something goes wrong.
options?SpawnOptions | undefinedPromise<string> (options?: SpawnOptions | undefined): Promise<GitBranch> Returns the current git branch name or throws if something goes wrong.
options?SpawnOptions | undefinedPromise<GitBranch> (branch?: string | undefined, options?: SpawnOptions | undefined): Promise<string | null> Returns the branch's latest commit hash or throws if something goes wrong.
branch?string | undefinedoptions?SpawnOptions | undefinedPromise<string | null> (branch: GitBranch, options?: SpawnOptions | undefined): Promise<void> Deletes a branch locally and throws if anything goes wrong.
branchoptions?SpawnOptions | undefinedPromise<void> (origin: GitOrigin, branch: GitBranch, options?: SpawnOptions | undefined): Promise<void> Deletes a branch remotely and throws if anything goes wrong.
originbranchoptions?SpawnOptions | undefinedPromise<void> (origin?: GitOrigin, branch?: GitBranch | undefined, options?: SpawnOptions | undefined): Promise<void> Calls git fetch and throws if anything goes wrong.
origin'origin' as GitOriginbranch?GitBranch | undefinedoptions?SpawnOptions | undefinedPromise<void> (options?: SpawnOptions | undefined): Promise<GitInfo> Get basic git info (commit hash and branch name) without throwing. Returns null values if git commands fail (e.g., not in a git repo).
options?SpawnOptions | undefinedPromise<GitInfo> (branch: GitBranch, options?: SpawnOptions | undefined): Promise<boolean> branchoptions?SpawnOptions | undefinedPromise<boolean> a boolean indicating if the local git branch exists
(stdout: string | null): GitWorkspaceStatus Parses the output of git status --porcelain -z (v1 format) into a status object.
This is a pure function that can be tested independently.
Format: XY path\0 where: - X = staged status (index) - Y = unstaged status (work tree) - path = file path (unescaped with -z)
Supported status codes: - M = modified - A = added - D = deleted - R = renamed - C = copied - T = type changed (regular file, symbolic link or submodule) - U = unmerged - ? = untracked - ! = ignored
For renames/copies: XY new\0old\0 (two NUL-separated paths)
Note: This implementation treats submodules the same as regular files. Submodule-specific status codes (lowercase m, ?) are interpreted as changes.
stdout- The raw output from git status --porcelain -z
string | nullGitWorkspaceStatus status object with flags for unstaged changes, staged changes, and untracked files
(origin?: GitOrigin, branch?: GitBranch | undefined, options?: SpawnOptions | undefined): Promise<void> Calls git pull and throws if anything goes wrong.
origin'origin' as GitOriginbranch?GitBranch | undefinedoptions?SpawnOptions | undefinedPromise<void> (origin: GitOrigin, branch?: GitBranch | undefined, options?: SpawnOptions | undefined, set_upstream?: boolean): Promise<void> Calls git push and throws if anything goes wrong.
originbranch?GitBranch | undefinedoptions?SpawnOptions | undefinedset_upstreambooleanfalsePromise<void> (origin?: GitOrigin, branch?: GitBranch | undefined, options?: SpawnOptions | undefined): Promise<void> Calls git push and throws if anything goes wrong.
origin'origin' as GitOriginbranch?GitBranch | undefinedoptions?SpawnOptions | undefinedPromise<void> (origin?: GitOrigin, branch?: GitBranch | undefined, options?: SpawnOptions | undefined): Promise<boolean> origin'origin' as GitOriginbranch?GitBranch | undefinedoptions?SpawnOptions | undefinedPromise<boolean> a boolean indicating if the remote git branch exists
(origin: GitOrigin, branch: GitBranch, options?: SpawnOptions | undefined): Promise<void> Resets the target branch back to its first commit both locally and remotely.
originbranchoptions?SpawnOptions | undefinedPromise<void> (status: GitWorkspaceStatus): boolean statusboolean true if the workspace has no changes at all
(status: GitWorkspaceStatus): boolean statusboolean true if the workspace has no unstaged changes and no untracked files (staged changes are OK)
(status: GitWorkspaceStatus): string Converts a workspace status to a human-readable message.
statusstring ZodString GitInfo Basic git repository info.
commitstring | nullbranchstring | nullZodString GitWorkspaceStatus Git workspace status flags indicating which types of changes are present.
unstaged_changesbooleanstaged_changesbooleanuntracked_filesbooleanSet<ChildProcess> We register spawned processes gloabally so we can gracefully exit child processes. Otherwise, errors can cause zombie processes, sometimes blocking ports even!
1.618033988749895 golden ratio/mean constants, useful for scaling: https://wikipedia.org/wiki/Golden_ratio
2.618033988749895 golden ratio/mean constants, GR**2, useful for scaling: https://wikipedia.org/wiki/Golden_ratio
0.38196601125010515 golden ratio/mean constants, 1/(GR**2), useful for scaling: https://wikipedia.org/wiki/Golden_ratio
4.23606797749979 golden ratio/mean constants, GR**3, useful for scaling: https://wikipedia.org/wiki/Golden_ratio
0.2360679774997897 golden ratio/mean constants, 1/(GR**3), useful for scaling: https://wikipedia.org/wiki/Golden_ratio
6.854101966249686 golden ratio/mean constants, GR**4, useful for scaling: https://wikipedia.org/wiki/Golden_ratio
0.14589803375031543 golden ratio/mean constants, 1/(GR**4), useful for scaling: https://wikipedia.org/wiki/Golden_ratio
11.090169943749476 golden ratio/mean constants, GR**5, useful for scaling: https://wikipedia.org/wiki/Golden_ratio
0.09016994374947422 golden ratio/mean constants, 1/(GR**5), useful for scaling: https://wikipedia.org/wiki/Golden_ratio
17.944271909999163 golden ratio/mean constants, GR**6, useful for scaling: https://wikipedia.org/wiki/Golden_ratio
0.0557280900008412 golden ratio/mean constants, 1/(GR**6), useful for scaling: https://wikipedia.org/wiki/Golden_ratio
29.03444185374864 golden ratio/mean constants, GR**7, useful for scaling: https://wikipedia.org/wiki/Golden_ratio
0.03444185374863302 golden ratio/mean constants, 1/(GR**7), useful for scaling: https://wikipedia.org/wiki/Golden_ratio
46.978713763747805 golden ratio/mean constants, GR**8, useful for scaling: https://wikipedia.org/wiki/Golden_ratio
0.02128623625220818 golden ratio/mean constants, 1/(GR**8), useful for scaling: https://wikipedia.org/wiki/Golden_ratio
76.01315561749645 golden ratio/mean constants, GR**9, useful for scaling: https://wikipedia.org/wiki/Golden_ratio
0.013155617496424835 golden ratio/mean constants, 1/(GR**9), useful for scaling: https://wikipedia.org/wiki/Golden_ratio
0.6180339887498948 golden ratio/mean constants, 1/GR, useful for scaling: https://wikipedia.org/wiki/Golden_ratio
Green (cb: (value: any, event: any) => void, swallow_event?: boolean): (e: any) => void Handles the value of an event's target and invokes a callback. Defaults to swallowing the event to prevent default actions and propagation.
cb(value: any, event: any) => voidswallow_eventbooleantrue(e: any) => void (hex: string): Hsl hexstringHsl (hex: string): Rgb hexstringRgb (hex: number): Rgb Converts a hex color to an RGB color.
hexnumberRgb Hsl (h: Hue, s: Saturation, l: Lightness): number hslnumber (h: Hue, s: Saturation, l: Lightness): string hslstring (h: Hue, s: Saturation, l: Lightness): Rgb Converts an HSL color value to RGB. Conversion formula adapted from http://wikipedia.org/wiki/HSL_color_space. Values h/s/l are in the range [0,1] and returns r/g/b in the range [0,255].
hslRgb (h: Hue, s: Saturation, l: Lightness): string hslstring Hue (p: number, q: number, t: number): number pnumberqnumbertnumbernumber <T>(t: T): T Returns the first arg.
tTT (el: Element): boolean Returns true if the element is within a contenteditable ancestor.
elElementboolean (el: any): boolean Checks if the given element is editable.
Returns true for text-based input types, textareas, and contenteditable elements.
elanyboolean (): boolean Returns a boolean indicating if the current browser window, if any, is iframed inside of another.
boolean (el: any): boolean Checks if the element is interactive (clickable, focusable, or otherwise accepts user input).
Returns true for buttons, links, form controls,
and elements with interactive attributes and ARIA roles.
elanyboolean (value: any): boolean Returns a boolean indicating if value is
a plain object, possibly created with Object.create(null).
But warning! This fails for some obscure corner cases, use a proper library for weird things.
valueanyboolean (value: unknown): value is Promise<unknown> Checks if value is a Promise (or thenable).
valueunknownboolean (str: string): str is Uuid Loosely validates a UUID string.
strstringboolean Json <T>(data: T, stringify?: (data: T) => string): string Embeds data as a JSON string, escaping single quotes.
Useful for optimizing JSON in JS because it parses faster.
dataTstringify(data: T) => stringJSON.stringifystring (value: unknown): string Serializes a value to JSON with deterministic key ordering. Recursively sorts object keys alphabetically for consistent hashing. Arrays and primitives are serialized as-is.
valueAny JSON-serializable value
unknownstring Deterministic JSON string representation
(value: Json): JsonType | undefined Returns the JsonType of value, which is like typeof json
but includes 'array' and omits 'undefined'.
valueJsonType | undefined JsonArray Array<Json>JsonObject Record<string, Json>JsonPrimitive JsonType Like typeof json, but includes arrays. Excludes 'undefined' because it's not valid JSON.
KeyofUnion<T> Like keyof but works for type unions.
T(a: number, b: number, amount: number): number Linear interpolation between a and b by amount.
anumberbnumberamountnumbernumber (a: string, b: string): number Calculates the Levenshtein distance between two strings. Useful for typo detection and fuzzy matching.
a- First string
stringb- Second string
stringnumber The edit distance between the strings
(package_json: { [x: string]: unknown; name: string; version: string; private?: boolean | undefined; description?: string | undefined; motto?: string | undefined; glyph?: string | undefined; logo?: string | undefined; ... 23 more ...; exports?: string | ... 2 more ... | undefined; }, source_json: { ...; }): LibraryJson Creates a LibraryJson with computed properties from package.json and source metadata.
package_json{ [x: string]: unknown; name: string; version: string; private?: boolean | undefined; description?: string | undefined; motto?: string | undefined; glyph?: string | undefined; logo?: string | undefined; ... 23 more ...; exports?: string | ... 2 more ... | undefined; }source_json{ [x: string]: unknown; name: string; version: string; modules?: { [x: string]: unknown; path: string; declarations?: { [x: string]: unknown; name: string; kind: "function" | "type" | "variable" | "class" | "constructor" | "component" | "json" | "css"; ... 19 more ...; alias_of?: { ...; } | undefined; }[] | undefine...LibraryJson (library: LibraryJson): string | null Extracts GitHub org URL from a library, e.g. https://github.com/ryanatkn.
librarystring | null (name: string): string Extracts repo name from a package name, e.g. @fuzdev/fuz_ui → fuz.
namestringstring LibraryJson A library's package.json and source metadata with computed properties.
namePackage name, e.g. @fuzdev/fuz_ui.
stringrepo_nameName without scope, e.g. fuz.
stringrepo_urlGitHub repo URL, e.g. https://github.com/fuzdev/fuz_ui.
owner_nameGitHub user/org, e.g. ryanatkn.
string | nullhomepage_urlUrl | nulllogo_urlLogo URL, falls back to favicon.png.
Url | nulllogo_altstringnpm_urlUrl | nullchangelog_urlUrl | nullpublishedTrue if has exports and version is not 0.0.1.
booleanpackage_jsonsource_jsonLightness (value: string | undefined): LogLevel | undefined Parses and validates a log level string.
valueThe value to parse as a log level
string | undefinedLogLevel | undefined The validated log level, or undefined if value is undefined
Error - if value is provided but invalid(level: LogLevel): number Converts a log level to its numeric value for comparison. Higher numbers indicate more verbose logging.
levelThe log level to convert
number Numeric value (0-4)
LogConsole Console interface subset used by Logger for output. Allows custom console implementations for testing.
Simple, flexible logger with support for child loggers and automatic context.
Features: - Instance-based configuration (no global state) - Child loggers with automatic label concatenation - Parent chain inheritance for level, console, and colors - Respects NO_COLOR environment variable
labeltype string
parenttype Logger
constructorCreates a new Logger instance.
type new (label?: string | undefined, options?: LoggerOptions): Logger
label?Optional label for this logger. Can be undefined for no label, or an
empty string '' which is functionally equivalent (both produce no brackets in output).
Note: Empty strings are only allowed for root loggers - child loggers cannot have empty labels.
string | undefinedoptionsOptional configuration for level, colors, and console
{}clear_level_overrideClears the level override for this logger, restoring inheritance from parent. After calling this, the logger will dynamically inherit the level from its parent (or use the default level if it has no parent).
type (): void
voidclear_colors_overrideClears the colors override for this logger, restoring inheritance from parent. After calling this, the logger will dynamically inherit colors from its parent (or use the default colors behavior if it has no parent).
type (): void
voidclear_console_overrideClears the console override for this logger, restoring inheritance from parent. After calling this, the logger will dynamically inherit the console from its parent (or use the global console if it has no parent).
type (): void
voidchildCreates a child logger with automatic label concatenation. Children inherit parent configuration unless overridden.
type (label: string, options?: LoggerOptions): Logger
labelChild label (will be concatenated with parent label using :).
Cannot be an empty string - empty labels would result in confusing output like parent:
with a trailing colon. Use undefined or '' only for root loggers.
stringoptionsOptional configuration overrides
{}New Logger instance with concatenated label
Error - if label is an empty stringerrorLogs an error message with 🞩error🞩 prefix.
Only outputs if current level is error or higher.
type (...args: unknown[]): void
argsunknown[]voidwarnLogs a warning message with ⚑warn⚑ prefix.
Only outputs if current level is warn or higher.
type (...args: unknown[]): void
argsunknown[]voidinfoLogs an informational message.
Unlike error/warn/debug, info has no character prefix - only the label is shown.
This keeps standard output clean since info is the default log level.
Only outputs if current level is info or higher.
type (...args: unknown[]): void
argsunknown[]voiddebugLogs a debug message with ┆debug┆ prefix.
Only outputs if current level is debug.
type (...args: unknown[]): void
argsunknown[]voidrawLogs raw output without any prefix, formatting, or level filtering. Bypasses the logger's level checking, prefix formatting, and color application entirely. Useful for outputting structured data or when you need full control over formatting.
Note: This method ignores the configured log level - it always outputs regardless of whether the logger is set to 'off' or any other level.
type (...args: unknown[]): void
argsValues to log directly to console
unknown[]voidLoggerOptions levelLog level for this logger instance. Inherits from parent or defaults to 'info'.
consoleConsole interface for output. Inherits from parent or defaults to global console. Useful for testing.
colorsWhether to use colors in output. Inherits from parent or defaults to enabled (unless NO_COLOR env var is set).
booleanLogLevel Log level hierarchy from least to most verbose.
- 'off': No logging
- 'error': Only errors
- 'warn': Errors and warnings
- 'info': Errors, warnings, and info (default)
- 'debug': All messages including debug
<T, R>(items: T[], fn: (item: T, index: number) => Promise<R>, concurrency: number): Promise<R[]> Maps over items with controlled concurrency, preserving input order.
itemsarray of items to process
T[]fnasync function to apply to each item
(item: T, index: number) => Promise<R>concurrencymaximum number of concurrent operations
numberPromise<R[]> promise resolving to array of results in same order as input
<T, R>(items: T[], fn: (item: T, index: number) => Promise<R>, concurrency: number): Promise<PromiseSettledResult<R>[]> Like map_concurrent but collects all results/errors instead of failing fast.
Returns an array of settlement objects matching the Promise.allSettled pattern.
itemsarray of items to process
T[]fnasync function to apply to each item
(item: T, index: number) => Promise<R>concurrencymaximum number of concurrent operations
numberPromise<PromiseSettledResult<R>[]> promise resolving to array of PromiseSettledResult objects in input order
<T, K extends string | number, U>(obj: Record<K, T>, mapper: (value: T, key: string) => U): Record<K, U> Iterated keys in for..in are always returned as strings,
so to prevent usage errors the key type of mapper is always a string.
Symbols are not enumerable as keys, so they're excluded.
objRecord<K, T>mapper(value: T, key: string) => URecord<K, U> (): Mash Mash ZodObject<{ path: ZodString; declarations: ZodOptional<ZodArray<ZodObject<{ name: ZodString; kind: ZodEnum<{ function: "function"; type: "type"; variable: "variable"; class: "class"; constructor: "constructor"; component: "component"; json: "json"; css: "css"; }>; ... 19 more ...; alias_of: ZodOptional<...>; }, $loo... A source file in src/lib/ with its exported declarations.
(...args: any[]): any Does nothing when called.
argsany[]any (...args: any[]): Promise<any> Async function that returns a resolved promise.
argsany[]Promise<any> Readonly<{ readonly ok: false; }> Frozen object representing a failed result.
NotNull<T> TReadonly<{ readonly ok: true; }> Frozen object representing a successful result.
<T extends Record<K, any>, K extends keyof T>(obj: T, keys: K[]): OmitStrict<T, K> Creates a new object without the specified keys.
objTkeysK[]OmitStrict<T, K> <T extends Record<string | number, any>>(obj: T): T omit_undefined is a commonly used form of pick_by. See this issue for why it's used so much: https://github.com/Microsoft/TypeScript/issues/13195
objTT obj with all undefined properties removed
OmitStrict<T, K> TKkeyof TZodObject<{ name: ZodString; version: ZodString; private: ZodOptional<ZodBoolean>; description: ZodOptional<ZodString>; ... 26 more ...; exports: ZodOptional<...>; }, $loose> ZodUnion<readonly [ZodString, ZodObject<{ name: ZodString; email: ZodOptional<ZodEmail>; url: ZodOptional<ZodURL>; }, $loose>]> ZodUnion<readonly [ZodString, ZodNull, ZodRecord<ZodString, ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>>]> Package exports can be: 1. A string (shorthand for main export) 2. null (to block exports) 3. A record of export conditions/paths
ZodUnion<readonly [ZodString, ZodObject<{ type: ZodString; url: ZodURL; }, $loose>]> ZodUnion<readonly [ZodString, ZodObject<{ type: ZodString; url: ZodURL; directory: ZodOptional<ZodString>; }, $loose>]> (str: string, target_width: number, align?: "left" | "right"): string Pad a string to a target display width (accounting for wide characters).
strstringtarget_widthnumberalign"left" | "right"'left'string ZodObject<{ name: ZodString; type: ZodString; optional: ZodOptional<ZodBoolean>; description: ZodOptional<ZodString>; default_value: ZodOptional<...>; }, $loose> Parameter information for functions and methods.
Kept distinct from ComponentPropInfo despite structural similarity.
Function parameters form a tuple with positional semantics:
calling order matters (fn(a, b) vs fn(b, a)),
may include rest parameters and destructuring patterns.
(hsl: string): Hsl hslstringHsl (path: string): string[] pathstringstring[] (raw_path: string): PathPiece[] Treats all paths as absolute, so the first piece is always a '/' with type 'separator'.
raw_pathstringPathPiece[] (path: string): string[] Gets the individual parts of a path, ignoring dots and separators.
pathstringstring[] PartialExcept<T, K> TKkeyof TPartialOnly<T, K> TKkeyof TPartialValues<T> TPathFilter A filter function for paths, can distinguish between files and directories.
PathId An absolute path on the filesystem. Named "id" to be consistent with Rollup.
PathInfo Basic information about a filesystem path.
idis_directorybooleanPathPiece A piece of a parsed path, either a path segment or separator.
<T extends Record<K, any>, K extends string | number>(obj: T, should_pick: (value: any, key: K) => boolean): Partial<T> Creates a new object with properties that pass the should_pick predicate.
objTshould_pick(value: any, key: K) => booleanPartial<T> PickUnion<T, K> Like Pick but works for type unions.
TKKeyofUnion<T>(count: number | null | undefined, suffix?: string): string Returns a plural suffix based on a count.
countnumber | null | undefinedsuffixstring's'string (value: boolean): string Formats a boolean for printing.
valuebooleanstring (child: ChildProcess): string childChildProcessstring (err: Error): string Formats an error for printing.
Because throwing errors and rejecting promises isn't typesafe,
don't assume the arg is an Error and try to return something useful.
errErrorstring (key: string, value: string | number): string Formats a key-value pair for printing.
keystringvaluestring | numberstring (ms: number, decimals?: number | undefined, separator?: string | undefined): string Formats a number of milliseconds for printing.
msnumberdecimals?number | undefinedseparator?string | undefinedstring (value: number): string Formats a number for printing.
valuenumberstring (v: string, separator?: string): string Formats a number with separators for improved readability.
vstringseparatorstring','string (result: SpawnResult): string Formats a SpawnResult for printing.
resultstring (value: string): string Formats a string for printing.
valuestringstring (key: string | number, timing: number | undefined): string Formats a timing entry with key for printing.
keystring | numbertimingnumber | undefinedstring (timings: Timings, log: Logger): void Prints all timings in a Timings object.
timingslogvoid (value: unknown): string Formats any value for printing.
valueunknownstring (pid: number): boolean Check if a PID is still running.
pidnumberboolean (random?: () => number): boolean Generates a random boolean.
random() => numberMath.randomboolean (min: number, max: number, random?: () => number): number Generates a random number between min and max.
minnumbermaxnumberrandom() => numberMath.randomnumber (min: number, max: number, random?: () => number): number Returns a random integer between min and max inclusive.
Node's randomInt is similar but exclusive of the max value, and makes min optional -
https://nodejs.org/docs/latest-v20.x/api/crypto.html#cryptorandomintmin-max-callback
minnumbermaxnumberrandom() => numberMath.randomnumber <T extends ReadonlyArray<any>>(arr: T, random?: () => number): ArrayElement<T> Selects a random item from an array.
arrTrandom() => numberMath.randomArrayElement<T> Red (child: ChildProcess): () => void Returns a function that unregisters the child.
childthe child process to register
ChildProcess() => void cleanup function that removes the child from global_spawn
(array: any[], index: number): void Removes an element from array at index in an unordered manner.
arrayany[]indexnumbervoid <T extends Record<K, any>, K extends string | number>(obj: T, keys: K[]): T A more explicit form of {put_this_first: obj.put_this_first, ...obj}.
objTkeysK[]T <T extends RegExp>(regexp: T): T Reset a RegExp's lastIndex to 0 for global and sticky patterns. Ensures consistent behavior by clearing state that affects subsequent matches.
regexpTT Promise<void> A singleton resolved Promise.
ResolvedPath A resolved path with both the original path string and its absolute id.
pathstringRestartableProcess restart() => voidkill() => Promise<void>Result<TValue, TError> An alternative pattern to throwing and catching errors. Uses the type system to strongly type error return values when desired. Catching errors is then reserved for unexpected situations.
TValueobjectTErrorobjectA custom error class that's thrown by unwrap. Wraps a failed Result with an optional message, and also accepts an optional message that overrides the result's. Useful for generic handling of unwrapped results to forward custom messages and other failed result data.
ErrorDEFAULT_MESSAGEresulttype {ok: false; message?: string}
constructortype new (result: { ok: false; message?: string | undefined; }, message?: string | undefined, options?: ErrorOptions | undefined): ResultError
result{ ok: false; message?: string | undefined; }message?string | undefinedoptions?ErrorOptions | undefinedRgb (r: number, g: number, b: number): number Converts an RGB color to a hex color.
rnumbergnumberbnumbernumber (r: number, g: number, b: number): string rnumbergnumberbnumberstring (r: number, g: number, b: number): Hsl Converts an RGB color value to HSL. Conversion formula adapted from http://wikipedia.org/wiki/HSL_color_space. Values r/g/b are in the range [0,255] and returns h/s/l in the range [0,1].
rnumbergnumberbnumberHsl (n: number, decimals: number): number Rounds a number to a specified number of decimal places.
nnumberdecimalsnumbernumber Saturation (cache: Map<string, { key: string; url: string; params: any; value: any; etag: string | null; last_modified: string | null; }>): string Converts FetchValueCache to a JSON string.
cacheMap<string, { key: string; url: string; params: any; value: any; etag: string | null; last_modified: string | null; }>string <T extends Array<any>>(array: T, random?: ((min: number, max: number, random?: () => number) => number) | undefined): T Mutates array with random ordering.
arrayTrandom?((min: number, max: number, random?: () => number) => number) | undefinedT (str: string, map_special_characters?: boolean): string Converts a string into a URL-compatible slug.
strthe string to convert
stringmap_special_charactersif true, characters like ñ are converted to their ASCII equivalents, runs around 5x faster when disabled
booleantruestring <T extends Map<any, any>>(map: T, comparator?: (a: [any, any], b: [any, any]) => number): T Sorts a map by comparator, a function that compares two entries,
defaulting to using localCompare and >.
mapTcomparator(a: [any, any], b: [any, any]) => numbercompare_simple_map_entriesT ZodObject<{ name: ZodString; version: ZodString; modules: ZodOptional<ZodArray<ZodObject<{ path: ZodString; declarations: ZodOptional<ZodArray<ZodObject<{ name: ZodString; kind: ZodEnum<{ function: "function"; ... 6 more ...; css: "css"; }>; ... 19 more ...; alias_of: ZodOptional<...>; }, $loose>>>; module_comment: ... Metadata for a library's src/lib/ exports.
(command: string, args?: readonly string[] | undefined, options?: SpawnOptions | undefined): Promise<SpawnResult> A convenient promise wrapper around spawn_process
intended for commands that have an end, not long running-processes like watchers.
Any more advanced usage should use spawn_process directly for access to the child process.
args[command: string, args?: readonly string[] | undefined, options?: SpawnOptions | undefined]Promise<SpawnResult> (command: string, args?: readonly string[], options?: SpawnOptions | undefined): Promise<SpawnedOut> Similar to spawn but buffers and returns stdout and stderr as strings.
commandstringargsreadonly string[][]options?SpawnOptions | undefinedPromise<SpawnedOut> (command: string, args?: readonly string[], options?: SpawnOptions | undefined): SpawnedProcess Wraps the normal Node childProcess.spawn with graceful child shutdown behavior.
Also returns a convenient closed promise.
If you only need closed, prefer the shorthand function spawn.
commandstringargsreadonly string[][]options?SpawnOptions | undefinedSpawnedProcess (command: string, args?: readonly string[], options?: SpawnOptions | undefined): RestartableProcess Like spawn_process but with restart and kill,
handling many concurrent restart calls gracefully.
commandstringargsreadonly string[][]options?SpawnOptions | undefinedRestartableProcess Spawned childChildProcesssignalNodeJS.Signals | nullcodenumber | nullSpawnedOut resultstdoutstring | nullstderrstring | nullSpawnedProcess childChildProcessclosedPromise<SpawnResult>SpawnResult (format: ForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[], text: string, options?: StyleTextOptions | undefined): string formatForegroundColors | BackgroundColors | Modifiers | (ForegroundColors | BackgroundColors | Modifiers)[]textstringoptions?StyleTextOptions | undefinedstring (values: number[], options?: StatsConfidenceIntervalOptions | undefined): [number, number] Calculate confidence interval for the mean.
values- Array of numbers
number[]options?- Configuration options
StatsConfidenceIntervalOptions | undefined[number, number] [lower_bound, upper_bound]
(mean: number, std_dev: number, sample_size: number, options?: StatsConfidenceIntervalOptions | undefined): [number, number] Calculate confidence interval from summary statistics (mean, std_dev, sample_size). Useful when raw data is not available.
mean- Mean of the data
numberstd_dev- Standard deviation of the data
numbersample_size- Number of samples
numberoptions?- Configuration options
StatsConfidenceIntervalOptions | undefined[number, number] [lower_bound, upper_bound]
(level: number): number Convert a confidence level (0-1) to a z-score. Uses a lookup table for common values, approximates others.
levelnumbernumber Record<number, number> Common z-scores for confidence intervals.
(mean: number, std_dev: number): number Calculate the coefficient of variation (CV). CV = standard deviation / mean, expressed as a ratio. Useful for comparing relative variability between datasets.
meannumberstd_devnumbernumber (x: number, a: number, b: number): number Approximate regularized incomplete beta function for p-value calculation. Uses continued fraction expansion for reasonable accuracy.
xnumberanumberbnumbernumber (z: number): number Log gamma function approximation (Lanczos approximation).
znumbernumber (values: number[]): number Calculate the mean (average) of an array of numbers.
valuesnumber[]number (values: number[]): number Calculate the median of an array of numbers.
valuesnumber[]number (values: number[]): { min: number; max: number; } Calculate min and max values.
valuesnumber[]{ min: number; max: number; } (x: number): number Standard normal CDF approximation (Abramowitz and Stegun formula 7.1.26).
xnumbernumber (values: number[], options?: StatsOutliersIqrOptions | undefined): StatsOutlierResult Detect outliers using the IQR (Interquartile Range) method. Values outside [Q1 - multiplier*IQR, Q3 + multiplier*IQR] are considered outliers.
valuesnumber[]options?StatsOutliersIqrOptions | undefinedStatsOutlierResult (values: number[], options?: StatsOutliersMadOptions | undefined): StatsOutlierResult Detect outliers using the MAD (Median Absolute Deviation) method. More robust than IQR for skewed distributions. Uses modified Z-score: |0.6745 * (x - median) / MAD| Values with modified Z-score > threshold are considered outliers.
valuesnumber[]options?StatsOutliersMadOptions | undefinedStatsOutlierResult (values: number[], p: number): number Calculate a percentile of an array of numbers using linear interpolation. Uses the "R-7" method (default in R, NumPy, Excel) which interpolates between data points for more accurate percentile estimates, especially with smaller samples.
values- Array of numbers
number[]p- Percentile (0-1, e.g., 0.95 for 95th percentile)
numbernumber (values: number[], mean?: number | undefined): number Calculate the standard deviation of an array of numbers. Uses population standard deviation (divides by n, not n-1). For benchmarks with many samples, this is typically appropriate.
valuesnumber[]mean?number | undefinednumber (t: number, df: number): number Approximate two-tailed p-value from t-distribution. For large df (>100), uses normal approximation. For smaller df, uses incomplete beta function.
t- Absolute value of t-statistic
numberdf- Degrees of freedom
numbernumber Two-tailed p-value
(values: number[], mean?: number | undefined): number Calculate the variance of an array of numbers.
valuesnumber[]mean?number | undefinednumber (mean1: number, std1: number, n1: number, mean2: number, std2: number, n2: number): StatsWelchTTestResult Calculate Welch's t-test statistic and degrees of freedom. Welch's t-test is more robust than Student's t-test when variances are unequal.
mean1- Mean of first sample
numberstd1- Standard deviation of first sample
numbern1- Size of first sample
numbermean2- Mean of second sample
numberstd2- Standard deviation of second sample
numbern2- Size of second sample
numberStatsWelchTTestResult StatsConfidenceIntervalOptions Configuration options for confidence interval calculation.
z_scoreZ-score for confidence level (default: 1.96 for 95% CI)
numberconfidence_levelConfidence level (0-1), alternative to z_score. If both provided, z_score takes precedence.
numberStatsOutlierResult Result from outlier detection.
cleanedValues after removing outliers
Array<number>outliersDetected outlier values
Array<number>StatsOutliersIqrOptions Configuration options for IQR outlier detection.
iqr_multiplierMultiplier for IQR bounds (default: 1.5)
numbermin_sample_sizeMinimum sample size to perform outlier detection (default: 3)
numberStatsOutliersMadOptions Configuration options for MAD outlier detection.
z_score_thresholdModified Z-score threshold for outlier detection (default: 3.5)
numberz_score_extremeExtreme Z-score threshold when too many outliers detected (default: 5.0)
numbermad_constantMAD constant for normal distribution (default: 0.6745)
numberoutlier_ratio_highRatio threshold to switch to extreme mode (default: 0.3)
numberoutlier_ratio_extremeRatio threshold to switch to keep-closest mode (default: 0.4)
numberoutlier_keep_ratioRatio of values to keep in keep-closest mode (default: 0.8)
numbermin_sample_sizeMinimum sample size to perform outlier detection (default: 3)
numberiqr_optionsOptions to pass to IQR fallback when MAD is zero
StatsWelchTTestResult Result from Welch's t-test calculation.
t_statisticThe t-statistic
numberdegrees_of_freedomWelch-Satterthwaite degrees of freedom
numberStopwatch (str: string): number Calculate the display width of a string in terminal columns.
- Strips ANSI escape codes (they have 0 width)
- Emojis and other wide characters take 2 columns
- Tab characters take 4 columns
- Newlines and other control characters take 0 columns
- Uses Intl.Segmenter to properly handle grapheme clusters (e.g., family emoji "👨👩👧👦")
strstringnumber (value: unknown): string Stringifies a value like JSON.stringify but with some corner cases handled better.
valueunknownstring (source: string, stripped: string): string Removes characters inclusive of stripped.
sourcestringstrippedstringstring (str: string): string Strips ANSI escape sequences from a string
strstringstring (source: string, stripped: string): string Removes characters inclusive of stripped.
sourcestringstrippedstringstring (source: string, stripped: string): string Removes characters inclusive of stripped.
sourcestringstrippedstringstring (source: string, stripped: string): string Removes characters inclusive of stripped.
sourcestringstrippedstringstring <T extends Pick<Event, "preventDefault" | "stopPropagation" | "stopImmediatePropagation">>(event: T, immediate?: boolean, preventDefault?: boolean): T Stops an event from bubbling and doing default behavior.
eventTimmediatedefaults to true to use stopImmediatePropagation over stopPropagation
booleantruepreventDefaultdefaults to true
booleantrueT <T extends (...args: Array<any>) => Promise<void>>(cb: T, { delay, when }?: ThrottleOptions): T Throttles calls to a callback that returns a void promise.
Immediately invokes the callback on the first call unless leading=false.
If the throttled function is called while the promise is already pending,
the call is queued to run after the pending promise completes plus delay,
and only the last call is invoked.
In other words, all calls and their args are discarded
during the pending window except for the most recent.
Unlike debouncing, this calls the throttled callback
both on the leading and trailing edges of the delay window by default,
and this can be customized by setting leading or `trailing.
It also differs from a queue where every call to the throttled callback eventually runs.
cbT__1EMPTY_OBJECTT same as cb
ThrottleOptions delayEnforced milliseconds between calls. For when='trailing' this is the debounce delay.
numberwhenWhen to call the throttled function. Defaults to both.
'both' | 'leading' | 'trailing'Thunk<T> Represents a value wrapped in a function. Useful for lazy values and bridging reactive boundaries in Svelte.
T<T>(fn: () => Promise<T>, timer?: Timer): Promise<{ result: T; timing: TimeResult; }> Time an asynchronous function execution.
fn- Async function to time
() => Promise<T>timer- Timer to use (defaults to timer_default)
timer_defaultPromise<{ result: T; timing: TimeResult; }> Object containing the function result and timing information
(ns: number, unit: TimeUnit, decimals?: number): string Format time with a specific unit.
ns- Time in nanoseconds
numberunit- Unit to use ('ns', 'us', 'ms', 's')
decimals- Number of decimal places (default: 2)
number2string Formatted string like "3.87μs"
(ns: number, decimals?: number): string Format time with adaptive units (ns/μs/ms/s) based on magnitude.
ns- Time in nanoseconds
numberdecimals- Number of decimal places (default: 2)
number2string Formatted string like "3.87μs" or "1.23ms"
(fn: () => unknown, iterations: number, timer?: Timer): Promise<number[]> Measure multiple executions of a function and return all timings.
fn- Function to measure (sync or async)
() => unknowniterations- Number of times to execute
numbertimer- Timer to use (defaults to timer_default)
timer_defaultPromise<number[]> Array of elapsed times in nanoseconds
1000000 1000000000 1000 Time units and conversions.
(ns: number): number Convert nanoseconds to milliseconds.
nsnumbernumber (ns: number): number Convert nanoseconds to seconds.
nsnumbernumber (ns: number): number Convert nanoseconds to microseconds.
nsnumbernumber <T>(fn: () => T, timer?: Timer): { result: T; timing: TimeResult; } Time a synchronous function execution.
fn- Sync function to time
() => Ttimer- Timer to use (defaults to timer_default)
timer_default{ result: T; timing: TimeResult; } Object containing the function result and timing information
(values_ns: number[]): TimeUnit Detect the best time unit for a set of nanosecond values. Chooses the unit where most values fall in the range 1-9999.
values_ns- Array of times in nanoseconds
number[]TimeUnit Best unit to use for all values
Record<TimeUnit, string> Display labels for time units (uses proper Unicode μ for microseconds).
Timer Timer interface for measuring elapsed time. Returns time in nanoseconds for maximum precision.
nowGet current time in nanoseconds
() => numberTimer Browser high-resolution timer using performance.now(). Converts milliseconds to nanoseconds for consistent API.
Precision varies by browser due to Spectre/Meltdown mitigations: - Chrome: ~100μs (coarsened) - Firefox: ~1ms (rounded) - Safari: ~100μs - Node.js: ~1μs
For nanosecond-precision benchmarks, use Node.js with timer_node.
Timer Auto-detected timer based on environment. Uses process.hrtime in Node.js, performance.now() in browsers. The timer function is detected once and cached for performance.
Timer Node.js high-resolution timer using process.hrtime.bigint(). Provides true nanosecond precision.
TimeResult Result from timing a function execution. All times in nanoseconds for maximum precision.
elapsed_nsElapsed time in nanoseconds
numberelapsed_usElapsed time in microseconds (convenience)
numberelapsed_msElapsed time in milliseconds (convenience)
numberstarted_at_nsStart time in nanoseconds (from timer.now())
numberended_at_nsEnd time in nanoseconds (from timer.now())
numberTimeUnit Time unit for formatting.
Tracks and manages multiple timing operations. Allows starting, stopping, and retrieving timings with optional precision.
decimalstype number | undefined
constructortype new (decimals?: number | undefined): Timings
decimals?number | undefinedstartStarts a timing operation for the given key.
type (key: TimingsKey, decimals?: number | undefined): () => number
keydecimalsnumber | undefinedthis.decimals() => numbergettype (key: TimingsKey): number
keynumberentriestype (): IterableIterator<[TimingsKey, number | undefined]>
IterableIterator<[TimingsKey, number | undefined]>mergeMerges other timings into this one, adding together values with identical keys.
type (timings: Timings): void
timingsvoidTimingsKey <T>(value: T): T extends readonly any[] ? T : T[] Converts value to an array if it's not already.
valueTT extends readonly any[] ? T : T[] (url: string, params: any, method: string): FetchValueCacheKey urlstringparamsanymethodstringFetchValueCacheKey (path_or_url: string | URL): string Converts a URL to a file path string, or returns the string as-is.
path_or_urlstring | URLstring (v: number): string vnumberstring <T extends ReadonlyArray<any>>(array: T): () => ArrayElement<T> Returns a function that returns the next item in the array
in a linear sequence, looping back to index 0 when it reaches the end.
arrayT() => ArrayElement<T> <T>(obj: T): T | undefined objTT | undefined (obj: any, cb: (key: string, value: any, obj: any) => void): void Performs a depth-first traversal of an object's enumerable properties,
calling cb for every key and value with the current obj context.
obj- any object with enumerable properties
anycb- receives the key, value, and obj for every enumerable property on obj and its descendents
(key: string, value: any, obj: any) => voidvoid (str: string, maxLength: number, suffix?: string): string Truncates a string to a maximum length, adding a suffix if needed that defaults to ....
strstringmaxLengthnumbersuffixstring'...'string (value: never, message?: string | undefined): asserts value is never Beyond terseness, this is useful because throw is not an expression,
and therefore can't be used in places like Svelte markup without a workaround,
at least until this proposal is accepted and widely available:
https://github.com/tc39/proposal-throw-expressions
valuenevermessage?string | undefinedvoid Error for asserting unreachable code paths in TypeScript. Useful for exhaustive matching.
Errorconstructortype new (value: never, message?: string, options?: ErrorOptions | undefined): UnreachableError
valuenevermessagestring`Unreachable case: ${value}`options?ErrorOptions | undefined<T>(value: T | Thunk<T>): T Returns the result of calling value if it's a function,
otherwise it's like the identity function and passes it through.
valueT | Thunk<T>T <TValue extends { value?: unknown; }, TError extends { message?: string; }>(result: Result<TValue, TError>, message?: string | undefined): TValue["value"] A helper that says,
"hey I know this is wrapped in a Result, but I expect it to be ok,
so if it's not, I understand it will throw an error that wraps the result".
resultSome Result object.
Result<TValue, TError>message?Optional custom error message.
string | undefinedTValue["value"] The wrapped value.
<TError extends object>(result: Result<object, TError>, message?: string): { ok: false; } & TError A helper that does the opposite of unwrap, throwing if the Result is ok.
Note that while unwrap returns the wrapped value, unwrap_error returns the entire result.
resultSome Result object.
Result<object, TError>messageOptional custom error message.
string'Failed to unwrap result error'{ ok: false; } & TError The type-narrowed result.
ZodURL Uuid RegExp Postgres doesn't support the namespace prefix, so neither does Felt. For more see the UUID RFC - https://tools.ietf.org/html/rfc4122 The Ajv validator does support the namespace, hence this custom implementation.
(duration?: number): Promise<void> Waits for the given duration before resolving.
durationnumber0Promise<void>