@sourceregistry/node-prometheus
Version:
A lightweight, zero-dependency TypeScript library for creating and exposing Prometheus metrics in standard exposition and OpenMetrics format.
338 lines (337 loc) • 9.98 kB
TypeScript
/**
* Supported Prometheus metric types.
*/
export type MetricType = 'counter' | 'gauge' | 'histogram' | 'summary' | 'untyped';
/**
* Represents a value that may be synchronous or asynchronous.
*/
export type MaybePromise<T> = Promise<T> | T;
/**
* Input formats accepted by value reader functions.
*/
type ValueReaderResult = number | [number, number] | [number, Record<string, string>] | [number, Record<string, string>, number];
/**
* Base class for all Prometheus metrics.
* Handles common functionality like HELP/TYPE comments and label formatting.
*
* @template T - The metric type (e.g., 'gauge', 'counter').
*/
export declare abstract class Metric<T extends MetricType> {
readonly type: T;
/**
* The sanitized metric name.
*/
readonly name: string;
/**
* Optional metric description (used in # HELP).
*/
readonly description?: string;
/**
* Default labels applied to all samples of this metric.
*/
readonly labels?: Record<string, string>;
/**
* Creates a new Metric instance.
*
* @param type - The Prometheus metric type.
* @param name - The raw metric name (will be cleaned).
* @param description - Optional description for # HELP.
* @param labels - Optional default labels.
*/
protected constructor(type: T, name?: string, description?: string, labels?: Record<string, string>);
/**
* Converts a label object to a Prometheus label string (e.g., `{foo="bar"}`).
*
* @param labels - The label key-value pairs.
* @returns The formatted label string.
*/
static labelString(labels?: Record<string, string | number>): string;
/**
* Sanitizes a metric name by removing or replacing invalid characters.
*
* Prometheus metric names must match [a-zA-Z_:][a-zA-Z0-9_:]*
* This removes hyphens, parens; replaces slashes and spaces with underscores.
*
* @param input - The raw metric name.
* @returns The cleaned metric name.
*/
static cleanText(input?: string): string | undefined;
/**
* Concatenates multiple metrics into a single exposition string.
*
* @param format - used to set the metric type
* @param metrics - The metrics to serialize.
* @returns A Promise resolving to the combined string.
*/
static concat(format?: 'prometheus' | 'openmetrics', ...metrics: Metric<MetricType>[]): Promise<string>;
/**
* Generates the common header lines (# HELP, # TYPE) for this metric.
* Called by subclasses before serializing their specific values.
*
* @returns The header string.
*/
protected generateHeader(): string;
/**
* Serializes the metric to Prometheus exposition format.
*
* @returns A Promise resolving to the serialized string.
*/
abstract stringify(): Promise<string>;
}
/**
* Base class for metrics that read values asynchronously (Counter, Gauge).
*
* @template T - The metric type ('counter' or 'gauge').
*/
declare abstract class ValueMetric<T extends 'counter' | 'gauge'> extends Metric<T> {
private readonly _reader;
/**
* Creates a new ValueMetric.
*
* @param type - The metric type.
* @param config - Configuration object.
* @param config.name - Metric name.
* @param config.description - Optional description.
* @param config.labels - Optional default labels.
* @param config.reader - Async or sync function returning values.
*/
protected constructor(type: T, config: {
name: string;
description?: string;
labels?: Record<string, string>;
reader: () => MaybePromise<ValueReaderResult[]>;
});
/**
* Serializes the current values with labels and timestamps.
*
* @returns Promise resolving to value lines.
*/
protected valueString(): Promise<string>;
/**
* @inheritdoc
*/
stringify(): Promise<string>;
}
/**
* A Prometheus Gauge metric.
* Represents a single numerical value that can arbitrarily go up and down.
*
* @example
* const gauge = new Gauge({
* name: "temperature_celsius",
* description: "Current temperature in Celsius",
* reader: () => [23.5]
* });
*/
export declare class Gauge extends ValueMetric<'gauge'> {
/**
* Creates a new Gauge.
*
* @param config - Configuration object.
*/
constructor(config: {
name: string;
description?: string;
labels?: Record<string, string>;
reader: () => MaybePromise<ValueReaderResult[]>;
});
}
/**
* A Prometheus Counter metric.
* Represents a cumulative metric that only increases.
*
* @example
* const counter = new Counter({
* name: "http_requests_total",
* description: "Total HTTP requests",
* reader: () => [1234]
* });
*/
export declare class Counter extends ValueMetric<'counter'> {
/**
* Creates a new Counter.
*
* @param config - Configuration object.
*/
constructor(config: {
name: string;
description?: string;
labels?: Record<string, string>;
reader: () => MaybePromise<ValueReaderResult[]>;
});
/**
* Increments the counter by a given value (convenience alias).
* Note: Since Counter uses a reader, this is just documentation — actual increment
* must be handled in the reader function or external state.
*
* @param delta - Amount to increment by (default: 1).
*/
inc(delta?: number): void;
}
/**
* A Prometheus Histogram metric.
* Counts observations in configurable buckets and provides sum + count.
*
* @example
* const hist = new Histogram({
* name: "response_time_seconds",
* description: "Response time in seconds",
* buckets: [0.1, 0.5, 1, 2, 5]
* });
* hist.observe(0.75);
*/
export declare class Histogram extends Metric<'histogram'> {
private readonly _buckets;
private _bucketCounts;
private _sum;
private _count;
/**
* Creates a new Histogram.
*
* @param config - Configuration object.
* @param config.name - Metric name.
* @param config.description - Optional description.
* @param config.buckets - Optional bucket thresholds (default: []). +Inf always added.
* @param config.labels - Optional default labels.
*/
constructor(config: {
name: string;
description?: string;
buckets?: number[];
labels?: Record<string, string>;
});
/**
* Resets all bucket counts, sum, and total count to zero.
*/
reset(): void;
/**
* Observes a value, updating buckets, sum, and count.
*
* @param value - The observed value.
*/
observe(value: number): void;
/**
* Alias for observe().
*
* @param value - The observed value.
*/
push(value: number): void;
/**
* Serializes bucket, sum, and count lines.
*
* @returns The serialized string.
*/
private bucketString;
/**
* @inheritdoc
*/
stringify(): Promise<string>;
}
/**
* A Prometheus Summary metric.
* Tracks φ-quantiles, sum, and count. Quantiles are calculated via user-provided function.
*
* @example
* const summary = new Summary({
* name: "request_duration_seconds",
* description: "Request duration in seconds",
* quantiles: [0.5, 0.9, 0.99],
* calculate: (value, quantile) => value * quantile // dummy algorithm
* });
* summary.observe(0.8);
*/
export declare class Summary extends Metric<'summary'> {
private _quantiles;
private _sum;
private _count;
private readonly _calculate;
/**
* Creates a new Summary.
*
* @param config - Configuration object.
* @param config.name - Metric name.
* @param config.description - Optional description.
* @param config.quantiles - Array of φ-quantiles (0 < φ < 1).
* @param config.calculate - Function to calculate quantile estimate given value and φ.
*/
constructor(config: {
name: string;
description?: string;
quantiles: readonly number[];
calculate: (value: number, quantile: number) => number;
});
/**
* Observes a value, updating quantiles, sum, and count.
*
* @param value - The observed value.
*/
observe(value: number): void;
/**
* Alias for observe().
*
* @param value - The observed value.
*/
push(value: number): void;
/**
* Serializes quantile, sum, and count lines.
*
* @returns The serialized string.
*/
private summaryString;
/**
* @inheritdoc
*/
stringify(): Promise<string>;
}
/**
* A Prometheus Untyped metric.
* Used when metric type is unknown. Behaves like a Gauge.
*
* @example
* const metric = new Untyped({
* name: "some_unknown_metric",
* value: 42
* });
* metric.set(43);
*/
export declare class Untyped extends Metric<'untyped'> {
private _value;
/**
* Creates a new Untyped metric.
*
* @param config - Configuration object.
* @param config.name - Metric name.
* @param config.description - Optional description.
* @param config.labels - Optional default labels.
* @param config.value - Initial value or [value, timestamp] tuple.
*/
constructor(config: {
name: string;
description?: string;
labels?: Record<string, string>;
value?: number | [number, number];
});
/**
* Sets the current value and timestamp.
*
* @param value - New value or [value, timestamp] tuple.
*/
set(value: number | [number, number]): void;
/**
* Gets the current value and timestamp.
*
* @returns [value, timestamp] tuple.
*/
get(): [number, number];
/**
* Serializes the current value.
*
* @returns The serialized string.
*/
private valueString;
/**
* @inheritdoc
*/
stringify(): Promise<string>;
}
export {};