### Metronome SDK Quick Start Example Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/00-index.md Demonstrates initializing the Metronome client and performing common operations such as ingesting usage events, creating a customer, creating a contract, and listing customers. Ensure the METRONOME_BEARER_TOKEN environment variable is set. ```typescript import Metronome from '@metronome/sdk'; const client = new Metronome({ bearerToken: process.env['METRONOME_BEARER_TOKEN'], }); // Send usage events await client.v1.usage.ingest({ usage: [ { transaction_id: '550e8400-e29b-41d4-a716-446655440000', customer_id: 'team@example.com', event_type: 'api_request', timestamp: '2024-01-15T10:30:00Z', properties: { endpoint: '/api/users', method: 'POST' }, }, ], }); // Create a customer const customer = await client.v1.customers.create({ name: 'Acme Corp', ingest_aliases: ['team@acme.com'], }); // Create a contract const contract = await client.v1.contracts.create({ customer_id: customer.customer_id, starting_at: '2024-02-01T00:00:00Z', rate_card_id: 'rate_card_123', billing_provider_configuration: { billing_provider: 'stripe', delivery_method: 'direct_to_billing_provider', }, }); // List customers for await (const cust of client.v1.customers.list()) { console.log(cust.id, cust.name); } ``` -------------------------------- ### Add and Run an Example Source: https://github.com/metronome-industries/metronome-node/blob/main/CONTRIBUTING.md Create a new TypeScript file in the examples directory and make it executable. Then, run the example using yarn tsn. ```ts // add an example to examples/.ts #!/usr/bin/env -S npm run tsn -T … ``` ```sh $ chmod +x examples/.ts # run the example against your api $ yarn tsn -T examples/.ts ``` -------------------------------- ### Workflow Examples Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/COMPLETION_REPORT.txt Examples demonstrating common workflows using the Metronome SDK. ```APIDOC ## Workflow Examples 1. **PLG (Product-Led Growth) Onboarding**: Create customer, configure billing, create contract, start ingesting usage. 2. **Enterprise Pricing**: Customer creation with custom fields, complex contract setup, pricing overrides, commit management, spend monitoring. 3. **Billing Corrections**: Manual balance adjustments, credit grant creation, dispute handling. 4. **Reporting**: Usage aggregation, dimensional breakdown, invoice retrieval, audit trail access. ``` -------------------------------- ### Install Dependencies and Build Project Source: https://github.com/metronome-industries/metronome-node/blob/main/CONTRIBUTING.md Run these commands to install all necessary dependencies and build the project output files. ```sh $ yarn $ yarn build ``` -------------------------------- ### Install from Git Source: https://github.com/metronome-industries/metronome-node/blob/main/CONTRIBUTING.md Use this command to install the repository directly from a Git SSH URL. ```sh $ npm install git+ssh://git@github.com:Metronome-Industries/metronome-node.git ``` -------------------------------- ### Billing Configuration Example Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/05-v1-customers-api.md An example of a billing configuration object that can be passed during customer creation. ```json { "billing_provider": "stripe", "delivery_method": "direct_to_billing_provider", "configuration": { "stripe_customer_id": "cus_xyz123", "stripe_collection_method": "charge_automatically", }, } ``` -------------------------------- ### Install Metronome SDK Source: https://github.com/metronome-industries/metronome-node/blob/main/README.md Install the Metronome SDK using npm. ```sh npm install @metronome/sdk ``` -------------------------------- ### Install Metronome SDK Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/00-index.md Install the Metronome SDK using npm, yarn, or pnpm. ```bash npm install @metronome/sdk # or yarn add @metronome/sdk # or pnpm add @metronome/sdk ``` -------------------------------- ### MCP Server Configuration JSON Example Source: https://github.com/metronome-industries/metronome-node/blob/main/packages/mcp-server/README.md Example configuration JSON for clients that support it. This specifies how to run the MCP server with specific arguments and environment variables. ```json { "mcpServers": { "metronome_sdk_api": { "command": "npx", "args": ["-y", "@metronome/mcp"], "env": { "METRONOME_BEARER_TOKEN": "My Bearer Token", "METRONOME_WEBHOOK_SECRET": "My Webhook Secret" } } } } ``` -------------------------------- ### Manual Pagination Example Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/03-pagination-and-responses.md Demonstrates how to fetch the first page, check for subsequent pages, and manually loop through all pages of customer data. ```typescript const page = await client.v1.customers.list(); console.log(page.data); console.log(page.next_page); if (page.hasNextPage()) { const nextPage = await page.getNextPage(); console.log(nextPage.data); } let page = await client.v1.customers.list(); while (page.hasNextPage()) { for (const item of page.data) { console.log(item); } page = await page.getNextPage(); } for (const item of page.data) { console.log(item); } ``` -------------------------------- ### Body-Based Pagination Example Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/03-pagination-and-responses.md Demonstrates how to use body-based pagination for fetching lists of items, including parameters like starting_on, ending_before, window_size, and next_page. ```APIDOC ## Usage list with body-based pagination This example shows how to paginate through usage data by providing pagination parameters directly in the request body. ### Method ```typescript client.v1.usage.list ``` ### Parameters - **starting_on** (string) - Required - The start date for the usage data. - **ending_before** (string) - Required - The end date for the usage data. - **window_size** (string) - Required - The time window size for grouping usage data (e.g., 'day'). - **next_page** (string | undefined) - Optional - A cursor for fetching the next page of results. Pass `undefined` for the first request. ``` -------------------------------- ### Create Contract Source: https://github.com/metronome-industries/metronome-node/blob/main/README.md This example shows how to create a new contract using the `client.v1.contracts.create` method. It defines the necessary parameters, including `customer_id` and `starting_at`, and demonstrates how to use the TypeScript types for request and response. ```APIDOC ## Create Contract ### Description Creates a new contract for a customer, defining the terms of service and billing. ### Method POST ### Endpoint /v1/contracts ### Parameters #### Request Body - **customer_id** (string) - Required - The unique identifier of the customer for whom the contract is being created. - **starting_at** (string) - Required - The date and time when the contract becomes effective (ISO 8601 format). ### Request Example ```json { "customer_id": "13117714-3f05-48e5-a6e9-a66093f13b4d", "starting_at": "2020-01-01T00:00:00.000Z" } ``` ### Response #### Success Response (200) - **contract** (object) - Details of the created contract. - **id** (string) - The unique identifier of the contract. - **customer_id** (string) - The ID of the customer associated with the contract. - **starting_at** (string) - The effective start date and time of the contract. - **created_at** (string) - The date and time when the contract was created. - **updated_at** (string) - The date and time when the contract was last updated. #### Response Example ```json { "contract": { "id": "c8b0f1a2-3e4d-5c6b-7a8f-9e0d1c2b3a4f", "customer_id": "13117714-3f05-48e5-a6e9-a66093f13b4d", "starting_at": "2020-01-01T00:00:00.000Z", "created_at": "2023-10-27T10:00:00.000Z", "updated_at": "2023-10-27T10:00:00.000Z" } } ``` ``` -------------------------------- ### Install and Run MCP Server Directly Source: https://github.com/metronome-industries/metronome-node/blob/main/packages/mcp-server/README.md Run the MCP Server directly using npx. Ensure your METRONOME_BEARER_TOKEN and METRONOME_WEBHOOK_SECRET environment variables are set. ```sh export METRONOME_BEARER_TOKEN="My Bearer Token" export METRONOME_WEBHOOK_SECRET="My Webhook Secret" npx -y @metronome/mcp@latest ``` -------------------------------- ### Initialize Invoices API Client Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/07-v1-billing-metrics-and-others.md Instantiate the client for interacting with the Invoices API. No setup is required beyond having an authenticated client instance. ```typescript const invoicesAPI = client.v1.invoices; ``` -------------------------------- ### Iterating Over Pages Example Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/03-pagination-and-responses.md Shows how to asynchronously iterate over all pages of customer data without auto-fetching items, processing each page as it becomes available. ```typescript const page = await client.v1.customers.list(); for await (const currentPage of page.iterPages()) { console.log(`Page with ${currentPage.data.length} items`); for (const item of currentPage.data) { // Process item } } ``` -------------------------------- ### PLG Onboarding Workflow Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/00-index.md This workflow demonstrates the steps to onboard a new customer using a Product-Led Growth (PLG) model. It includes creating a customer, configuring their billing, setting up a contract with a rate card, and starting usage ingestion. ```typescript // 1. Create customer const customer = await client.v1.customers.create({ name: customer_name, ingest_aliases: [customer_email], }); // 2. Configure billing await client.v1.customers.billingConfig.create({ customer_id: customer.customer_id, billing_provider_configurations: [{ billing_provider: 'stripe', delivery_method: 'direct_to_billing_provider', configuration: { stripe_customer_id: stripe_customer_id }, }], }); // 3. Create contract with rate card const contract = await client.v1.contracts.create({ customer_id: customer.customer_id, starting_at: new Date().toISOString(), rate_card_id: rate_card_id, billing_provider_configuration: { billing_provider: 'stripe', delivery_method: 'direct_to_billing_provider', }, }); // 4. Start ingesting usage await client.v1.usage.ingest({ usage: [{ transaction_id: uuid(), customer_id: customer_email, event_type: 'api_call', timestamp: new Date().toISOString(), properties: { endpoint: path, method, region }, }], }); ``` -------------------------------- ### GET /v1/customers/{customer_id}/plans Source: https://github.com/metronome-industries/metronome-node/blob/main/api.md Retrieves a list of plans for a given customer. Supports pagination. ```APIDOC ## GET /v1/customers/{customer_id}/plans ### Description Retrieves a paginated list of plans associated with a specific customer. ### Method GET ### Endpoint /v1/customers/{customer_id}/plans ### Parameters #### Path Parameters - **customer_id** (string) - Required - The unique identifier for the customer. #### Query Parameters - **params** (object) - Optional - Parameters for pagination and filtering. ### Response #### Success Response (200) - **PlanListResponsesCursorPage** - The response contains a cursor-based paginated list of plans. ``` -------------------------------- ### Reporting Workflows Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/00-index.md This section provides examples for retrieving various types of usage and billing data. It includes fetching usage data by customer and metric, usage breakdowns by group (e.g., region), listing and retrieving invoices, and accessing the audit trail. ```typescript // Get usage data by customer and metric for await (const usage of client.v1.usage.list({ starting_on: '2024-01-01T00:00:00Z', ending_before: '2024-01-31T23:59:59Z', window_size: 'day', })) { console.log(`${usage.billable_metric_name}: ${usage.value} on ${usage.start_timestamp}`); } // Get usage breakdown by region for await (const usage of client.v1.usage.listWithGroups({ customer_id: customer_id, billable_metric_id: metric_id, window_size: 'day', starting_on: '2024-01-01T00:00:00Z', ending_before: '2024-01-31T23:59:59Z', group_key: ['region'], })) { console.log(`Region ${usage.group.region}: ${usage.value} units`); } // List invoices for await (const invoice of client.v1.customers.invoices.list({ customer_id: customer_id, })) { console.log(`Invoice ${invoice.id}: $${invoice.total / 100}`); } // Get invoice details const invoice = await client.v1.customers.invoices.retrieve({ customer_id: customer_id, invoice_id: invoice_id, }); // List audit trail for await (const entry of client.v1.audit_logs.list()) { console.log(`${entry.timestamp}: ${entry.action} by ${entry.actor}`); } ``` -------------------------------- ### Fetch First Page and Next Page Cursor Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/03-pagination-and-responses.md Demonstrates how to fetch the first page of results and retrieve the cursor for the next page. Use this to get initial data and prepare for subsequent fetches. ```typescript // Get first page const page = await client.v1.customers.list(); console.log(page.data); console.log(page.next_page); // Check if more pages exist if (page.hasNextPage()) { const nextPage = await page.getNextPage(); console.log(nextPage.data); } ``` -------------------------------- ### Ingest Usage Data Source: https://github.com/metronome-industries/metronome-node/blob/main/README.md This example demonstrates how to ingest usage data using the `client.v1.usage.ingest` method. It includes a sample usage payload with transaction details, customer information, event type, timestamp, and properties. ```APIDOC ## Ingest Usage Data ### Description Ingests usage data for billing and analytics purposes. ### Method POST ### Endpoint /v1/usage/ingest ### Request Body - **usage** (array) - Required - An array of usage records. - **transaction_id** (string) - Required - Unique identifier for the transaction. - **customer_id** (string) - Required - Identifier for the customer. - **event_type** (string) - Required - The type of usage event. - **timestamp** (string) - Required - The time the event occurred (ISO 8601 format). - **properties** (object) - Optional - Additional properties for the usage event. - **cluster_id** (string) - Optional - Identifier for the cluster. - **cpu_seconds** (number) - Optional - CPU time consumed in seconds. - **region** (string) - Optional - The region where the usage occurred. ### Request Example ```json { "usage": [ { "transaction_id": "90e9401f-0f8c-4cd3-9a9f-d6beb56d8d72", "customer_id": "team@example.com", "event_type": "heartbeat", "timestamp": "2024-01-01T00:00:00Z", "properties": { "cluster_id": "42", "cpu_seconds": 60, "region": "Europe" } } ] } ``` ### Response #### Success Response (200) An empty object `{}` is returned on successful ingestion. ``` -------------------------------- ### Get Detailed Plan Configuration Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/07-v1-billing-metrics-and-others.md Fetch the detailed configuration for a specific billing plan. Requires plan identification parameters. ```typescript getDetails(params: PlanGetDetailsParams, options?: RequestOptions): APIPromise ``` -------------------------------- ### Custom Endpoint POST Request Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/01-client-initialization.md Example of making a POST request to a custom endpoint with a request body and query parameters. ```typescript const result = await client.post('/custom/endpoint', { body: { key: 'value' }, query: { param: 'value' }, }); ``` -------------------------------- ### MCP Server Configuration JSON Source: https://github.com/metronome-industries/metronome-node/blob/main/packages/mcp-server/README.md Example JSON configuration for an MCP server, specifying the URL and authorization headers for a Metronome SDK API. ```json { "mcpServers": { "metronome_sdk_api": { "url": "http://localhost:3000", "headers": { "Authorization": "Bearer " } } } } ``` -------------------------------- ### Body-Based Pagination Example Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/03-pagination-and-responses.md Use this pattern when the API requires pagination parameters in the request body. Pass the `next_page` token from the previous response to fetch subsequent pages. ```typescript for await (const item of client.v1.usage.list({ starting_on: '2024-01-01T00:00:00Z', ending_before: '2024-01-31T23:59:59Z', window_size: 'day', next_page: undefined, // Pass next_page from previous response })) { console.log('Usage data:', item); } ``` -------------------------------- ### Install MCP Server with Claude Code Source: https://github.com/metronome-industries/metronome-node/blob/main/packages/mcp-server/README.md Command to add the Metronome MCP server using Claude Code. Environment variables must be set during the command execution. ```bash claude mcp add metronome_mcp_api --env METRONOME_BEARER_TOKEN="My Bearer Token" METRONOME_WEBHOOK_SECRET="My Webhook Secret" -- npx -y @metronome/mcp ``` -------------------------------- ### Example Property Usage in Metronome Events Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/04-v1-usage-api.md Illustrates how to use properties within Metronome events for metric matching, grouping, and segmentation. These properties help in defining billable metrics and enabling dimensional analysis. ```typescript { // Properties used for metric matching endpoint: '/v1/users', method: 'POST', // Properties for grouping/segmentation region: 'us-west-2', team: 'engineering', environment: 'production', // Metrics values response_time_ms: 45, cpu_seconds: 120, } ``` -------------------------------- ### Customer Ingest Aliases Configuration Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/05-v1-customers-api.md Example of configuring multiple aliases for a customer to support various ID formats during usage event ingestion. This allows referencing customers by email, external IDs, or legacy system IDs. ```typescript ingest_aliases: [ 'customer@example.com', 'cus_stripe_123', 'legacy-account-42', ] ``` -------------------------------- ### Run Mock Server Source: https://github.com/metronome-industries/metronome-node/blob/main/CONTRIBUTING.md Execute this script to set up a mock server required for running tests. ```sh $ ./scripts/mock ``` -------------------------------- ### Dashboards API Source: https://github.com/metronome-industries/metronome-node/blob/main/api.md Get embeddable URLs for dashboards. ```APIDOC ## POST /v1/dashboards/getEmbeddableUrl ### Description Retrieves an embeddable URL for a dashboard. ### Method POST ### Endpoint /v1/dashboards/getEmbeddableUrl ### Request Example ```json { "params": { ... } } ``` ### Response #### Success Response (200) - **DashboardGetEmbeddableURLResponse** (object) - The response object containing the embeddable URL. ``` -------------------------------- ### Get Contract Edit History Source: https://github.com/metronome-industries/metronome-node/blob/main/api.md Retrieves the edit history for a contract. ```APIDOC ## POST /v2/contracts/getEditHistory ### Description Retrieves the edit history for a contract. ### Method POST ### Endpoint /v2/contracts/getEditHistory ### Parameters #### Request Body - **params** (object) - Required - Parameters for retrieving the contract edit history. ``` -------------------------------- ### Get Subscription Seats History Source: https://github.com/metronome-industries/metronome-node/blob/main/api.md Retrieves the history of subscription seats for a contract. ```APIDOC ## POST /v1/contracts/getSubscriptionSeatsHistory ### Description Retrieves the historical data for subscription seats related to a contract. ### Method POST ### Endpoint /v1/contracts/getSubscriptionSeatsHistory ### Request Body - **params** (object) - Required - Parameters for retrieving subscription seats history. ### Response #### Success Response (200) - **ContractGetSubscriptionSeatsHistoryResponse** - The response object containing subscription seats history. ``` -------------------------------- ### Get Net Balance Source: https://github.com/metronome-industries/metronome-node/blob/main/api.md Retrieves the net balance for a customer's contract. ```APIDOC ## POST /v1/contracts/customerBalances/getNetBalance ### Description Retrieves the net balance for a customer associated with a contract. ### Method POST ### Endpoint /v1/contracts/customerBalances/getNetBalance ### Request Body - **params** (object) - Required - Parameters for retrieving the net balance. ### Response #### Success Response (200) - **ContractGetNetBalanceResponse** - The response object containing the net balance. ``` -------------------------------- ### GET /v1/customers/{customer_id}/billing-config/{billing_provider_type} Source: https://github.com/metronome-industries/metronome-node/blob/main/api.md Retrieves billing configuration for a customer. ```APIDOC ## GET /v1/customers/{customer_id}/billing-config/{billing_provider_type} ### Description Retrieves the billing configuration for a customer with a specified billing provider. ### Method GET ### Endpoint /v1/customers/{customer_id}/billing-config/{billing_provider_type} ### Parameters #### Path Parameters - **customer_id** (string) - Required - The unique identifier for the customer. - **billing_provider_type** (string) - Required - The type of the billing provider. ### Response #### Success Response (200) - **BillingConfigRetrieveResponse** - The billing configuration details. ``` -------------------------------- ### Proxy Configuration with Deno Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/09-configuration-and-advanced.md Configure an HTTP proxy for Deno environments by creating a Deno.createHttpClient with proxy settings and passing it via fetchOptions. ```typescript import Metronome from 'npm:@metronome/sdk'; const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' }, }); const client = new Metronome({ bearerToken: 'token', fetchOptions: { client: httpClient, }, }); ``` -------------------------------- ### GET /v1/customers/{customer_id}/invoices/{invoice_id} Source: https://github.com/metronome-industries/metronome-node/blob/main/api.md Retrieves a specific invoice for a customer. ```APIDOC ## GET /v1/customers/{customer_id}/invoices/{invoice_id} ### Description Retrieves details of a specific invoice for a customer. ### Method GET ### Endpoint /v1/customers/{customer_id}/invoices/{invoice_id} ### Parameters #### Path Parameters - **customer_id** (string) - Required - The unique identifier for the customer. - **invoice_id** (string) - Required - The unique identifier for the invoice. ### Response #### Success Response (200) - **InvoiceRetrieveResponse** - The details of the requested invoice. ``` -------------------------------- ### GET /v1/customers/{customer_id}/invoices Source: https://github.com/metronome-industries/metronome-node/blob/main/api.md Retrieves a list of invoices for a customer. Supports pagination. ```APIDOC ## GET /v1/customers/{customer_id}/invoices ### Description Retrieves a paginated list of invoices for a customer. ### Method GET ### Endpoint /v1/customers/{customer_id}/invoices ### Parameters #### Path Parameters - **customer_id** (string) - Required - The unique identifier for the customer. #### Query Parameters - **params** (object) - Optional - Parameters for pagination and filtering. ### Response #### Success Response (200) - **InvoicesCursorPage** - The response contains a cursor-based paginated list of invoices. ``` -------------------------------- ### Enterprise Pricing Workflow Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/00-index.md This workflow illustrates how to set up enterprise-level pricing, including custom terms, discounts, and prepaid commitments. It covers creating a customer with custom fields, establishing a contract with overrides and commits, and monitoring spend against the commitment. ```typescript // 1. Create customer const customer = await client.v1.customers.create({ name: 'Enterprise Corp', custom_fields: { tier: 'enterprise', sales_rep: 'john@company.com' }, }); // 2. Create contract with custom terms const contract = await client.v1.contracts.create({ customer_id: customer.customer_id, starting_at: '2024-03-01T00:00:00Z', ending_before: '2025-03-01T00:00:00Z', // 1-year term rate_card_id: rate_card_id, overrides: [{ name: 'Enterprise Discount', discount: { percentage: '25' }, starting_at: '2024-03-01T00:00:00Z', ending_before: '2025-03-01T00:00:00Z', }], commits: [{ product_id: commit_product_id, type: 'PREPAID', amount: '100000.00', // $100,000 prepaid invoice_schedule: { starting_at: '2024-03-01T00:00:00Z' }, }], billing_provider_configuration: { billing_provider: 'stripe', delivery_method: 'direct_to_billing_provider', }, }); // 3. Add pricing overrides for specific use cases // Done during contract creation (above) or via amendments // 4. Monitor spend against commit const balance = await client.v1.contracts.getNetBalance({ customer_id: customer.customer_id, filters: [{ balance_types: ['PREPAID_COMMIT'] }], }); console.log(`Remaining commitment: $${balance.balance / 100}`); ``` -------------------------------- ### Dashboards API - Get Embeddable URL Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/07-v1-billing-metrics-and-others.md Retrieves an embeddable URL for a specific dashboard. ```APIDOC ## Dashboards API - Get Embeddable URL ### Description Get embeddable dashboard URL. ### Method `getEmbeddableURL` ### Parameters #### Path Parameters - **params** (DashboardGetEmbeddableURLParams) - Required - Parameters for getting the embeddable URL. - **options** (RequestOptions) - Optional - Request options. ### Response #### Success Response - **APIPromise** - A promise that resolves to the dashboard embeddable URL response. ### Request Example ```typescript const dashboard = await client.v1.dashboards.getEmbeddableURL({ customer_id: 'cus_123', dashboard_type: 'usage', }); console.log('Embed URL:', dashboard.url); ``` ``` -------------------------------- ### Create Product Source: https://github.com/metronome-industries/metronome-node/blob/main/api.md Creates a new product. Requires product details as parameters. ```APIDOC ## POST /v1/contract-pricing/products/create ### Description Creates a new product. ### Method POST ### Endpoint /v1/contract-pricing/products/create ### Parameters #### Request Body - **params** (object) - Required - Product details for creation. ``` -------------------------------- ### GET /v1/customers/{customer_id}/invoices/breakdowns Source: https://github.com/metronome-industries/metronome-node/blob/main/api.md Retrieves breakdowns for a customer's invoices. Supports pagination. ```APIDOC ## GET /v1/customers/{customer_id}/invoices/breakdowns ### Description Retrieves a paginated list of invoice breakdowns for a customer. ### Method GET ### Endpoint /v1/customers/{customer_id}/invoices/breakdowns ### Parameters #### Path Parameters - **customer_id** (string) - Required - The unique identifier for the customer. #### Query Parameters - **params** (object) - Optional - Parameters for pagination and filtering. ### Response #### Success Response (200) - **InvoiceListBreakdownsResponsesCursorPage** - The response contains a cursor-based paginated list of invoice breakdowns. ``` -------------------------------- ### Client Initialization Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/COMPLETION_REPORT.txt Details on how to initialize and configure the Metronome client. ```APIDOC ## Client Initialization ### Description Guides users through setting up and configuring the Metronome client. ### Configuration Options - 13 ClientOptions properties - 5 environment variables - 7 proxy configurations - 5 logger configurations ``` -------------------------------- ### GET /v1/customers/{customer_id}/invoices/{invoice_id}/pdf Source: https://github.com/metronome-industries/metronome-node/blob/main/api.md Retrieves the PDF version of a specific invoice for a customer. ```APIDOC ## GET /v1/customers/{customer_id}/invoices/{invoice_id}/pdf ### Description Retrieves the PDF document for a specific customer invoice. ### Method GET ### Endpoint /v1/customers/{customer_id}/invoices/{invoice_id}/pdf ### Parameters #### Path Parameters - **customer_id** (string) - Required - The unique identifier for the customer. - **invoice_id** (string) - Required - The unique identifier for the invoice. ### Response #### Success Response (200) - **Response** - The PDF content of the invoice. ``` -------------------------------- ### Run Tests Source: https://github.com/metronome-industries/metronome-node/blob/main/CONTRIBUTING.md Execute the test suite for the project. ```sh $ yarn run test ``` -------------------------------- ### GET /v1/customers/{customer_id}/plans/{customer_plan_id}/priceAdjustments Source: https://github.com/metronome-industries/metronome-node/blob/main/api.md Retrieves price adjustments for a specific customer plan. ```APIDOC ## GET /v1/customers/{customer_id}/plans/{customer_plan_id}/priceAdjustments ### Description Retrieves a list of price adjustments for a specific customer plan. ### Method GET ### Endpoint /v1/customers/{customer_id}/plans/{customer_plan_id}/priceAdjustments ### Parameters #### Path Parameters - **customer_id** (string) - Required - The unique identifier for the customer. - **customer_plan_id** (string) - Required - The unique identifier for the customer's plan. #### Query Parameters - **params** (object) - Optional - Parameters for pagination and filtering. ### Response #### Success Response (200) - **PlanListPriceAdjustmentsResponsesCursorPage** - The response contains a cursor-based paginated list of price adjustments. ``` -------------------------------- ### Make Custom GET Request Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/09-configuration-and-advanced.md Use the client.get method for undocumented endpoints, specifying query parameters as needed. ```typescript const data = await client.get('/v1/custom/info', { query: { filter: 'active' }, }); ``` -------------------------------- ### Make Custom DELETE Request Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/09-configuration-and-advanced.md Use the client.delete method for undocumented endpoints. No body or query parameters are shown in this example. ```typescript await client.delete('/v1/custom/resource'); ``` -------------------------------- ### create() Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/06-v1-contracts-api.md Creates a new contract for a customer with specified pricing, terms, and billing configurations. ```APIDOC ## create() ### Description Create a new contract for a customer. ### Method create(params: ContractCreateParams, options?: RequestOptions): APIPromise ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **customer_id** (string) - Required - Metronome customer ID - **starting_at** (string) - Required - Contract start date (ISO 8601) - **ending_before** (string) - Optional - Contract end date (ISO 8601). Omit for perpetual - **rate_card_id** (string) - Optional - Rate card UUID for usage-based pricing - **rate_card_alias** (string) - Optional - Rate card alias (alternative to ID) - **billing_provider_configuration** (object) - Required - Billing system configuration (Stripe, Zuora, etc.) - **usage_filters** (Array) - Optional - Route specific usage to this contract - **overrides** (Array) - Optional - Time-bounded pricing overrides - **commits** (Array) - Optional - Prepaid/postpaid spending commitments - **credits** (Array) - Optional - Credit grants and allowances - **subscriptions** (Array) - Optional - Fixed recurring charges - **scheduled_charges** (Array) - Optional - One-time or recurring charges on specific dates - **spend_threshold_configuration** (object) - Optional - Automatic threshold billing triggers - **prepaid_balance_configuration** (object) - Optional - Minimum prepaid balance requirements ### Request Example ```typescript const contract = await client.v1.contracts.create({ customer_id: '13117714-3f05-48e5-a6e9-a66093f13b4d', starting_at: '2024-02-01T00:00:00Z', rate_card_id: 'd7abd0cd-4ae9-4db7-8676-e986a4ebd8dc', billing_provider_configuration: { billing_provider: 'stripe', delivery_method: 'direct_to_billing_provider', }, overrides: [ { name: 'Enterprise Discount', discount: { percentage: '20', }, starting_at: '2024-02-01T00:00:00Z', ending_before: '2024-12-31T23:59:59Z', }, ], commits: [ { product_id: 'prod_commit_123', type: 'PREPAID', amount: '5000.00', invoice_schedule: { starting_at: '2024-02-01T00:00:00Z', }, }, ], }); ``` ### Response #### Success Response (200) - **Promise** - Full contract details #### Response Example None provided in source. ``` -------------------------------- ### Initialize Credit Grants API Client Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/07-v1-billing-metrics-and-others.md Instantiate the client for interacting with the Credit Grants API. Ensure you have an authenticated client instance. ```typescript const creditsAPI = client.v1.credit_grants; ``` -------------------------------- ### Configuration Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/COMPLETION_REPORT.txt Details on how to configure the Metronome SDK. ```APIDOC ## Configuration - Environment variables. - Constructor options. - Request options. - Per-request overrides. ``` -------------------------------- ### Initialize Packages API Client Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/07-v1-billing-metrics-and-others.md Instantiate the client for interacting with the Packages API. This client is used for all subsequent package-related operations. ```typescript const packagesAPI = client.v1.packages; ``` -------------------------------- ### Configure Node.js Proxy with undici Source: https://github.com/metronome-industries/metronome-node/blob/main/README.md Use custom fetchOptions with undici.ProxyAgent to configure proxy behavior in Node.js. Ensure undici is installed. ```typescript import Metronome from '@metronome/sdk'; import * as undici from 'undici'; const proxyAgent = new undici.ProxyAgent('http://localhost:8888'); const client = new Metronome({ fetchOptions: { dispatcher: proxyAgent, }, }); ``` -------------------------------- ### Get Embeddable Dashboard URL Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/07-v1-billing-metrics-and-others.md Retrieves a URL for embedding a dashboard. Requires a 'customer_id' and 'dashboard_type'. The response contains the embeddable 'url'. ```typescript const dashboard = await client.v1.dashboards.getEmbeddableURL({ customer_id: 'cus_123', dashboard_type: 'usage', }); console.log('Embed URL:', dashboard.url); ``` -------------------------------- ### BaseUsageFilter Type Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/08-types-reference.md Routes usage to specific contracts based on group keys and values. Can optionally specify a start date for the filter. ```typescript interface BaseUsageFilter { group_key: string; group_values: Array; starting_at?: string; } ``` -------------------------------- ### Configure Deno Proxy with Deno.createHttpClient Source: https://github.com/metronome-industries/metronome-node/blob/main/README.md Configure proxy behavior in Deno using Deno.createHttpClient and passing the resulting httpClient to the Metronome SDK's fetchOptions. Requires Deno v1.28.0 or higher. ```typescript import Metronome from 'npm:@metronome/sdk'; const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } }); const client = new Metronome({ fetchOptions: { client: httpClient, }, }); ``` -------------------------------- ### Packages API Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/07-v1-billing-metrics-and-others.md Manage pre-built product packages. ```APIDOC ## Packages API Manage pre-built product packages. ### Methods #### create() Create a package. ```typescript create(params: PackageCreateParams, options?: RequestOptions): APIPromise ``` #### list() List packages. ```typescript list(query?: PackageListParams, options?: RequestOptions): PagePromise ``` #### retrieve() Get package details. ```typescript retrieve(params: PackageRetrieveParams, options?: RequestOptions): APIPromise ``` #### archive() Archive a package. ```typescript archive(params: PackageArchiveParams, options?: RequestOptions): APIPromise ``` #### listContractsOnPackage() List contracts using this package. ```typescript listContractsOnPackage( params: PackageListContractsOnPackageParams, options?: RequestOptions ): PagePromise< PackageListContractsOnPackageResponsesCursorPage, PackageListContractsOnPackageResponse > ``` ``` -------------------------------- ### ScheduleDuration Type Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/08-types-reference.md Defines a time period with a start and an optional end date. Used for recurring billing or events that span a duration. ```typescript interface ScheduleDuration { starting_at: string; ending_before?: string; } ``` -------------------------------- ### Pagination with Query Parameters Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/03-pagination-and-responses.md Illustrates how to use query parameters like 'limit' for controlling the number of items per page and 'next_page' to resume fetching from a specific cursor. ```typescript for await (const customer of client.v1.customers.list({ limit: 10 })) { console.log(customer); } const firstPage = await client.v1.customers.list({ limit: 50 }); const secondPage = await client.v1.customers.list({ limit: 50, next_page: firstPage.next_page, }); ``` -------------------------------- ### Initialize Plans API Client Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/07-v1-billing-metrics-and-others.md Instantiate the client for interacting with the Plans API. This client is used to manage billing plans. ```typescript const plansAPI = client.v1.plans; ``` -------------------------------- ### POST /v1/customers/{customer_id}/plans/add Source: https://github.com/metronome-industries/metronome-node/blob/main/api.md Adds a new plan for a given customer. ```APIDOC ## POST /v1/customers/{customer_id}/plans/add ### Description Adds a new plan to a customer's account. ### Method POST ### Endpoint /v1/customers/{customer_id}/plans/add ### Parameters #### Path Parameters - **customer_id** (string) - Required - The unique identifier for the customer. #### Request Body - **params** (object) - Required - Parameters for adding the plan. ### Response #### Success Response (200) - **PlanAddResponse** - Details of the newly added plan. ``` -------------------------------- ### Proxy Configuration with Bun Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/09-configuration-and-advanced.md Configure an HTTP proxy for Bun environments by specifying the proxy URL directly within the fetchOptions. ```typescript const client = new Metronome({ bearerToken: 'token', fetchOptions: { proxy: 'http://localhost:8888', }, }); ``` -------------------------------- ### Metronome Client Constructor and Methods Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/README.md Initialize the Metronome client and use its core methods for API interactions. ```APIDOC ## Metronome Client ### Description The Metronome client provides methods to interact with the Metronome API. It can be initialized with various options and offers utility methods for making API requests. ### Methods - `constructor(options: ClientOptions)`: Initializes a new Metronome client instance. - `withOptions(options: Partial): Metronome`: Returns a new Metronome client instance with merged options. - `get(path, opts?): APIPromise`: Makes a GET request to the specified API path. - `post(path, opts?): APIPromise`: Makes a POST request to the specified API path. - `patch(path, opts?): APIPromise`: Makes a PATCH request to the specified API path. - `put(path, opts?): APIPromise`: Makes a PUT request to the specified API path. - `delete(path, opts?): APIPromise`: Makes a DELETE request to the specified API path. ``` -------------------------------- ### Get Net Balance Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/06-v1-contracts-api.md Retrieve the combined balance across commits and credits for a customer. Supports filtering by balance type, IDs, and custom fields. ```typescript // Get all credit balance const response = await client.v1.contracts.getNetBalance({ customer_id: 'cus_123', filters: [ { balance_types: ['CREDIT'], }, ], }); console.log('Available credits:', response.balance / 100); // Convert cents to dollars // Get free-trial credits OR signup-promotion commits const response = await client.v1.contracts.getNetBalance({ customer_id: 'cus_123', filters: [ { balance_types: ['CREDIT'], custom_fields: { campaign: 'free-trial' }, }, { balance_types: ['PREPAID_COMMIT'], custom_fields: { campaign: 'signup-promotion' }, }, ], }); ``` -------------------------------- ### Access Parsed API Response Data Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/03-pagination-and-responses.md Explains how to get the parsed data directly from an API promise. This is the standard way to access the results of an API call. ```typescript // Get parsed response const response = await apiPromise; ``` -------------------------------- ### Initialize Pricing Units API Client Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/07-v1-billing-metrics-and-others.md Instantiate the client for interacting with the Pricing Units API. This client is used to manage custom pricing units like credits or tokens. ```typescript const unitsAPI = client.v1.pricing_units; ``` -------------------------------- ### Initialize Billable Metrics API Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/07-v1-billing-metrics-and-others.md Instantiate the Billable Metrics API client. This is typically done once when setting up your service. ```typescript const metricsAPI = client.v1.billable_metrics; ``` -------------------------------- ### SDK Entry Point Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/COMPLETION_REPORT.txt The main entry point for the Metronome SDK, exporting core classes and types. ```APIDOC ## SDK Entry Point (src/index.ts) - Metronome class export - Error classes export - Pagination classes export - Type exports ``` -------------------------------- ### Get Subscription Seats History Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/06-v1-contracts-api.md Retrieve seat assignment history for a subscription. You can specify a `covering_date` for a specific point in time or a date range using `starting_at` and `ending_before`. ```typescript getSubscriptionSeatsHistory( params: ContractGetSubscriptionSeatsHistoryParams, options?: RequestOptions ): APIPromise ``` ```typescript // Get active seats for specific date const response = await client.v1.contracts.getSubscriptionSeatsHistory({ contract_id: 'd7abd0cd-4ae9-4db7-8676-e986a4ebd8dc', customer_id: '13117714-3f05-48e5-a6e9-a66093f13b4d', subscription_id: '1a824d53-bde6-4d82-96d7-6347ff227d5c', covering_date: '2024-01-15T00:00:00Z', }); ``` ```typescript // Get seat assignment changes over time range const response = await client.v1.contracts.getSubscriptionSeatsHistory({ contract_id: 'd7abd0cd-4ae9-4db7-8676-e986a4ebd8dc', customer_id: '13117714-3f05-48e5-a6e9-a66093f13b4d', subscription_id: '1a824d53-bde6-4d82-96d7-6347ff227d5c', starting_at: '2024-01-01T00:00:00Z', ending_before: '2024-12-31T23:59:59Z', limit: 50, }); ``` -------------------------------- ### Create Customer Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/00-index.md Shows how to create a new customer in the Metronome system. This is a prerequisite for creating contracts. ```APIDOC ## Create Customer ### Description Create a new customer in the Metronome system. ### Method `client.v1.customers.create(params)` ### Parameters #### Request Body - **name** (string) - Required - The name of the customer. - **ingest_aliases** (array) - Optional - A list of aliases for ingesting usage data for this customer. ### Request Example ```json { "name": "Acme Corp", "ingest_aliases": ["team@acme.com"] } ``` ### Response #### Success Response (200) - **customer_id** (string) - The unique identifier for the newly created customer. - **name** (string) - The name of the customer. - **ingest_aliases** (array) - The ingest aliases for the customer. ``` -------------------------------- ### Initialize Services API Client Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/07-v1-billing-metrics-and-others.md Instantiate the client for interacting with the Services API. This client is used to manage services within your platform. ```typescript const servicesAPI = client.v1.services; ``` -------------------------------- ### Use Undocumented Request Parameters Source: https://github.com/metronome-industries/metronome-node/blob/main/README.md Add undocumented parameters to requests using '// @ts-expect-error'. Extra parameters are sent in the query for GET requests, and in the body for others. ```typescript client.v1.usage.ingest({ // ... // @ts-expect-error baz is not yet public baz: 'undocumented option', }); ``` -------------------------------- ### Access Raw Response Headers and Status Source: https://github.com/metronome-industries/metronome-node/blob/main/README.md Use the `.asResponse()` method to get the raw `Response` object from `fetch()`. This allows access to headers and status before the body is consumed. ```typescript const client = new Metronome(); const response = await client.v1.contracts .create({ customer_id: '13117714-3f05-48e5-a6e9-a66093f13b4d', starting_at: '2020-01-01T00:00:00.000Z', }) .asResponse(); console.log(response.headers.get('X-My-Header')); console.log(response.statusText); // access the underlying Response object ``` -------------------------------- ### client.v1.packages.create Source: https://github.com/metronome-industries/metronome-node/blob/main/api.md Creates a new package. This method is part of the packages API. ```APIDOC ## POST /v1/packages/create ### Description Creates a new package. ### Method POST ### Endpoint /v1/packages/create ### Parameters #### Request Body - **params** (object) - Required - Parameters for creating a package. ### Response #### Success Response (200) - **PackageCreateResponse** (object) - Details of the created package. ``` -------------------------------- ### Request Cancellation with AbortController Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/09-configuration-and-advanced.md Cancel ongoing requests using the standard `AbortController` API. This allows you to stop requests that are no longer needed, for example, due to user interaction or timeouts. ```APIDOC ## Request Cancellation with AbortController ```typescript const controller = new AbortController(); const promise = client.v1.customers.list( {}, { signal: controller.signal } ); // Cancel after 2 seconds setTimeout(() => controller.abort(), 2000); try { await promise; } catch (err) { if (err instanceof Metronome.APIUserAbortError) { console.log('Request was cancelled'); } } ``` ``` -------------------------------- ### List Products Source: https://github.com/metronome-industries/metronome-node/blob/main/api.md Lists all products, supporting pagination. Requires pagination parameters. ```APIDOC ## POST /v1/contract-pricing/products/list ### Description Lists all products, supporting pagination. ### Method POST ### Endpoint /v1/contract-pricing/products/list ### Parameters #### Request Body - **params** (object) - Required - Pagination parameters. ``` -------------------------------- ### Basic API Error Handling Source: https://github.com/metronome-industries/metronome-node/blob/main/_autodocs/02-error-handling.md Catch and inspect general API errors. This example demonstrates how to access common properties like status, message, headers, and the error object. ```typescript import Metronome from '@metronome/sdk'; const client = new Metronome({ bearerToken: 'token' }); try { await client.v1.customers.retrieve({ customer_id: 'invalid-id' }); } catch (err) { if (err instanceof Metronome.APIError) { console.log(err.status); // 404 console.log(err.message); // '404 Customer not found' console.log(err.headers); // Response headers console.log(err.error); // { message: 'Customer not found' } } } ```