# TypeScript SDK

Install the TypeScript metrics SDK, authenticate in Node.js or a browser, and call the Metrics API with an asynchronous client.

The official TypeScript SDK provides typed operation requests and responses, local request validation, browser-safe bearer authentication, Node.js M2M token exchange, and typed API errors. The packages are ESM-only and work with TypeScript or modern JavaScript.

Use the [API reference](/api-reference) when you need the parameters, response schema, examples, and documented errors for a specific operation.

## Requirements

The SDK supports Node.js 22 or newer and modern browsers. Install the Metrics client and shared runtime:

```bash
npm install @omascloud/sdk-metrics @omascloud/sdk-core
```

## Configure authentication

For an unattended Node.js workload, use an exchange-only M2M credential. On the **API tokens** page, [create a token](/docs/tokens#create-a-token-in-the-ui) and select **Exchange only** as its access mode. Store the credential in your secret manager and expose it to the process as `OMAS_M2M_TOKEN`; never commit it to source control.

Import `M2mAuthProvider` from the Node.js-only entry point. It exchanges the credential for short-lived, metrics-scoped access tokens and refreshes them automatically:

```ts
import { M2mAuthProvider } from "@omascloud/sdk-core/node";

const authProvider = new M2mAuthProvider(
    process.env.OMAS_M2M_TOKEN ?? "",
);
```

For browser applications or Node.js code that already has an access token, use the browser-safe `BearerAuthProvider` export instead:

```ts
import { BearerAuthProvider } from "@omascloud/sdk-core";

const authProvider = new BearerAuthProvider(accessToken);
```

Do not embed an M2M credential in browser code.

## Create a client

Create one client and reuse it across requests:

```ts
import { MetricsClient } from "@omascloud/sdk-metrics";

const metrics = new MetricsClient({ authProvider });

const response = await metrics.listMetrics({ maxResults: 25 });

for (const metric of response.metrics) {
    console.log(metric.name);
}
```

Every operation is asynchronous and accepts an optional `AbortSignal` in its second argument for cancellation and deadlines.

## Send a metric

Operation requests are flat objects: path and query parameters sit beside request-body fields, and the client serializes each field to the correct location.

```ts
await metrics.putMetricData({
    metricName: "cpu_usage",
    entries: [
        {
            timestamp: Date.now(),
            value: 42.7,
            resolution: 60,
        },
    ],
});
```

See [Send your first metric](/docs/send-metric) for dimensions and pre-aggregated statistic sets.

## Query metric data

Pass Unix epoch milliseconds for the time range. The returned promise resolves to the typed response:

```ts
const endTimestamp = Date.now();
const response = await metrics.getMetricData({
    metricName: "cpu_usage",
    startTimestamp: endTimestamp - 3_600_000,
    endTimestamp,
    resolution: 60,
    aggregation: "avg",
});
```

Read [Metric rollups and resolution](/docs/metric-rollups-resolution) before choosing an aggregation and resolution for production queries.

## Cancel a request

Pass an `AbortSignal` through the per-call options when a caller needs to cancel work or enforce a deadline:

```ts
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5_000);

try {
    await metrics.listMetrics({}, { signal: controller.signal });
} finally {
    clearTimeout(timeout);
}
```

## Handle errors

Known service errors have generated classes that can be checked with `instanceof`. Unknown server error codes remain available as `ApiError`, so the client remains forward-compatible:

```ts
import { ApiError } from "@omascloud/sdk-core";
import { ResourceNotFoundError } from "@omascloud/sdk-metrics";

try {
    await metrics.getMetricData({
        metricName: "cpu_usage",
        startTimestamp: Date.now() - 3_600_000,
    });
} catch (error) {
    if (error instanceof ResourceNotFoundError) {
        console.error("Metric not found", error.requestId, error.details);
    } else if (error instanceof ApiError) {
        console.error(
            "Metrics request failed",
            error.status,
            error.errorCode,
            error.requestId,
        );
    } else {
        throw error;
    }
}
```

Request validation fails before a request is sent. Authentication, timeout, serialization, and transport failures use SDK error classes from `@omascloud/sdk-core`. Log the request ID when it is available and retry only when the failure and operation make that safe.

## Next steps

- Browse the [API reference](/api-reference) for operation parameters, responses, examples, and documented errors.
- Review the [public SDK repository](https://github.com/omascloud/sdks) for source code and release information.
- Use [Send your first metric](/docs/send-metric) for richer ingestion examples.
- Use [Metric rollups and resolution](/docs/metric-rollups-resolution) to design queries, dashboards, and alarms.
