Args CLI arguments container.
Positional arguments stored in _, named flags/options as string keys.
Produced by argv_parse or external parsers (mri, minimist, etc.).
_
Array<string>utility belt for JS
54 modules ยท 435 declarations
Args CLI arguments container.
Positional arguments stored in _, named flags/options as string keys.
Produced by argv_parse or external parsers (mri, minimist, etc.).
_Array<string>(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): ArgsAliasesResult Extracts alias mappings and canonical keys from a zod schema's metadata.
Useful for consumers building custom tooling (help generators, conflict detection, etc.). Results are cached per schema (WeakMap).
Note: Returns copies of the cached data to prevent mutation of internal cache.
schemazod object schema with optional .meta({aliases}) on fields
ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>ArgsAliasesResult <TOutput extends Record<string, ArgValue> = Args>(unparsed_args: Args, schema: ZodType<TOutput, unknown, $ZodTypeInternals<TOutput, unknown>>): ZodSafeParseResult<...> Validates parsed CLI args against a zod schema.
Handles CLI-specific concerns before validation:
1. Validates schema (cached) - returns error if alias conflicts exist
2. Expands aliases defined in schema .meta({aliases: ['v']})
3. Strips alias keys (required for strictObject schemas)
4. Validates with zod
5. After validation, syncs no- prefixed boolean flags with their base keys
Schema analysis is cached per schema (WeakMap) for performance.
unparsed_argsargs object from CLI parser (mri, minimist, etc.)
schemazod object schema with optional alias metadata
ZodType<TOutput, unknown, $ZodTypeInternals<TOutput, unknown>>ZodSafeParseResult<TOutput> z.ZodSafeParseResult with expanded/synced data on success
(args: Args, schema?: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> | undefined): string[] Serializes Args to CLI string array for subprocess forwarding.
Handles CLI conventions:
- Positionals first, then flags
- Single-char keys get single dash, multi-char get double dash
- Boolean true becomes bare flag, false is skipped
- undefined values are skipped
- no- prefixed keys skipped when base key is truthy (avoid contradiction)
- When schema provided, extracts aliases and prefers shortest form
Schema analysis is cached per schema (WeakMap) for performance.
argsschema?optional zod schema to extract aliases for short form preference
ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> | undefinedstring[] (schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): { success: true; } | { success: false; error: ZodError<unknown>; } Validates a zod schema for CLI arg usage.
Checks for: - Alias conflicts with canonical keys - Duplicate aliases across different keys
Results are cached per schema (WeakMap). Safe to call multiple times.
schemazod object schema with optional alias metadata
ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>{ success: true; } | { success: false; error: ZodError<unknown>; } validation result with success flag and optional error
ArgsAliasesResult Result of alias extraction from a schema. Includes canonical keys for downstream conflict detection.
aliasesMap<string, string>canonical_keysSet<string>ArgSchema Schema description for help text generation. Not used by args_parse/args_serialize directly - provided for consumers building CLI help output.
typestringdefaultdescriptionstring(argv: string[]): ParsedArgs Parses raw CLI argv array into an Args object.
A lightweight, dependency-free alternative to mri/minimist with compatible behavior.
Features:
- --flag โ {flag: true}
- --flag value โ {flag: 'value'} or {flag: 123} (numeric coercion)
- --flag=value โ equals syntax
- --flag= โ {flag: ''} (empty string, differs from mri which returns true)
- -f โ {f: true} (short flag)
- -f value โ {f: 'value'}
- -abc โ {a: true, b: true, c: true} (combined short flags)
- -abc value โ {a: true, b: true, c: 'value'} (last flag gets value)
- --no-flag โ {flag: false} (negation prefix)
- -- โ stops flag parsing, rest become positionals
- Positionals collected in _ array
- Repeated flags become arrays
Intentional differences from mri:
- --flag= returns '' (mri returns true)
- --flag= next returns {flag: '', _: ['next']} (mri takes next as the value)
- ---flag returns {'-flag': true} (mri strips all dashes)
- ['--flag', ''] preserves '' (mri coerces to 0)
- --__proto__ works as a normal key (mri silently fails)
The returned object uses Object.create(null) to prevent prototype pollution
and allow any key name including __proto__ and constructor.
argvraw argument array (typically process.argv.slice(2))
string[]ParsedArgs parsed Args object with guaranteed _ array (null prototype)
ArgValue Value types supported in CLI arguments.
ArrayElement<T> T<R extends object, P extends keyof R, const V extends R[P]>(obj: R, property: P, value: V): asserts obj is Extract<R, Record<P, V>> Narrows a discriminated union by a literal property value, failing the test if the value doesn't match. The assertion signature propagates the narrowed type so callers can access variant-specific fields directly.
Works with any discriminator key (kind, ok, type, _tag, etc.).
objRpropertyPvalueVvoid RobjectPkeyof RVR[P]type Shape =
| {kind: 'circle'; radius: number}
| {kind: 'square'; side: number};
const shape: Shape = get_shape();
assert_property(shape, 'kind', 'circle');
assert.strictEqual(shape.radius, 5); // `radius` now typed as `number`(fn: () => Promise<unknown>, pattern?: RegExp | undefined): Promise<Error> Asserts that fn rejects with an Error.
Optionally matches the error message against pattern.
Returns the caught Error for further assertions by the caller.
assert.fail is placed after the catch block so that assertion failures
from the test itself are not swallowed by the catch.
fnasync function expected to reject
() => Promise<unknown>pattern?optional regex to match against the error message
RegExp | undefinedPromise<Error> the caught Error
Assignable<T, K> TKkeyof Tkeyof TAsync semaphore for concurrency limiting.
With Infinity permits, acquire() always resolves immediately.
constructortype new (permits: number): AsyncSemaphore
permitsnumberError - if `permits < 0`acquiretype (): Promise<void>
Promise<void>releasetype (): void
voidAsyncStatus (options?: { 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) | undefined; graceful_timeout_ms?: number | ... 1 more ... | undefined; } | undefined): () => void Attaches an uncaughtException handler to the default registry.
options?{ 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) | undefined; graceful_timeout_ms?: number | ... 1 more...() => void ``ProcessRegistry.attach_error_handler``
Benchmark class for measuring and comparing function performance.
constructortype new (config?: BenchmarkConfig): Benchmark
config{}addAdd a benchmark task.
type (name: string, fn: () => unknown): this
nametask name or full task object
stringfnFunction to benchmark (if name is string). Return values are ignored.
() => unknownthisthis Benchmark instance for chaining
Error - if a task with the same name already exists, or if `fn` is missing when `name` is a stringaddtype (name: string, fn: () => unknown): this
namestringfn() => unknownthisaddtype (name: string, fn: () => unknown): this
namestringfn() => unknownthisremoveRemove a benchmark task by name.
type (name: string): this
namestringthisthis Benchmark instance for chaining
Error - if task with given name doesn't existrunRun all benchmark tasks.
Tasks execute in add() order. The first task runs against a colder
runtime than subsequent ones (uncompiled JS, cold caches) โ a
property of in-process benchmarking that matters more when an early
task has aggressive overrides like low warmup_iterations or
min_iterations. If first-position bias is a concern, put a
throwaway warm-up task first, or call run() twice and use the
second result set.
type (): Promise<BenchmarkResult[]>
Promise<BenchmarkResult[]>tableFormat results as an ASCII table with percentiles, min/max, and relative performance.
type (options?: BenchmarkFormatTableOptions | undefined): string
options?BenchmarkFormatTableOptions | undefinedstringmarkdownFormat 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.
type (): BenchmarkResult[]
BenchmarkResult[]shallow copy of the results array (prevents external mutation)
results_by_nameGet results as a map for convenient lookup by task name.
type (): Map<string, BenchmarkResult>
Map<string, BenchmarkResult>fresh Map of task name to benchmark result (prevents external mutation)
resetReset the benchmark results. Keeps tasks intact so benchmarks can be rerun.
type (): this
thisthis Benchmark instance for chaining
clearClear everything (results and tasks).
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.
resultsBenchmarkResult[]optionscomparison options including regression threshold and staleness warning
{}Promise<BenchmarkBaselineComparisonResult> comparison result with regressions, improvements, and unchanged tasks
const bench = new Benchmark();
bench.add('test', () => fn());
await bench.run();
const comparison = await benchmark_baseline_compare(bench.results(), {
regression_threshold: 1.05, // Only flag regressions 5% or more slower
staleness_warning_days: 7, // Warn if baseline is older than 7 days
});
if (comparison.regressions.length > 0) {
console.log('Performance regressions detected!');
for (const r of comparison.regressions) {
console.log(` ${r.name}: ${r.comparison.speedup_ratio.toFixed(2)}x slower`);
}
process.exit(1);
}benchmark_baseline.ts view source
(result: BenchmarkBaselineComparisonResult): string Format a baseline comparison result as a human-readable string.
resultcomparison result from benchmark_baseline_compare
string benchmark_baseline.ts view source
(result: BenchmarkBaselineComparisonResult, options?: { pretty?: boolean | undefined; }): string Format a baseline comparison result as JSON for programmatic consumption.
resultcomparison result from benchmark_baseline_compare
options{ pretty?: boolean | undefined; }{}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: { ...; }[]; metadata?: Record<...> | undefined; } | null> Load the current baseline from disk.
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; ... 9 more ...; budget: { ...; }; }[]; metadata?: Record<...> | undefined; } | null> the baseline, or null if not found or invalid
const baseline = await benchmark_baseline_load();
if (baseline) {
console.log(`Baseline from ${baseline.timestamp}`);
}benchmark_baseline.ts view source
(results: BenchmarkResult[], options?: BenchmarkBaselineSaveOptions): Promise<void> Save benchmark results as the current baseline.
Each entry's effective time-budget (duration_ms, warmup_iterations,
min_iterations, max_iterations) is persisted alongside the stats so a
later benchmark_baseline_compare can detect methodology drift โ a budget
mismatch between baseline and current routes the task to the
methodology_changed bucket instead of producing false regressions /
improvements. Suite-level config (timer, cooldown_ms) is *not*
persisted; keep it stable across runs in the same baseline lineage.
resultsBenchmarkResult[]options{}Promise<void> Error - if creating the baseline directory or writing the file failsconst bench = new Benchmark();
bench.add('test', () => fn());
await bench.run();
await benchmark_baseline_save(bench.results());benchmark_baseline.ts view source
(baseline: { duration_ms: number; warmup_iterations: number; min_iterations: number; max_iterations: number; async_resolved: boolean; }, current: { duration_ms: number; warmup_iterations: number; min_iterations: number; max_iterations: number; async_resolved: boolean; }): BenchmarkBudgetDiffEntry[] Compute the per-field diff between two effective budgets. Returns an empty array if budgets are identical โ the formatters use the length as a quick "methodology changed?" check without re-deriving the boolean.
baseline{ duration_ms: number; warmup_iterations: number; min_iterations: number; max_iterations: number; async_resolved: boolean; }current{ duration_ms: number; warmup_iterations: number; min_iterations: number; max_iterations: number; async_resolved: boolean; }BenchmarkBudgetDiffEntry[] benchmark_format.ts view source
(results: BenchmarkResult[], options?: BenchmarkFormatJsonOptions | undefined): string Format results as JSON.
resultsBenchmarkResult[]options?BenchmarkFormatJsonOptions | undefinedstring console.log(format_json(results));
console.log(format_json(results, {pretty: false}));
console.log(format_json(results, {include_timings: true}));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.
resultsBenchmarkResult[]baseline?optional task name to use as baseline for comparison (defaults to fastest)
string | undefinedstring Error - if `baseline` is provided but no result has that nameconsole.log(benchmark_format_markdown(results));
// | Task Name | ops/sec | p50 (ฮผs) | p75 (ฮผs) | p90 (ฮผs) | p95 (ฮผs) | p99 (ฮผs) | min (ฮผs) | max (ฮผs) | vs Best |
// |------------|------------|----------|----------|----------|----------|----------|----------|----------|----------|
// | slugify v2 | 1,237,144 | 0.81 | 0.85 | 0.89 | 0.95 | 1.20 | 0.72 | 2.45 | baseline |
// | slugify | 261,619 | 3.82 | 3.95 | 4.12 | 4.35 | 5.10 | 3.21 | 12.45 | 4.73x |benchmark_format.ts view source
(results: BenchmarkResult[], groups: BenchmarkGroup[]): string Format results as grouped Markdown tables with headers between groups.
resultsBenchmarkResult[]groupsBenchmarkGroup[]string const groups = [
{ name: 'Fast Paths', filter: (r) => r.name.includes('fast'), baseline: 'fast/reference' },
{ name: 'Slow Paths', filter: (r) => r.name.includes('slow') },
];
console.log(benchmark_format_markdown_grouped(results, groups));
// ### Fast Paths
// | Task Name | ops/sec | ... | vs fast/reference |
// |-----------|---------|-----|-------------------|
// | ... | ... | ... | ... |
//
// ### Slow Paths
// | Task Name | ops/sec | ... | vs Best |
// |-----------|---------|-----|---------|
// | ... | ... | ... | ... |benchmark_format.ts view source
(n: number, decimals?: number) => string Format a number with fixed decimal places and thousands separators.
``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.
resultsBenchmarkResult[]baseline?optional task name to use as baseline for comparison (defaults to fastest)
string | undefinedstring Error - if `baseline` is provided but no result has that nameconsole.log(benchmark_format_table(results));
// โโโโโโโโโโโโโโโฌโโโโโโโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโฌโโโโโโโโโโโ
// โ Task Name โ ops/sec โ p50 (ฮผs) โ p75 (ฮผs) โ p90 (ฮผs) โ p95 (ฮผs) โ p99 (ฮผs) โ min (ฮผs) โ max (ฮผs) โ vs Best โ
// โโโโโโโโโโโโโโโผโโโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโผโโโโโโโโโโโค
// โ slugify v2 โ 1,237,144 โ 0.81 โ 0.85 โ 0.89 โ 0.95 โ 1.20 โ 0.72 โ 2.45 โ baseline โ
// โ slugify โ 261,619 โ 3.82 โ 3.95 โ 4.12 โ 4.35 โ 5.10 โ 3.21 โ 12.45 โ 4.73x โ
// โโโโโโโโโโโโโโโดโโโโโโโโโโโโโดโโโโโโโโโโโดโโโโโโโโโโโดโโโโโโโโโโโดโโโโโโโโโโโดโโโโโโโโโโโดโโโโโโโโโโโดโโโโโโโโโโโดโโโโโโโโโโโbenchmark_format.ts view source
(results: BenchmarkResult[], groups: BenchmarkGroup[]): string Format results as a grouped table with visual separators between groups.
resultsBenchmarkResult[]groupsBenchmarkGroup[]string const groups = [
{ name: 'FAST PATHS', filter: (r) => r.name.includes('fast') },
{ name: 'SLOW PATHS', filter: (r) => r.name.includes('slow') },
];
console.log(benchmark_format_table_grouped(results, groups));
// ๐ฆ FAST PATHS
// โโโโโโฌโโโโโโโโโโโโโโฌโโโโโโโโโโโโโฌ...โ
// โ ๐ โ fast test 1 โ 1,237,144 โ...โ
// โ ๐ โ fast test 2 โ 261,619 โ...โ
// โโโโโโดโโโโโโโโโโโโโโดโโโโโโโโโโโโโด...โ
//
// ๐ฆ SLOW PATHS
// โโโโโโฌโโโโโโโโโโโโโโฌโโโโโโโโโโโโโฌ...โ
// โ ๐ข โ slow test 1 โ 10,123 โ...โ
// โโโโโโดโโโโโโโโโโโโโโดโโโโโโโโโโโโโด...โbenchmark_stats.ts view source
(a: BenchmarkStatsComparable, b: BenchmarkStatsComparable, options?: BenchmarkCompareOptions | undefined): BenchmarkComparison Compare two benchmark results for practical and statistical significance. Uses percentage difference for effect magnitude classification, with Welch's t-test for statistical confidence. Cohen's d is computed as an informational metric but does not drive classification โ its thresholds (0.2/0.5/0.8) are calibrated for social science and produce false positives in benchmarking where within-run variance is tight.
afirst benchmark stats (or any object with required properties)
bsecond benchmark stats (or any object with required properties)
options?BenchmarkCompareOptions | undefinedBenchmarkComparison comparison result with significance, effect size, and recommendation
const comparison = benchmark_stats_compare(result_a.stats, result_b.stats);
if (comparison.significant) {
console.log(`${comparison.faster} is ${comparison.speedup_ratio.toFixed(2)}x faster`);
}(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.
When no async_hint is provided, at least one detection iteration runs even
if iterations is 0 โ otherwise async detection would be impossible and
async functions would have their returned promises leaked as unhandled.
fnfunction to warmup (sync or async)
() => unknowniterationsnumberasync_hint?if provided, use this instead of detecting
boolean | undefinedPromise<boolean> whether the function is async
const is_async = await benchmark_warmup(() => expensive_operation(), 10);benchmark_baseline.ts view source
ZodObject<{ version: ZodNumber; timestamp: ZodString; git_commit: ZodNullable<ZodString>; git_branch: ZodNullable<ZodString>; node_version: ZodString; entries: ZodArray<...>; metadata: ZodOptional<...>; }, $strip> Schema for the complete baseline file.
metadata is an opt-in passthrough bag for context that applies to the whole
run but isn't part of the comparison math โ corpus identity (file counts,
total bytes), dependency versions, binary sizes, hardware notes, build flags.
Pass it on save and read it back on load; it's not interpreted by
benchmark_baseline_compare. The intended use is to let consumers attach
"did this run measure the same thing as the baseline?" context (e.g. corpus
shape) without forking the schema, then surface mismatches in their own
reporting. fuz_util doesn't surface metadata in comparison output because it
has no shape โ consumers know what their metadata means and how to display
the diff.
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)
numbermin_percent_differenceMinimum percentage difference to consider meaningful, as a ratio. Passed through to benchmark_stats_compare. See BenchmarkCompareOptions. Default: 0.10 (10%)
numbernoise_warning_cv_thresholdCoefficient of variation (std_dev / mean) at or above which a
comparison is flagged with noise_warning: true. Doesn't affect
bucketing โ the task still routes to regressions / improvements /
unchanged as the Welch math dictates โ but tells the formatter (and
any custom consumer) that the underlying measurement is noisy enough
that a "significant" call should be read with skepticism. The default
is calibrated for system-noise/thermal/background-load contamination,
not microbenchmark floor effects; lower it (e.g. 0.15) for
sub-microsecond functions where any cv signal matters, raise it for
inherently noisy workloads where 0.3 fires on every run.
Default: 0.30
numbernoise_warning_outlier_ratio_thresholdOutlier ratio (fraction of iterations rejected by MAD outlier removal)
at or above which the comparison is flagged with noise_warning: true,
OR-gated with the cv check. Catches the case where the post-cleaning
cv looks tight because outlier removal already deflated the spread โ
a third of the iterations being tail events is itself a noise signal,
even if the surviving samples cluster cleanly. Set higher (e.g. 0.2)
for benchmarks where outliers are expected (allocator-bound, async
I/O), lower (e.g. 0.05) for tight CPU loops.
Default: 0.10
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
booleanbaseline_node_versionNode.js version recorded in the baseline (null if no baseline).
string | nullcurrent_node_versionNode.js version of the process that produced the current results.
stringnode_version_changedTrue if the baseline's node version differs from the current process. Informational only โ surfaced in the comparison header so readers can apply the caveat across all task comparisons; does not affect per-task classification (Node bumps affect every task uniformly).
booleanbaseline_metadataThe metadata bag persisted in the baseline file, or null if the
baseline didn't have one (or no baseline was found). Returned verbatim โ
fuz_util doesn't validate the shape or diff it against any "current run"
metadata. If the consumer needs a diff, they pass options.metadata
(current-run context) and walk the two records themselves.
Record<string, unknown> | nullcomparisonsIndividual task comparisons for tasks where Welch's math is meaningful โ
i.e., budget unchanged between baseline and current. Methodology-changed
tasks are NOT in here; they live in methodology_changed. Excluding them
here keeps aggregate reads of c.comparison.faster /
c.comparison.speedup_ratio / c.comparison.recommendation safe โ those
fields are still computed for methodology-changed rows but answer a
counterfactual question (the math is correct over mismatched sample
sizes) and would mislead consumers iterating this array.
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>methodology_changedTasks whose effective budget differs between baseline and current. Excluded from regressions/improvements/unchanged because the Welch comparison is contaminated by sample-size or warmup differences โ the math is correct but answers a different question than the reader thinks. Re-save the baseline after intentional methodology changes to surface any genuine drift that was masked.
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; ... 7 more ...; budget: ZodObject<...>; }, $strip> Schema for a single benchmark entry in the baseline.
outlier_ratio is persisted as a noise signal independent of the
post-cleaning std_dev_ns/cv: outlier removal *deflates* std_dev (the
cleaned set is by construction less variable than the raw set), so cv
alone misses runs where a third of the iterations were tail events.
benchmark_baseline_compare OR-gates noise_warning on this field so
a noisy raw distribution gets flagged even when the cleaned cv looks tight.
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 | nullmetadataOpt-in passthrough for run-level context (corpus identity, dependency
versions, binary sizes, hardware notes). Round-trips on _load and is
accessible via BenchmarkBaselineComparisonResult.baseline_metadata, but
is *not* interpreted by _compare โ consumers decide what to do with
mismatches. Keep values JSON-serializable; this is written verbatim to
the baseline file.
Record<string, unknown>benchmark_baseline.ts view source
BenchmarkBaselineTaskComparison Comparison result for a single task.
namestringbaselinecurrentcomparisonWelch comparison of baseline vs. current means.
When the row is in methodology_changed, every field of this object
is contaminated by sample-size or warmup differences โ not just
recommendation. The Welch math runs end-to-end and populates faster,
speedup_ratio, significant, p_value, percent_difference,
effect_size, effect_magnitude, ci_overlap, and recommendation,
but it's comparing distributions produced under different methodologies.
Treat the result as diagnostic ("how dramatic is the contamination?"),
not authoritative.
The built-in formatters (benchmark_baseline_format,
benchmark_baseline_format_json) never render comparison.* for
methodology-changed rows for this reason โ they show only the budget
diff. Custom consumers reading this field directly should check
methodology_changed first.
methodology_changedTrue if the effective time budget differs between baseline and current.
When set, the task is routed to methodology_changed instead of
regressions/improvements/unchanged, and the comparison field's contents
become unreliable per the doc above.
booleannoise_warningTrue when measurement noise is high enough to undermine the
significance call on this row. OR-gated across two signals:
- max(baseline.cv, current.cv) >= noise_warning_cv_threshold
where cv = std_dev_ns / mean_ns (post-outlier-removal).
- `max(baseline.outlier_ratio, current.outlier_ratio)
>= noise_warning_outlier_ratio_threshold`, since outlier removal
deflates cv โ a high outlier ratio is itself a noise signal even
when the cleaned cv looks tight.
Independent of methodology_changed. The Welch math still ran; this
flag tells the reader to take comparison.significant with skepticism
on this row. Cv is recomputed at comparison time from persisted
mean_ns/std_dev_ns; outlier_ratio is persisted directly.
booleanmax_cvThe larger of the two coefficients of variation across baseline and
current, exposed so consumers can render the actual noise level.
Recomputed at comparison time from persisted mean_ns and
std_dev_ns โ not a persisted field.
numbermax_outlier_ratioThe larger of the two outlier ratios across baseline and current.
Read directly from the persisted entries. Exposed so consumers can
render the actual outlier rate alongside noise_warning.
numberbenchmark_types.ts view source
BenchmarkBudget Effective time-budget config used to produce a benchmark sample set. Resolved from per-task overrides on top of suite defaults โ what the measurement loop actually saw, not what was configured.
async_resolved captures the boolean that benchmark_warmup actually
returned for the measurement run โ *not* the user's task.async hint.
The two diverge when (a) the hint is undefined and the function is
auto-detected sync vs. async, or (b) a conditional-async fn resolves
differently between runs. Persisting the resolved value is what makes
the budget describe "what the loop saw," not "what was configured."
duration_msnumberwarmup_iterationsnumbermin_iterationsnumbermax_iterationsnumberasync_resolvedbooleanbenchmark_baseline.ts view source
BenchmarkBudgetDiffEntry Per-field diff entry produced by benchmark_budget_diff. The async_resolved
entry carries booleans; every other entry carries numbers. Consumers reading
baseline/current should narrow on field before using the value
arithmetically.
benchmark_stats.ts view source
BenchmarkCompareOptions Options for benchmark comparison.
alphaSignificance level for hypothesis testing (default: 0.05)
numbermin_percent_differenceMinimum percentage difference to consider practically meaningful, as a ratio.
Below this threshold, differences are classified as 'negligible' and
significant is forced to false, regardless of p-value.
This prevents the t-test's oversensitivity at large sample sizes from
flagging system-level noise (thermal throttle, OS scheduler, cache pressure)
as meaningful differences.
Effect magnitude thresholds scale from this value: negligible < min, small < min*3, medium < min*5, large >= min*5.
Default: 0.10 (10%).
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 both statistically and practically significant
booleanp_valueP-value from Welch's t-test (lower = more confident the difference is real)
numberpercent_differencePercentage difference between means as a ratio (0.05 = 5%, 1.0 = 100%)
numbereffect_sizeCohen's d effect size (informational โ not used for classification)
numbereffect_magnitudeInterpretation of practical significance based on percentage difference
ci_overlapWhether the 95% confidence intervals of the two means overlap.
Informational only โ do not use this field to infer significance.
Two means with overlapping 95% CIs can still differ significantly at
p<0.05 (overlap of up to ~25% of CI width is consistent with
significance); conversely, non-overlapping CIs are slightly *stronger*
than the standard p<0.05 bar but the relationship is not strict.
Use significant and p_value for classification. This field is
exposed for consumers who want to render CIs side-by-side and need
the visual overlap check.
Note: the underlying CIs are computed with a z-score (1.96) rather
than the strict t-score, so at small n the CIs are slightly narrow
โ overlap is reported less often than a t-based CI would. Effect is
~2-3% at the n=30 floor after Bessel's correction on std_dev_ns.
booleanrecommendationHuman-readable interpretation of the comparison
stringbenchmark_types.ts view source
BenchmarkConfig Configuration options for a benchmark suite.
duration_msTarget measurement duration per task in milliseconds. The loop runs
at least min_iterations iterations *and* at least this long, with
max_iterations and on_iteration abort() as hard ceilings.
Default: 1000ms
numberwarmup_iterationsNumber of warmup iterations before actual measurements. Warmup helps stabilize JIT compilation and caches. Default: 10
numbercooldown_msCooldown time between tasks in milliseconds. Lets the runtime settle GC and (partially) thermal state between tasks. Fixed regardless of the previous task's duration or allocation footprint โ if a suite mixes heavy and light tasks, raise this so light tasks downstream don't run in the prior task's GC shadow. Default: 100ms
numbermin_iterationsMinimum number of iterations to run. The loop continues past
duration_ms if needed to reach this floor, so raising it in a slow
suite extends wall-clock past duration_ms.
The default (30) is sized so the Welch's-t DOF approximation used by
benchmark_stats_compare stays stable on the floor case. Lowering it
below ~15 produces statistically unreliable significance calls on slow
tasks that hit the floor exactly โ the math still runs but
comparison.significant becomes a coin flip on noisy outliers.
Default: 30
numbermax_iterationsMaximum number of iterations to run. Prevents infinite loops on extremely fast functions, and also sizes the pre-allocated timings array โ set this only as high as you expect to fill, since oversized caps waste memory and add GC pressure during measurement. 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 wall-clock time for the task (setup + warmup + measurement + teardown) in milliseconds
numbertimings_nsRaw timing data for each iteration in nanoseconds.
Length equals iterations (the array is right-sized after measurement).
Useful for custom statistical analysis, histogram generation,
or exporting to external tools.
Array<number>budgetEffective per-task time budget after applying overrides to suite defaults.
Persisted into baselines so benchmark_baseline_compare can detect
methodology drift โ a min_iterations bump between baseline and current
shifts Welch's DOF and produces "regressions" that are sample-size
artifacts, not real drift.
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.
The time-budget fields (duration_ms, warmup_iterations, min_iterations,
max_iterations) override the suite-level BenchmarkConfig for this task
only. Use them when one task is much faster or slower than the others โ
e.g. raise min_iterations on a slow task so its percentile/CI math has
enough samples without inflating the budget for the fast tasks.
Reading output across overrides: when per-task overrides diverge
across rows in the same table, cross-row comparison weakens. Percentiles
(p50, p99, โฆ) become unreliable when sample counts differ โ p99 at
n=30 and p99 at n=50000 estimate different things. Means (and the
vs Best column) stay reasonable only if warmup_iterations is held
comparable across tasks; asymmetric warmup biases the under-warmed task's
mean upward. Per-task percentiles remain valid for that task alone.
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.
Mutations to fn and name made here are honored by the measurement
loop โ useful for dynamic configuration that depends on async state
resolved during setup.
() => 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. Auto-detected during
warmup if not set; async: false skips per-iteration promise checking
for sync functions, while async: true forces an await on every
measurement iteration.
Setting async: true on a function that returns sync forces an
unnecessary microtask per iteration โ for sub-microsecond functions
this adds measurable bias. Prefer leaving async undefined (auto-
detected during warmup) unless the conditional-async hazard below
applies.
Required for conditional-async fns โ without async: true, a
first call that happens to return synchronously locks in the sync
code path and any later Promise returns leak as unhandled rejections.
booleanduration_msOverride the suite's duration_ms for this task only.
Useful when one task is much slower than others and needs a longer (or shorter)
measurement window than the suite default.
numberwarmup_iterationsOverride the suite's warmup_iterations for this task only.
Slow tasks may want fewer warmup iterations to keep wall-clock reasonable;
tight/complex functions may want more so TurboFan reaches steady state.
numbermin_iterationsOverride the suite's min_iterations for this task only.
Raise this on slow tasks so percentile and CI math have enough
samples. Wins over duration_ms (see the suite field) โ a slow task
with a raised floor extends wall-clock until the count is reached.
Prefer raising this over duration_ms when you need more samples:
per-iteration noise (GC, scheduler, thermal) is a time-rate process,
so a longer wall-clock window proportionally inflates exposure to
rare tail events. Raising the sample floor fixes the statistical-power
problem without that inflation.
numbermax_iterationsOverride the suite's max_iterations for this task only.
Cap a fast task to a fixed sample count, or raise the ceiling on a
slow task that would otherwise be limited by the suite default. Also
sizes the per-task pre-allocation โ avoid extreme caps that won't
actually be filled. When this differs sharply across tasks in the
same suite, the larger allocation can leak GC pressure into
subsequent tasks (cooldown_ms is fixed regardless of prior task
footprint).
numberPromise<void> Resolves when the BLAKE3 WASM module is initialized and ready. Initialization starts eagerly on import. Idempotent โ safe to await multiple times. In Node.js/Deno (sync init), this resolves immediately.
ZodString Zod schema for a BLAKE3 hex hash โ 64 lowercase hex characters (256-bit output).
Blue Brand<T> TBranded<TValue, TName> TValueTNamesvelte_preprocess_helpers.ts view source
(ast: Root): Map<string, string> Builds a map of statically resolvable const bindings from a Svelte AST.
Scans top-level const variable declarations in both instance and module scripts.
For each declarator with a plain Identifier pattern and a statically evaluable
initializer, adds the binding to the map. Processes declarations in source order
so that chained references resolve: const a = 'x'; const b = a; maps b to 'x'.
Skips destructuring patterns, let/var declarations, and declarations
whose initializers reference dynamic values.
astthe parsed Svelte AST root node
RootMap<string, string> map of variable names to their resolved static string values
(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>; ... 6 more ...; since: 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.
svelte_preprocess_helpers.ts view source
ConditionalChainBranch A single branch in a conditional chain extracted from nested ternary expressions.
test_sourceThe source text of the test expression, or null for the final else branch.
string | nullvalueThe resolved static string value for this branch.
string(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 an object with a promise and its resolve/reject handlers.
Deferred<T> (): MockLogger Creates a mock Logger with vi.fn() on each logging method
and tracking arrays for inspecting logged messages.
Follows the fuz-stack convention of plain object mocks over mocking libraries.
MockLogger (...seed: unknown[]): RandomAlea Seeded pseudo-random number generator. DO NOT USE when security matters, use webcrypto APIs instead.
seedunknown[]RandomAlea (seed?: number | undefined): RandomXoshiro Seeded pseudo-random number generator using the Xoshiro128** algorithm. DO NOT USE when security matters, use webcrypto APIs instead.
seed?number | undefinedRandomXoshiro (decimals?: number): Stopwatch Tracks elapsed time in milliseconds.
decimalsnumber2Stopwatch (): string & $brand<"Uuid"> string & $brand<"Uuid"> CreateCounter DagNode Minimum shape for a DAG node.
idstringdepends_onArray<string>DagNodeResult Result for a single node.
idstringstatus'completed' | 'failed' | 'skipped'errorstringduration_msnumberDagOptions<T> Options for running a DAG.
TnodesNodes to execute.
Array<T>executeExecute a node. Throw on failure.
(node: T) => Promise<void>on_errorCalled after a node fails. For observability โ the error is already recorded.
(node: T, error: Error) => Promise<void>on_skipCalled when a node is skipped (pre-skip or dependency failure).
(node: T, reason: string) => Promise<void>should_skipReturn true to skip a node without executing. Dependents still proceed.
(node: T) => booleanmax_concurrencyMaximum concurrent executions. Default: Infinity.
numberstop_on_failureStop starting new nodes on first failure. Default: true.
booleanskip_validationSkip internal graph validation (caller already validated).
booleanDagResult Result of a DAG execution.
successWhether all executed nodes succeeded.
booleanresultsPer-node results.
Map<string, DagNodeResult>completedNumber of nodes that completed successfully.
numberfailedNumber of nodes that failed.
numberskippedNumber of nodes that were skipped.
numberduration_msTotal execution time in milliseconds.
numbererrorError message if any nodes failed.
string$ZodBranded<ZodISODateTime, "Datetime", "out"> ZodDefault<$ZodBranded<ZodISODateTime, "Datetime", "out">> โ ๏ธ deprecated: Use `generateImport` from `@fuzdev/svelte-docinfo/types.js` instead.
(declaration: { [x: string]: unknown; name: string; kind: "function" | "type" | "variable" | "class" | "constructor" | "component" | "json" | "css"; doc_comment?: string | undefined; type_signature?: string | undefined; ... 18 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; ... 18 more ...; alias_of?: { ...; } | undefined; }module_pathstringlibrary_namestringstring declaration_generate_import({name: 'Foo', kind: 'type'}, 'foo.ts', '@pkg/lib')
// => "import type {Foo} from '@pkg/lib/foo.js';"โ ๏ธ deprecated: Use `getDisplayName` from `@fuzdev/svelte-docinfo/types.js` instead.
(declaration: { [x: string]: unknown; name: string; kind: "function" | "type" | "variable" | "class" | "constructor" | "component" | "json" | "css"; doc_comment?: string | undefined; type_signature?: string | undefined; ... 18 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; ... 18 more ...; alias_of?: { ...; } | undefined; }string declaration_get_display_name({name: 'Map', kind: 'type', generic_params: [{name: 'K'}, {name: 'V'}]})
// => 'Map<K, V>'ZodObject<{ name: ZodString; kind: ZodEnum<{ function: "function"; type: "type"; variable: "variable"; class: "class"; constructor: "constructor"; component: "component"; json: "json"; css: "css"; }>; ... 20 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 + enumerable own properties)
- Promises always return false (cannot be meaningfully compared)
- Maps/Sets compare by reference for object keys/values
aunknownbunknownboolean true if deeply equal, false otherwise
Deferred<T> 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, options?: DespawnOptions | undefined): Promise<SpawnResult> Kills a child process and returns the result.
childChildProcessoptions?DespawnOptions | undefinedPromise<SpawnResult> const result = await despawn(child, {timeout_ms: 5000});
// If process ignores SIGTERM, SIGKILL sent after 5s(options?: DespawnOptions | undefined): Promise<SpawnResult[]> Kills all processes in the default registry.
options?DespawnOptions | undefinedPromise<SpawnResult[]> DespawnOptions Options for killing processes.
signalSignal to send.
NodeJS.Signalstimeout_msTimeout in ms before escalating to SIGKILL. Must be non-negative. Useful for processes that may ignore SIGTERM. A value of 0 triggers immediate SIGKILL escalation.
number(a: string, b: string): DiffLine[] Generate a line-based diff between two strings using LCS algorithm.
athe original/current content
stringbthe new/desired content
stringDiffLine[] DiffLine Line diff result
type'same' | 'add' | 'remove'linestring<T>(items: Iterable<T>, concurrency: number, fn: (item: T, index: number) => void | Promise<void>, signal?: AbortSignal | undefined): Promise<...> Runs a function on each item with controlled concurrency. Like map_concurrent but doesn't collect results (more efficient for side effects).
itemsIterable<T>concurrencymaximum number of concurrent operations
numberfn(item: T, index: number) => void | Promise<void>signal?optional AbortSignal to cancel processing
AbortSignal | undefinedPromise<void> Error - if `concurrency < 1`await each_concurrent(
file_paths,
5, // max 5 concurrent deletions
async (path) => { await unlink(path); },
);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 (value: string): string Escapes a string for use inside a single-quoted JS string literal.
Uses a single-pass regex replacement to escape backslashes, single quotes, newlines, carriage returns, and Unicode line/paragraph separators.
valuestringstring (str: string): string Escapes a string for literal matching in a RegExp.
strstringstring svelte_preprocess_helpers.ts view source
(text: string): string Escapes text for safe embedding in Svelte template markup.
Uses a single-pass regex replacement to avoid corruption that occurs with sequential
.replace() calls (where the second replace matches characters introduced by the first).
Escapes four characters:
- { โ {'{'} and } โ {'}'} โ prevents Svelte expression interpretation
- < โ < โ prevents HTML/Svelte tag interpretation
- & โ & โ prevents HTML entity interpretation
The & escaping is necessary because runtime MdzNodeView.svelte renders text
with {node.content} (a Svelte expression), which auto-escapes & to &.
The preprocessor emits raw template text where & is NOT auto-escaped, so
manual escaping is required to match the runtime behavior.
textstringstring svelte_preprocess_helpers.ts view source
(expr: Expression, bindings?: ReadonlyMap<string, string> | undefined): string | null Recursively evaluates an expression AST node to a static string value.
Handles string Literal, TemplateLiteral (including interpolations when all
expressions resolve), BinaryExpression with +, and Identifier lookup
via an optional bindings map built by build_static_bindings.
Returns null for dynamic expressions, non-string literals, or unsupported node types.
expran ESTree expression AST node
Expressionbindings?optional map of variable names to their resolved static string values
ReadonlyMap<string, string> | undefinedstring | null the resolved static string, or null if the expression is dynamic
ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> svelte_preprocess_helpers.ts view source
(value: true | ExpressionTag | (ExpressionTag | Text)[], bindings?: ReadonlyMap<string, string> | undefined): string | null Extracts a static string value from a Svelte attribute value AST node.
Handles three forms:
- Boolean true (bare attribute like inline) -- returns null.
- Array with a single Text node (quoted attribute like content="text") --
returns the text data.
- ExpressionTag (expression like content={'text'}) -- delegates to evaluate_static_expr.
Returns null for null literals, mixed arrays, dynamic expressions, and non-string values.
valuethe attribute value from AST.Attribute['value']
true | ExpressionTag | (ExpressionTag | Text)[]bindings?optional map of variable names to their resolved static string values
ReadonlyMap<string, string> | undefinedstring | null the resolved static string, or null if the value is dynamic
<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 happening 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.
(diff: DiffLine[], context_lines?: number): DiffLine[] Filter diff to only include lines within N lines of context around changes.
diffDiffLine[]context_linesnumber of context lines to show around changes (default: 3)
number3DiffLine[] filtered diff with ellipsis markers for skipped regions
svelte_preprocess_helpers.ts view source
(node: Component, name: string): Attribute | undefined Finds an attribute by name on a component AST node.
Iterates the node's attributes array and returns the first Attribute
node whose name matches. Skips SpreadAttribute, directive, and other node types.
nodeComponentnamestringAttribute | undefined the matching Attribute node, or undefined if not found
svelte_preprocess_helpers.ts view source
(script: Script): number Finds the position to insert new import statements within a script block.
Returns the end position of the last ImportDeclaration, or the start
of the script body content if no imports exist.
scriptScriptnumber 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): string Formats a byte count as a human-readable string.
nnumberstring formatted string like '1.2 KB' or '3.4 MB'
(diff: DiffLine[], current_path: string, desired_path: string, options?: FormatDiffOptions): string Format a diff for display.
diffDiffLine[]current_pathpath label for "current" content
stringdesired_pathpath label for "desired" content
stringoptions{}string (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 FormatDiffOptions Format options for diff output.
prefixPrefix for each line (for indentation in plan output).
stringuse_colorWhether to use ANSI colors.
booleanmax_linesMaximum number of diff lines to show (0 = unlimited).
number(hex: string): Uint8Array<ArrayBufferLike> | null Decodes a hex string to a Uint8Array.
Whitespace is stripped before parsing. Returns null for invalid hex.
hexhex string to decode (case-insensitive, whitespace allowed)
stringUint8Array<ArrayBufferLike> | null decoded bytes, or null if the input is not valid hex
(error: unknown): FsError Classifies a thrown filesystem error into a discriminated FsError.
Reads the Node code property (ENOENT/EACCES/EPERM/EEXIST) โ Deno
surfaces the same codes when throwing from node:fs/promises. Unknown codes
fall through to io_error.
errorunknownFsError (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[]> FsError Discriminated filesystem error kinds.
The shared error shape for Result<{value: T}, FsError>-returning filesystem
deps across the ecosystem. Callers branch on kind instead of regex-matching
message. The set is deliberately small โ add kinds only when a caller
needs to distinguish them.
FsJsonError Extends FsError with invalid_json for read_json-style ops where the
file exists but parse fails. Callers can distinguish missing from corrupt
(e.g. self-healing config loads) without regex-matching message.
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 | null(current: string, desired: string, path: string, options?: FormatDiffOptions): string | null Generate a formatted diff between two strings.
Combines diff_lines, filter_diff_context, and format_diff for convenience. Returns null if content is binary.
currentstringdesiredstringpathfile path for labels
stringoptions{}string | null svelte_preprocess_helpers.ts view source
(imports: Map<string, PreprocessImportInfo>, indent?: string): string Generates indented import statement lines from an import map.
Default imports produce import Name from 'path'; lines.
Named imports are grouped by path into import {a, b} from 'path'; lines.
importsmap of local names to their import info
Map<string, PreprocessImportInfo>indentindentation prefix for each line
string'\t'string a string of newline-separated import statements
ZodObject<{ name: ZodString; constraint: ZodOptional<ZodString>; default_type: ZodOptional<ZodString>; }, $loose> Generic type parameter information.
(): string & $brand<"Datetime"> Returns an ISO 8601 datetime string for the current time.
string & $brand<"Datetime"> (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> (branch: GitBranch, options?: SpawnOptions | undefined): Promise<GitBranch | null> Calls git checkout.
branchoptions?SpawnOptions | undefinedPromise<GitBranch | null> the previous branch name, if it changed
Error - if the underlying git command fails(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.
options?SpawnOptions | undefinedPromise<string> Error - if the underlying git command fails(options?: SpawnOptions | undefined): Promise<GitBranch> Returns the current git branch name.
options?SpawnOptions | undefinedPromise<GitBranch> Error - if the underlying git command fails(branch?: string | undefined, options?: SpawnOptions | undefined): Promise<string | null> Returns the branch's latest commit hash.
branch?string | undefinedoptions?SpawnOptions | undefinedPromise<string | null> Error - if the underlying git command fails(branch: GitBranch, options?: SpawnOptions | undefined): Promise<void> Deletes a branch locally.
branchoptions?SpawnOptions | undefinedPromise<void> Error - if the underlying git command fails(origin: GitOrigin, branch: GitBranch, options?: SpawnOptions | undefined): Promise<void> Deletes a branch remotely.
originbranchoptions?SpawnOptions | undefinedPromise<void> Error - if the underlying git command fails(origin?: GitOrigin, branch?: GitBranch | undefined, options?: SpawnOptions | undefined): Promise<void> Calls git fetch.
origin'origin' as GitOriginbranch?GitBranch | undefinedoptions?SpawnOptions | undefinedPromise<void> Error - if the underlying git command fails(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> Checks if a local git branch exists.
branchoptions?SpawnOptions | undefinedPromise<boolean> (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.
stdoutthe raw output from git status --porcelain -z
string | nullGitWorkspaceStatus (origin?: GitOrigin, branch?: GitBranch | undefined, options?: SpawnOptions | undefined): Promise<void> Calls git pull.
origin'origin' as GitOriginbranch?GitBranch | undefinedoptions?SpawnOptions | undefinedPromise<void> Error - if the underlying git command fails(origin: GitOrigin, branch?: GitBranch | undefined, options?: SpawnOptions | undefined, set_upstream?: boolean): Promise<void> Calls git push.
originbranch?GitBranch | undefinedoptions?SpawnOptions | undefinedset_upstreambooleanfalsePromise<void> Error - if the underlying git command fails(origin?: GitOrigin, branch?: GitBranch | undefined, options?: SpawnOptions | undefined): Promise<void> Calls git push, setting upstream if the remote branch does not yet exist.
origin'origin' as GitOriginbranch?GitBranch | undefinedoptions?SpawnOptions | undefinedPromise<void> Error - if the underlying git command fails(origin?: GitOrigin, branch?: GitBranch | undefined, options?: SpawnOptions | undefined): Promise<boolean> Checks if a remote git branch exists.
origin'origin' as GitOriginbranch?GitBranch | undefinedoptions?SpawnOptions | undefinedPromise<boolean> Error - if the `git ls-remote` command fails for a reason other than the branch not existing(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_filesboolean1.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 svelte_preprocess_helpers.ts view source
(error: unknown, prefix: string, filename: string | undefined, on_error: "log" | "throw"): void Handles errors during Svelte preprocessing with configurable behavior.
errorunknownprefixlog prefix (e.g. '[fuz-mdz]', '[fuz-code]')
stringfilenamestring | undefinedon_error'throw' to re-throw as a new Error, 'log' to console.error
"log" | "throw"void Error - wrapping `error` (with original as `cause`) when `on_error` is `'throw'`(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 svelte_preprocess_helpers.ts view source
(node: unknown, name: string, skip?: Set<unknown> | undefined): boolean Checks if an identifier with the given name appears anywhere in an AST subtree.
Recursively walks all object and array properties of the tree, matching
ESTree Identifier nodes ({type: 'Identifier', name}). Nodes in the
skip set are excluded from traversal โ used to skip ImportDeclaration
nodes so the import's own specifier identifier doesn't false-positive.
Skips Identifier nodes in non-reference positions defined by
NON_REFERENCE_FIELDS โ for example, obj.Mdz (non-computed member property),
{ Mdz: value } (non-computed object key), and statement labels.
Safe for Svelte template ASTs: Component.name is a plain string property
(not an Identifier node), so <Mdz> tags do not produce false matches.
nodethe AST subtree to search
unknownnamethe identifier name to look for
stringskip?set of AST nodes to skip during traversal
Set<unknown> | undefinedboolean true if a matching Identifier node is found
(data: string | Uint8Array<ArrayBufferLike> | BufferSource): string Computes a BLAKE3 hash synchronously.
dataString or binary data to hash. Strings are UTF-8 encoded.
string | Uint8Array<ArrayBufferLike> | BufferSourcestring 64-character hexadecimal hash string (32 bytes)
(data: string | BufferSource): string Computes a fast non-cryptographic hash using DJB2 algorithm. Use for content comparison and cache keys, not security.
Note: Strings use UTF-16 code units, buffers use raw bytes.
For non-ASCII, hash_insecure(str) !== hash_insecure(encoder.encode(str)).
datastring or binary data to hash
string | BufferSourcestring 8-character hex-encoded unsigned 32-bit hash
(data: string | BufferSource): Promise<string> Computes a SHA-1 hash using Web Crypto API.
dataString or binary data to hash. Strings are UTF-8 encoded.
string | BufferSourcePromise<string> 40-character hexadecimal hash string
(data: string | BufferSource): Promise<string> Computes a SHA-256 hash using Web Crypto API.
dataString or binary data to hash. Strings are UTF-8 encoded.
string | BufferSourcePromise<string> 64-character hexadecimal hash string
(data: string | BufferSource): Promise<string> Computes a SHA-384 hash using Web Crypto API.
dataString or binary data to hash. Strings are UTF-8 encoded.
string | BufferSourcePromise<string> 96-character hexadecimal hash string
(data: string | BufferSource): Promise<string> Computes a SHA-512 hash using Web Crypto API.
dataString or binary data to hash. Strings are UTF-8 encoded.
string | BufferSourcePromise<string> 128-character hexadecimal hash string
(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): boolean 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.
valueunknownstring 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.
astringbstringnumber the edit distance between the strings
(package_json: { [x: string]: unknown; name: string; version?: string | undefined; private?: boolean | undefined; description?: string | undefined; tagline?: string | undefined; glyph?: string | undefined; ... 24 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 | undefined; private?: boolean | undefined; description?: string | undefined; tagline?: 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"; ... 20 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.
valuestring | 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.
levelnumber 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
// Basic logger
const log = new Logger('app');
log.info('starting'); // [app] โค starting
// Child logger
const db_log = log.child('db');
db_log.info('connected'); // [app:db] โค connected
// Custom configuration
const verbose_log = new Logger('debug', { level: 'debug', colors: true });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.
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
argsunknown[]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
Bounded LRU (least-recently-used) map with a hard capacity.
Behaves like Map for get/set/has/delete/size/iteration, with these differences:
- Inserting a new key when size === capacity evicts the least-recently-used entry.
- get(key) marks the entry as most-recently-used.
- set(key, value) marks the entry as most-recently-used (including when overwriting).
- has(key) does NOT mark as used (matches Map parity).
- peek(key) reads without marking as used.
Iteration order is LRU โ MRU, matching Map's insertion-order guarantee where "insertion"
is redefined as "last use".
Implementation uses a single backing Map and relies on its insertion-order iteration โ
on use, the entry is deleted and re-inserted to move it to the MRU end.
Iterators (keys(), values(), entries(), [Symbol.iterator]) are live views over the
backing Map, not snapshots. Per the ECMAScript Map iteration spec, calling get(key) or
set(existing_key, โฆ) during iteration moves that entry to the MRU end and causes it to be
re-visited later in the same iteration. If you need a stable view while mutating, copy first
(e.g. [...lru.entries()]).
KVconst cache = new LruMap<string, Buffer>(100, {
on_evict: (key, value) => value.release(),
});
cache.set('a.png', buf_a);
cache.set('b.png', buf_b);
cache.get('a.png'); // refreshes 'a.png' as most-recently-usedcapacitytype number
constructortype new <K, V>(capacity: number, options?: LruMapOptions<K, V> | undefined): LruMap<K, V>
capacitymaximum number of entries; must be a positive integer
numberoptions?optional on_evict hook
LruMapOptions<K, V> | undefinedError - if `capacity` is not a positive integergetReturns the value for key and marks it as most-recently-used.
type (key: K): V | undefined
keyKV | undefinedpeekReturns the value for key without affecting eviction order.
type (key: K): V | undefined
keyKV | undefinedhasReturns true if key is present. Does NOT mark as used (matches Map).
type (key: K): boolean
keyKbooleansetSets value for key and marks it as most-recently-used.
Evicts the least-recently-used entry when inserting a new key at capacity.
The on_evict hook (if any) fires AFTER the new entry is inserted.
type (key: K, value: V): this
keyKvalueVthisdeletetype (key: K): boolean
keyKbooleancleartype (): void
void[Symbol.iterator]type (): IterableIterator<[K, V]>
IterableIterator<[K, V]>keystype (): IterableIterator<K>
IterableIterator<K>valuestype (): IterableIterator<V>
IterableIterator<V>entriestype (): IterableIterator<[K, V]>
IterableIterator<[K, V]>LruMapOnEvict<K, V> Optional hook invoked when an entry is evicted due to capacity overflow.
Not called on delete() or clear().
Called AFTER the new entry is inserted, so the map is already in its post-set state
when the callback runs. A throwing callback does not leave the map inconsistent โ
the eviction and insertion are already committed.
KVLruMapOptions<K, V> Options for LruMap.
KVon_evictCalled with the evicted (key, value) when a set() exceeds capacity.
Fires after the new entry is inserted. Not called on delete() or clear().
LruMapOnEvict<K, V><T, R>(items: Iterable<T>, concurrency: number, fn: (item: T, index: number) => R | Promise<R>, signal?: AbortSignal | undefined): Promise<...> Maps over items with controlled concurrency, preserving input order.
itemsIterable<T>concurrencymaximum number of concurrent operations
numberfn(item: T, index: number) => R | Promise<R>signal?optional AbortSignal to cancel processing
AbortSignal | undefinedPromise<R[]> array of results in same order as input
Error - if `concurrency < 1`const results = await map_concurrent(
file_paths,
5, // max 5 concurrent reads
async (path) => readFile(path, 'utf8'),
);<T, R>(items: Iterable<T>, concurrency: number, fn: (item: T, index: number) => R | Promise<R>, signal?: AbortSignal | undefined): Promise<...> Like map_concurrent but collects all results/errors instead of failing fast.
Returns an array of settlement objects matching the Promise.allSettled pattern.
On abort, resolves with partial results: completed items keep their real settlements, in-flight and un-started items are settled as rejected with the abort reason.
itemsIterable<T>concurrencymaximum number of concurrent operations
numberfn(item: T, index: number) => R | Promise<R>signal?optional AbortSignal to cancel processing
AbortSignal | undefinedPromise<PromiseSettledResult<R>[]> array of PromiseSettledResult objects in input order
Error - if `concurrency < 1`const results = await map_concurrent_settled(urls, 5, fetch);
for (const [i, result] of results.entries()) {
if (result.status === 'fulfilled') {
console.log(`${urls[i]}: ${result.value.status}`);
} else {
console.error(`${urls[i]}: ${result.reason}`);
}
}<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> MockLogger 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"; }>; ... 20 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 A commonly used form of pick_by.
objTT obj with all undefined properties removed
OmitStrict<T, K> TKkeyof TZodObject<{ name: ZodString; version: ZodOptional<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[] parse_path_parts('./foo/bar/baz.ts') // => ['foo', 'foo/bar', 'foo/bar/baz.ts'](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[] parse_path_segments('/foo/bar/baz.ts') // => ['foo', 'bar', 'baz.ts']ParsedArgs Parsed CLI arguments with guaranteed positionals array.
Returned by argv_parse which always initializes _.
_Array<string>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 svelte_preprocess_helpers.ts view source
PreprocessImportInfo Import metadata for a single import specifier.
pathThe module path to import from.
stringkindWhether this is a default or named import.
'default' | 'named'(value: boolean): string Formats a boolean for printing.
valuebooleanstring (child: ChildProcess): string Formats a child process for display.
childChildProcessstring `pid(1234) <- node server.js`(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 spawn result for display.
Returns 'ok' for success, or the error/signal/code for failures.
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 Checks if a process with the given PID is running. Uses signal 0 which checks existence without sending a signal.
pidthe process ID to check (must be a positive integer)
numberboolean true if the process exists (even without permission to signal it),
false if the process doesn't exist or if pid is invalid (non-positive, non-integer, NaN, Infinity)
ProcessRegistry Default process registry used by module-level spawn functions. For testing or isolated process groups, create a new ProcessRegistry instance.
Manages a collection of spawned processes for lifecycle tracking and cleanup.
The default instance process_registry_default is used by module-level functions. Create separate instances for isolated process groups or testing.
// Use default registry via module functions
const result = await spawn('echo', ['hello']);
// Or create isolated registry for testing
const registry = new ProcessRegistry();
const {child, closed} = registry.spawn('node', ['server.js']);
await registry.despawn_all();processesAll currently tracked child processes
type Set<ChildProcess>
spawnSpawns a process and tracks it in this registry. The process is automatically unregistered when it exits.
type (command: string, args?: readonly string[], options?: SpawnProcessOptions | undefined): SpawnedProcess
commandstringargsreadonly string[][]options?spawn options including signal and timeout_ms
SpawnProcessOptions | undefinedError - if `timeout_ms` is negativespawn_outSpawns a process and captures stdout/stderr as strings.
Sets stdio: 'pipe' automatically.
type (command: string, args?: readonly string[], options?: SpawnProcessOptions | undefined): Promise<SpawnedOut>
commandstringargsreadonly string[][]options?SpawnProcessOptions | undefinedPromise<SpawnedOut>result with captured stdout and stderr
- null means spawn failed (ENOENT, etc.) or stream was unavailable
- '' (empty string) means process ran but produced no output
- non-empty string contains the captured output
Error - if `timeout_ms` is negativedespawnKills a child process and waits for it to exit.
type (child: ChildProcess, options?: DespawnOptions | undefined): Promise<SpawnResult>
childChildProcessoptions?kill options including signal and timeout
DespawnOptions | undefinedPromise<SpawnResult>Error - if `timeout_ms` is negativedespawn_allKills all processes in this registry.
type (options?: DespawnOptions | undefined): Promise<SpawnResult[]>
options?kill options applied to all processes
DespawnOptions | undefinedPromise<SpawnResult[]>attach_error_handlerAttaches an uncaughtException handler that kills all processes before exiting.
Prevents zombie processes when the parent crashes.
By default uses SIGKILL for immediate termination. Set graceful_timeout_ms
to attempt SIGTERM first (allowing processes to clean up) before escalating
to SIGKILL after the timeout.
Note: Node's uncaughtException handler cannot await async operations, so graceful shutdown uses a blocking busy-wait. This may not be sufficient for processes that need significant cleanup time.
type (options?: { 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) | undefined; graceful_timeout_ms?: number | ... 1 more ... | undefined; } | undefined): () => void
options?configuration options
{ 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) | undefined; graceful_timeout_ms?: number | ... 1 more...() => voidcleanup function to remove the handler
Error - if a handler is already attached to this registry(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> RandomAlea Alea: a seedable pseudo-random number generator by Johannes Baagรธe.
Supports variadic and string seeds (create_random_alea('my', 3, 'seeds')).
For numeric seeds, prefer create_random_xoshiro which is faster with equal quality.
DO NOT USE when security matters โ use the Web Crypto API (crypto.getRandomValues) instead.
Alea passes all 11 distribution quality tests at 10M samples,
performing on par with Math.random (V8's xorshift128+):
- mean, variance, chi-squared uniformity, Kolmogorov-Smirnov - lag-1 through lag-8 autocorrelation - runs test, gap test, permutation test (triples) - bit-level frequency (bits 0-7) - 2D serial pairs (25x25 through 200x200 grids) - birthday spacings (Marsaglia parameters)
Speed is ~19% slower than Math.random (~12.2M ops/sec vs ~15.0M ops/sec).
To reproduce:
npm run benchmark_random_quality # distribution tests (N=1M)
npm run benchmark_random_quality -- --deep # thorough (N=10M, multi-trial)
npm run benchmark_random # speed comparisonuint32() => numberfract53() => numberversionstringseedsArray<unknown>RandomXoshiro Xoshiro128**: a seedable pseudo-random number generator by Blackman & Vigna (2018). Recommended for reproducible randomness (testing, simulations, procedural generation).
DO NOT USE when security matters โ use the Web Crypto API (crypto.getRandomValues) instead.
Xoshiro128** has a 2^128-1 period and passes BigCrush.
It uses pure 32-bit arithmetic (shifts, rotates, XOR, multiply)
making it very fast in JavaScript via Math.imul.
Xoshiro128** passes all 11 distribution quality tests at 10M samples,
performing on par with Math.random (V8's xorshift128+):
- mean, variance, chi-squared uniformity, Kolmogorov-Smirnov - lag-1 through lag-8 autocorrelation - runs test, gap test, permutation test (triples) - bit-level frequency (bits 0-7) - 2D serial pairs (25x25 through 200x200 grids) - birthday spacings (Marsaglia parameters)
Speed is near-native (~4% slower than Math.random) and ~18% faster than Alea
(~14.4M ops/sec vs ~15.0M and ~12.2M respectively).
To reproduce:
npm run benchmark_random_quality # distribution tests (N=1M)
npm run benchmark_random_quality -- --deep # thorough (N=10M, multi-trial)
npm run benchmark_random # speed comparisonuint32() => numberfract53() => numberversionstringseednumberRed svelte_preprocess_helpers.ts view source
(s: { remove: (start: number, end: number) => unknown; }, import_node: ImportDeclaration & { start: number; end: number; }, source: string): void Removes an ImportDeclaration from source using MagicString.
Consumes leading whitespace (tabs/spaces) and trailing newline to avoid leaving blank lines.
s{ remove: (start: number, end: number) => unknown; }import_nodethe ImportDeclaration AST node with Svelte position data
ImportDeclaration & { start: number; end: number; }sourcestringvoid svelte_preprocess_helpers.ts view source
(s: { overwrite: (start: number, end: number, content: string) => unknown; }, node: ImportDeclaration & { start: number; end: number; }, specifier_to_remove: ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier, source: string, additional_lines?: string): void Removes a specifier from a multi-specifier import declaration by reconstructing the statement without the removed specifier.
Overwrites the entire declaration range to avoid character-level comma surgery.
Handles:
- import Mdz, {other} from '...' โ import {other} from '...'
- import {default as Mdz, other} from '...' โ import {other} from '...'
- import {Mdz, other} from '...' โ import {other} from '...'
s{ overwrite: (start: number, end: number, content: string) => unknown; }nodeImportDeclaration & { start: number; end: number; }specifier_to_removeImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifiersourcestringadditional_linesextra content appended after the reconstructed import (used to bundle new imports into the overwrite to avoid MagicString boundary conflicts).
string''void (array: any[], index: number): void Removes an element from array at index in an unordered manner.
arrayany[]indexnumbervoid svelte_preprocess_helpers.ts view source
(s: { remove: (start: number, end: number) => unknown; }, declaration_node: VariableDeclaration & { start: number; end: number; }, source: string): void Removes a single-declarator VariableDeclaration from source using MagicString.
Consumes leading whitespace (tabs/spaces) and trailing newline to avoid leaving
blank lines. Only safe for single-declarator statements (const x = 'val';);
callers must verify node.declarations.length === 1 before calling.
s{ remove: (start: number, end: number) => unknown; }declaration_nodethe VariableDeclaration AST node with Svelte position data
VariableDeclaration & { start: number; end: number; }sourcestringvoid <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 svelte_preprocess_helpers.ts view source
(ast: Root, component_imports: string[]): Map<string, ResolvedComponentImport> Resolves local names that import from specified source paths.
Scans ImportDeclaration nodes in both the instance and module scripts.
Handles default, named, and aliased imports. Skips namespace imports
and import type declarations (both whole-declaration and per-specifier).
Returns import node references alongside names to support import removal.
astthe parsed Svelte AST root node
Rootcomponent_importsarray of import source paths to match against
string[]Map<string, ResolvedComponentImport> map of local names to their resolved import info
Promise<void> A singleton resolved Promise.
svelte_preprocess_helpers.ts view source
ResolvedComponentImport Information about a resolved component import.
import_nodeThe ImportDeclaration AST node that provides this name.
ImportDeclarationspecifierThe specific import specifier for this name.
ImportSpecifier | ImportDefaultSpecifierResolvedPath A resolved path with both the original path string and its absolute id.
pathstringRestartableProcess Handle for a process that can be restarted.
Exposes closed promise for observing exits and implementing restart policies.
restartRestart the process, killing the current one if active. Concurrent calls are coalesced - multiple calls before the first completes will share the same restart operation.
() => Promise<void>killKill the process and set active to false
() => Promise<void>activeWhether this handle is managing a process.
Note: This reflects handle state, not whether the underlying OS process is executing.
Remains true after a process exits naturally until kill() or restart() is called.
To check if the process actually exited, await closed.
booleanchildThe current child process, or null if not active
ChildProcess | nullclosedPromise that resolves when the current process exits
Promise<SpawnResult>spawnedPromise that resolves when the initial spawn_process() call completes.
Note: This resolves when the spawn syscall returns, NOT when the process
is "ready" or has produced output. For commands that fail immediately
(e.g., ENOENT), spawned still resolves - check closed for errors.
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 <T extends DagNode>(options: DagOptions<T>): Promise<DagResult> Execute nodes in a dependency graph concurrently.
Independent nodes (no unmet dependencies) run in parallel up to
max_concurrency. When a node completes, its dependents become
eligible to start. Failure cascading and stop-on-failure are handled
per the options.
optionsDAG execution options
DagOptions<T>Promise<DagResult> aggregated result with per-node details
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 (filename: string | undefined, exclude: (string | RegExp)[]): boolean Checks if a filename matches any exclusion pattern.
Returns false when filename is undefined, empty string, or exclude is empty.
String patterns use substring matching. RegExp patterns use .test().
filenamethe file path to check, or undefined for virtual files
string | undefinedexcludearray of string or RegExp exclusion patterns
(string | RegExp)[]boolean true if the file should be excluded from processing
<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.
strstringmap_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 localeCompare and >.
mapTcomparator(a: [any, any], b: [any, any]) => numbercompare_simple_map_entriesT Sortable Minimum shape required for topological sorting.
idstringdepends_onArray<string>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"; }>; ... 20 more ...; alias_of: ZodOptional<...>; }, $loose>>>; module_comment: ... Metadata for a library's src/lib/ exports.
(command: string, args?: readonly string[], options?: SpawnProcessOptions | undefined): Promise<SpawnResult> Spawns a process and returns a promise that resolves when it exits. Use this for commands that complete (not long-running processes).
commandstringargsreadonly string[][]options?SpawnProcessOptions | undefinedPromise<SpawnResult> const result = await spawn('npm', ['install']);
if (!result.ok) console.error('Install failed');(command: string, args?: readonly string[], options?: SpawnOptions | undefined): SpawnDetachedResult Spawns a detached process that continues after parent exits.
Unlike other spawn functions, this is NOT tracked in any ProcessRegistry. The spawned process is meant to outlive the parent (e.g., daemon processes).
commandstringargsreadonly string[][]options?spawn options (use stdio to redirect output to file descriptors)
SpawnOptions | undefinedSpawnDetachedResult result with pid on success, or error message on failure
// Simple detached process
const result = spawn_detached('node', ['daemon.js'], {cwd: '/app'});
// With log file (caller handles file opening)
import {openSync, closeSync} from 'node:fs';
const log_fd = openSync('/var/log/daemon.log', 'a');
const result = spawn_detached('node', ['daemon.js'], {
cwd: '/app',
stdio: ['ignore', log_fd, log_fd],
});
closeSync(log_fd);(command: string, args?: readonly string[], options?: SpawnProcessOptions | undefined): Promise<SpawnedOut> Spawns a process and captures stdout/stderr as strings.
commandstringargsreadonly string[][]options?SpawnProcessOptions | undefinedPromise<SpawnedOut> const {result, stdout} = await spawn_out('git', ['status', '--porcelain']);
if (result.ok && stdout) console.log(stdout);(command: string, args?: readonly string[], options?: SpawnProcessOptions | undefined): SpawnedProcess Spawns a process with graceful shutdown behavior.
Returns a handle with access to the child process and closed promise.
commandstringargsreadonly string[][]options?SpawnProcessOptions | undefinedSpawnedProcess const {child, closed} = spawn_process('node', ['server.js']);
// Later...
child.kill();
const result = await closed;(command: string, args?: readonly string[], options?: SpawnProcessOptions | undefined): RestartableProcess Spawns a process that can be restarted. Handles concurrent restart calls gracefully.
Note: The signal and timeout_ms options are reapplied on each restart.
If the AbortSignal is already aborted when restart() is called, the new
process will be killed immediately.
commandstringargsreadonly string[][]options?SpawnProcessOptions | undefinedRestartableProcess Simple restart on crash
const rp = spawn_restartable_process('node', ['server.js']);
while (rp.active) {
const result = await rp.closed;
if (result.ok) break; // Clean exit
await rp.restart();
}Restart with backoff
const rp = spawn_restartable_process('node', ['server.js']);
let failures = 0;
while (rp.active) {
const result = await rp.closed;
if (result.ok || ++failures > 5) break;
await new Promise((r) => setTimeout(r, 1000 * failures));
await rp.restart();
}(result: SpawnResult): string Formats a spawn result for use in error messages.
resultstring SpawnDetachedResult Result of spawning a detached process.
SpawnedOut Result of spawn_out with captured output streams.
resultstdoutCaptured stdout, or null if stream unavailable
string | nullstderrCaptured stderr, or null if stream unavailable
string | nullSpawnedProcess Handle for a spawned process with access to the child and completion promise.
childThe underlying Node.js ChildProcess
ChildProcessclosedResolves when the process exits
Promise<SpawnResult>SpawnProcessOptions Options for spawning processes, extending Node's SpawnOptions.
SpawnOptionssignalAbortSignal to cancel the process. When aborted, sends SIGTERM to the child.
AbortSignaltimeout_msTimeout in milliseconds. Must be non-negative. Sends SIGTERM when exceeded. A value of 0 triggers immediate SIGTERM.
numberspawn_child_processCustom spawn function for testing. Defaults to node:child_process spawn.
typeof node_spawn_child_processSpawnResult Discriminated union representing all possible spawn outcomes.
Narrow via result.kind === 'error' | 'exited' | 'signaled'.
SpawnResultError Spawn failed before the process could run.
Note: child is still present because node:child_process.spawn returns a
ChildProcess synchronously and then emits 'error' asynchronously โ the
handle exists but the OS process never started.
ENOENT when command not found
kind'error'okfalsechildChildProcesserrorErrorSpawnResultExited Process ran and exited with a code.
ok is true when code is 0.
kind'exited'okbooleanchildChildProcesscodenumberSpawnResultSignaled Process was terminated by a signal (e.g., SIGTERM, SIGKILL).
kind'signaled'okfalsechildChildProcesssignalNodeJS.Signals(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.
valuesnumber[]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.
meannumberstd_devnumbersample_sizenumberoptions?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 Error - if `level` is not in the open interval (0, 1)stats_confidence_level_to_z_score(0.95); // 1.96
stats_confidence_level_to_z_score(0.99); // 2.576Record<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. NaN values are filtered out before computing.
valuesnumber[]number (values: number[]): { min: number; max: number; } Calculate min and max values. NaN values are ignored.
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.
valuesnumber[]ppercentile (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.
tabsolute value of t-statistic
numberdfdegrees 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.
Params suffixed 1 describe the first sample, 2 the second.
mean1numberstd1numbern1numbermean2numberstd2numbern2numberStatsWelchTTestResult 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 (content: string): boolean Check if content appears to be binary.
Checks for null bytes in the first 8KB of content.
contentstringboolean (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 when to '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() => Promise<T>timertimer to use (defaults to timer_default)
timer_defaultPromise<{ result: T; timing: TimeResult; }> const {result, timing} = await time_async(async () => {
await fetch('https://api.example.com/data');
return 42;
});
console.log(`Result: ${result}, took ${time_format_adaptive(timing.elapsed_ns)}`);(ns: number, unit: TimeUnit, decimals?: number): string Format time with a specific unit.
nsnumberunitdecimalsnumber2string formatted string like "3.87ฮผs"
(ns: number, decimals?: number): string Format time with adaptive units (ns/ฮผs/ms/s) based on magnitude.
nsnumberdecimalsnumber2string formatted string like "3.87ฮผs" or "1.23ms"
time_format_adaptive(1500) // "1.50ฮผs"
time_format_adaptive(3870) // "3.87ฮผs"
time_format_adaptive(1500000) // "1.50ms"
time_format_adaptive(1500000000) // "1.50s"(fn: () => unknown, iterations: number, timer?: Timer): Promise<number[]> Measure multiple executions of a function and return all timings.
fn() => unknowniterationsnumbertimertimer to use (defaults to timer_default)
timer_defaultPromise<number[]> array of elapsed times in nanoseconds
const timings_ns = await time_measure(async () => {
await process_data();
}, 100);
import {BenchmarkStats} from './benchmark_stats.js';
const stats = new BenchmarkStats(timings_ns);
console.log(`Mean: ${time_format_adaptive(stats.mean_ns)}`);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() => Ttimertimer to use (defaults to timer_default)
timer_default{ result: T; timing: TimeResult; } const {result, timing} = time_sync(() => {
return expensive_computation();
});
console.log(`Result: ${result}, took ${time_format_adaptive(timing.elapsed_ns)}`);(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_nsnumber[]TimeUnit 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[] (data: string | Uint8Array<ArrayBufferLike> | BufferSource): Uint8Array<ArrayBufferLike> Converts string or binary data to a Uint8Array.
Strings are UTF-8 encoded. Uint8Array inputs are returned as-is.
datastring | Uint8Array<ArrayBufferLike> | BufferSourceUint8Array<ArrayBufferLike> Uint8Array view of the data
(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 (bytes: Uint8Array<ArrayBufferLike>): string Converts a Uint8Array to a lowercase hex string.
bytesUint8Array<ArrayBufferLike>string hex string with two characters per byte
(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 extends Sortable>(items: T[], label?: string): TopologicalSortResult<T> Sort items by their dependencies using Kahn's algorithm.
Returns items ordered so that dependencies come before dependents. If a cycle is detected, returns an error with the cycle path.
itemsarray of items to sort
T[]labellabel for error messages (e.g. "resource", "step")
string'item'TopologicalSortResult<T> sorted items or error if cycle detected
TopologicalSortResult<T> Result of topological sort.
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.
objanycbreceives 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 svelte_preprocess_helpers.ts view source
(value: true | ExpressionTag | (ExpressionTag | Text)[], source: string, bindings: ReadonlyMap<string, string>): ConditionalChainBranch[] | null Extracts a chain of conditional expressions where all leaf values are static strings.
Handles nested ternaries like a ? 'x' : b ? 'y' : 'z' by iteratively walking
the right-recursive ConditionalExpression chain. At each level, evaluates the
consequent via evaluate_static_expr and continues into the alternate if it is
another ConditionalExpression. The final alternate is the else branch.
Returns null if the attribute value is not an ExpressionTag containing a
ConditionalExpression, if any leaf fails to resolve to a static string, or
if the chain exceeds 10 branches (safety limit).
A 2-branch result covers the simple ternary case (a ? 'x' : 'y').
valuethe attribute value from AST.Attribute['value']
true | ExpressionTag | (ExpressionTag | Text)[]sourcethe full source string (needed to slice test expression source text)
stringbindingsmap of variable names to their resolved static string values
ReadonlyMap<string, string>ConditionalChainBranch[] | null array of conditional chain branches, or null if not extractable
(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".
resultResult<TValue, TError>message?string | undefinedTValue["value"] ResultError - if `result.ok` is false<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.
resultResult<object, TError>messagestring'Failed to unwrap result error'{ ok: false; } & TError Error - if `result.ok` is trueZodURL $ZodBranded<ZodUUID, "Uuid", "out"> 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.
ZodDefault<$ZodBranded<ZodUUID, "Uuid", "out">> (duration?: number): Promise<void> Waits for the given duration before resolving.
durationnumber0Promise<void> (schema: ZodObject<$ZodLooseShape, $strip>): ZodFieldInfo[] Extract field metadata from a Zod object schema.
schemaZodObject<$ZodLooseShape, $strip>ZodFieldInfo[] (value: unknown): string Format a value for display in help text.
valueunknownstring (schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): string Get the base type name for a Zod schema, unwrapping all wrappers.
schemaZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>string base type name (e.g. 'string', 'object', 'uuid')
(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>, key: string): ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> Get the field schema for a key in an object schema.
schemaZod schema (typically a ZodObject with possible wrappers)
ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>keystringZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> Error - if the schema is not an object or the key is missing(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> Unwrap a schema through every wrapper type (optional, nullable, default,
transform, pipe, prefault) to reach the innermost schema. Like zod_unwrap_def
but returns the schema (so callers can .shape, instanceof-check, etc.)
instead of the def.
schemaZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> the innermost non-wrapper schema
<T extends z.ZodType>(schema: T): (keyof output<T> & string)[] Get all property keys from an object schema, unwrapping wrappers. Returns an empty array if the innermost type is not an object.
schemaZod schema (typically a ZodObject with possible wrappers)
T(keyof output<T> & string)[] (schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): boolean Check if a schema has a default value at any wrapping level.
Unlike zod_to_schema_default (which returns the value), this returns a boolean. Distinguishes "no default" from "default is undefined".
schemaZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>boolean (schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): boolean Check if a schema accepts null at any wrapping level.
schemaZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>boolean (schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): boolean Check if a schema is optional at the outermost level.
schemaZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>boolean (schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>, key: string): ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> | undefined Get the field schema for a key in an object schema, returning undefined if
the schema is not an object or the key is missing.
schemaZod schema (typically a ZodObject with possible wrappers)
ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>keythe property name
stringZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> | undefined the field's schema, or undefined
(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): string[] Get aliases from a schema's metadata, unwrapping if needed.
schemaZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>string[] (schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): unknown Get the default value from a schema, unwrapping if needed.
schemaZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>unknown default value or undefined
(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): string | null Get the description from a schema's metadata, unwrapping if needed.
schemaZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>string | null description string or null if not found
(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): Set<string> Get all property names and their aliases from an object schema.
schemaZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>Set<string> (schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): ZodSchemaProperty[] Extract properties from a Zod object schema.
schemaZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>ZodSchemaProperty[] (schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): string Get the type string for a schema, suitable for display.
schemaZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>string human-readable type string
(def: $ZodTypeDef): ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> | undefined Unwrap nested schema types (optional, default, nullable, etc).
def$ZodTypeDefZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>> | undefined inner schema if wrapped, undefined otherwise
(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): $ZodTypeDef Unwrap Zod wrappers (optional, default, nullable, pipe, transform) to get the base type definition.
schemaZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>$ZodTypeDef the innermost non-wrapper type definition
(schema: ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>): ZodObject<$ZodLooseShape, $strip> | null Unwrap a schema to find the inner ZodObject, or null if not an object schema.
Handles wrappers like z.strictObject({...}).default({...}).
schemaZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>ZodObject<$ZodLooseShape, $strip> | null Set<string> Zod wrapper type names that zod_unwrap_def traverses through.
ZodFieldInfo Metadata extracted from a single field of a Zod object schema.
namestringbase_typestringrequiredbooleanhas_defaultbooleannullablebooleanZodSchemaProperty Property extracted from an object schema.
namestringtypestringdescriptionstringdefaultunknownaliasesArray<string>