/** * Metrics operations for B2C Commerce (Observability). * * This module provides typed, high-level functions for retrieving operational * time-series metrics from the SCAPI Observability Metrics API * (`observability/metrics/v1`). Each metric *category* has its own function; all * return the same {@link MetricsDataResponse} envelope. * * ## Categories * * - {@link getOverallMetrics} — overall application metrics * - {@link getSalesMetrics} — sales metrics * - {@link getEcdnMetrics} — embedded CDN metrics * - {@link getThirdPartyMetrics} — third-party service call metrics (filterable by service) * - {@link getScapiMetrics} — SCAPI request metrics (filterable by API family/name) * - {@link getScapiHooksMetrics} — SCAPI hook execution metrics * - {@link getMrtMetrics} — Managed Runtime metrics * - {@link getControllerMetrics} — controller/pipeline metrics * - {@link getOcapiMetrics} — OCAPI request metrics (filterable by category/api) * * {@link getMetricsByCategory} dispatches to the correct function by category * name — convenient for CLIs and tools that take a category as input. * * ## Usage * * ```typescript * import {createMetricsClient} from '@salesforce/b2c-tooling-sdk/clients'; * import {getOverallMetrics} from '@salesforce/b2c-tooling-sdk/operations/metrics'; * * const client = createMetricsClient({shortCode, tenantId}, auth); * const result = await getOverallMetrics(client, tenantId, {from, to}); * for (const metric of result.data) { * console.log(metric.title, metric.dataSeries.length); * } * ``` * * ## Authentication * * Requires OAuth client-credentials with the `sfcc.metrics` admin scope. The * {@link createMetricsClient} factory attaches this scope plus the tenant scope * automatically. * * @module operations/metrics */ import type { MetricsClient, MetricsDataResponse } from '../../clients/metrics.js'; export type { MetricsClient, MetricsClientConfig, MetricsDataResponse, Metric, MetricDataSeries, MetricDataPoint, MetricsError, } from '../../clients/metrics.js'; /** * All metric categories exposed by the Metrics API, in a stable, documented order. * * Values match the API path segments (e.g. `overall` → `/metrics/overall`). */ export declare const METRIC_CATEGORIES: readonly ["overall", "sales", "ecdn", "third-party", "scapi", "scapi-hooks", "mrt", "controller", "ocapi"]; /** * A metric category name. One of {@link METRIC_CATEGORIES}. */ export type MetricCategory = (typeof METRIC_CATEGORIES)[number]; /** * Time-window options common to every metrics operation. * * Accepts either a {@link Date} or a number of **epoch milliseconds** (the same * unit as `Date.now()`), for both `from` and `to`. Both are optional; when * omitted the API applies its default window. When both are supplied, `from` * must be before `to` or the API returns a 400. * * > **Note:** The Metrics API wire format is epoch **seconds**, and the data * > points it returns are timestamped in **seconds**. These operations convert * > millisecond inputs to seconds on the way out and normalize response * > timestamps back to **milliseconds** on the way in, so callers work in * > JS-native millisecond time throughout (e.g. `new Date(point.timestamp)`). */ export interface MetricsTimeWindow { /** Start of the window — a {@link Date} or epoch milliseconds (inclusive). */ from?: Date | number; /** End of the window — a {@link Date} or epoch milliseconds (inclusive). */ to?: Date | number; } /** * Options for {@link getThirdPartyMetrics}: time window plus an optional * third-party service filter. */ export interface ThirdPartyMetricsOptions extends MetricsTimeWindow { /** Restrict results to a single third-party service by its id. */ thirdPartyServiceId?: string; } /** * Options for {@link getScapiMetrics}: time window plus optional SCAPI filters. */ export interface ScapiMetricsOptions extends MetricsTimeWindow { /** Restrict results to a SCAPI API family (e.g. `product`, `checkout`). */ apiFamily?: string; /** Restrict results to a SCAPI API name (e.g. `shopper-products`). */ apiName?: string; } /** * Options for {@link getOcapiMetrics}: time window plus optional OCAPI filters. */ export interface OcapiMetricsOptions extends MetricsTimeWindow { /** Restrict results to an OCAPI category (e.g. `shop`, `data`). */ ocapiCategory?: string; /** Restrict results to a specific OCAPI API. */ ocapiApi?: string; } /** * Union of every option shape accepted by {@link getMetricsByCategory}. */ export type MetricsQueryOptions = MetricsTimeWindow & Partial> & Partial> & Partial>; /** * How far back the Metrics API retains data: `from` must be no older than * `serverNow - 30 days`, or the API returns 400. */ export declare const METRICS_RETENTION_MS: number; /** * Default (and maximum) width of a metrics time window: 24 hours. * * The Metrics API pairs a request that omits `to` with its own `now` and then * enforces a maximum window of `to - from ≤ 24h`, rejecting anything wider with a * 400. An open-ended `from` older than 24h therefore always fails. To make the * behavior predictable, {@link resolveMetricsWindow} fills in a 24-hour window * (clamped so `to` never exceeds `now`) for any bound the caller leaves open, and * always sends both `from` and `to`. This is only a *default* for derivation — an * explicit `from`+`to` range wider than 24h is still sent as-is, letting the API * remain authoritative and return its own error. */ export declare const METRICS_DEFAULT_WINDOW_MS: number; /** * Safety margin kept *inside* the retention window when clamping `from`. Because * the server evaluates retention against its own clock at request time, a `from` * computed as exactly "30 days ago" on the client is reliably rejected once * request latency and client/server clock skew are added. {@link resolveMetricsWindow} * therefore clamps a `from` that lands within this margin of the retention floor * up to `now - 30 days + margin`, so edge requests (e.g. `--from 30d`) succeed. * 5 minutes comfortably covers latency and typical skew while costing a * negligible fraction of the 30-day window. */ export declare const METRICS_RETENTION_SAFETY_MARGIN_MS: number; /** * A metrics bound as accepted from a CLI flag or MCP argument: a {@link Date}, * epoch **milliseconds**, or a human string — a relative duration (`5m`, `1h`, * `2d`, interpreted as "ago") or an ISO 8601 timestamp. */ export type MetricsBoundInput = Date | number | string; /** * Parses a single metrics time bound (`from` or `to`) into a {@link Date}. * * This is the shared bound parser for the CLI `metrics get` command and the MCP * `metrics_get` tool. It resolves a single bound in isolation; deriving the * companion bound and applying the 24-hour default window is the job of * {@link resolveMetricsWindow}. * * @param value - The bound: a Date, epoch milliseconds, a relative duration * (`5m`/`1h`/`2d`, relative to `now`), or an ISO 8601 timestamp * @param now - Reference time for relative durations (defaults to the current * time; injectable for deterministic tests) * @returns The resolved {@link Date} * @throws TypeError if a string value is neither a valid relative duration nor * a parseable ISO 8601 timestamp * * @example * ```typescript * const from = parseMetricsBound('2d'); // 2 days ago * const to = parseMetricsBound('2026-01-25T12:00:00Z'); * await getSalesMetrics(client, tenantId, {from, to}); * ``` */ export declare function parseMetricsBound(value: MetricsBoundInput, now?: Date): Date; /** * Raw `from`/`to`/`window` inputs, as accepted from CLI flags or MCP arguments, * before resolution. Any subset may be provided. */ export interface MetricsWindowInput { /** Start bound (Date, epoch ms, relative like `7d`, or ISO 8601). */ from?: MetricsBoundInput; /** End bound (Date, epoch ms, relative like `6h`, or ISO 8601). */ to?: MetricsBoundInput; /** * Window duration as a relative string (`1h`, `30m`, `2d`) or a number of * **milliseconds**. Combined with exactly one of `from`/`to` it derives the * other bound; supplied alone it means "the last {window}". */ window?: number | string; } /** * A resolved metrics window. Both `from` and `to` are always present: the * resolver derives whichever bound the caller left open using the 24-hour * default window (see {@link METRICS_DEFAULT_WINDOW_MS}) and always sends an * explicit range, so the request never depends on the server's implicit `to`. * Epoch-second echoes are included for reporting. */ export interface ResolvedMetricsWindow { /** Resolved start bound. */ from: Date; /** Resolved end bound. */ to: Date; /** ISO 8601 form of {@link from}. */ fromIso: string; /** ISO 8601 form of {@link to}. */ toIso: string; /** Epoch **seconds** form of {@link from} (the API wire unit). */ fromEpochSeconds: number; /** Epoch **seconds** form of {@link to} (the API wire unit). */ toEpochSeconds: number; /** * True when `from` was clamped forward to stay inside the retention window * (see {@link METRICS_RETENTION_SAFETY_MARGIN_MS}). Surfaced so callers can * report that the effective start differs slightly from what was requested. */ clampedFrom: boolean; /** * True when a bound was derived from the 24-hour default window rather than * supplied by the caller (e.g. `from` alone, `to` alone, or nothing at all). * Surfaced so callers can note that the effective range was defaulted. */ defaultedWindow: boolean; } /** * Resolves `from`/`to`/`window` inputs into the concrete bounds to send to the * Metrics API. This is the shared resolver for the CLI `metrics get` command and * the MCP `metrics_get` tool, so both share identical, tested semantics. * * The resolver always produces an explicit `from`+`to` pair. The Metrics API * pairs a request that omits `to` with its own `now` and enforces a 24-hour * maximum window, so an open-ended `from` older than 24 hours always fails; to * make the behavior predictable, any bound the caller leaves open is filled from * the 24-hour default window (see {@link METRICS_DEFAULT_WINDOW_MS}) rather than * relying on the server's implicit end. * * The `window` duration makes fixed-width lookbacks easy without hand-computing * a second timestamp — e.g. "a 1-hour window starting 7 days ago" is * `{from: '7d', window: '1h'}`. Resolution rules: * * - `from` + `to` — used as given; `window` must NOT also be set. An explicit * range wider than the 24-hour maximum is still sent as-is, leaving the API to * return its own error. * - `from` + `window` — `to = from + window`. * - `to` + `window` — `from = to - window`. * - `window` only — the last `window`: `to = now`, `from = now - window`. * - `from` only — a 24-hour window forward from `from`: `to = min(from + 24h, now)`. * - `to` only — a 24-hour window back from `to`: `from = to - 24h`. * - nothing — the last 24 hours: `to = now`, `from = now - 24h`. * * Bounds filled from the 24-hour default (the last three rules) set * {@link ResolvedMetricsWindow.defaultedWindow}. Validation is structural * (over-specification and `from` after `to`). Additionally, a `from` that lands * at or beyond the 30-day retention floor is clamped *forward* to * `now - 30 days + margin` (see {@link METRICS_RETENTION_SAFETY_MARGIN_MS}) so * requests like `--from 30d` are not rejected by the server's own slightly-later * clock; the clamp is applied before deriving the companion bound so the window * width is preserved, only ever moves `from` toward `now`, and is reported via * {@link ResolvedMetricsWindow.clampedFrom}. * * @param input - The raw `from`/`to`/`window` inputs * @param now - Reference time for relative bounds, default/window modes, and the * retention clamp (defaults to the current time; injectable for deterministic tests) * @returns The resolved bounds plus ISO/epoch-second echoes and clamp/default flags * @throws TypeError if a bound or the window string is unparseable * @throws RangeError if all three are supplied, or the resolved `from` is after `to` * * @example * ```typescript * // A 1-hour window starting 7 days ago: * const w = resolveMetricsWindow({from: '7d', window: '1h'}); * await getScapiMetrics(client, tenantId, {from: w.from, to: w.to}); * ``` */ export declare function resolveMetricsWindow(input?: MetricsWindowInput, now?: Date): ResolvedMetricsWindow; /** * Retrieves overall application metrics for an organization. * * @param client - Metrics API client from {@link createMetricsClient} * @param tenantId - Tenant ID (with or without the `f_ecom_` prefix) * @param options - Optional time window (epoch milliseconds) * @returns The metrics data response * @throws Error if the request fails */ export declare function getOverallMetrics(client: MetricsClient, tenantId: string, options?: MetricsTimeWindow): Promise; /** * Retrieves sales metrics for an organization. * * @param client - Metrics API client from {@link createMetricsClient} * @param tenantId - Tenant ID (with or without the `f_ecom_` prefix) * @param options - Optional time window (epoch milliseconds) * @returns The metrics data response * @throws Error if the request fails */ export declare function getSalesMetrics(client: MetricsClient, tenantId: string, options?: MetricsTimeWindow): Promise; /** * Retrieves embedded CDN (eCDN) metrics for an organization. * * @param client - Metrics API client from {@link createMetricsClient} * @param tenantId - Tenant ID (with or without the `f_ecom_` prefix) * @param options - Optional time window (epoch milliseconds) * @returns The metrics data response * @throws Error if the request fails */ export declare function getEcdnMetrics(client: MetricsClient, tenantId: string, options?: MetricsTimeWindow): Promise; /** * Retrieves third-party service call metrics for an organization. * * @param client - Metrics API client from {@link createMetricsClient} * @param tenantId - Tenant ID (with or without the `f_ecom_` prefix) * @param options - Optional time window and `thirdPartyServiceId` filter * @returns The metrics data response * @throws Error if the request fails */ export declare function getThirdPartyMetrics(client: MetricsClient, tenantId: string, options?: ThirdPartyMetricsOptions): Promise; /** * Retrieves SCAPI request metrics for an organization. * * @param client - Metrics API client from {@link createMetricsClient} * @param tenantId - Tenant ID (with or without the `f_ecom_` prefix) * @param options - Optional time window and `apiFamily`/`apiName` filters * @returns The metrics data response * @throws Error if the request fails */ export declare function getScapiMetrics(client: MetricsClient, tenantId: string, options?: ScapiMetricsOptions): Promise; /** * Retrieves SCAPI hook execution metrics for an organization. * * @param client - Metrics API client from {@link createMetricsClient} * @param tenantId - Tenant ID (with or without the `f_ecom_` prefix) * @param options - Optional time window (epoch milliseconds) * @returns The metrics data response * @throws Error if the request fails */ export declare function getScapiHooksMetrics(client: MetricsClient, tenantId: string, options?: MetricsTimeWindow): Promise; /** * Retrieves Managed Runtime (MRT) metrics for an organization. * * @param client - Metrics API client from {@link createMetricsClient} * @param tenantId - Tenant ID (with or without the `f_ecom_` prefix) * @param options - Optional time window (epoch milliseconds) * @returns The metrics data response * @throws Error if the request fails */ export declare function getMrtMetrics(client: MetricsClient, tenantId: string, options?: MetricsTimeWindow): Promise; /** * Retrieves controller/pipeline metrics for an organization. * * @param client - Metrics API client from {@link createMetricsClient} * @param tenantId - Tenant ID (with or without the `f_ecom_` prefix) * @param options - Optional time window (epoch milliseconds) * @returns The metrics data response * @throws Error if the request fails */ export declare function getControllerMetrics(client: MetricsClient, tenantId: string, options?: MetricsTimeWindow): Promise; /** * Retrieves OCAPI request metrics for an organization. * * @param client - Metrics API client from {@link createMetricsClient} * @param tenantId - Tenant ID (with or without the `f_ecom_` prefix) * @param options - Optional time window and `ocapiCategory`/`ocapiApi` filters * @returns The metrics data response * @throws Error if the request fails */ export declare function getOcapiMetrics(client: MetricsClient, tenantId: string, options?: OcapiMetricsOptions): Promise; /** * Retrieves metrics for a category by name, dispatching to the category-specific * function. Category-specific filters (`thirdPartyServiceId`, `apiFamily`, * `apiName`, `ocapiCategory`, `ocapiApi`) are applied only for the categories * that support them and ignored otherwise. * * @param client - Metrics API client from {@link createMetricsClient} * @param tenantId - Tenant ID (with or without the `f_ecom_` prefix) * @param category - One of {@link METRIC_CATEGORIES} * @param options - Optional time window and category-specific filters * @returns The metrics data response * @throws Error if the request fails or the category is unknown */ export declare function getMetricsByCategory(client: MetricsClient, tenantId: string, category: MetricCategory, options?: MetricsQueryOptions): Promise; export { parseSeriesTags, enrichMetricsTags } from './tags.js'; export type { MetricSeriesTags, MetricsTagContext, MetricsTaggedResponse } from './tags.js';