@monigo/sdk 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -23,7 +23,9 @@ export declare interface CreateCustomerRequest {
23
23
  /** Your internal ID for this customer. */
24
24
  external_id: string;
25
25
  name: string;
26
- email: string;
26
+ email?: string;
27
+ /** Phone number in E.164 international format (e.g. +2348012345678). Optional. */
28
+ phone?: string;
27
29
  metadata?: Record<string, unknown>;
28
30
  }
29
31
 
@@ -93,6 +95,8 @@ export declare interface Customer {
93
95
  external_id: string;
94
96
  name: string;
95
97
  email: string;
98
+ /** Phone number in E.164 international format (e.g. +2348012345678). */
99
+ phone: string;
96
100
  /** Arbitrary JSON metadata. */
97
101
  metadata: Record<string, unknown> | null;
98
102
  created_at: string;
@@ -893,6 +897,8 @@ export declare type SubscriptionStatusValue = (typeof SubscriptionStatus)[keyof
893
897
  export declare interface UpdateCustomerRequest {
894
898
  name?: string;
895
899
  email?: string;
900
+ /** Phone number in E.164 international format (e.g. +2348012345678). Optional. */
901
+ phone?: string;
896
902
  metadata?: Record<string, unknown>;
897
903
  }
898
904
 
@@ -1 +1 @@
1
- {"version":3,"file":"monigo.cjs","sources":["../src/errors.ts","../src/resources/events.ts","../src/resources/customers.ts","../src/resources/metrics.ts","../src/resources/plans.ts","../src/resources/subscriptions.ts","../src/resources/payout-accounts.ts","../src/resources/invoices.ts","../src/resources/usage.ts","../src/client.ts","../src/types.ts"],"sourcesContent":["/**\n * Thrown for any non-2xx response from the Monigo API.\n *\n * @example\n * ```ts\n * try {\n * await client.customers.get('bad-id')\n * } catch (err) {\n * if (MonigoAPIError.isNotFound(err)) {\n * console.log('Customer does not exist')\n * }\n * }\n * ```\n */\nexport class MonigoAPIError extends Error {\n /** HTTP status code returned by the API. */\n readonly statusCode: number\n /** Human-readable error message from the API. */\n readonly message: string\n /** Optional structured field-level validation details. */\n readonly details: Record<string, string> | undefined\n\n constructor(\n statusCode: number,\n message: string,\n details?: Record<string, string>,\n ) {\n super(message)\n this.name = 'MonigoAPIError'\n this.statusCode = statusCode\n this.message = message\n this.details = details\n // Maintain proper stack trace in V8 (Node.js / Chrome)\n const capture = (Error as unknown as Record<string, unknown>)[\n 'captureStackTrace'\n ] as ((target: Error, constructor: Function) => void) | undefined\n capture?.(this, MonigoAPIError)\n }\n\n // -------------------------------------------------------------------------\n // Instance guards (for use on a caught error known to be MonigoAPIError)\n // -------------------------------------------------------------------------\n\n get isNotFound(): boolean {\n return this.statusCode === 404\n }\n\n get isUnauthorized(): boolean {\n return this.statusCode === 401\n }\n\n get isForbidden(): boolean {\n return this.statusCode === 403\n }\n\n get isRateLimited(): boolean {\n return this.statusCode === 429\n }\n\n get isConflict(): boolean {\n return this.statusCode === 409\n }\n\n get isQuotaExceeded(): boolean {\n return this.statusCode === 402\n }\n\n get isServerError(): boolean {\n return this.statusCode >= 500\n }\n\n // -------------------------------------------------------------------------\n // Static type-narrowing helpers (for use in catch clauses on `unknown`)\n // -------------------------------------------------------------------------\n\n static isNotFound(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 404\n }\n\n static isUnauthorized(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 401\n }\n\n static isForbidden(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 403\n }\n\n static isRateLimited(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 429\n }\n\n static isConflict(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 409\n }\n\n static isQuotaExceeded(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 402\n }\n\n static isServerError(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode >= 500\n }\n}\n","import { MonigoClient } from '../client.js'\nimport type { MutationOptions } from '../client.js'\nimport type {\n IngestRequest,\n IngestResponse,\n StartReplayRequest,\n EventReplayJob,\n} from '../types.js'\n\n/** Handles usage event ingestion and asynchronous event replay. */\nexport class EventsResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Ingest one or more usage events into the Monigo pipeline.\n *\n * Events are processed asynchronously. The response confirms receipt\n * and reports any duplicate idempotency keys.\n *\n * **Requires `ingest` scope.**\n *\n * @example\n * ```ts\n * const result = await monigo.events.ingest({\n * events: [{\n * event_name: 'api_call',\n * customer_id: 'cust_abc',\n * idempotency_key: crypto.randomUUID(),\n * timestamp: new Date().toISOString(),\n * properties: { endpoint: '/checkout', region: 'eu-west-1' },\n * }],\n * })\n * console.log('Ingested:', result.ingested.length)\n * console.log('Duplicates:', result.duplicates.length)\n * ```\n */\n async ingest(request: IngestRequest, options?: MutationOptions): Promise<IngestResponse> {\n const body = {\n events: request.events.map((e) => ({\n ...e,\n timestamp: e.timestamp\n ? MonigoClient.toISOString(e.timestamp)\n : new Date().toISOString(),\n })),\n }\n return this.client._request<IngestResponse>('POST', '/v1/ingest', {\n body,\n idempotencyKey: options?.idempotencyKey,\n })\n }\n\n /**\n * Start an asynchronous replay of all raw events in a given time window\n * through the current processing pipeline. Useful for backfilling usage\n * data after changing metric definitions.\n *\n * Returns a replay job immediately — poll `getReplay()` to track progress.\n *\n * **Requires `ingest` scope.**\n *\n * @example\n * ```ts\n * const job = await monigo.events.startReplay({\n * from: '2025-01-01T00:00:00Z',\n * to: '2025-01-31T23:59:59Z',\n * event_name: 'api_call', // omit to replay all event types\n * })\n * console.log('Replay job:', job.id, job.status)\n * ```\n */\n async startReplay(request: StartReplayRequest, options?: MutationOptions): Promise<EventReplayJob> {\n const body = {\n from: MonigoClient.toISOString(request.from),\n to: MonigoClient.toISOString(request.to),\n ...(request.event_name ? { event_name: request.event_name } : {}),\n }\n const wrapper = await this.client._request<{ job: EventReplayJob }>(\n 'POST',\n '/v1/events/replay',\n { body, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.job\n }\n\n /**\n * Fetch the current status and progress of an event replay job.\n *\n * **Requires `ingest` scope.**\n *\n * @example\n * ```ts\n * const job = await monigo.events.getReplay(jobId)\n * if (job.status === 'completed') {\n * console.log(`Replayed ${job.events_replayed} / ${job.events_total} events`)\n * }\n * ```\n */\n async getReplay(jobId: string): Promise<EventReplayJob> {\n const wrapper = await this.client._request<{ job: EventReplayJob }>(\n 'GET',\n `/v1/events/replay/${jobId}`,\n )\n return wrapper.job\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n Customer,\n CreateCustomerRequest,\n UpdateCustomerRequest,\n ListCustomersResponse,\n} from '../types.js'\n\n/** Manage end-customers in your Monigo organisation. */\nexport class CustomersResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Register a new customer.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const customer = await monigo.customers.create({\n * external_id: 'usr_12345',\n * name: 'Acme Corp',\n * email: 'billing@acme.com',\n * metadata: { plan_tier: 'enterprise' },\n * })\n * ```\n */\n async create(request: CreateCustomerRequest, options?: MutationOptions): Promise<Customer> {\n const wrapper = await this.client._request<{ customer: Customer }>(\n 'POST',\n '/v1/customers',\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.customer\n }\n\n /**\n * Return all customers in the authenticated organisation.\n *\n * **Requires `read` scope.**\n */\n async list(): Promise<ListCustomersResponse> {\n return this.client._request<ListCustomersResponse>('GET', '/v1/customers')\n }\n\n /**\n * Fetch a single customer by their Monigo UUID.\n *\n * **Requires `read` scope.**\n */\n async get(customerId: string): Promise<Customer> {\n const wrapper = await this.client._request<{ customer: Customer }>(\n 'GET',\n `/v1/customers/${customerId}`,\n )\n return wrapper.customer\n }\n\n /**\n * Update a customer's name, email, or metadata.\n * Only fields that are present in `request` are updated.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const updated = await monigo.customers.update(customerId, {\n * email: 'new@acme.com',\n * })\n * ```\n */\n async update(\n customerId: string,\n request: UpdateCustomerRequest,\n options?: MutationOptions,\n ): Promise<Customer> {\n const wrapper = await this.client._request<{ customer: Customer }>(\n 'PUT',\n `/v1/customers/${customerId}`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.customer\n }\n\n /**\n * Permanently delete a customer record.\n *\n * **Requires `write` scope.**\n */\n async delete(customerId: string): Promise<void> {\n await this.client._request<void>('DELETE', `/v1/customers/${customerId}`)\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n Metric,\n CreateMetricRequest,\n UpdateMetricRequest,\n ListMetricsResponse,\n} from '../types.js'\n\n/** Manage billing metrics — what usage gets counted and how it is aggregated. */\nexport class MetricsResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Create a new metric.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const metric = await monigo.metrics.create({\n * name: 'API Calls',\n * event_name: 'api_call',\n * aggregation: 'count',\n * })\n * ```\n */\n async create(request: CreateMetricRequest, options?: MutationOptions): Promise<Metric> {\n const wrapper = await this.client._request<{ metric: Metric }>(\n 'POST',\n '/v1/metrics',\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.metric\n }\n\n /**\n * Return all metrics in the authenticated organisation.\n *\n * **Requires `read` scope.**\n */\n async list(): Promise<ListMetricsResponse> {\n return this.client._request<ListMetricsResponse>('GET', '/v1/metrics')\n }\n\n /**\n * Fetch a single metric by its UUID.\n *\n * **Requires `read` scope.**\n */\n async get(metricId: string): Promise<Metric> {\n const wrapper = await this.client._request<{ metric: Metric }>(\n 'GET',\n `/v1/metrics/${metricId}`,\n )\n return wrapper.metric\n }\n\n /**\n * Update a metric's name, event name, aggregation, or description.\n *\n * **Requires `write` scope.**\n */\n async update(metricId: string, request: UpdateMetricRequest, options?: MutationOptions): Promise<Metric> {\n const wrapper = await this.client._request<{ metric: Metric }>(\n 'PUT',\n `/v1/metrics/${metricId}`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.metric\n }\n\n /**\n * Permanently delete a metric.\n *\n * **Requires `write` scope.**\n */\n async delete(metricId: string): Promise<void> {\n await this.client._request<void>('DELETE', `/v1/metrics/${metricId}`)\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n Plan,\n CreatePlanRequest,\n UpdatePlanRequest,\n ListPlansResponse,\n} from '../types.js'\n\n/** Manage billing plans and their prices. */\nexport class PlansResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Create a new billing plan, optionally with prices attached.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const plan = await monigo.plans.create({\n * name: 'Pro',\n * currency: 'NGN',\n * billing_period: 'monthly',\n * prices: [{\n * metric_id: 'metric_abc',\n * model: 'flat',\n * unit_price: '2.500000',\n * }],\n * })\n * ```\n */\n async create(request: CreatePlanRequest, options?: MutationOptions): Promise<Plan> {\n const wrapper = await this.client._request<{ plan: Plan }>(\n 'POST',\n '/v1/plans',\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.plan\n }\n\n /**\n * Return all billing plans in the authenticated organisation.\n *\n * **Requires `read` scope.**\n */\n async list(): Promise<ListPlansResponse> {\n return this.client._request<ListPlansResponse>('GET', '/v1/plans')\n }\n\n /**\n * Fetch a single plan by its UUID, including its prices.\n *\n * **Requires `read` scope.**\n */\n async get(planId: string): Promise<Plan> {\n const wrapper = await this.client._request<{ plan: Plan }>(\n 'GET',\n `/v1/plans/${planId}`,\n )\n return wrapper.plan\n }\n\n /**\n * Update a plan's name, description, currency, or prices.\n *\n * **Requires `write` scope.**\n */\n async update(planId: string, request: UpdatePlanRequest, options?: MutationOptions): Promise<Plan> {\n const wrapper = await this.client._request<{ plan: Plan }>(\n 'PUT',\n `/v1/plans/${planId}`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.plan\n }\n\n /**\n * Permanently delete a plan.\n *\n * **Requires `write` scope.**\n */\n async delete(planId: string): Promise<void> {\n await this.client._request<void>('DELETE', `/v1/plans/${planId}`)\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n Subscription,\n CreateSubscriptionRequest,\n ListSubscriptionsParams,\n ListSubscriptionsResponse,\n SubscriptionStatusValue,\n} from '../types.js'\n\n/** Link customers to billing plans and manage subscription lifecycle. */\nexport class SubscriptionsResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Subscribe a customer to a plan.\n *\n * Returns a 409 Conflict error (check with `MonigoAPIError.isConflict(err)`)\n * if the customer already has an active subscription to the same plan.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const sub = await monigo.subscriptions.create({\n * customer_id: 'cust_abc',\n * plan_id: 'plan_xyz',\n * })\n * ```\n */\n async create(request: CreateSubscriptionRequest, options?: MutationOptions): Promise<Subscription> {\n const wrapper = await this.client._request<{ subscription: Subscription }>(\n 'POST',\n '/v1/subscriptions',\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.subscription\n }\n\n /**\n * Return subscriptions, optionally filtered by customer, plan, or status.\n *\n * **Requires `read` scope.**\n *\n * @example\n * ```ts\n * const { subscriptions } = await monigo.subscriptions.list({\n * customer_id: 'cust_abc',\n * status: 'active',\n * })\n * ```\n */\n async list(params: ListSubscriptionsParams = {}): Promise<ListSubscriptionsResponse> {\n return this.client._request<ListSubscriptionsResponse>('GET', '/v1/subscriptions', {\n query: {\n customer_id: params.customer_id,\n plan_id: params.plan_id,\n status: params.status,\n },\n })\n }\n\n /**\n * Fetch a single subscription by its UUID.\n *\n * **Requires `read` scope.**\n */\n async get(subscriptionId: string): Promise<Subscription> {\n const wrapper = await this.client._request<{ subscription: Subscription }>(\n 'GET',\n `/v1/subscriptions/${subscriptionId}`,\n )\n return wrapper.subscription\n }\n\n /**\n * Change the status of a subscription.\n * Use `SubscriptionStatus` constants: `\"active\"`, `\"paused\"`, `\"canceled\"`.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * await monigo.subscriptions.updateStatus(subId, SubscriptionStatus.Paused)\n * ```\n */\n async updateStatus(\n subscriptionId: string,\n status: SubscriptionStatusValue,\n options?: MutationOptions,\n ): Promise<Subscription> {\n const wrapper = await this.client._request<{ subscription: Subscription }>(\n 'PATCH',\n `/v1/subscriptions/${subscriptionId}`,\n { body: { status }, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.subscription\n }\n\n /**\n * Cancel and delete a subscription record.\n *\n * **Requires `write` scope.**\n */\n async delete(subscriptionId: string): Promise<void> {\n await this.client._request<void>('DELETE', `/v1/subscriptions/${subscriptionId}`)\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n PayoutAccount,\n CreatePayoutAccountRequest,\n UpdatePayoutAccountRequest,\n ListPayoutAccountsResponse,\n} from '../types.js'\n\n/** Manage bank and mobile-money payout accounts for customers. */\nexport class PayoutAccountsResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Add a payout account for a customer.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const account = await monigo.payoutAccounts.create('cust_abc', {\n * account_name: 'Acme Corp',\n * payout_method: 'bank_transfer',\n * bank_name: 'Zenith Bank',\n * bank_code: '057',\n * account_number: '1234567890',\n * currency: 'NGN',\n * is_default: true,\n * })\n * ```\n */\n async create(\n customerId: string,\n request: CreatePayoutAccountRequest,\n options?: MutationOptions,\n ): Promise<PayoutAccount> {\n const wrapper = await this.client._request<{ payout_account: PayoutAccount }>(\n 'POST',\n `/v1/customers/${customerId}/payout-accounts`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.payout_account\n }\n\n /**\n * Return all payout accounts for a customer.\n *\n * **Requires `read` scope.**\n */\n async list(customerId: string): Promise<ListPayoutAccountsResponse> {\n return this.client._request<ListPayoutAccountsResponse>(\n 'GET',\n `/v1/customers/${customerId}/payout-accounts`,\n )\n }\n\n /**\n * Fetch a single payout account by its UUID.\n *\n * **Requires `read` scope.**\n */\n async get(customerId: string, accountId: string): Promise<PayoutAccount> {\n const wrapper = await this.client._request<{ payout_account: PayoutAccount }>(\n 'GET',\n `/v1/customers/${customerId}/payout-accounts/${accountId}`,\n )\n return wrapper.payout_account\n }\n\n /**\n * Update a payout account's details.\n *\n * **Requires `write` scope.**\n */\n async update(\n customerId: string,\n accountId: string,\n request: UpdatePayoutAccountRequest,\n options?: MutationOptions,\n ): Promise<PayoutAccount> {\n const wrapper = await this.client._request<{ payout_account: PayoutAccount }>(\n 'PUT',\n `/v1/customers/${customerId}/payout-accounts/${accountId}`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.payout_account\n }\n\n /**\n * Delete a payout account.\n *\n * **Requires `write` scope.**\n */\n async delete(customerId: string, accountId: string): Promise<void> {\n await this.client._request<void>(\n 'DELETE',\n `/v1/customers/${customerId}/payout-accounts/${accountId}`,\n )\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n Invoice,\n ListInvoicesParams,\n ListInvoicesResponse,\n} from '../types.js'\n\n/** Manage invoice generation, finalization, and voiding. */\nexport class InvoicesResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Generate a draft invoice for a subscription based on current period usage.\n * The invoice starts in `\"draft\"` status and is not sent to the customer yet.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const invoice = await monigo.invoices.generate('sub_xyz')\n * console.log('Draft invoice total:', invoice.total)\n * ```\n */\n async generate(subscriptionId: string, options?: MutationOptions): Promise<Invoice> {\n const wrapper = await this.client._request<{ invoice: Invoice }>(\n 'POST',\n '/v1/invoices/generate',\n { body: { subscription_id: subscriptionId }, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.invoice\n }\n\n /**\n * Return invoices, optionally filtered by status or customer.\n *\n * **Requires `read` scope.**\n *\n * @example\n * ```ts\n * const { invoices } = await monigo.invoices.list({\n * status: 'finalized',\n * customer_id: 'cust_abc',\n * })\n * ```\n */\n async list(params: ListInvoicesParams = {}): Promise<ListInvoicesResponse> {\n return this.client._request<ListInvoicesResponse>('GET', '/v1/invoices', {\n query: {\n status: params.status,\n customer_id: params.customer_id,\n },\n })\n }\n\n /**\n * Fetch a single invoice by its UUID, including line items.\n *\n * **Requires `read` scope.**\n */\n async get(invoiceId: string): Promise<Invoice> {\n const wrapper = await this.client._request<{ invoice: Invoice }>(\n 'GET',\n `/v1/invoices/${invoiceId}`,\n )\n return wrapper.invoice\n }\n\n /**\n * Finalize a draft invoice, making it ready for payment.\n * A finalized invoice cannot be edited.\n *\n * **Requires `write` scope.**\n */\n async finalize(invoiceId: string, options?: MutationOptions): Promise<Invoice> {\n const wrapper = await this.client._request<{ invoice: Invoice }>(\n 'POST',\n `/v1/invoices/${invoiceId}/finalize`,\n { idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.invoice\n }\n\n /**\n * Void an invoice, making it permanently non-payable.\n * Only admins and owners can void invoices.\n *\n * **Requires `write` scope.**\n */\n async void(invoiceId: string, options?: MutationOptions): Promise<Invoice> {\n const wrapper = await this.client._request<{ invoice: Invoice }>(\n 'POST',\n `/v1/invoices/${invoiceId}/void`,\n { idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.invoice\n }\n}\n","import { MonigoClient } from '../client.js'\nimport type { UsageQueryParams, UsageQueryResult } from '../types.js'\n\n/** Query aggregated usage rollups from the Monigo metering pipeline. */\nexport class UsageResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Return per-customer, per-metric usage rollups for the organisation.\n * All parameters are optional — omitting them returns the full current\n * billing period for all customers and metrics.\n *\n * **Requires `read` scope.**\n *\n * @example\n * ```ts\n * // All usage for one customer this period\n * const { rollups } = await monigo.usage.query({\n * customer_id: 'cust_abc',\n * })\n *\n * // Filtered by metric and custom date range\n * const { rollups: filtered } = await monigo.usage.query({\n * metric_id: 'metric_xyz',\n * from: '2025-01-01T00:00:00Z',\n * to: '2025-01-31T23:59:59Z',\n * })\n * ```\n */\n async query(params: UsageQueryParams = {}): Promise<UsageQueryResult> {\n const query: Record<string, string | undefined> = {\n customer_id: params.customer_id,\n metric_id: params.metric_id,\n }\n if (params.from !== undefined) {\n query.from = MonigoClient.toISOString(params.from)\n }\n if (params.to !== undefined) {\n query.to = MonigoClient.toISOString(params.to)\n }\n return this.client._request<UsageQueryResult>('GET', '/v1/usage', { query })\n }\n}\n","import { MonigoAPIError } from './errors.js'\nimport { EventsResource } from './resources/events.js'\nimport { CustomersResource } from './resources/customers.js'\nimport { MetricsResource } from './resources/metrics.js'\nimport { PlansResource } from './resources/plans.js'\nimport { SubscriptionsResource } from './resources/subscriptions.js'\nimport { PayoutAccountsResource } from './resources/payout-accounts.js'\nimport { InvoicesResource } from './resources/invoices.js'\nimport { UsageResource } from './resources/usage.js'\n\nconst DEFAULT_BASE_URL = 'https://api.monigo.co'\nconst DEFAULT_TIMEOUT_MS = 30_000\n\nexport interface MonigoClientOptions {\n /**\n * Your Monigo API key. Obtain one from the API Keys section of your\n * Monigo dashboard. Never expose this key in client-side code.\n */\n apiKey: string\n /**\n * Override the default API base URL (`https://api.monigo.co`).\n * Useful for self-hosted deployments or pointing at a local dev server.\n *\n * @default \"https://api.monigo.co\"\n */\n baseURL?: string\n /**\n * Custom `fetch` implementation. Defaults to `globalThis.fetch`.\n * Pass a polyfill for environments that do not have native fetch\n * (Node.js < 18) or to inject a mock in tests.\n */\n fetch?: typeof globalThis.fetch\n /**\n * Request timeout in milliseconds.\n *\n * @default 30000\n */\n timeout?: number\n}\n\n/**\n * Options accepted by every mutating method (POST, PUT, PATCH).\n */\nexport interface MutationOptions {\n /**\n * A unique key that prevents the same request from being processed more than\n * once. Pass a stable value (e.g. a request ID from your own system) to make\n * retries safe. When omitted, the SDK generates a UUID v4 automatically.\n */\n idempotencyKey?: string\n}\n\n/** @internal */\nexport interface RequestOptions {\n body?: unknown\n query?: Record<string, string | undefined>\n idempotencyKey?: string\n}\n\n/**\n * The Monigo API client.\n *\n * Instantiate once and reuse across your application:\n *\n * ```ts\n * import { MonigoClient } from '@monigo/sdk'\n *\n * const monigo = new MonigoClient({ apiKey: process.env.MONIGO_API_KEY! })\n *\n * // Ingest a usage event\n * await monigo.events.ingest({\n * events: [{\n * event_name: 'api_call',\n * customer_id: 'cust_abc123',\n * idempotency_key: crypto.randomUUID(),\n * }],\n * })\n * ```\n */\nexport class MonigoClient {\n /** @internal */\n readonly _apiKey: string\n /** @internal */\n readonly _baseURL: string\n /** @internal */\n readonly _fetchFn: typeof globalThis.fetch\n /** @internal */\n readonly _timeout: number\n\n /** Ingest usage events and manage event replays. Requires `ingest` scope. */\n readonly events: EventsResource\n /** Manage your end-customers (CRUD). Requires `read` / `write` scope. */\n readonly customers: CustomersResource\n /** Manage billing metrics — what gets counted and how. Requires `read` / `write` scope. */\n readonly metrics: MetricsResource\n /** Manage billing plans and their prices. Requires `read` / `write` scope. */\n readonly plans: PlansResource\n /** Link customers to plans and manage subscription lifecycle. Requires `read` / `write` scope. */\n readonly subscriptions: SubscriptionsResource\n /** Manage bank / mobile-money payout accounts for customers. Requires `read` / `write` scope. */\n readonly payoutAccounts: PayoutAccountsResource\n /** Generate, list, finalize, and void invoices. Requires `read` / `write` scope. */\n readonly invoices: InvoicesResource\n /** Query aggregated usage rollups per customer and metric. Requires `read` scope. */\n readonly usage: UsageResource\n\n constructor(options: MonigoClientOptions) {\n if (!options.apiKey) {\n throw new Error('MonigoClient: apiKey is required')\n }\n\n this._apiKey = options.apiKey\n this._baseURL = (options.baseURL ?? DEFAULT_BASE_URL).replace(/\\/$/, '')\n this._timeout = options.timeout ?? DEFAULT_TIMEOUT_MS\n\n const fetchFn = options.fetch ?? (typeof globalThis !== 'undefined' ? globalThis.fetch : undefined)\n if (!fetchFn) {\n throw new Error(\n 'MonigoClient: fetch is not available in this environment. ' +\n 'Pass a custom fetch implementation via options.fetch, ' +\n 'or upgrade to Node.js 18+.',\n )\n }\n this._fetchFn = fetchFn.bind(globalThis)\n\n this.events = new EventsResource(this)\n this.customers = new CustomersResource(this)\n this.metrics = new MetricsResource(this)\n this.plans = new PlansResource(this)\n this.subscriptions = new SubscriptionsResource(this)\n this.payoutAccounts = new PayoutAccountsResource(this)\n this.invoices = new InvoicesResource(this)\n this.usage = new UsageResource(this)\n }\n\n /**\n * Execute an authenticated HTTP request against the Monigo API.\n * @internal — use the resource methods instead.\n */\n async _request<T>(\n method: string,\n path: string,\n options: RequestOptions = {},\n ): Promise<T> {\n let url = this._baseURL + path\n\n if (options.query) {\n const params = new URLSearchParams()\n for (const [key, value] of Object.entries(options.query)) {\n if (value !== undefined && value !== '') {\n params.set(key, value)\n }\n }\n const qs = params.toString()\n if (qs) url += '?' + qs\n }\n\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), this._timeout)\n\n const isMutating = method === 'POST' || method === 'PUT' || method === 'PATCH'\n const idempotencyKey = isMutating\n ? (options.idempotencyKey ?? globalThis.crypto.randomUUID())\n : undefined\n\n try {\n const response = await this._fetchFn(url, {\n method,\n headers: {\n Authorization: `Bearer ${this._apiKey}`,\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n ...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),\n },\n body: options.body != null ? JSON.stringify(options.body) : undefined,\n signal: controller.signal,\n })\n\n const text = await response.text()\n\n if (!response.ok) {\n let message = text || response.statusText\n let details: Record<string, string> | undefined\n try {\n const parsed = JSON.parse(text) as {\n error?: string\n message?: string\n details?: Record<string, string>\n }\n message = parsed.error ?? parsed.message ?? message\n details = parsed.details\n } catch {\n // Use raw text as the error message\n }\n throw new MonigoAPIError(response.status, message, details)\n }\n\n if (!text) return undefined as T\n return JSON.parse(text) as T\n } catch (err) {\n if (err instanceof MonigoAPIError) throw err\n if (err instanceof Error && err.name === 'AbortError') {\n throw new Error(\n `MonigoClient: request to ${url} timed out after ${this._timeout}ms`,\n )\n }\n throw err\n } finally {\n clearTimeout(timeoutId)\n }\n }\n\n /** Normalise a `Date | string` value to an ISO 8601 string. */\n static toISOString(value: string | Date): string {\n return value instanceof Date ? value.toISOString() : value\n }\n}\n","// =============================================================================\n// Aggregation constants\n// =============================================================================\n\nexport const Aggregation = {\n Count: 'count',\n Sum: 'sum',\n Max: 'max',\n Min: 'minimum',\n Average: 'average',\n Unique: 'unique',\n} as const\n\nexport type AggregationType = (typeof Aggregation)[keyof typeof Aggregation]\n\n// =============================================================================\n// Pricing model constants\n// =============================================================================\n\nexport const PricingModel = {\n Flat: 'flat',\n Tiered: 'tiered',\n Volume: 'volume',\n Package: 'package',\n Overage: 'overage',\n WeightedTiered: 'weighted_tiered',\n} as const\n\nexport type PricingModelType = (typeof PricingModel)[keyof typeof PricingModel]\n\n// =============================================================================\n// Plan constants\n// =============================================================================\n\nexport const PlanType = {\n Collection: 'collection',\n Payout: 'payout',\n} as const\n\nexport type PlanTypeValue = (typeof PlanType)[keyof typeof PlanType]\n\nexport const BillingPeriod = {\n Daily: 'daily',\n Weekly: 'weekly',\n Monthly: 'monthly',\n Quarterly: 'quarterly',\n Annually: 'annually',\n} as const\n\nexport type BillingPeriodValue = (typeof BillingPeriod)[keyof typeof BillingPeriod]\n\n// =============================================================================\n// Subscription status constants\n// =============================================================================\n\nexport const SubscriptionStatus = {\n Active: 'active',\n Paused: 'paused',\n Canceled: 'canceled',\n} as const\n\nexport type SubscriptionStatusValue = (typeof SubscriptionStatus)[keyof typeof SubscriptionStatus]\n\n// =============================================================================\n// Invoice status constants\n// =============================================================================\n\nexport const InvoiceStatus = {\n Draft: 'draft',\n Finalized: 'finalized',\n Paid: 'paid',\n Void: 'void',\n} as const\n\nexport type InvoiceStatusValue = (typeof InvoiceStatus)[keyof typeof InvoiceStatus]\n\n// =============================================================================\n// Payout method constants\n// =============================================================================\n\nexport const PayoutMethod = {\n BankTransfer: 'bank_transfer',\n MobileMoney: 'mobile_money',\n} as const\n\nexport type PayoutMethodValue = (typeof PayoutMethod)[keyof typeof PayoutMethod]\n\n// =============================================================================\n// Events\n// =============================================================================\n\n/** A single usage event sent to the Monigo ingestion pipeline. */\nexport interface IngestEvent {\n /**\n * The name of the event, e.g. `\"api_call\"` or `\"storage.write\"`.\n * Must match the `event_name` on one or more metrics you have configured.\n */\n event_name: string\n /** The Monigo customer UUID this event belongs to. */\n customer_id: string\n /**\n * A unique key for this event. Re-sending the same key is safe — the server\n * will de-duplicate automatically. Use a UUID or any stable ID you control.\n */\n idempotency_key: string\n /**\n * ISO 8601 timestamp for when the event occurred. Backdated events are\n * accepted within the configured replay window. Defaults to now if omitted.\n */\n timestamp?: string | Date\n /**\n * Arbitrary key-value pairs attached to the event. Use these for dimensions\n * such as `{ endpoint: \"/checkout\", region: \"eu-west-1\" }`.\n */\n properties?: Record<string, unknown>\n}\n\n/** Request body for `POST /v1/ingest`. */\nexport interface IngestRequest {\n events: IngestEvent[]\n}\n\n/** Response from `POST /v1/ingest`. */\nexport interface IngestResponse {\n /** Idempotency keys of events that were successfully ingested. */\n ingested: string[]\n /** Idempotency keys that were skipped because they already existed. */\n duplicates: string[]\n}\n\n/** Request body for `POST /v1/events/replay`. */\nexport interface StartReplayRequest {\n /** Start of the replay window (ISO 8601). */\n from: string | Date\n /** End of the replay window (ISO 8601). */\n to: string | Date\n /** Optional event name to replay. Omit to replay all event types. */\n event_name?: string\n}\n\n/** Tracks the progress of an asynchronous event replay job. */\nexport interface EventReplayJob {\n id: string\n org_id: string\n initiated_by: string\n /** `pending` | `processing` | `completed` | `failed` */\n status: string\n from_timestamp: string\n to_timestamp: string\n event_name: string | null\n is_test: boolean\n events_total: number\n events_replayed: number\n error_message: string | null\n started_at: string | null\n completed_at: string | null\n created_at: string\n updated_at: string\n}\n\n// =============================================================================\n// Customers\n// =============================================================================\n\n/** An end-customer record in your Monigo organisation. */\nexport interface Customer {\n id: string\n org_id: string\n /** The ID for this customer in your own system. */\n external_id: string\n name: string\n email: string\n /** Arbitrary JSON metadata. */\n metadata: Record<string, unknown> | null\n created_at: string\n updated_at: string\n}\n\nexport interface CreateCustomerRequest {\n /** Your internal ID for this customer. */\n external_id: string\n name: string\n email: string\n metadata?: Record<string, unknown>\n}\n\nexport interface UpdateCustomerRequest {\n name?: string\n email?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface ListCustomersResponse {\n customers: Customer[]\n count: number\n}\n\n// =============================================================================\n// Metrics\n// =============================================================================\n\n/** Defines what usage is counted and how. */\nexport interface Metric {\n id: string\n org_id: string\n name: string\n /** The `event_name` value that this metric tracks. */\n event_name: string\n /** How events are aggregated. Use `Aggregation` constants. */\n aggregation: AggregationType\n /** For sum/max/min/average: the Properties key whose value is used. */\n aggregation_property?: string\n description?: string\n created_at: string\n updated_at: string\n}\n\nexport interface CreateMetricRequest {\n /** Human-readable label, e.g. `\"API Calls\"`. */\n name: string\n /** The `event_name` value to track. */\n event_name: string\n /** How events are aggregated. Use `Aggregation` constants. */\n aggregation: AggregationType\n description?: string\n /** Required for sum/max/min/average aggregations. */\n aggregation_property?: string\n}\n\nexport interface UpdateMetricRequest {\n name?: string\n event_name?: string\n aggregation?: AggregationType\n description?: string\n aggregation_property?: string\n}\n\nexport interface ListMetricsResponse {\n metrics: Metric[]\n count: number\n}\n\n// =============================================================================\n// Plans & Prices\n// =============================================================================\n\n/**\n * One price step in a tiered/volume/weighted_tiered pricing model.\n * Set `up_to` to `null` for the final (infinite) tier.\n */\nexport interface PriceTier {\n up_to: number | null\n /** Price per unit in this tier as a decimal string, e.g. `\"0.50\"`. */\n unit_amount: string\n}\n\n/** Describes a price to attach when creating a plan. */\nexport interface CreatePriceRequest {\n /** UUID of the metric this price is based on. */\n metric_id: string\n /** Pricing model. Use `PricingModel` constants. */\n model: PricingModelType\n /** Flat price per unit as a decimal string (used for flat/overage/package models). */\n unit_price?: string\n /** Price tiers for tiered/volume/weighted_tiered models. */\n tiers?: PriceTier[]\n}\n\n/** Describes an updated price. Include `id` to update an existing price; omit to add a new one. */\nexport interface UpdatePriceRequest {\n id?: string\n metric_id?: string\n model?: PricingModelType\n unit_price?: string\n tiers?: PriceTier[]\n}\n\n/** A pricing rule attached to a plan. */\nexport interface Price {\n id: string\n plan_id: string\n metric_id: string\n model: PricingModelType\n unit_price: string\n tiers: PriceTier[] | null\n created_at: string\n updated_at: string\n}\n\n/** A billing plan that defines pricing for one or more metrics. */\nexport interface Plan {\n id: string\n org_id: string\n name: string\n description?: string\n /** ISO 4217 currency code, e.g. `\"NGN\"`. */\n currency: string\n /** Use `PlanType` constants. */\n plan_type: PlanTypeValue\n /** Use `BillingPeriod` constants. */\n billing_period: BillingPeriodValue\n trial_period_days: number\n prices?: Price[]\n created_at: string\n updated_at: string\n}\n\nexport interface CreatePlanRequest {\n name: string\n description?: string\n /** ISO 4217 currency code. Defaults to `\"NGN\"`. */\n currency?: string\n /** Use `PlanType` constants. Defaults to `\"collection\"`. */\n plan_type?: PlanTypeValue\n /** Use `BillingPeriod` constants. Defaults to `\"monthly\"`. */\n billing_period?: BillingPeriodValue\n /** Trial period in days. Set to `0` for no trial. */\n trial_period_days?: number\n prices?: CreatePriceRequest[]\n}\n\nexport interface UpdatePlanRequest {\n name?: string\n description?: string\n currency?: string\n plan_type?: PlanTypeValue\n billing_period?: BillingPeriodValue\n prices?: UpdatePriceRequest[]\n}\n\nexport interface ListPlansResponse {\n plans: Plan[]\n count: number\n}\n\n// =============================================================================\n// Subscriptions\n// =============================================================================\n\n/** Links a customer to a billing plan. */\nexport interface Subscription {\n id: string\n org_id: string\n customer_id: string\n plan_id: string\n /** Use `SubscriptionStatus` constants. */\n status: SubscriptionStatusValue\n current_period_start: string\n current_period_end: string\n trial_ends_at: string | null\n created_at: string\n updated_at: string\n}\n\nexport interface CreateSubscriptionRequest {\n /** UUID of the customer to subscribe. */\n customer_id: string\n /** UUID of the plan to subscribe the customer to. */\n plan_id: string\n}\n\nexport interface ListSubscriptionsParams {\n /** Filter to a specific customer UUID. */\n customer_id?: string\n /** Filter to a specific plan UUID. */\n plan_id?: string\n /** Filter by status. Use `SubscriptionStatus` constants. */\n status?: SubscriptionStatusValue\n}\n\nexport interface ListSubscriptionsResponse {\n subscriptions: Subscription[]\n count: number\n}\n\n// =============================================================================\n// Payout accounts\n// =============================================================================\n\n/** A bank or mobile-money account that a customer can be paid to. */\nexport interface PayoutAccount {\n id: string\n customer_id: string\n org_id: string\n account_name: string\n bank_name?: string\n bank_code?: string\n account_number?: string\n mobile_money_number?: string\n /** Use `PayoutMethod` constants. */\n payout_method: PayoutMethodValue\n currency: string\n is_default: boolean\n metadata: Record<string, unknown> | null\n created_at: string\n updated_at: string\n}\n\nexport interface CreatePayoutAccountRequest {\n account_name: string\n /** Use `PayoutMethod` constants. */\n payout_method: PayoutMethodValue\n bank_name?: string\n bank_code?: string\n account_number?: string\n mobile_money_number?: string\n currency?: string\n is_default?: boolean\n metadata?: Record<string, unknown>\n}\n\nexport interface UpdatePayoutAccountRequest {\n account_name?: string\n payout_method?: PayoutMethodValue\n bank_name?: string\n account_number?: string\n currency?: string\n is_default?: boolean\n metadata?: Record<string, unknown>\n}\n\nexport interface ListPayoutAccountsResponse {\n payout_accounts: PayoutAccount[]\n count: number\n}\n\n// =============================================================================\n// Invoices\n// =============================================================================\n\n/** One line item on an invoice. */\nexport interface InvoiceLineItem {\n id: string\n invoice_id: string\n metric_id: string\n price_id?: string\n description: string\n quantity: string\n unit_price: string\n /** Amount for this line as a decimal string. */\n amount: string\n created_at: string\n}\n\n/**\n * A billing invoice.\n * All monetary values (`subtotal`, `vat_amount`, `total`) are decimal strings\n * to avoid floating-point precision issues.\n */\nexport interface Invoice {\n id: string\n org_id: string\n customer_id: string\n subscription_id: string\n /** Use `InvoiceStatus` constants. */\n status: InvoiceStatusValue\n currency: string\n subtotal: string\n vat_enabled: boolean\n vat_rate?: string\n vat_amount?: string\n total: string\n period_start: string\n period_end: string\n finalized_at: string | null\n paid_at: string | null\n provider_invoice_id?: string\n line_items?: InvoiceLineItem[]\n created_at: string\n updated_at: string\n}\n\nexport interface ListInvoicesParams {\n /** Filter by status. Use `InvoiceStatus` constants. */\n status?: InvoiceStatusValue\n /** Filter to a specific customer UUID. */\n customer_id?: string\n}\n\nexport interface ListInvoicesResponse {\n invoices: Invoice[]\n count: number\n}\n\n// =============================================================================\n// Usage\n// =============================================================================\n\n/** One aggregated usage record for a (customer, metric, period) tuple. */\nexport interface UsageRollup {\n id: string\n org_id: string\n customer_id: string\n metric_id: string\n period_start: string\n period_end: string\n aggregation: AggregationType\n /** Aggregated value (count, sum, max, etc.). */\n value: number\n event_count: number\n last_event_at: string | null\n is_test: boolean\n created_at: string\n updated_at: string\n}\n\nexport interface UsageQueryParams {\n /** Filter rollups to a specific customer UUID. */\n customer_id?: string\n /** Filter rollups to a specific metric UUID. */\n metric_id?: string\n /**\n * Lower bound for `period_start` (ISO 8601).\n * Defaults to the start of the current billing period.\n */\n from?: string | Date\n /**\n * Exclusive upper bound for `period_start` (ISO 8601).\n * Defaults to the end of the current billing period.\n */\n to?: string | Date\n}\n\nexport interface UsageQueryResult {\n rollups: UsageRollup[]\n count: number\n}\n"],"names":[],"mappings":";;AAcO,MAAM,uBAAuB,MAAM;AAAA,EAQxC,YACE,YACA,SACA,SACA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,UAAU;AACf,SAAK,UAAU;AAEf,UAAM,UAAW,MACf,mBACF;AACA,cAAU,MAAM,cAAc;AAAA,EAChC;AAAA;AAAA;AAAA;AAAA,EAMA,IAAI,aAAsB;AACxB,WAAO,KAAK,eAAe;AAAA,EAC7B;AAAA,EAEA,IAAI,iBAA0B;AAC5B,WAAO,KAAK,eAAe;AAAA,EAC7B;AAAA,EAEA,IAAI,cAAuB;AACzB,WAAO,KAAK,eAAe;AAAA,EAC7B;AAAA,EAEA,IAAI,gBAAyB;AAC3B,WAAO,KAAK,eAAe;AAAA,EAC7B;AAAA,EAEA,IAAI,aAAsB;AACxB,WAAO,KAAK,eAAe;AAAA,EAC7B;AAAA,EAEA,IAAI,kBAA2B;AAC7B,WAAO,KAAK,eAAe;AAAA,EAC7B;AAAA,EAEA,IAAI,gBAAyB;AAC3B,WAAO,KAAK,cAAc;AAAA,EAC5B;AAAA;AAAA;AAAA;AAAA,EAM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AAAA,EACP,WAAW;AAAA,EACX,MAAM;AAAA,EACN,MAAM;AACR;AAQO,MAAM,eAAe;AAAA,EAC1B,cAAc;AAAA,EACd,aAAa;AACf;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"monigo.cjs","sources":["../src/errors.ts","../src/resources/events.ts","../src/resources/customers.ts","../src/resources/metrics.ts","../src/resources/plans.ts","../src/resources/subscriptions.ts","../src/resources/payout-accounts.ts","../src/resources/invoices.ts","../src/resources/usage.ts","../src/client.ts","../src/types.ts"],"sourcesContent":["/**\n * Thrown for any non-2xx response from the Monigo API.\n *\n * @example\n * ```ts\n * try {\n * await client.customers.get('bad-id')\n * } catch (err) {\n * if (MonigoAPIError.isNotFound(err)) {\n * console.log('Customer does not exist')\n * }\n * }\n * ```\n */\nexport class MonigoAPIError extends Error {\n /** HTTP status code returned by the API. */\n readonly statusCode: number\n /** Human-readable error message from the API. */\n readonly message: string\n /** Optional structured field-level validation details. */\n readonly details: Record<string, string> | undefined\n\n constructor(\n statusCode: number,\n message: string,\n details?: Record<string, string>,\n ) {\n super(message)\n this.name = 'MonigoAPIError'\n this.statusCode = statusCode\n this.message = message\n this.details = details\n // Maintain proper stack trace in V8 (Node.js / Chrome)\n const capture = (Error as unknown as Record<string, unknown>)[\n 'captureStackTrace'\n ] as ((target: Error, constructor: Function) => void) | undefined\n capture?.(this, MonigoAPIError)\n }\n\n // -------------------------------------------------------------------------\n // Instance guards (for use on a caught error known to be MonigoAPIError)\n // -------------------------------------------------------------------------\n\n get isNotFound(): boolean {\n return this.statusCode === 404\n }\n\n get isUnauthorized(): boolean {\n return this.statusCode === 401\n }\n\n get isForbidden(): boolean {\n return this.statusCode === 403\n }\n\n get isRateLimited(): boolean {\n return this.statusCode === 429\n }\n\n get isConflict(): boolean {\n return this.statusCode === 409\n }\n\n get isQuotaExceeded(): boolean {\n return this.statusCode === 402\n }\n\n get isServerError(): boolean {\n return this.statusCode >= 500\n }\n\n // -------------------------------------------------------------------------\n // Static type-narrowing helpers (for use in catch clauses on `unknown`)\n // -------------------------------------------------------------------------\n\n static isNotFound(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 404\n }\n\n static isUnauthorized(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 401\n }\n\n static isForbidden(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 403\n }\n\n static isRateLimited(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 429\n }\n\n static isConflict(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 409\n }\n\n static isQuotaExceeded(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 402\n }\n\n static isServerError(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode >= 500\n }\n}\n","import { MonigoClient } from '../client.js'\nimport type { MutationOptions } from '../client.js'\nimport type {\n IngestRequest,\n IngestResponse,\n StartReplayRequest,\n EventReplayJob,\n} from '../types.js'\n\n/** Handles usage event ingestion and asynchronous event replay. */\nexport class EventsResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Ingest one or more usage events into the Monigo pipeline.\n *\n * Events are processed asynchronously. The response confirms receipt\n * and reports any duplicate idempotency keys.\n *\n * **Requires `ingest` scope.**\n *\n * @example\n * ```ts\n * const result = await monigo.events.ingest({\n * events: [{\n * event_name: 'api_call',\n * customer_id: 'cust_abc',\n * idempotency_key: crypto.randomUUID(),\n * timestamp: new Date().toISOString(),\n * properties: { endpoint: '/checkout', region: 'eu-west-1' },\n * }],\n * })\n * console.log('Ingested:', result.ingested.length)\n * console.log('Duplicates:', result.duplicates.length)\n * ```\n */\n async ingest(request: IngestRequest, options?: MutationOptions): Promise<IngestResponse> {\n const body = {\n events: request.events.map((e) => ({\n ...e,\n timestamp: e.timestamp\n ? MonigoClient.toISOString(e.timestamp)\n : new Date().toISOString(),\n })),\n }\n return this.client._request<IngestResponse>('POST', '/v1/ingest', {\n body,\n idempotencyKey: options?.idempotencyKey,\n })\n }\n\n /**\n * Start an asynchronous replay of all raw events in a given time window\n * through the current processing pipeline. Useful for backfilling usage\n * data after changing metric definitions.\n *\n * Returns a replay job immediately — poll `getReplay()` to track progress.\n *\n * **Requires `ingest` scope.**\n *\n * @example\n * ```ts\n * const job = await monigo.events.startReplay({\n * from: '2025-01-01T00:00:00Z',\n * to: '2025-01-31T23:59:59Z',\n * event_name: 'api_call', // omit to replay all event types\n * })\n * console.log('Replay job:', job.id, job.status)\n * ```\n */\n async startReplay(request: StartReplayRequest, options?: MutationOptions): Promise<EventReplayJob> {\n const body = {\n from: MonigoClient.toISOString(request.from),\n to: MonigoClient.toISOString(request.to),\n ...(request.event_name ? { event_name: request.event_name } : {}),\n }\n const wrapper = await this.client._request<{ job: EventReplayJob }>(\n 'POST',\n '/v1/events/replay',\n { body, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.job\n }\n\n /**\n * Fetch the current status and progress of an event replay job.\n *\n * **Requires `ingest` scope.**\n *\n * @example\n * ```ts\n * const job = await monigo.events.getReplay(jobId)\n * if (job.status === 'completed') {\n * console.log(`Replayed ${job.events_replayed} / ${job.events_total} events`)\n * }\n * ```\n */\n async getReplay(jobId: string): Promise<EventReplayJob> {\n const wrapper = await this.client._request<{ job: EventReplayJob }>(\n 'GET',\n `/v1/events/replay/${jobId}`,\n )\n return wrapper.job\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n Customer,\n CreateCustomerRequest,\n UpdateCustomerRequest,\n ListCustomersResponse,\n} from '../types.js'\n\n/** Manage end-customers in your Monigo organisation. */\nexport class CustomersResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Register a new customer.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const customer = await monigo.customers.create({\n * external_id: 'usr_12345',\n * name: 'Acme Corp',\n * email: 'billing@acme.com',\n * metadata: { plan_tier: 'enterprise' },\n * })\n * ```\n */\n async create(request: CreateCustomerRequest, options?: MutationOptions): Promise<Customer> {\n const wrapper = await this.client._request<{ customer: Customer }>(\n 'POST',\n '/v1/customers',\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.customer\n }\n\n /**\n * Return all customers in the authenticated organisation.\n *\n * **Requires `read` scope.**\n */\n async list(): Promise<ListCustomersResponse> {\n return this.client._request<ListCustomersResponse>('GET', '/v1/customers')\n }\n\n /**\n * Fetch a single customer by their Monigo UUID.\n *\n * **Requires `read` scope.**\n */\n async get(customerId: string): Promise<Customer> {\n const wrapper = await this.client._request<{ customer: Customer }>(\n 'GET',\n `/v1/customers/${customerId}`,\n )\n return wrapper.customer\n }\n\n /**\n * Update a customer's name, email, or metadata.\n * Only fields that are present in `request` are updated.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const updated = await monigo.customers.update(customerId, {\n * email: 'new@acme.com',\n * })\n * ```\n */\n async update(\n customerId: string,\n request: UpdateCustomerRequest,\n options?: MutationOptions,\n ): Promise<Customer> {\n const wrapper = await this.client._request<{ customer: Customer }>(\n 'PUT',\n `/v1/customers/${customerId}`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.customer\n }\n\n /**\n * Permanently delete a customer record.\n *\n * **Requires `write` scope.**\n */\n async delete(customerId: string): Promise<void> {\n await this.client._request<void>('DELETE', `/v1/customers/${customerId}`)\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n Metric,\n CreateMetricRequest,\n UpdateMetricRequest,\n ListMetricsResponse,\n} from '../types.js'\n\n/** Manage billing metrics — what usage gets counted and how it is aggregated. */\nexport class MetricsResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Create a new metric.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const metric = await monigo.metrics.create({\n * name: 'API Calls',\n * event_name: 'api_call',\n * aggregation: 'count',\n * })\n * ```\n */\n async create(request: CreateMetricRequest, options?: MutationOptions): Promise<Metric> {\n const wrapper = await this.client._request<{ metric: Metric }>(\n 'POST',\n '/v1/metrics',\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.metric\n }\n\n /**\n * Return all metrics in the authenticated organisation.\n *\n * **Requires `read` scope.**\n */\n async list(): Promise<ListMetricsResponse> {\n return this.client._request<ListMetricsResponse>('GET', '/v1/metrics')\n }\n\n /**\n * Fetch a single metric by its UUID.\n *\n * **Requires `read` scope.**\n */\n async get(metricId: string): Promise<Metric> {\n const wrapper = await this.client._request<{ metric: Metric }>(\n 'GET',\n `/v1/metrics/${metricId}`,\n )\n return wrapper.metric\n }\n\n /**\n * Update a metric's name, event name, aggregation, or description.\n *\n * **Requires `write` scope.**\n */\n async update(metricId: string, request: UpdateMetricRequest, options?: MutationOptions): Promise<Metric> {\n const wrapper = await this.client._request<{ metric: Metric }>(\n 'PUT',\n `/v1/metrics/${metricId}`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.metric\n }\n\n /**\n * Permanently delete a metric.\n *\n * **Requires `write` scope.**\n */\n async delete(metricId: string): Promise<void> {\n await this.client._request<void>('DELETE', `/v1/metrics/${metricId}`)\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n Plan,\n CreatePlanRequest,\n UpdatePlanRequest,\n ListPlansResponse,\n} from '../types.js'\n\n/** Manage billing plans and their prices. */\nexport class PlansResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Create a new billing plan, optionally with prices attached.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const plan = await monigo.plans.create({\n * name: 'Pro',\n * currency: 'NGN',\n * billing_period: 'monthly',\n * prices: [{\n * metric_id: 'metric_abc',\n * model: 'flat',\n * unit_price: '2.500000',\n * }],\n * })\n * ```\n */\n async create(request: CreatePlanRequest, options?: MutationOptions): Promise<Plan> {\n const wrapper = await this.client._request<{ plan: Plan }>(\n 'POST',\n '/v1/plans',\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.plan\n }\n\n /**\n * Return all billing plans in the authenticated organisation.\n *\n * **Requires `read` scope.**\n */\n async list(): Promise<ListPlansResponse> {\n return this.client._request<ListPlansResponse>('GET', '/v1/plans')\n }\n\n /**\n * Fetch a single plan by its UUID, including its prices.\n *\n * **Requires `read` scope.**\n */\n async get(planId: string): Promise<Plan> {\n const wrapper = await this.client._request<{ plan: Plan }>(\n 'GET',\n `/v1/plans/${planId}`,\n )\n return wrapper.plan\n }\n\n /**\n * Update a plan's name, description, currency, or prices.\n *\n * **Requires `write` scope.**\n */\n async update(planId: string, request: UpdatePlanRequest, options?: MutationOptions): Promise<Plan> {\n const wrapper = await this.client._request<{ plan: Plan }>(\n 'PUT',\n `/v1/plans/${planId}`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.plan\n }\n\n /**\n * Permanently delete a plan.\n *\n * **Requires `write` scope.**\n */\n async delete(planId: string): Promise<void> {\n await this.client._request<void>('DELETE', `/v1/plans/${planId}`)\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n Subscription,\n CreateSubscriptionRequest,\n ListSubscriptionsParams,\n ListSubscriptionsResponse,\n SubscriptionStatusValue,\n} from '../types.js'\n\n/** Link customers to billing plans and manage subscription lifecycle. */\nexport class SubscriptionsResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Subscribe a customer to a plan.\n *\n * Returns a 409 Conflict error (check with `MonigoAPIError.isConflict(err)`)\n * if the customer already has an active subscription to the same plan.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const sub = await monigo.subscriptions.create({\n * customer_id: 'cust_abc',\n * plan_id: 'plan_xyz',\n * })\n * ```\n */\n async create(request: CreateSubscriptionRequest, options?: MutationOptions): Promise<Subscription> {\n const wrapper = await this.client._request<{ subscription: Subscription }>(\n 'POST',\n '/v1/subscriptions',\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.subscription\n }\n\n /**\n * Return subscriptions, optionally filtered by customer, plan, or status.\n *\n * **Requires `read` scope.**\n *\n * @example\n * ```ts\n * const { subscriptions } = await monigo.subscriptions.list({\n * customer_id: 'cust_abc',\n * status: 'active',\n * })\n * ```\n */\n async list(params: ListSubscriptionsParams = {}): Promise<ListSubscriptionsResponse> {\n return this.client._request<ListSubscriptionsResponse>('GET', '/v1/subscriptions', {\n query: {\n customer_id: params.customer_id,\n plan_id: params.plan_id,\n status: params.status,\n },\n })\n }\n\n /**\n * Fetch a single subscription by its UUID.\n *\n * **Requires `read` scope.**\n */\n async get(subscriptionId: string): Promise<Subscription> {\n const wrapper = await this.client._request<{ subscription: Subscription }>(\n 'GET',\n `/v1/subscriptions/${subscriptionId}`,\n )\n return wrapper.subscription\n }\n\n /**\n * Change the status of a subscription.\n * Use `SubscriptionStatus` constants: `\"active\"`, `\"paused\"`, `\"canceled\"`.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * await monigo.subscriptions.updateStatus(subId, SubscriptionStatus.Paused)\n * ```\n */\n async updateStatus(\n subscriptionId: string,\n status: SubscriptionStatusValue,\n options?: MutationOptions,\n ): Promise<Subscription> {\n const wrapper = await this.client._request<{ subscription: Subscription }>(\n 'PATCH',\n `/v1/subscriptions/${subscriptionId}`,\n { body: { status }, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.subscription\n }\n\n /**\n * Cancel and delete a subscription record.\n *\n * **Requires `write` scope.**\n */\n async delete(subscriptionId: string): Promise<void> {\n await this.client._request<void>('DELETE', `/v1/subscriptions/${subscriptionId}`)\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n PayoutAccount,\n CreatePayoutAccountRequest,\n UpdatePayoutAccountRequest,\n ListPayoutAccountsResponse,\n} from '../types.js'\n\n/** Manage bank and mobile-money payout accounts for customers. */\nexport class PayoutAccountsResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Add a payout account for a customer.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const account = await monigo.payoutAccounts.create('cust_abc', {\n * account_name: 'Acme Corp',\n * payout_method: 'bank_transfer',\n * bank_name: 'Zenith Bank',\n * bank_code: '057',\n * account_number: '1234567890',\n * currency: 'NGN',\n * is_default: true,\n * })\n * ```\n */\n async create(\n customerId: string,\n request: CreatePayoutAccountRequest,\n options?: MutationOptions,\n ): Promise<PayoutAccount> {\n const wrapper = await this.client._request<{ payout_account: PayoutAccount }>(\n 'POST',\n `/v1/customers/${customerId}/payout-accounts`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.payout_account\n }\n\n /**\n * Return all payout accounts for a customer.\n *\n * **Requires `read` scope.**\n */\n async list(customerId: string): Promise<ListPayoutAccountsResponse> {\n return this.client._request<ListPayoutAccountsResponse>(\n 'GET',\n `/v1/customers/${customerId}/payout-accounts`,\n )\n }\n\n /**\n * Fetch a single payout account by its UUID.\n *\n * **Requires `read` scope.**\n */\n async get(customerId: string, accountId: string): Promise<PayoutAccount> {\n const wrapper = await this.client._request<{ payout_account: PayoutAccount }>(\n 'GET',\n `/v1/customers/${customerId}/payout-accounts/${accountId}`,\n )\n return wrapper.payout_account\n }\n\n /**\n * Update a payout account's details.\n *\n * **Requires `write` scope.**\n */\n async update(\n customerId: string,\n accountId: string,\n request: UpdatePayoutAccountRequest,\n options?: MutationOptions,\n ): Promise<PayoutAccount> {\n const wrapper = await this.client._request<{ payout_account: PayoutAccount }>(\n 'PUT',\n `/v1/customers/${customerId}/payout-accounts/${accountId}`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.payout_account\n }\n\n /**\n * Delete a payout account.\n *\n * **Requires `write` scope.**\n */\n async delete(customerId: string, accountId: string): Promise<void> {\n await this.client._request<void>(\n 'DELETE',\n `/v1/customers/${customerId}/payout-accounts/${accountId}`,\n )\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n Invoice,\n ListInvoicesParams,\n ListInvoicesResponse,\n} from '../types.js'\n\n/** Manage invoice generation, finalization, and voiding. */\nexport class InvoicesResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Generate a draft invoice for a subscription based on current period usage.\n * The invoice starts in `\"draft\"` status and is not sent to the customer yet.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const invoice = await monigo.invoices.generate('sub_xyz')\n * console.log('Draft invoice total:', invoice.total)\n * ```\n */\n async generate(subscriptionId: string, options?: MutationOptions): Promise<Invoice> {\n const wrapper = await this.client._request<{ invoice: Invoice }>(\n 'POST',\n '/v1/invoices/generate',\n { body: { subscription_id: subscriptionId }, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.invoice\n }\n\n /**\n * Return invoices, optionally filtered by status or customer.\n *\n * **Requires `read` scope.**\n *\n * @example\n * ```ts\n * const { invoices } = await monigo.invoices.list({\n * status: 'finalized',\n * customer_id: 'cust_abc',\n * })\n * ```\n */\n async list(params: ListInvoicesParams = {}): Promise<ListInvoicesResponse> {\n return this.client._request<ListInvoicesResponse>('GET', '/v1/invoices', {\n query: {\n status: params.status,\n customer_id: params.customer_id,\n },\n })\n }\n\n /**\n * Fetch a single invoice by its UUID, including line items.\n *\n * **Requires `read` scope.**\n */\n async get(invoiceId: string): Promise<Invoice> {\n const wrapper = await this.client._request<{ invoice: Invoice }>(\n 'GET',\n `/v1/invoices/${invoiceId}`,\n )\n return wrapper.invoice\n }\n\n /**\n * Finalize a draft invoice, making it ready for payment.\n * A finalized invoice cannot be edited.\n *\n * **Requires `write` scope.**\n */\n async finalize(invoiceId: string, options?: MutationOptions): Promise<Invoice> {\n const wrapper = await this.client._request<{ invoice: Invoice }>(\n 'POST',\n `/v1/invoices/${invoiceId}/finalize`,\n { idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.invoice\n }\n\n /**\n * Void an invoice, making it permanently non-payable.\n * Only admins and owners can void invoices.\n *\n * **Requires `write` scope.**\n */\n async void(invoiceId: string, options?: MutationOptions): Promise<Invoice> {\n const wrapper = await this.client._request<{ invoice: Invoice }>(\n 'POST',\n `/v1/invoices/${invoiceId}/void`,\n { idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.invoice\n }\n}\n","import { MonigoClient } from '../client.js'\nimport type { UsageQueryParams, UsageQueryResult } from '../types.js'\n\n/** Query aggregated usage rollups from the Monigo metering pipeline. */\nexport class UsageResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Return per-customer, per-metric usage rollups for the organisation.\n * All parameters are optional — omitting them returns the full current\n * billing period for all customers and metrics.\n *\n * **Requires `read` scope.**\n *\n * @example\n * ```ts\n * // All usage for one customer this period\n * const { rollups } = await monigo.usage.query({\n * customer_id: 'cust_abc',\n * })\n *\n * // Filtered by metric and custom date range\n * const { rollups: filtered } = await monigo.usage.query({\n * metric_id: 'metric_xyz',\n * from: '2025-01-01T00:00:00Z',\n * to: '2025-01-31T23:59:59Z',\n * })\n * ```\n */\n async query(params: UsageQueryParams = {}): Promise<UsageQueryResult> {\n const query: Record<string, string | undefined> = {\n customer_id: params.customer_id,\n metric_id: params.metric_id,\n }\n if (params.from !== undefined) {\n query.from = MonigoClient.toISOString(params.from)\n }\n if (params.to !== undefined) {\n query.to = MonigoClient.toISOString(params.to)\n }\n return this.client._request<UsageQueryResult>('GET', '/v1/usage', { query })\n }\n}\n","import { MonigoAPIError } from './errors.js'\nimport { EventsResource } from './resources/events.js'\nimport { CustomersResource } from './resources/customers.js'\nimport { MetricsResource } from './resources/metrics.js'\nimport { PlansResource } from './resources/plans.js'\nimport { SubscriptionsResource } from './resources/subscriptions.js'\nimport { PayoutAccountsResource } from './resources/payout-accounts.js'\nimport { InvoicesResource } from './resources/invoices.js'\nimport { UsageResource } from './resources/usage.js'\n\nconst DEFAULT_BASE_URL = 'https://api.monigo.co'\nconst DEFAULT_TIMEOUT_MS = 30_000\n\nexport interface MonigoClientOptions {\n /**\n * Your Monigo API key. Obtain one from the API Keys section of your\n * Monigo dashboard. Never expose this key in client-side code.\n */\n apiKey: string\n /**\n * Override the default API base URL (`https://api.monigo.co`).\n * Useful for self-hosted deployments or pointing at a local dev server.\n *\n * @default \"https://api.monigo.co\"\n */\n baseURL?: string\n /**\n * Custom `fetch` implementation. Defaults to `globalThis.fetch`.\n * Pass a polyfill for environments that do not have native fetch\n * (Node.js < 18) or to inject a mock in tests.\n */\n fetch?: typeof globalThis.fetch\n /**\n * Request timeout in milliseconds.\n *\n * @default 30000\n */\n timeout?: number\n}\n\n/**\n * Options accepted by every mutating method (POST, PUT, PATCH).\n */\nexport interface MutationOptions {\n /**\n * A unique key that prevents the same request from being processed more than\n * once. Pass a stable value (e.g. a request ID from your own system) to make\n * retries safe. When omitted, the SDK generates a UUID v4 automatically.\n */\n idempotencyKey?: string\n}\n\n/** @internal */\nexport interface RequestOptions {\n body?: unknown\n query?: Record<string, string | undefined>\n idempotencyKey?: string\n}\n\n/**\n * The Monigo API client.\n *\n * Instantiate once and reuse across your application:\n *\n * ```ts\n * import { MonigoClient } from '@monigo/sdk'\n *\n * const monigo = new MonigoClient({ apiKey: process.env.MONIGO_API_KEY! })\n *\n * // Ingest a usage event\n * await monigo.events.ingest({\n * events: [{\n * event_name: 'api_call',\n * customer_id: 'cust_abc123',\n * idempotency_key: crypto.randomUUID(),\n * }],\n * })\n * ```\n */\nexport class MonigoClient {\n /** @internal */\n readonly _apiKey: string\n /** @internal */\n readonly _baseURL: string\n /** @internal */\n readonly _fetchFn: typeof globalThis.fetch\n /** @internal */\n readonly _timeout: number\n\n /** Ingest usage events and manage event replays. Requires `ingest` scope. */\n readonly events: EventsResource\n /** Manage your end-customers (CRUD). Requires `read` / `write` scope. */\n readonly customers: CustomersResource\n /** Manage billing metrics — what gets counted and how. Requires `read` / `write` scope. */\n readonly metrics: MetricsResource\n /** Manage billing plans and their prices. Requires `read` / `write` scope. */\n readonly plans: PlansResource\n /** Link customers to plans and manage subscription lifecycle. Requires `read` / `write` scope. */\n readonly subscriptions: SubscriptionsResource\n /** Manage bank / mobile-money payout accounts for customers. Requires `read` / `write` scope. */\n readonly payoutAccounts: PayoutAccountsResource\n /** Generate, list, finalize, and void invoices. Requires `read` / `write` scope. */\n readonly invoices: InvoicesResource\n /** Query aggregated usage rollups per customer and metric. Requires `read` scope. */\n readonly usage: UsageResource\n\n constructor(options: MonigoClientOptions) {\n if (!options.apiKey) {\n throw new Error('MonigoClient: apiKey is required')\n }\n\n this._apiKey = options.apiKey\n this._baseURL = (options.baseURL ?? DEFAULT_BASE_URL).replace(/\\/$/, '')\n this._timeout = options.timeout ?? DEFAULT_TIMEOUT_MS\n\n const fetchFn = options.fetch ?? (typeof globalThis !== 'undefined' ? globalThis.fetch : undefined)\n if (!fetchFn) {\n throw new Error(\n 'MonigoClient: fetch is not available in this environment. ' +\n 'Pass a custom fetch implementation via options.fetch, ' +\n 'or upgrade to Node.js 18+.',\n )\n }\n this._fetchFn = fetchFn.bind(globalThis)\n\n this.events = new EventsResource(this)\n this.customers = new CustomersResource(this)\n this.metrics = new MetricsResource(this)\n this.plans = new PlansResource(this)\n this.subscriptions = new SubscriptionsResource(this)\n this.payoutAccounts = new PayoutAccountsResource(this)\n this.invoices = new InvoicesResource(this)\n this.usage = new UsageResource(this)\n }\n\n /**\n * Execute an authenticated HTTP request against the Monigo API.\n * @internal — use the resource methods instead.\n */\n async _request<T>(\n method: string,\n path: string,\n options: RequestOptions = {},\n ): Promise<T> {\n let url = this._baseURL + path\n\n if (options.query) {\n const params = new URLSearchParams()\n for (const [key, value] of Object.entries(options.query)) {\n if (value !== undefined && value !== '') {\n params.set(key, value)\n }\n }\n const qs = params.toString()\n if (qs) url += '?' + qs\n }\n\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), this._timeout)\n\n const isMutating = method === 'POST' || method === 'PUT' || method === 'PATCH'\n const idempotencyKey = isMutating\n ? (options.idempotencyKey ?? globalThis.crypto.randomUUID())\n : undefined\n\n try {\n const response = await this._fetchFn(url, {\n method,\n headers: {\n Authorization: `Bearer ${this._apiKey}`,\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n ...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),\n },\n body: options.body != null ? JSON.stringify(options.body) : undefined,\n signal: controller.signal,\n })\n\n const text = await response.text()\n\n if (!response.ok) {\n let message = text || response.statusText\n let details: Record<string, string> | undefined\n try {\n const parsed = JSON.parse(text) as {\n error?: string\n message?: string\n details?: Record<string, string>\n }\n message = parsed.error ?? parsed.message ?? message\n details = parsed.details\n } catch {\n // Use raw text as the error message\n }\n throw new MonigoAPIError(response.status, message, details)\n }\n\n if (!text) return undefined as T\n return JSON.parse(text) as T\n } catch (err) {\n if (err instanceof MonigoAPIError) throw err\n if (err instanceof Error && err.name === 'AbortError') {\n throw new Error(\n `MonigoClient: request to ${url} timed out after ${this._timeout}ms`,\n )\n }\n throw err\n } finally {\n clearTimeout(timeoutId)\n }\n }\n\n /** Normalise a `Date | string` value to an ISO 8601 string. */\n static toISOString(value: string | Date): string {\n return value instanceof Date ? value.toISOString() : value\n }\n}\n","// =============================================================================\n// Aggregation constants\n// =============================================================================\n\nexport const Aggregation = {\n Count: 'count',\n Sum: 'sum',\n Max: 'max',\n Min: 'minimum',\n Average: 'average',\n Unique: 'unique',\n} as const\n\nexport type AggregationType = (typeof Aggregation)[keyof typeof Aggregation]\n\n// =============================================================================\n// Pricing model constants\n// =============================================================================\n\nexport const PricingModel = {\n Flat: 'flat',\n Tiered: 'tiered',\n Volume: 'volume',\n Package: 'package',\n Overage: 'overage',\n WeightedTiered: 'weighted_tiered',\n} as const\n\nexport type PricingModelType = (typeof PricingModel)[keyof typeof PricingModel]\n\n// =============================================================================\n// Plan constants\n// =============================================================================\n\nexport const PlanType = {\n Collection: 'collection',\n Payout: 'payout',\n} as const\n\nexport type PlanTypeValue = (typeof PlanType)[keyof typeof PlanType]\n\nexport const BillingPeriod = {\n Daily: 'daily',\n Weekly: 'weekly',\n Monthly: 'monthly',\n Quarterly: 'quarterly',\n Annually: 'annually',\n} as const\n\nexport type BillingPeriodValue = (typeof BillingPeriod)[keyof typeof BillingPeriod]\n\n// =============================================================================\n// Subscription status constants\n// =============================================================================\n\nexport const SubscriptionStatus = {\n Active: 'active',\n Paused: 'paused',\n Canceled: 'canceled',\n} as const\n\nexport type SubscriptionStatusValue = (typeof SubscriptionStatus)[keyof typeof SubscriptionStatus]\n\n// =============================================================================\n// Invoice status constants\n// =============================================================================\n\nexport const InvoiceStatus = {\n Draft: 'draft',\n Finalized: 'finalized',\n Paid: 'paid',\n Void: 'void',\n} as const\n\nexport type InvoiceStatusValue = (typeof InvoiceStatus)[keyof typeof InvoiceStatus]\n\n// =============================================================================\n// Payout method constants\n// =============================================================================\n\nexport const PayoutMethod = {\n BankTransfer: 'bank_transfer',\n MobileMoney: 'mobile_money',\n} as const\n\nexport type PayoutMethodValue = (typeof PayoutMethod)[keyof typeof PayoutMethod]\n\n// =============================================================================\n// Events\n// =============================================================================\n\n/** A single usage event sent to the Monigo ingestion pipeline. */\nexport interface IngestEvent {\n /**\n * The name of the event, e.g. `\"api_call\"` or `\"storage.write\"`.\n * Must match the `event_name` on one or more metrics you have configured.\n */\n event_name: string\n /** The Monigo customer UUID this event belongs to. */\n customer_id: string\n /**\n * A unique key for this event. Re-sending the same key is safe — the server\n * will de-duplicate automatically. Use a UUID or any stable ID you control.\n */\n idempotency_key: string\n /**\n * ISO 8601 timestamp for when the event occurred. Backdated events are\n * accepted within the configured replay window. Defaults to now if omitted.\n */\n timestamp?: string | Date\n /**\n * Arbitrary key-value pairs attached to the event. Use these for dimensions\n * such as `{ endpoint: \"/checkout\", region: \"eu-west-1\" }`.\n */\n properties?: Record<string, unknown>\n}\n\n/** Request body for `POST /v1/ingest`. */\nexport interface IngestRequest {\n events: IngestEvent[]\n}\n\n/** Response from `POST /v1/ingest`. */\nexport interface IngestResponse {\n /** Idempotency keys of events that were successfully ingested. */\n ingested: string[]\n /** Idempotency keys that were skipped because they already existed. */\n duplicates: string[]\n}\n\n/** Request body for `POST /v1/events/replay`. */\nexport interface StartReplayRequest {\n /** Start of the replay window (ISO 8601). */\n from: string | Date\n /** End of the replay window (ISO 8601). */\n to: string | Date\n /** Optional event name to replay. Omit to replay all event types. */\n event_name?: string\n}\n\n/** Tracks the progress of an asynchronous event replay job. */\nexport interface EventReplayJob {\n id: string\n org_id: string\n initiated_by: string\n /** `pending` | `processing` | `completed` | `failed` */\n status: string\n from_timestamp: string\n to_timestamp: string\n event_name: string | null\n is_test: boolean\n events_total: number\n events_replayed: number\n error_message: string | null\n started_at: string | null\n completed_at: string | null\n created_at: string\n updated_at: string\n}\n\n// =============================================================================\n// Customers\n// =============================================================================\n\n/** An end-customer record in your Monigo organisation. */\nexport interface Customer {\n id: string\n org_id: string\n /** The ID for this customer in your own system. */\n external_id: string\n name: string\n email: string\n /** Phone number in E.164 international format (e.g. +2348012345678). */\n phone: string\n /** Arbitrary JSON metadata. */\n metadata: Record<string, unknown> | null\n created_at: string\n updated_at: string\n}\n\nexport interface CreateCustomerRequest {\n /** Your internal ID for this customer. */\n external_id: string\n name: string\n email?: string\n /** Phone number in E.164 international format (e.g. +2348012345678). Optional. */\n phone?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface UpdateCustomerRequest {\n name?: string\n email?: string\n /** Phone number in E.164 international format (e.g. +2348012345678). Optional. */\n phone?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface ListCustomersResponse {\n customers: Customer[]\n count: number\n}\n\n// =============================================================================\n// Metrics\n// =============================================================================\n\n/** Defines what usage is counted and how. */\nexport interface Metric {\n id: string\n org_id: string\n name: string\n /** The `event_name` value that this metric tracks. */\n event_name: string\n /** How events are aggregated. Use `Aggregation` constants. */\n aggregation: AggregationType\n /** For sum/max/min/average: the Properties key whose value is used. */\n aggregation_property?: string\n description?: string\n created_at: string\n updated_at: string\n}\n\nexport interface CreateMetricRequest {\n /** Human-readable label, e.g. `\"API Calls\"`. */\n name: string\n /** The `event_name` value to track. */\n event_name: string\n /** How events are aggregated. Use `Aggregation` constants. */\n aggregation: AggregationType\n description?: string\n /** Required for sum/max/min/average aggregations. */\n aggregation_property?: string\n}\n\nexport interface UpdateMetricRequest {\n name?: string\n event_name?: string\n aggregation?: AggregationType\n description?: string\n aggregation_property?: string\n}\n\nexport interface ListMetricsResponse {\n metrics: Metric[]\n count: number\n}\n\n// =============================================================================\n// Plans & Prices\n// =============================================================================\n\n/**\n * One price step in a tiered/volume/weighted_tiered pricing model.\n * Set `up_to` to `null` for the final (infinite) tier.\n */\nexport interface PriceTier {\n up_to: number | null\n /** Price per unit in this tier as a decimal string, e.g. `\"0.50\"`. */\n unit_amount: string\n}\n\n/** Describes a price to attach when creating a plan. */\nexport interface CreatePriceRequest {\n /** UUID of the metric this price is based on. */\n metric_id: string\n /** Pricing model. Use `PricingModel` constants. */\n model: PricingModelType\n /** Flat price per unit as a decimal string (used for flat/overage/package models). */\n unit_price?: string\n /** Price tiers for tiered/volume/weighted_tiered models. */\n tiers?: PriceTier[]\n}\n\n/** Describes an updated price. Include `id` to update an existing price; omit to add a new one. */\nexport interface UpdatePriceRequest {\n id?: string\n metric_id?: string\n model?: PricingModelType\n unit_price?: string\n tiers?: PriceTier[]\n}\n\n/** A pricing rule attached to a plan. */\nexport interface Price {\n id: string\n plan_id: string\n metric_id: string\n model: PricingModelType\n unit_price: string\n tiers: PriceTier[] | null\n created_at: string\n updated_at: string\n}\n\n/** A billing plan that defines pricing for one or more metrics. */\nexport interface Plan {\n id: string\n org_id: string\n name: string\n description?: string\n /** ISO 4217 currency code, e.g. `\"NGN\"`. */\n currency: string\n /** Use `PlanType` constants. */\n plan_type: PlanTypeValue\n /** Use `BillingPeriod` constants. */\n billing_period: BillingPeriodValue\n trial_period_days: number\n prices?: Price[]\n created_at: string\n updated_at: string\n}\n\nexport interface CreatePlanRequest {\n name: string\n description?: string\n /** ISO 4217 currency code. Defaults to `\"NGN\"`. */\n currency?: string\n /** Use `PlanType` constants. Defaults to `\"collection\"`. */\n plan_type?: PlanTypeValue\n /** Use `BillingPeriod` constants. Defaults to `\"monthly\"`. */\n billing_period?: BillingPeriodValue\n /** Trial period in days. Set to `0` for no trial. */\n trial_period_days?: number\n prices?: CreatePriceRequest[]\n}\n\nexport interface UpdatePlanRequest {\n name?: string\n description?: string\n currency?: string\n plan_type?: PlanTypeValue\n billing_period?: BillingPeriodValue\n prices?: UpdatePriceRequest[]\n}\n\nexport interface ListPlansResponse {\n plans: Plan[]\n count: number\n}\n\n// =============================================================================\n// Subscriptions\n// =============================================================================\n\n/** Links a customer to a billing plan. */\nexport interface Subscription {\n id: string\n org_id: string\n customer_id: string\n plan_id: string\n /** Use `SubscriptionStatus` constants. */\n status: SubscriptionStatusValue\n current_period_start: string\n current_period_end: string\n trial_ends_at: string | null\n created_at: string\n updated_at: string\n}\n\nexport interface CreateSubscriptionRequest {\n /** UUID of the customer to subscribe. */\n customer_id: string\n /** UUID of the plan to subscribe the customer to. */\n plan_id: string\n}\n\nexport interface ListSubscriptionsParams {\n /** Filter to a specific customer UUID. */\n customer_id?: string\n /** Filter to a specific plan UUID. */\n plan_id?: string\n /** Filter by status. Use `SubscriptionStatus` constants. */\n status?: SubscriptionStatusValue\n}\n\nexport interface ListSubscriptionsResponse {\n subscriptions: Subscription[]\n count: number\n}\n\n// =============================================================================\n// Payout accounts\n// =============================================================================\n\n/** A bank or mobile-money account that a customer can be paid to. */\nexport interface PayoutAccount {\n id: string\n customer_id: string\n org_id: string\n account_name: string\n bank_name?: string\n bank_code?: string\n account_number?: string\n mobile_money_number?: string\n /** Use `PayoutMethod` constants. */\n payout_method: PayoutMethodValue\n currency: string\n is_default: boolean\n metadata: Record<string, unknown> | null\n created_at: string\n updated_at: string\n}\n\nexport interface CreatePayoutAccountRequest {\n account_name: string\n /** Use `PayoutMethod` constants. */\n payout_method: PayoutMethodValue\n bank_name?: string\n bank_code?: string\n account_number?: string\n mobile_money_number?: string\n currency?: string\n is_default?: boolean\n metadata?: Record<string, unknown>\n}\n\nexport interface UpdatePayoutAccountRequest {\n account_name?: string\n payout_method?: PayoutMethodValue\n bank_name?: string\n account_number?: string\n currency?: string\n is_default?: boolean\n metadata?: Record<string, unknown>\n}\n\nexport interface ListPayoutAccountsResponse {\n payout_accounts: PayoutAccount[]\n count: number\n}\n\n// =============================================================================\n// Invoices\n// =============================================================================\n\n/** One line item on an invoice. */\nexport interface InvoiceLineItem {\n id: string\n invoice_id: string\n metric_id: string\n price_id?: string\n description: string\n quantity: string\n unit_price: string\n /** Amount for this line as a decimal string. */\n amount: string\n created_at: string\n}\n\n/**\n * A billing invoice.\n * All monetary values (`subtotal`, `vat_amount`, `total`) are decimal strings\n * to avoid floating-point precision issues.\n */\nexport interface Invoice {\n id: string\n org_id: string\n customer_id: string\n subscription_id: string\n /** Use `InvoiceStatus` constants. */\n status: InvoiceStatusValue\n currency: string\n subtotal: string\n vat_enabled: boolean\n vat_rate?: string\n vat_amount?: string\n total: string\n period_start: string\n period_end: string\n finalized_at: string | null\n paid_at: string | null\n provider_invoice_id?: string\n line_items?: InvoiceLineItem[]\n created_at: string\n updated_at: string\n}\n\nexport interface ListInvoicesParams {\n /** Filter by status. Use `InvoiceStatus` constants. */\n status?: InvoiceStatusValue\n /** Filter to a specific customer UUID. */\n customer_id?: string\n}\n\nexport interface ListInvoicesResponse {\n invoices: Invoice[]\n count: number\n}\n\n// =============================================================================\n// Usage\n// =============================================================================\n\n/** One aggregated usage record for a (customer, metric, period) tuple. */\nexport interface UsageRollup {\n id: string\n org_id: string\n customer_id: string\n metric_id: string\n period_start: string\n period_end: string\n aggregation: AggregationType\n /** Aggregated value (count, sum, max, etc.). */\n value: number\n event_count: number\n last_event_at: string | null\n is_test: boolean\n created_at: string\n updated_at: string\n}\n\nexport interface UsageQueryParams {\n /** Filter rollups to a specific customer UUID. */\n customer_id?: string\n /** Filter rollups to a specific metric UUID. */\n metric_id?: string\n /**\n * Lower bound for `period_start` (ISO 8601).\n * Defaults to the start of the current billing period.\n */\n from?: string | Date\n /**\n * Exclusive upper bound for `period_start` (ISO 8601).\n * Defaults to the end of the current billing period.\n */\n to?: string | Date\n}\n\nexport interface Usage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AAQ;AAAA,QAAA;AAAA,MAEpE;AACA,YAAM;AAAA,IACR,UAAA;AACE,mBAAa,SAAS;AAAA,IACxB;AAAA,EACF;AAAA;AAAA,EAGA,OAAO,YAAY,OAA8B;AAC/C,WAAO,iBAAiB,OAAO,MAAM,YAAA,IAAgB;AAAA,EACvD;AACF;ACpNO,MAAM,cAAc;AAAA,EACzB,OAAO;AAAA,EACP,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,SAAS;AAAA,EACT,QAAQ;AACV;AAQO,MAAM,eAAe;AAAA,EAC1B,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,SAAS;AAAA,EACT,gBAAgB;AAClB;AAQO,MAAM,WAAW;AAAA,EACtB,YAAY;AAAA,EACZ,QAAQ;AACV;AAIO,MAAM,gBAAgB;AAAA,EAC3B,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,WAAW;AAAA,EACX,UAAU;AACZ;AAQO,MAAM,qBAAqB;AAAA,EAChC,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,UAAU;AACZ;AAQO,MAAM,gBAAgB;AAAA,EAC3B,OAAO;AAAA,EACP,WAAW;AAAA,EACX,MAAM;AAAA,EACN,MAAM;AACR;AAQO,MAAM,eAAe;AAAA,EAC1B,cAAc;AAAA,EACd,aAAa;AACf;;;;;;;;;;;;;;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"monigo.js","sources":["../src/errors.ts","../src/resources/events.ts","../src/resources/customers.ts","../src/resources/metrics.ts","../src/resources/plans.ts","../src/resources/subscriptions.ts","../src/resources/payout-accounts.ts","../src/resources/invoices.ts","../src/resources/usage.ts","../src/client.ts","../src/types.ts"],"sourcesContent":["/**\n * Thrown for any non-2xx response from the Monigo API.\n *\n * @example\n * ```ts\n * try {\n * await client.customers.get('bad-id')\n * } catch (err) {\n * if (MonigoAPIError.isNotFound(err)) {\n * console.log('Customer does not exist')\n * }\n * }\n * ```\n */\nexport class MonigoAPIError extends Error {\n /** HTTP status code returned by the API. */\n readonly statusCode: number\n /** Human-readable error message from the API. */\n readonly message: string\n /** Optional structured field-level validation details. */\n readonly details: Record<string, string> | undefined\n\n constructor(\n statusCode: number,\n message: string,\n details?: Record<string, string>,\n ) {\n super(message)\n this.name = 'MonigoAPIError'\n this.statusCode = statusCode\n this.message = message\n this.details = details\n // Maintain proper stack trace in V8 (Node.js / Chrome)\n const capture = (Error as unknown as Record<string, unknown>)[\n 'captureStackTrace'\n ] as ((target: Error, constructor: Function) => void) | undefined\n capture?.(this, MonigoAPIError)\n }\n\n // -------------------------------------------------------------------------\n // Instance guards (for use on a caught error known to be MonigoAPIError)\n // -------------------------------------------------------------------------\n\n get isNotFound(): boolean {\n return this.statusCode === 404\n }\n\n get isUnauthorized(): boolean {\n return this.statusCode === 401\n }\n\n get isForbidden(): boolean {\n return this.statusCode === 403\n }\n\n get isRateLimited(): boolean {\n return this.statusCode === 429\n }\n\n get isConflict(): boolean {\n return this.statusCode === 409\n }\n\n get isQuotaExceeded(): boolean {\n return this.statusCode === 402\n }\n\n get isServerError(): boolean {\n return this.statusCode >= 500\n }\n\n // -------------------------------------------------------------------------\n // Static type-narrowing helpers (for use in catch clauses on `unknown`)\n // -------------------------------------------------------------------------\n\n static isNotFound(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 404\n }\n\n static isUnauthorized(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 401\n }\n\n static isForbidden(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 403\n }\n\n static isRateLimited(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 429\n }\n\n static isConflict(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 409\n }\n\n static isQuotaExceeded(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 402\n }\n\n static isServerError(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode >= 500\n }\n}\n","import { MonigoClient } from '../client.js'\nimport type { MutationOptions } from '../client.js'\nimport type {\n IngestRequest,\n IngestResponse,\n StartReplayRequest,\n EventReplayJob,\n} from '../types.js'\n\n/** Handles usage event ingestion and asynchronous event replay. */\nexport class EventsResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Ingest one or more usage events into the Monigo pipeline.\n *\n * Events are processed asynchronously. The response confirms receipt\n * and reports any duplicate idempotency keys.\n *\n * **Requires `ingest` scope.**\n *\n * @example\n * ```ts\n * const result = await monigo.events.ingest({\n * events: [{\n * event_name: 'api_call',\n * customer_id: 'cust_abc',\n * idempotency_key: crypto.randomUUID(),\n * timestamp: new Date().toISOString(),\n * properties: { endpoint: '/checkout', region: 'eu-west-1' },\n * }],\n * })\n * console.log('Ingested:', result.ingested.length)\n * console.log('Duplicates:', result.duplicates.length)\n * ```\n */\n async ingest(request: IngestRequest, options?: MutationOptions): Promise<IngestResponse> {\n const body = {\n events: request.events.map((e) => ({\n ...e,\n timestamp: e.timestamp\n ? MonigoClient.toISOString(e.timestamp)\n : new Date().toISOString(),\n })),\n }\n return this.client._request<IngestResponse>('POST', '/v1/ingest', {\n body,\n idempotencyKey: options?.idempotencyKey,\n })\n }\n\n /**\n * Start an asynchronous replay of all raw events in a given time window\n * through the current processing pipeline. Useful for backfilling usage\n * data after changing metric definitions.\n *\n * Returns a replay job immediately — poll `getReplay()` to track progress.\n *\n * **Requires `ingest` scope.**\n *\n * @example\n * ```ts\n * const job = await monigo.events.startReplay({\n * from: '2025-01-01T00:00:00Z',\n * to: '2025-01-31T23:59:59Z',\n * event_name: 'api_call', // omit to replay all event types\n * })\n * console.log('Replay job:', job.id, job.status)\n * ```\n */\n async startReplay(request: StartReplayRequest, options?: MutationOptions): Promise<EventReplayJob> {\n const body = {\n from: MonigoClient.toISOString(request.from),\n to: MonigoClient.toISOString(request.to),\n ...(request.event_name ? { event_name: request.event_name } : {}),\n }\n const wrapper = await this.client._request<{ job: EventReplayJob }>(\n 'POST',\n '/v1/events/replay',\n { body, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.job\n }\n\n /**\n * Fetch the current status and progress of an event replay job.\n *\n * **Requires `ingest` scope.**\n *\n * @example\n * ```ts\n * const job = await monigo.events.getReplay(jobId)\n * if (job.status === 'completed') {\n * console.log(`Replayed ${job.events_replayed} / ${job.events_total} events`)\n * }\n * ```\n */\n async getReplay(jobId: string): Promise<EventReplayJob> {\n const wrapper = await this.client._request<{ job: EventReplayJob }>(\n 'GET',\n `/v1/events/replay/${jobId}`,\n )\n return wrapper.job\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n Customer,\n CreateCustomerRequest,\n UpdateCustomerRequest,\n ListCustomersResponse,\n} from '../types.js'\n\n/** Manage end-customers in your Monigo organisation. */\nexport class CustomersResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Register a new customer.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const customer = await monigo.customers.create({\n * external_id: 'usr_12345',\n * name: 'Acme Corp',\n * email: 'billing@acme.com',\n * metadata: { plan_tier: 'enterprise' },\n * })\n * ```\n */\n async create(request: CreateCustomerRequest, options?: MutationOptions): Promise<Customer> {\n const wrapper = await this.client._request<{ customer: Customer }>(\n 'POST',\n '/v1/customers',\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.customer\n }\n\n /**\n * Return all customers in the authenticated organisation.\n *\n * **Requires `read` scope.**\n */\n async list(): Promise<ListCustomersResponse> {\n return this.client._request<ListCustomersResponse>('GET', '/v1/customers')\n }\n\n /**\n * Fetch a single customer by their Monigo UUID.\n *\n * **Requires `read` scope.**\n */\n async get(customerId: string): Promise<Customer> {\n const wrapper = await this.client._request<{ customer: Customer }>(\n 'GET',\n `/v1/customers/${customerId}`,\n )\n return wrapper.customer\n }\n\n /**\n * Update a customer's name, email, or metadata.\n * Only fields that are present in `request` are updated.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const updated = await monigo.customers.update(customerId, {\n * email: 'new@acme.com',\n * })\n * ```\n */\n async update(\n customerId: string,\n request: UpdateCustomerRequest,\n options?: MutationOptions,\n ): Promise<Customer> {\n const wrapper = await this.client._request<{ customer: Customer }>(\n 'PUT',\n `/v1/customers/${customerId}`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.customer\n }\n\n /**\n * Permanently delete a customer record.\n *\n * **Requires `write` scope.**\n */\n async delete(customerId: string): Promise<void> {\n await this.client._request<void>('DELETE', `/v1/customers/${customerId}`)\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n Metric,\n CreateMetricRequest,\n UpdateMetricRequest,\n ListMetricsResponse,\n} from '../types.js'\n\n/** Manage billing metrics — what usage gets counted and how it is aggregated. */\nexport class MetricsResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Create a new metric.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const metric = await monigo.metrics.create({\n * name: 'API Calls',\n * event_name: 'api_call',\n * aggregation: 'count',\n * })\n * ```\n */\n async create(request: CreateMetricRequest, options?: MutationOptions): Promise<Metric> {\n const wrapper = await this.client._request<{ metric: Metric }>(\n 'POST',\n '/v1/metrics',\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.metric\n }\n\n /**\n * Return all metrics in the authenticated organisation.\n *\n * **Requires `read` scope.**\n */\n async list(): Promise<ListMetricsResponse> {\n return this.client._request<ListMetricsResponse>('GET', '/v1/metrics')\n }\n\n /**\n * Fetch a single metric by its UUID.\n *\n * **Requires `read` scope.**\n */\n async get(metricId: string): Promise<Metric> {\n const wrapper = await this.client._request<{ metric: Metric }>(\n 'GET',\n `/v1/metrics/${metricId}`,\n )\n return wrapper.metric\n }\n\n /**\n * Update a metric's name, event name, aggregation, or description.\n *\n * **Requires `write` scope.**\n */\n async update(metricId: string, request: UpdateMetricRequest, options?: MutationOptions): Promise<Metric> {\n const wrapper = await this.client._request<{ metric: Metric }>(\n 'PUT',\n `/v1/metrics/${metricId}`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.metric\n }\n\n /**\n * Permanently delete a metric.\n *\n * **Requires `write` scope.**\n */\n async delete(metricId: string): Promise<void> {\n await this.client._request<void>('DELETE', `/v1/metrics/${metricId}`)\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n Plan,\n CreatePlanRequest,\n UpdatePlanRequest,\n ListPlansResponse,\n} from '../types.js'\n\n/** Manage billing plans and their prices. */\nexport class PlansResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Create a new billing plan, optionally with prices attached.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const plan = await monigo.plans.create({\n * name: 'Pro',\n * currency: 'NGN',\n * billing_period: 'monthly',\n * prices: [{\n * metric_id: 'metric_abc',\n * model: 'flat',\n * unit_price: '2.500000',\n * }],\n * })\n * ```\n */\n async create(request: CreatePlanRequest, options?: MutationOptions): Promise<Plan> {\n const wrapper = await this.client._request<{ plan: Plan }>(\n 'POST',\n '/v1/plans',\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.plan\n }\n\n /**\n * Return all billing plans in the authenticated organisation.\n *\n * **Requires `read` scope.**\n */\n async list(): Promise<ListPlansResponse> {\n return this.client._request<ListPlansResponse>('GET', '/v1/plans')\n }\n\n /**\n * Fetch a single plan by its UUID, including its prices.\n *\n * **Requires `read` scope.**\n */\n async get(planId: string): Promise<Plan> {\n const wrapper = await this.client._request<{ plan: Plan }>(\n 'GET',\n `/v1/plans/${planId}`,\n )\n return wrapper.plan\n }\n\n /**\n * Update a plan's name, description, currency, or prices.\n *\n * **Requires `write` scope.**\n */\n async update(planId: string, request: UpdatePlanRequest, options?: MutationOptions): Promise<Plan> {\n const wrapper = await this.client._request<{ plan: Plan }>(\n 'PUT',\n `/v1/plans/${planId}`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.plan\n }\n\n /**\n * Permanently delete a plan.\n *\n * **Requires `write` scope.**\n */\n async delete(planId: string): Promise<void> {\n await this.client._request<void>('DELETE', `/v1/plans/${planId}`)\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n Subscription,\n CreateSubscriptionRequest,\n ListSubscriptionsParams,\n ListSubscriptionsResponse,\n SubscriptionStatusValue,\n} from '../types.js'\n\n/** Link customers to billing plans and manage subscription lifecycle. */\nexport class SubscriptionsResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Subscribe a customer to a plan.\n *\n * Returns a 409 Conflict error (check with `MonigoAPIError.isConflict(err)`)\n * if the customer already has an active subscription to the same plan.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const sub = await monigo.subscriptions.create({\n * customer_id: 'cust_abc',\n * plan_id: 'plan_xyz',\n * })\n * ```\n */\n async create(request: CreateSubscriptionRequest, options?: MutationOptions): Promise<Subscription> {\n const wrapper = await this.client._request<{ subscription: Subscription }>(\n 'POST',\n '/v1/subscriptions',\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.subscription\n }\n\n /**\n * Return subscriptions, optionally filtered by customer, plan, or status.\n *\n * **Requires `read` scope.**\n *\n * @example\n * ```ts\n * const { subscriptions } = await monigo.subscriptions.list({\n * customer_id: 'cust_abc',\n * status: 'active',\n * })\n * ```\n */\n async list(params: ListSubscriptionsParams = {}): Promise<ListSubscriptionsResponse> {\n return this.client._request<ListSubscriptionsResponse>('GET', '/v1/subscriptions', {\n query: {\n customer_id: params.customer_id,\n plan_id: params.plan_id,\n status: params.status,\n },\n })\n }\n\n /**\n * Fetch a single subscription by its UUID.\n *\n * **Requires `read` scope.**\n */\n async get(subscriptionId: string): Promise<Subscription> {\n const wrapper = await this.client._request<{ subscription: Subscription }>(\n 'GET',\n `/v1/subscriptions/${subscriptionId}`,\n )\n return wrapper.subscription\n }\n\n /**\n * Change the status of a subscription.\n * Use `SubscriptionStatus` constants: `\"active\"`, `\"paused\"`, `\"canceled\"`.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * await monigo.subscriptions.updateStatus(subId, SubscriptionStatus.Paused)\n * ```\n */\n async updateStatus(\n subscriptionId: string,\n status: SubscriptionStatusValue,\n options?: MutationOptions,\n ): Promise<Subscription> {\n const wrapper = await this.client._request<{ subscription: Subscription }>(\n 'PATCH',\n `/v1/subscriptions/${subscriptionId}`,\n { body: { status }, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.subscription\n }\n\n /**\n * Cancel and delete a subscription record.\n *\n * **Requires `write` scope.**\n */\n async delete(subscriptionId: string): Promise<void> {\n await this.client._request<void>('DELETE', `/v1/subscriptions/${subscriptionId}`)\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n PayoutAccount,\n CreatePayoutAccountRequest,\n UpdatePayoutAccountRequest,\n ListPayoutAccountsResponse,\n} from '../types.js'\n\n/** Manage bank and mobile-money payout accounts for customers. */\nexport class PayoutAccountsResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Add a payout account for a customer.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const account = await monigo.payoutAccounts.create('cust_abc', {\n * account_name: 'Acme Corp',\n * payout_method: 'bank_transfer',\n * bank_name: 'Zenith Bank',\n * bank_code: '057',\n * account_number: '1234567890',\n * currency: 'NGN',\n * is_default: true,\n * })\n * ```\n */\n async create(\n customerId: string,\n request: CreatePayoutAccountRequest,\n options?: MutationOptions,\n ): Promise<PayoutAccount> {\n const wrapper = await this.client._request<{ payout_account: PayoutAccount }>(\n 'POST',\n `/v1/customers/${customerId}/payout-accounts`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.payout_account\n }\n\n /**\n * Return all payout accounts for a customer.\n *\n * **Requires `read` scope.**\n */\n async list(customerId: string): Promise<ListPayoutAccountsResponse> {\n return this.client._request<ListPayoutAccountsResponse>(\n 'GET',\n `/v1/customers/${customerId}/payout-accounts`,\n )\n }\n\n /**\n * Fetch a single payout account by its UUID.\n *\n * **Requires `read` scope.**\n */\n async get(customerId: string, accountId: string): Promise<PayoutAccount> {\n const wrapper = await this.client._request<{ payout_account: PayoutAccount }>(\n 'GET',\n `/v1/customers/${customerId}/payout-accounts/${accountId}`,\n )\n return wrapper.payout_account\n }\n\n /**\n * Update a payout account's details.\n *\n * **Requires `write` scope.**\n */\n async update(\n customerId: string,\n accountId: string,\n request: UpdatePayoutAccountRequest,\n options?: MutationOptions,\n ): Promise<PayoutAccount> {\n const wrapper = await this.client._request<{ payout_account: PayoutAccount }>(\n 'PUT',\n `/v1/customers/${customerId}/payout-accounts/${accountId}`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.payout_account\n }\n\n /**\n * Delete a payout account.\n *\n * **Requires `write` scope.**\n */\n async delete(customerId: string, accountId: string): Promise<void> {\n await this.client._request<void>(\n 'DELETE',\n `/v1/customers/${customerId}/payout-accounts/${accountId}`,\n )\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n Invoice,\n ListInvoicesParams,\n ListInvoicesResponse,\n} from '../types.js'\n\n/** Manage invoice generation, finalization, and voiding. */\nexport class InvoicesResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Generate a draft invoice for a subscription based on current period usage.\n * The invoice starts in `\"draft\"` status and is not sent to the customer yet.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const invoice = await monigo.invoices.generate('sub_xyz')\n * console.log('Draft invoice total:', invoice.total)\n * ```\n */\n async generate(subscriptionId: string, options?: MutationOptions): Promise<Invoice> {\n const wrapper = await this.client._request<{ invoice: Invoice }>(\n 'POST',\n '/v1/invoices/generate',\n { body: { subscription_id: subscriptionId }, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.invoice\n }\n\n /**\n * Return invoices, optionally filtered by status or customer.\n *\n * **Requires `read` scope.**\n *\n * @example\n * ```ts\n * const { invoices } = await monigo.invoices.list({\n * status: 'finalized',\n * customer_id: 'cust_abc',\n * })\n * ```\n */\n async list(params: ListInvoicesParams = {}): Promise<ListInvoicesResponse> {\n return this.client._request<ListInvoicesResponse>('GET', '/v1/invoices', {\n query: {\n status: params.status,\n customer_id: params.customer_id,\n },\n })\n }\n\n /**\n * Fetch a single invoice by its UUID, including line items.\n *\n * **Requires `read` scope.**\n */\n async get(invoiceId: string): Promise<Invoice> {\n const wrapper = await this.client._request<{ invoice: Invoice }>(\n 'GET',\n `/v1/invoices/${invoiceId}`,\n )\n return wrapper.invoice\n }\n\n /**\n * Finalize a draft invoice, making it ready for payment.\n * A finalized invoice cannot be edited.\n *\n * **Requires `write` scope.**\n */\n async finalize(invoiceId: string, options?: MutationOptions): Promise<Invoice> {\n const wrapper = await this.client._request<{ invoice: Invoice }>(\n 'POST',\n `/v1/invoices/${invoiceId}/finalize`,\n { idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.invoice\n }\n\n /**\n * Void an invoice, making it permanently non-payable.\n * Only admins and owners can void invoices.\n *\n * **Requires `write` scope.**\n */\n async void(invoiceId: string, options?: MutationOptions): Promise<Invoice> {\n const wrapper = await this.client._request<{ invoice: Invoice }>(\n 'POST',\n `/v1/invoices/${invoiceId}/void`,\n { idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.invoice\n }\n}\n","import { MonigoClient } from '../client.js'\nimport type { UsageQueryParams, UsageQueryResult } from '../types.js'\n\n/** Query aggregated usage rollups from the Monigo metering pipeline. */\nexport class UsageResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Return per-customer, per-metric usage rollups for the organisation.\n * All parameters are optional — omitting them returns the full current\n * billing period for all customers and metrics.\n *\n * **Requires `read` scope.**\n *\n * @example\n * ```ts\n * // All usage for one customer this period\n * const { rollups } = await monigo.usage.query({\n * customer_id: 'cust_abc',\n * })\n *\n * // Filtered by metric and custom date range\n * const { rollups: filtered } = await monigo.usage.query({\n * metric_id: 'metric_xyz',\n * from: '2025-01-01T00:00:00Z',\n * to: '2025-01-31T23:59:59Z',\n * })\n * ```\n */\n async query(params: UsageQueryParams = {}): Promise<UsageQueryResult> {\n const query: Record<string, string | undefined> = {\n customer_id: params.customer_id,\n metric_id: params.metric_id,\n }\n if (params.from !== undefined) {\n query.from = MonigoClient.toISOString(params.from)\n }\n if (params.to !== undefined) {\n query.to = MonigoClient.toISOString(params.to)\n }\n return this.client._request<UsageQueryResult>('GET', '/v1/usage', { query })\n }\n}\n","import { MonigoAPIError } from './errors.js'\nimport { EventsResource } from './resources/events.js'\nimport { CustomersResource } from './resources/customers.js'\nimport { MetricsResource } from './resources/metrics.js'\nimport { PlansResource } from './resources/plans.js'\nimport { SubscriptionsResource } from './resources/subscriptions.js'\nimport { PayoutAccountsResource } from './resources/payout-accounts.js'\nimport { InvoicesResource } from './resources/invoices.js'\nimport { UsageResource } from './resources/usage.js'\n\nconst DEFAULT_BASE_URL = 'https://api.monigo.co'\nconst DEFAULT_TIMEOUT_MS = 30_000\n\nexport interface MonigoClientOptions {\n /**\n * Your Monigo API key. Obtain one from the API Keys section of your\n * Monigo dashboard. Never expose this key in client-side code.\n */\n apiKey: string\n /**\n * Override the default API base URL (`https://api.monigo.co`).\n * Useful for self-hosted deployments or pointing at a local dev server.\n *\n * @default \"https://api.monigo.co\"\n */\n baseURL?: string\n /**\n * Custom `fetch` implementation. Defaults to `globalThis.fetch`.\n * Pass a polyfill for environments that do not have native fetch\n * (Node.js < 18) or to inject a mock in tests.\n */\n fetch?: typeof globalThis.fetch\n /**\n * Request timeout in milliseconds.\n *\n * @default 30000\n */\n timeout?: number\n}\n\n/**\n * Options accepted by every mutating method (POST, PUT, PATCH).\n */\nexport interface MutationOptions {\n /**\n * A unique key that prevents the same request from being processed more than\n * once. Pass a stable value (e.g. a request ID from your own system) to make\n * retries safe. When omitted, the SDK generates a UUID v4 automatically.\n */\n idempotencyKey?: string\n}\n\n/** @internal */\nexport interface RequestOptions {\n body?: unknown\n query?: Record<string, string | undefined>\n idempotencyKey?: string\n}\n\n/**\n * The Monigo API client.\n *\n * Instantiate once and reuse across your application:\n *\n * ```ts\n * import { MonigoClient } from '@monigo/sdk'\n *\n * const monigo = new MonigoClient({ apiKey: process.env.MONIGO_API_KEY! })\n *\n * // Ingest a usage event\n * await monigo.events.ingest({\n * events: [{\n * event_name: 'api_call',\n * customer_id: 'cust_abc123',\n * idempotency_key: crypto.randomUUID(),\n * }],\n * })\n * ```\n */\nexport class MonigoClient {\n /** @internal */\n readonly _apiKey: string\n /** @internal */\n readonly _baseURL: string\n /** @internal */\n readonly _fetchFn: typeof globalThis.fetch\n /** @internal */\n readonly _timeout: number\n\n /** Ingest usage events and manage event replays. Requires `ingest` scope. */\n readonly events: EventsResource\n /** Manage your end-customers (CRUD). Requires `read` / `write` scope. */\n readonly customers: CustomersResource\n /** Manage billing metrics — what gets counted and how. Requires `read` / `write` scope. */\n readonly metrics: MetricsResource\n /** Manage billing plans and their prices. Requires `read` / `write` scope. */\n readonly plans: PlansResource\n /** Link customers to plans and manage subscription lifecycle. Requires `read` / `write` scope. */\n readonly subscriptions: SubscriptionsResource\n /** Manage bank / mobile-money payout accounts for customers. Requires `read` / `write` scope. */\n readonly payoutAccounts: PayoutAccountsResource\n /** Generate, list, finalize, and void invoices. Requires `read` / `write` scope. */\n readonly invoices: InvoicesResource\n /** Query aggregated usage rollups per customer and metric. Requires `read` scope. */\n readonly usage: UsageResource\n\n constructor(options: MonigoClientOptions) {\n if (!options.apiKey) {\n throw new Error('MonigoClient: apiKey is required')\n }\n\n this._apiKey = options.apiKey\n this._baseURL = (options.baseURL ?? DEFAULT_BASE_URL).replace(/\\/$/, '')\n this._timeout = options.timeout ?? DEFAULT_TIMEOUT_MS\n\n const fetchFn = options.fetch ?? (typeof globalThis !== 'undefined' ? globalThis.fetch : undefined)\n if (!fetchFn) {\n throw new Error(\n 'MonigoClient: fetch is not available in this environment. ' +\n 'Pass a custom fetch implementation via options.fetch, ' +\n 'or upgrade to Node.js 18+.',\n )\n }\n this._fetchFn = fetchFn.bind(globalThis)\n\n this.events = new EventsResource(this)\n this.customers = new CustomersResource(this)\n this.metrics = new MetricsResource(this)\n this.plans = new PlansResource(this)\n this.subscriptions = new SubscriptionsResource(this)\n this.payoutAccounts = new PayoutAccountsResource(this)\n this.invoices = new InvoicesResource(this)\n this.usage = new UsageResource(this)\n }\n\n /**\n * Execute an authenticated HTTP request against the Monigo API.\n * @internal — use the resource methods instead.\n */\n async _request<T>(\n method: string,\n path: string,\n options: RequestOptions = {},\n ): Promise<T> {\n let url = this._baseURL + path\n\n if (options.query) {\n const params = new URLSearchParams()\n for (const [key, value] of Object.entries(options.query)) {\n if (value !== undefined && value !== '') {\n params.set(key, value)\n }\n }\n const qs = params.toString()\n if (qs) url += '?' + qs\n }\n\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), this._timeout)\n\n const isMutating = method === 'POST' || method === 'PUT' || method === 'PATCH'\n const idempotencyKey = isMutating\n ? (options.idempotencyKey ?? globalThis.crypto.randomUUID())\n : undefined\n\n try {\n const response = await this._fetchFn(url, {\n method,\n headers: {\n Authorization: `Bearer ${this._apiKey}`,\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n ...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),\n },\n body: options.body != null ? JSON.stringify(options.body) : undefined,\n signal: controller.signal,\n })\n\n const text = await response.text()\n\n if (!response.ok) {\n let message = text || response.statusText\n let details: Record<string, string> | undefined\n try {\n const parsed = JSON.parse(text) as {\n error?: string\n message?: string\n details?: Record<string, string>\n }\n message = parsed.error ?? parsed.message ?? message\n details = parsed.details\n } catch {\n // Use raw text as the error message\n }\n throw new MonigoAPIError(response.status, message, details)\n }\n\n if (!text) return undefined as T\n return JSON.parse(text) as T\n } catch (err) {\n if (err instanceof MonigoAPIError) throw err\n if (err instanceof Error && err.name === 'AbortError') {\n throw new Error(\n `MonigoClient: request to ${url} timed out after ${this._timeout}ms`,\n )\n }\n throw err\n } finally {\n clearTimeout(timeoutId)\n }\n }\n\n /** Normalise a `Date | string` value to an ISO 8601 string. */\n static toISOString(value: string | Date): string {\n return value instanceof Date ? value.toISOString() : value\n }\n}\n","// =============================================================================\n// Aggregation constants\n// =============================================================================\n\nexport const Aggregation = {\n Count: 'count',\n Sum: 'sum',\n Max: 'max',\n Min: 'minimum',\n Average: 'average',\n Unique: 'unique',\n} as const\n\nexport type AggregationType = (typeof Aggregation)[keyof typeof Aggregation]\n\n// =============================================================================\n// Pricing model constants\n// =============================================================================\n\nexport const PricingModel = {\n Flat: 'flat',\n Tiered: 'tiered',\n Volume: 'volume',\n Package: 'package',\n Overage: 'overage',\n WeightedTiered: 'weighted_tiered',\n} as const\n\nexport type PricingModelType = (typeof PricingModel)[keyof typeof PricingModel]\n\n// =============================================================================\n// Plan constants\n// =============================================================================\n\nexport const PlanType = {\n Collection: 'collection',\n Payout: 'payout',\n} as const\n\nexport type PlanTypeValue = (typeof PlanType)[keyof typeof PlanType]\n\nexport const BillingPeriod = {\n Daily: 'daily',\n Weekly: 'weekly',\n Monthly: 'monthly',\n Quarterly: 'quarterly',\n Annually: 'annually',\n} as const\n\nexport type BillingPeriodValue = (typeof BillingPeriod)[keyof typeof BillingPeriod]\n\n// =============================================================================\n// Subscription status constants\n// =============================================================================\n\nexport const SubscriptionStatus = {\n Active: 'active',\n Paused: 'paused',\n Canceled: 'canceled',\n} as const\n\nexport type SubscriptionStatusValue = (typeof SubscriptionStatus)[keyof typeof SubscriptionStatus]\n\n// =============================================================================\n// Invoice status constants\n// =============================================================================\n\nexport const InvoiceStatus = {\n Draft: 'draft',\n Finalized: 'finalized',\n Paid: 'paid',\n Void: 'void',\n} as const\n\nexport type InvoiceStatusValue = (typeof InvoiceStatus)[keyof typeof InvoiceStatus]\n\n// =============================================================================\n// Payout method constants\n// =============================================================================\n\nexport const PayoutMethod = {\n BankTransfer: 'bank_transfer',\n MobileMoney: 'mobile_money',\n} as const\n\nexport type PayoutMethodValue = (typeof PayoutMethod)[keyof typeof PayoutMethod]\n\n// =============================================================================\n// Events\n// =============================================================================\n\n/** A single usage event sent to the Monigo ingestion pipeline. */\nexport interface IngestEvent {\n /**\n * The name of the event, e.g. `\"api_call\"` or `\"storage.write\"`.\n * Must match the `event_name` on one or more metrics you have configured.\n */\n event_name: string\n /** The Monigo customer UUID this event belongs to. */\n customer_id: string\n /**\n * A unique key for this event. Re-sending the same key is safe — the server\n * will de-duplicate automatically. Use a UUID or any stable ID you control.\n */\n idempotency_key: string\n /**\n * ISO 8601 timestamp for when the event occurred. Backdated events are\n * accepted within the configured replay window. Defaults to now if omitted.\n */\n timestamp?: string | Date\n /**\n * Arbitrary key-value pairs attached to the event. Use these for dimensions\n * such as `{ endpoint: \"/checkout\", region: \"eu-west-1\" }`.\n */\n properties?: Record<string, unknown>\n}\n\n/** Request body for `POST /v1/ingest`. */\nexport interface IngestRequest {\n events: IngestEvent[]\n}\n\n/** Response from `POST /v1/ingest`. */\nexport interface IngestResponse {\n /** Idempotency keys of events that were successfully ingested. */\n ingested: string[]\n /** Idempotency keys that were skipped because they already existed. */\n duplicates: string[]\n}\n\n/** Request body for `POST /v1/events/replay`. */\nexport interface StartReplayRequest {\n /** Start of the replay window (ISO 8601). */\n from: string | Date\n /** End of the replay window (ISO 8601). */\n to: string | Date\n /** Optional event name to replay. Omit to replay all event types. */\n event_name?: string\n}\n\n/** Tracks the progress of an asynchronous event replay job. */\nexport interface EventReplayJob {\n id: string\n org_id: string\n initiated_by: string\n /** `pending` | `processing` | `completed` | `failed` */\n status: string\n from_timestamp: string\n to_timestamp: string\n event_name: string | null\n is_test: boolean\n events_total: number\n events_replayed: number\n error_message: string | null\n started_at: string | null\n completed_at: string | null\n created_at: string\n updated_at: string\n}\n\n// =============================================================================\n// Customers\n// =============================================================================\n\n/** An end-customer record in your Monigo organisation. */\nexport interface Customer {\n id: string\n org_id: string\n /** The ID for this customer in your own system. */\n external_id: string\n name: string\n email: string\n /** Arbitrary JSON metadata. */\n metadata: Record<string, unknown> | null\n created_at: string\n updated_at: string\n}\n\nexport interface CreateCustomerRequest {\n /** Your internal ID for this customer. */\n external_id: string\n name: string\n email: string\n metadata?: Record<string, unknown>\n}\n\nexport interface UpdateCustomerRequest {\n name?: string\n email?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface ListCustomersResponse {\n customers: Customer[]\n count: number\n}\n\n// =============================================================================\n// Metrics\n// =============================================================================\n\n/** Defines what usage is counted and how. */\nexport interface Metric {\n id: string\n org_id: string\n name: string\n /** The `event_name` value that this metric tracks. */\n event_name: string\n /** How events are aggregated. Use `Aggregation` constants. */\n aggregation: AggregationType\n /** For sum/max/min/average: the Properties key whose value is used. */\n aggregation_property?: string\n description?: string\n created_at: string\n updated_at: string\n}\n\nexport interface CreateMetricRequest {\n /** Human-readable label, e.g. `\"API Calls\"`. */\n name: string\n /** The `event_name` value to track. */\n event_name: string\n /** How events are aggregated. Use `Aggregation` constants. */\n aggregation: AggregationType\n description?: string\n /** Required for sum/max/min/average aggregations. */\n aggregation_property?: string\n}\n\nexport interface UpdateMetricRequest {\n name?: string\n event_name?: string\n aggregation?: AggregationType\n description?: string\n aggregation_property?: string\n}\n\nexport interface ListMetricsResponse {\n metrics: Metric[]\n count: number\n}\n\n// =============================================================================\n// Plans & Prices\n// =============================================================================\n\n/**\n * One price step in a tiered/volume/weighted_tiered pricing model.\n * Set `up_to` to `null` for the final (infinite) tier.\n */\nexport interface PriceTier {\n up_to: number | null\n /** Price per unit in this tier as a decimal string, e.g. `\"0.50\"`. */\n unit_amount: string\n}\n\n/** Describes a price to attach when creating a plan. */\nexport interface CreatePriceRequest {\n /** UUID of the metric this price is based on. */\n metric_id: string\n /** Pricing model. Use `PricingModel` constants. */\n model: PricingModelType\n /** Flat price per unit as a decimal string (used for flat/overage/package models). */\n unit_price?: string\n /** Price tiers for tiered/volume/weighted_tiered models. */\n tiers?: PriceTier[]\n}\n\n/** Describes an updated price. Include `id` to update an existing price; omit to add a new one. */\nexport interface UpdatePriceRequest {\n id?: string\n metric_id?: string\n model?: PricingModelType\n unit_price?: string\n tiers?: PriceTier[]\n}\n\n/** A pricing rule attached to a plan. */\nexport interface Price {\n id: string\n plan_id: string\n metric_id: string\n model: PricingModelType\n unit_price: string\n tiers: PriceTier[] | null\n created_at: string\n updated_at: string\n}\n\n/** A billing plan that defines pricing for one or more metrics. */\nexport interface Plan {\n id: string\n org_id: string\n name: string\n description?: string\n /** ISO 4217 currency code, e.g. `\"NGN\"`. */\n currency: string\n /** Use `PlanType` constants. */\n plan_type: PlanTypeValue\n /** Use `BillingPeriod` constants. */\n billing_period: BillingPeriodValue\n trial_period_days: number\n prices?: Price[]\n created_at: string\n updated_at: string\n}\n\nexport interface CreatePlanRequest {\n name: string\n description?: string\n /** ISO 4217 currency code. Defaults to `\"NGN\"`. */\n currency?: string\n /** Use `PlanType` constants. Defaults to `\"collection\"`. */\n plan_type?: PlanTypeValue\n /** Use `BillingPeriod` constants. Defaults to `\"monthly\"`. */\n billing_period?: BillingPeriodValue\n /** Trial period in days. Set to `0` for no trial. */\n trial_period_days?: number\n prices?: CreatePriceRequest[]\n}\n\nexport interface UpdatePlanRequest {\n name?: string\n description?: string\n currency?: string\n plan_type?: PlanTypeValue\n billing_period?: BillingPeriodValue\n prices?: UpdatePriceRequest[]\n}\n\nexport interface ListPlansResponse {\n plans: Plan[]\n count: number\n}\n\n// =============================================================================\n// Subscriptions\n// =============================================================================\n\n/** Links a customer to a billing plan. */\nexport interface Subscription {\n id: string\n org_id: string\n customer_id: string\n plan_id: string\n /** Use `SubscriptionStatus` constants. */\n status: SubscriptionStatusValue\n current_period_start: string\n current_period_end: string\n trial_ends_at: string | null\n created_at: string\n updated_at: string\n}\n\nexport interface CreateSubscriptionRequest {\n /** UUID of the customer to subscribe. */\n customer_id: string\n /** UUID of the plan to subscribe the customer to. */\n plan_id: string\n}\n\nexport interface ListSubscriptionsParams {\n /** Filter to a specific customer UUID. */\n customer_id?: string\n /** Filter to a specific plan UUID. */\n plan_id?: string\n /** Filter by status. Use `SubscriptionStatus` constants. */\n status?: SubscriptionStatusValue\n}\n\nexport interface ListSubscriptionsResponse {\n subscriptions: Subscription[]\n count: number\n}\n\n// =============================================================================\n// Payout accounts\n// =============================================================================\n\n/** A bank or mobile-money account that a customer can be paid to. */\nexport interface PayoutAccount {\n id: string\n customer_id: string\n org_id: string\n account_name: string\n bank_name?: string\n bank_code?: string\n account_number?: string\n mobile_money_number?: string\n /** Use `PayoutMethod` constants. */\n payout_method: PayoutMethodValue\n currency: string\n is_default: boolean\n metadata: Record<string, unknown> | null\n created_at: string\n updated_at: string\n}\n\nexport interface CreatePayoutAccountRequest {\n account_name: string\n /** Use `PayoutMethod` constants. */\n payout_method: PayoutMethodValue\n bank_name?: string\n bank_code?: string\n account_number?: string\n mobile_money_number?: string\n currency?: string\n is_default?: boolean\n metadata?: Record<string, unknown>\n}\n\nexport interface UpdatePayoutAccountRequest {\n account_name?: string\n payout_method?: PayoutMethodValue\n bank_name?: string\n account_number?: string\n currency?: string\n is_default?: boolean\n metadata?: Record<string, unknown>\n}\n\nexport interface ListPayoutAccountsResponse {\n payout_accounts: PayoutAccount[]\n count: number\n}\n\n// =============================================================================\n// Invoices\n// =============================================================================\n\n/** One line item on an invoice. */\nexport interface InvoiceLineItem {\n id: string\n invoice_id: string\n metric_id: string\n price_id?: string\n description: string\n quantity: string\n unit_price: string\n /** Amount for this line as a decimal string. */\n amount: string\n created_at: string\n}\n\n/**\n * A billing invoice.\n * All monetary values (`subtotal`, `vat_amount`, `total`) are decimal strings\n * to avoid floating-point precision issues.\n */\nexport interface Invoice {\n id: string\n org_id: string\n customer_id: string\n subscription_id: string\n /** Use `InvoiceStatus` constants. */\n status: InvoiceStatusValue\n currency: string\n subtotal: string\n vat_enabled: boolean\n vat_rate?: string\n vat_amount?: string\n total: string\n period_start: string\n period_end: string\n finalized_at: string | null\n paid_at: string | null\n provider_invoice_id?: string\n line_items?: InvoiceLineItem[]\n created_at: string\n updated_at: string\n}\n\nexport interface ListInvoicesParams {\n /** Filter by status. Use `InvoiceStatus` constants. */\n status?: InvoiceStatusValue\n /** Filter to a specific customer UUID. */\n customer_id?: string\n}\n\nexport interface ListInvoicesResponse {\n invoices: Invoice[]\n count: number\n}\n\n// =============================================================================\n// Usage\n// =============================================================================\n\n/** One aggregated usage record for a (customer, metric, period) tuple. */\nexport interface UsageRollup {\n id: string\n org_id: string\n customer_id: string\n metric_id: string\n period_start: string\n period_end: string\n aggregation: AggregationType\n /** Aggregated value (count, sum, max, etc.). */\n value: number\n event_count: number\n last_event_at: string | null\n is_test: boolean\n created_at: string\n updated_at: string\n}\n\nexport interface UsageQueryParams {\n /** Filter rollups to a specific customer UUID. */\n customer_id?: string\n /** Filter rollups to a specific metric UUID. */\n metric_id?: string\n /**\n * Lower bound for `period_start` (ISO 8601).\n * Defaults to the start of the current billing period.\n */\n from?: string | Date\n /**\n * Exclusive upper bound for `period_start` (ISO 8601).\n * Defaults to the end of the current billing period.\n */\n to?: string | Date\n}\n\nexport interface UsageQueryResult {\n rollups: UsageRollup[]\n count: number\n}\n"],"names":[],"mappings":"AAcO,MAAM,uBAAuB,MAAM;AAAA,EAQxC,YACE,YACA,SACA,SACA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,UAAU;AACf,SAAK,UAAU;AAEf,UAAM,UAAW,MACf,mBACF;AACA,cAAU,MAAM,cAAc;AAAA,EAChC;AAAA;AAAA;AAAA;AAAA,EAMA,IAAI,aAAsB;AACxB,WAAO,KAAK,eAAe;AAAA,EAC7B;AAAA,EAEA,IAAI,iBAA0B;AAC5B,WAAO,KAAK,eAAe;AAAA,EAC7B;AAAA,EAEA,IAAI,cAAuB;AACzB,WAAO,KAAK,eAAe;AAAA,EAC7B;AAAA,EAEA,IAAI,gBAAyB;AAC3B,WAAO,KAAK,eAAe;AAAA,EAC7B;AAAA,EAEA,IAAI,aAAsB;AACxB,WAAO,KAAK,eAAe;AAAA,EAC7B;AAAA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ACT,WAAW;AAAA,EACX,UAAU;AACZ;AAQO,MAAM,qBAAqB;AAAA,EAChC,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,UAAU;AACZ;AAQO,MAAM,gBAAgB;AAAA,EAC3B,OAAO;AAAA,EACP,WAAW;AAAA,EACX,MAAM;AAAA,EACN,MAAM;AACR;AAQO,MAAM,eAAe;AAAA,EAC1B,cAAc;AAAA,EACd,aAAa;AACf;"}
1
+ {"version":3,"file":"monigo.js","sources":["../src/errors.ts","../src/resources/events.ts","../src/resources/customers.ts","../src/resources/metrics.ts","../src/resources/plans.ts","../src/resources/subscriptions.ts","../src/resources/payout-accounts.ts","../src/resources/invoices.ts","../src/resources/usage.ts","../src/client.ts","../src/types.ts"],"sourcesContent":["/**\n * Thrown for any non-2xx response from the Monigo API.\n *\n * @example\n * ```ts\n * try {\n * await client.customers.get('bad-id')\n * } catch (err) {\n * if (MonigoAPIError.isNotFound(err)) {\n * console.log('Customer does not exist')\n * }\n * }\n * ```\n */\nexport class MonigoAPIError extends Error {\n /** HTTP status code returned by the API. */\n readonly statusCode: number\n /** Human-readable error message from the API. */\n readonly message: string\n /** Optional structured field-level validation details. */\n readonly details: Record<string, string> | undefined\n\n constructor(\n statusCode: number,\n message: string,\n details?: Record<string, string>,\n ) {\n super(message)\n this.name = 'MonigoAPIError'\n this.statusCode = statusCode\n this.message = message\n this.details = details\n // Maintain proper stack trace in V8 (Node.js / Chrome)\n const capture = (Error as unknown as Record<string, unknown>)[\n 'captureStackTrace'\n ] as ((target: Error, constructor: Function) => void) | undefined\n capture?.(this, MonigoAPIError)\n }\n\n // -------------------------------------------------------------------------\n // Instance guards (for use on a caught error known to be MonigoAPIError)\n // -------------------------------------------------------------------------\n\n get isNotFound(): boolean {\n return this.statusCode === 404\n }\n\n get isUnauthorized(): boolean {\n return this.statusCode === 401\n }\n\n get isForbidden(): boolean {\n return this.statusCode === 403\n }\n\n get isRateLimited(): boolean {\n return this.statusCode === 429\n }\n\n get isConflict(): boolean {\n return this.statusCode === 409\n }\n\n get isQuotaExceeded(): boolean {\n return this.statusCode === 402\n }\n\n get isServerError(): boolean {\n return this.statusCode >= 500\n }\n\n // -------------------------------------------------------------------------\n // Static type-narrowing helpers (for use in catch clauses on `unknown`)\n // -------------------------------------------------------------------------\n\n static isNotFound(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 404\n }\n\n static isUnauthorized(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 401\n }\n\n static isForbidden(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 403\n }\n\n static isRateLimited(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 429\n }\n\n static isConflict(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 409\n }\n\n static isQuotaExceeded(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode === 402\n }\n\n static isServerError(err: unknown): err is MonigoAPIError {\n return err instanceof MonigoAPIError && err.statusCode >= 500\n }\n}\n","import { MonigoClient } from '../client.js'\nimport type { MutationOptions } from '../client.js'\nimport type {\n IngestRequest,\n IngestResponse,\n StartReplayRequest,\n EventReplayJob,\n} from '../types.js'\n\n/** Handles usage event ingestion and asynchronous event replay. */\nexport class EventsResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Ingest one or more usage events into the Monigo pipeline.\n *\n * Events are processed asynchronously. The response confirms receipt\n * and reports any duplicate idempotency keys.\n *\n * **Requires `ingest` scope.**\n *\n * @example\n * ```ts\n * const result = await monigo.events.ingest({\n * events: [{\n * event_name: 'api_call',\n * customer_id: 'cust_abc',\n * idempotency_key: crypto.randomUUID(),\n * timestamp: new Date().toISOString(),\n * properties: { endpoint: '/checkout', region: 'eu-west-1' },\n * }],\n * })\n * console.log('Ingested:', result.ingested.length)\n * console.log('Duplicates:', result.duplicates.length)\n * ```\n */\n async ingest(request: IngestRequest, options?: MutationOptions): Promise<IngestResponse> {\n const body = {\n events: request.events.map((e) => ({\n ...e,\n timestamp: e.timestamp\n ? MonigoClient.toISOString(e.timestamp)\n : new Date().toISOString(),\n })),\n }\n return this.client._request<IngestResponse>('POST', '/v1/ingest', {\n body,\n idempotencyKey: options?.idempotencyKey,\n })\n }\n\n /**\n * Start an asynchronous replay of all raw events in a given time window\n * through the current processing pipeline. Useful for backfilling usage\n * data after changing metric definitions.\n *\n * Returns a replay job immediately — poll `getReplay()` to track progress.\n *\n * **Requires `ingest` scope.**\n *\n * @example\n * ```ts\n * const job = await monigo.events.startReplay({\n * from: '2025-01-01T00:00:00Z',\n * to: '2025-01-31T23:59:59Z',\n * event_name: 'api_call', // omit to replay all event types\n * })\n * console.log('Replay job:', job.id, job.status)\n * ```\n */\n async startReplay(request: StartReplayRequest, options?: MutationOptions): Promise<EventReplayJob> {\n const body = {\n from: MonigoClient.toISOString(request.from),\n to: MonigoClient.toISOString(request.to),\n ...(request.event_name ? { event_name: request.event_name } : {}),\n }\n const wrapper = await this.client._request<{ job: EventReplayJob }>(\n 'POST',\n '/v1/events/replay',\n { body, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.job\n }\n\n /**\n * Fetch the current status and progress of an event replay job.\n *\n * **Requires `ingest` scope.**\n *\n * @example\n * ```ts\n * const job = await monigo.events.getReplay(jobId)\n * if (job.status === 'completed') {\n * console.log(`Replayed ${job.events_replayed} / ${job.events_total} events`)\n * }\n * ```\n */\n async getReplay(jobId: string): Promise<EventReplayJob> {\n const wrapper = await this.client._request<{ job: EventReplayJob }>(\n 'GET',\n `/v1/events/replay/${jobId}`,\n )\n return wrapper.job\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n Customer,\n CreateCustomerRequest,\n UpdateCustomerRequest,\n ListCustomersResponse,\n} from '../types.js'\n\n/** Manage end-customers in your Monigo organisation. */\nexport class CustomersResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Register a new customer.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const customer = await monigo.customers.create({\n * external_id: 'usr_12345',\n * name: 'Acme Corp',\n * email: 'billing@acme.com',\n * metadata: { plan_tier: 'enterprise' },\n * })\n * ```\n */\n async create(request: CreateCustomerRequest, options?: MutationOptions): Promise<Customer> {\n const wrapper = await this.client._request<{ customer: Customer }>(\n 'POST',\n '/v1/customers',\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.customer\n }\n\n /**\n * Return all customers in the authenticated organisation.\n *\n * **Requires `read` scope.**\n */\n async list(): Promise<ListCustomersResponse> {\n return this.client._request<ListCustomersResponse>('GET', '/v1/customers')\n }\n\n /**\n * Fetch a single customer by their Monigo UUID.\n *\n * **Requires `read` scope.**\n */\n async get(customerId: string): Promise<Customer> {\n const wrapper = await this.client._request<{ customer: Customer }>(\n 'GET',\n `/v1/customers/${customerId}`,\n )\n return wrapper.customer\n }\n\n /**\n * Update a customer's name, email, or metadata.\n * Only fields that are present in `request` are updated.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const updated = await monigo.customers.update(customerId, {\n * email: 'new@acme.com',\n * })\n * ```\n */\n async update(\n customerId: string,\n request: UpdateCustomerRequest,\n options?: MutationOptions,\n ): Promise<Customer> {\n const wrapper = await this.client._request<{ customer: Customer }>(\n 'PUT',\n `/v1/customers/${customerId}`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.customer\n }\n\n /**\n * Permanently delete a customer record.\n *\n * **Requires `write` scope.**\n */\n async delete(customerId: string): Promise<void> {\n await this.client._request<void>('DELETE', `/v1/customers/${customerId}`)\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n Metric,\n CreateMetricRequest,\n UpdateMetricRequest,\n ListMetricsResponse,\n} from '../types.js'\n\n/** Manage billing metrics — what usage gets counted and how it is aggregated. */\nexport class MetricsResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Create a new metric.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const metric = await monigo.metrics.create({\n * name: 'API Calls',\n * event_name: 'api_call',\n * aggregation: 'count',\n * })\n * ```\n */\n async create(request: CreateMetricRequest, options?: MutationOptions): Promise<Metric> {\n const wrapper = await this.client._request<{ metric: Metric }>(\n 'POST',\n '/v1/metrics',\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.metric\n }\n\n /**\n * Return all metrics in the authenticated organisation.\n *\n * **Requires `read` scope.**\n */\n async list(): Promise<ListMetricsResponse> {\n return this.client._request<ListMetricsResponse>('GET', '/v1/metrics')\n }\n\n /**\n * Fetch a single metric by its UUID.\n *\n * **Requires `read` scope.**\n */\n async get(metricId: string): Promise<Metric> {\n const wrapper = await this.client._request<{ metric: Metric }>(\n 'GET',\n `/v1/metrics/${metricId}`,\n )\n return wrapper.metric\n }\n\n /**\n * Update a metric's name, event name, aggregation, or description.\n *\n * **Requires `write` scope.**\n */\n async update(metricId: string, request: UpdateMetricRequest, options?: MutationOptions): Promise<Metric> {\n const wrapper = await this.client._request<{ metric: Metric }>(\n 'PUT',\n `/v1/metrics/${metricId}`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.metric\n }\n\n /**\n * Permanently delete a metric.\n *\n * **Requires `write` scope.**\n */\n async delete(metricId: string): Promise<void> {\n await this.client._request<void>('DELETE', `/v1/metrics/${metricId}`)\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n Plan,\n CreatePlanRequest,\n UpdatePlanRequest,\n ListPlansResponse,\n} from '../types.js'\n\n/** Manage billing plans and their prices. */\nexport class PlansResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Create a new billing plan, optionally with prices attached.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const plan = await monigo.plans.create({\n * name: 'Pro',\n * currency: 'NGN',\n * billing_period: 'monthly',\n * prices: [{\n * metric_id: 'metric_abc',\n * model: 'flat',\n * unit_price: '2.500000',\n * }],\n * })\n * ```\n */\n async create(request: CreatePlanRequest, options?: MutationOptions): Promise<Plan> {\n const wrapper = await this.client._request<{ plan: Plan }>(\n 'POST',\n '/v1/plans',\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.plan\n }\n\n /**\n * Return all billing plans in the authenticated organisation.\n *\n * **Requires `read` scope.**\n */\n async list(): Promise<ListPlansResponse> {\n return this.client._request<ListPlansResponse>('GET', '/v1/plans')\n }\n\n /**\n * Fetch a single plan by its UUID, including its prices.\n *\n * **Requires `read` scope.**\n */\n async get(planId: string): Promise<Plan> {\n const wrapper = await this.client._request<{ plan: Plan }>(\n 'GET',\n `/v1/plans/${planId}`,\n )\n return wrapper.plan\n }\n\n /**\n * Update a plan's name, description, currency, or prices.\n *\n * **Requires `write` scope.**\n */\n async update(planId: string, request: UpdatePlanRequest, options?: MutationOptions): Promise<Plan> {\n const wrapper = await this.client._request<{ plan: Plan }>(\n 'PUT',\n `/v1/plans/${planId}`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.plan\n }\n\n /**\n * Permanently delete a plan.\n *\n * **Requires `write` scope.**\n */\n async delete(planId: string): Promise<void> {\n await this.client._request<void>('DELETE', `/v1/plans/${planId}`)\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n Subscription,\n CreateSubscriptionRequest,\n ListSubscriptionsParams,\n ListSubscriptionsResponse,\n SubscriptionStatusValue,\n} from '../types.js'\n\n/** Link customers to billing plans and manage subscription lifecycle. */\nexport class SubscriptionsResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Subscribe a customer to a plan.\n *\n * Returns a 409 Conflict error (check with `MonigoAPIError.isConflict(err)`)\n * if the customer already has an active subscription to the same plan.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const sub = await monigo.subscriptions.create({\n * customer_id: 'cust_abc',\n * plan_id: 'plan_xyz',\n * })\n * ```\n */\n async create(request: CreateSubscriptionRequest, options?: MutationOptions): Promise<Subscription> {\n const wrapper = await this.client._request<{ subscription: Subscription }>(\n 'POST',\n '/v1/subscriptions',\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.subscription\n }\n\n /**\n * Return subscriptions, optionally filtered by customer, plan, or status.\n *\n * **Requires `read` scope.**\n *\n * @example\n * ```ts\n * const { subscriptions } = await monigo.subscriptions.list({\n * customer_id: 'cust_abc',\n * status: 'active',\n * })\n * ```\n */\n async list(params: ListSubscriptionsParams = {}): Promise<ListSubscriptionsResponse> {\n return this.client._request<ListSubscriptionsResponse>('GET', '/v1/subscriptions', {\n query: {\n customer_id: params.customer_id,\n plan_id: params.plan_id,\n status: params.status,\n },\n })\n }\n\n /**\n * Fetch a single subscription by its UUID.\n *\n * **Requires `read` scope.**\n */\n async get(subscriptionId: string): Promise<Subscription> {\n const wrapper = await this.client._request<{ subscription: Subscription }>(\n 'GET',\n `/v1/subscriptions/${subscriptionId}`,\n )\n return wrapper.subscription\n }\n\n /**\n * Change the status of a subscription.\n * Use `SubscriptionStatus` constants: `\"active\"`, `\"paused\"`, `\"canceled\"`.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * await monigo.subscriptions.updateStatus(subId, SubscriptionStatus.Paused)\n * ```\n */\n async updateStatus(\n subscriptionId: string,\n status: SubscriptionStatusValue,\n options?: MutationOptions,\n ): Promise<Subscription> {\n const wrapper = await this.client._request<{ subscription: Subscription }>(\n 'PATCH',\n `/v1/subscriptions/${subscriptionId}`,\n { body: { status }, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.subscription\n }\n\n /**\n * Cancel and delete a subscription record.\n *\n * **Requires `write` scope.**\n */\n async delete(subscriptionId: string): Promise<void> {\n await this.client._request<void>('DELETE', `/v1/subscriptions/${subscriptionId}`)\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n PayoutAccount,\n CreatePayoutAccountRequest,\n UpdatePayoutAccountRequest,\n ListPayoutAccountsResponse,\n} from '../types.js'\n\n/** Manage bank and mobile-money payout accounts for customers. */\nexport class PayoutAccountsResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Add a payout account for a customer.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const account = await monigo.payoutAccounts.create('cust_abc', {\n * account_name: 'Acme Corp',\n * payout_method: 'bank_transfer',\n * bank_name: 'Zenith Bank',\n * bank_code: '057',\n * account_number: '1234567890',\n * currency: 'NGN',\n * is_default: true,\n * })\n * ```\n */\n async create(\n customerId: string,\n request: CreatePayoutAccountRequest,\n options?: MutationOptions,\n ): Promise<PayoutAccount> {\n const wrapper = await this.client._request<{ payout_account: PayoutAccount }>(\n 'POST',\n `/v1/customers/${customerId}/payout-accounts`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.payout_account\n }\n\n /**\n * Return all payout accounts for a customer.\n *\n * **Requires `read` scope.**\n */\n async list(customerId: string): Promise<ListPayoutAccountsResponse> {\n return this.client._request<ListPayoutAccountsResponse>(\n 'GET',\n `/v1/customers/${customerId}/payout-accounts`,\n )\n }\n\n /**\n * Fetch a single payout account by its UUID.\n *\n * **Requires `read` scope.**\n */\n async get(customerId: string, accountId: string): Promise<PayoutAccount> {\n const wrapper = await this.client._request<{ payout_account: PayoutAccount }>(\n 'GET',\n `/v1/customers/${customerId}/payout-accounts/${accountId}`,\n )\n return wrapper.payout_account\n }\n\n /**\n * Update a payout account's details.\n *\n * **Requires `write` scope.**\n */\n async update(\n customerId: string,\n accountId: string,\n request: UpdatePayoutAccountRequest,\n options?: MutationOptions,\n ): Promise<PayoutAccount> {\n const wrapper = await this.client._request<{ payout_account: PayoutAccount }>(\n 'PUT',\n `/v1/customers/${customerId}/payout-accounts/${accountId}`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.payout_account\n }\n\n /**\n * Delete a payout account.\n *\n * **Requires `write` scope.**\n */\n async delete(customerId: string, accountId: string): Promise<void> {\n await this.client._request<void>(\n 'DELETE',\n `/v1/customers/${customerId}/payout-accounts/${accountId}`,\n )\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n Invoice,\n ListInvoicesParams,\n ListInvoicesResponse,\n} from '../types.js'\n\n/** Manage invoice generation, finalization, and voiding. */\nexport class InvoicesResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Generate a draft invoice for a subscription based on current period usage.\n * The invoice starts in `\"draft\"` status and is not sent to the customer yet.\n *\n * **Requires `write` scope.**\n *\n * @example\n * ```ts\n * const invoice = await monigo.invoices.generate('sub_xyz')\n * console.log('Draft invoice total:', invoice.total)\n * ```\n */\n async generate(subscriptionId: string, options?: MutationOptions): Promise<Invoice> {\n const wrapper = await this.client._request<{ invoice: Invoice }>(\n 'POST',\n '/v1/invoices/generate',\n { body: { subscription_id: subscriptionId }, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.invoice\n }\n\n /**\n * Return invoices, optionally filtered by status or customer.\n *\n * **Requires `read` scope.**\n *\n * @example\n * ```ts\n * const { invoices } = await monigo.invoices.list({\n * status: 'finalized',\n * customer_id: 'cust_abc',\n * })\n * ```\n */\n async list(params: ListInvoicesParams = {}): Promise<ListInvoicesResponse> {\n return this.client._request<ListInvoicesResponse>('GET', '/v1/invoices', {\n query: {\n status: params.status,\n customer_id: params.customer_id,\n },\n })\n }\n\n /**\n * Fetch a single invoice by its UUID, including line items.\n *\n * **Requires `read` scope.**\n */\n async get(invoiceId: string): Promise<Invoice> {\n const wrapper = await this.client._request<{ invoice: Invoice }>(\n 'GET',\n `/v1/invoices/${invoiceId}`,\n )\n return wrapper.invoice\n }\n\n /**\n * Finalize a draft invoice, making it ready for payment.\n * A finalized invoice cannot be edited.\n *\n * **Requires `write` scope.**\n */\n async finalize(invoiceId: string, options?: MutationOptions): Promise<Invoice> {\n const wrapper = await this.client._request<{ invoice: Invoice }>(\n 'POST',\n `/v1/invoices/${invoiceId}/finalize`,\n { idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.invoice\n }\n\n /**\n * Void an invoice, making it permanently non-payable.\n * Only admins and owners can void invoices.\n *\n * **Requires `write` scope.**\n */\n async void(invoiceId: string, options?: MutationOptions): Promise<Invoice> {\n const wrapper = await this.client._request<{ invoice: Invoice }>(\n 'POST',\n `/v1/invoices/${invoiceId}/void`,\n { idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.invoice\n }\n}\n","import { MonigoClient } from '../client.js'\nimport type { UsageQueryParams, UsageQueryResult } from '../types.js'\n\n/** Query aggregated usage rollups from the Monigo metering pipeline. */\nexport class UsageResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Return per-customer, per-metric usage rollups for the organisation.\n * All parameters are optional — omitting them returns the full current\n * billing period for all customers and metrics.\n *\n * **Requires `read` scope.**\n *\n * @example\n * ```ts\n * // All usage for one customer this period\n * const { rollups } = await monigo.usage.query({\n * customer_id: 'cust_abc',\n * })\n *\n * // Filtered by metric and custom date range\n * const { rollups: filtered } = await monigo.usage.query({\n * metric_id: 'metric_xyz',\n * from: '2025-01-01T00:00:00Z',\n * to: '2025-01-31T23:59:59Z',\n * })\n * ```\n */\n async query(params: UsageQueryParams = {}): Promise<UsageQueryResult> {\n const query: Record<string, string | undefined> = {\n customer_id: params.customer_id,\n metric_id: params.metric_id,\n }\n if (params.from !== undefined) {\n query.from = MonigoClient.toISOString(params.from)\n }\n if (params.to !== undefined) {\n query.to = MonigoClient.toISOString(params.to)\n }\n return this.client._request<UsageQueryResult>('GET', '/v1/usage', { query })\n }\n}\n","import { MonigoAPIError } from './errors.js'\nimport { EventsResource } from './resources/events.js'\nimport { CustomersResource } from './resources/customers.js'\nimport { MetricsResource } from './resources/metrics.js'\nimport { PlansResource } from './resources/plans.js'\nimport { SubscriptionsResource } from './resources/subscriptions.js'\nimport { PayoutAccountsResource } from './resources/payout-accounts.js'\nimport { InvoicesResource } from './resources/invoices.js'\nimport { UsageResource } from './resources/usage.js'\n\nconst DEFAULT_BASE_URL = 'https://api.monigo.co'\nconst DEFAULT_TIMEOUT_MS = 30_000\n\nexport interface MonigoClientOptions {\n /**\n * Your Monigo API key. Obtain one from the API Keys section of your\n * Monigo dashboard. Never expose this key in client-side code.\n */\n apiKey: string\n /**\n * Override the default API base URL (`https://api.monigo.co`).\n * Useful for self-hosted deployments or pointing at a local dev server.\n *\n * @default \"https://api.monigo.co\"\n */\n baseURL?: string\n /**\n * Custom `fetch` implementation. Defaults to `globalThis.fetch`.\n * Pass a polyfill for environments that do not have native fetch\n * (Node.js < 18) or to inject a mock in tests.\n */\n fetch?: typeof globalThis.fetch\n /**\n * Request timeout in milliseconds.\n *\n * @default 30000\n */\n timeout?: number\n}\n\n/**\n * Options accepted by every mutating method (POST, PUT, PATCH).\n */\nexport interface MutationOptions {\n /**\n * A unique key that prevents the same request from being processed more than\n * once. Pass a stable value (e.g. a request ID from your own system) to make\n * retries safe. When omitted, the SDK generates a UUID v4 automatically.\n */\n idempotencyKey?: string\n}\n\n/** @internal */\nexport interface RequestOptions {\n body?: unknown\n query?: Record<string, string | undefined>\n idempotencyKey?: string\n}\n\n/**\n * The Monigo API client.\n *\n * Instantiate once and reuse across your application:\n *\n * ```ts\n * import { MonigoClient } from '@monigo/sdk'\n *\n * const monigo = new MonigoClient({ apiKey: process.env.MONIGO_API_KEY! })\n *\n * // Ingest a usage event\n * await monigo.events.ingest({\n * events: [{\n * event_name: 'api_call',\n * customer_id: 'cust_abc123',\n * idempotency_key: crypto.randomUUID(),\n * }],\n * })\n * ```\n */\nexport class MonigoClient {\n /** @internal */\n readonly _apiKey: string\n /** @internal */\n readonly _baseURL: string\n /** @internal */\n readonly _fetchFn: typeof globalThis.fetch\n /** @internal */\n readonly _timeout: number\n\n /** Ingest usage events and manage event replays. Requires `ingest` scope. */\n readonly events: EventsResource\n /** Manage your end-customers (CRUD). Requires `read` / `write` scope. */\n readonly customers: CustomersResource\n /** Manage billing metrics — what gets counted and how. Requires `read` / `write` scope. */\n readonly metrics: MetricsResource\n /** Manage billing plans and their prices. Requires `read` / `write` scope. */\n readonly plans: PlansResource\n /** Link customers to plans and manage subscription lifecycle. Requires `read` / `write` scope. */\n readonly subscriptions: SubscriptionsResource\n /** Manage bank / mobile-money payout accounts for customers. Requires `read` / `write` scope. */\n readonly payoutAccounts: PayoutAccountsResource\n /** Generate, list, finalize, and void invoices. Requires `read` / `write` scope. */\n readonly invoices: InvoicesResource\n /** Query aggregated usage rollups per customer and metric. Requires `read` scope. */\n readonly usage: UsageResource\n\n constructor(options: MonigoClientOptions) {\n if (!options.apiKey) {\n throw new Error('MonigoClient: apiKey is required')\n }\n\n this._apiKey = options.apiKey\n this._baseURL = (options.baseURL ?? DEFAULT_BASE_URL).replace(/\\/$/, '')\n this._timeout = options.timeout ?? DEFAULT_TIMEOUT_MS\n\n const fetchFn = options.fetch ?? (typeof globalThis !== 'undefined' ? globalThis.fetch : undefined)\n if (!fetchFn) {\n throw new Error(\n 'MonigoClient: fetch is not available in this environment. ' +\n 'Pass a custom fetch implementation via options.fetch, ' +\n 'or upgrade to Node.js 18+.',\n )\n }\n this._fetchFn = fetchFn.bind(globalThis)\n\n this.events = new EventsResource(this)\n this.customers = new CustomersResource(this)\n this.metrics = new MetricsResource(this)\n this.plans = new PlansResource(this)\n this.subscriptions = new SubscriptionsResource(this)\n this.payoutAccounts = new PayoutAccountsResource(this)\n this.invoices = new InvoicesResource(this)\n this.usage = new UsageResource(this)\n }\n\n /**\n * Execute an authenticated HTTP request against the Monigo API.\n * @internal — use the resource methods instead.\n */\n async _request<T>(\n method: string,\n path: string,\n options: RequestOptions = {},\n ): Promise<T> {\n let url = this._baseURL + path\n\n if (options.query) {\n const params = new URLSearchParams()\n for (const [key, value] of Object.entries(options.query)) {\n if (value !== undefined && value !== '') {\n params.set(key, value)\n }\n }\n const qs = params.toString()\n if (qs) url += '?' + qs\n }\n\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), this._timeout)\n\n const isMutating = method === 'POST' || method === 'PUT' || method === 'PATCH'\n const idempotencyKey = isMutating\n ? (options.idempotencyKey ?? globalThis.crypto.randomUUID())\n : undefined\n\n try {\n const response = await this._fetchFn(url, {\n method,\n headers: {\n Authorization: `Bearer ${this._apiKey}`,\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n ...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),\n },\n body: options.body != null ? JSON.stringify(options.body) : undefined,\n signal: controller.signal,\n })\n\n const text = await response.text()\n\n if (!response.ok) {\n let message = text || response.statusText\n let details: Record<string, string> | undefined\n try {\n const parsed = JSON.parse(text) as {\n error?: string\n message?: string\n details?: Record<string, string>\n }\n message = parsed.error ?? parsed.message ?? message\n details = parsed.details\n } catch {\n // Use raw text as the error message\n }\n throw new MonigoAPIError(response.status, message, details)\n }\n\n if (!text) return undefined as T\n return JSON.parse(text) as T\n } catch (err) {\n if (err instanceof MonigoAPIError) throw err\n if (err instanceof Error && err.name === 'AbortError') {\n throw new Error(\n `MonigoClient: request to ${url} timed out after ${this._timeout}ms`,\n )\n }\n throw err\n } finally {\n clearTimeout(timeoutId)\n }\n }\n\n /** Normalise a `Date | string` value to an ISO 8601 string. */\n static toISOString(value: string | Date): string {\n return value instanceof Date ? value.toISOString() : value\n }\n}\n","// =============================================================================\n// Aggregation constants\n// =============================================================================\n\nexport const Aggregation = {\n Count: 'count',\n Sum: 'sum',\n Max: 'max',\n Min: 'minimum',\n Average: 'average',\n Unique: 'unique',\n} as const\n\nexport type AggregationType = (typeof Aggregation)[keyof typeof Aggregation]\n\n// =============================================================================\n// Pricing model constants\n// =============================================================================\n\nexport const PricingModel = {\n Flat: 'flat',\n Tiered: 'tiered',\n Volume: 'volume',\n Package: 'package',\n Overage: 'overage',\n WeightedTiered: 'weighted_tiered',\n} as const\n\nexport type PricingModelType = (typeof PricingModel)[keyof typeof PricingModel]\n\n// =============================================================================\n// Plan constants\n// =============================================================================\n\nexport const PlanType = {\n Collection: 'collection',\n Payout: 'payout',\n} as const\n\nexport type PlanTypeValue = (typeof PlanType)[keyof typeof PlanType]\n\nexport const BillingPeriod = {\n Daily: 'daily',\n Weekly: 'weekly',\n Monthly: 'monthly',\n Quarterly: 'quarterly',\n Annually: 'annually',\n} as const\n\nexport type BillingPeriodValue = (typeof BillingPeriod)[keyof typeof BillingPeriod]\n\n// =============================================================================\n// Subscription status constants\n// =============================================================================\n\nexport const SubscriptionStatus = {\n Active: 'active',\n Paused: 'paused',\n Canceled: 'canceled',\n} as const\n\nexport type SubscriptionStatusValue = (typeof SubscriptionStatus)[keyof typeof SubscriptionStatus]\n\n// =============================================================================\n// Invoice status constants\n// =============================================================================\n\nexport const InvoiceStatus = {\n Draft: 'draft',\n Finalized: 'finalized',\n Paid: 'paid',\n Void: 'void',\n} as const\n\nexport type InvoiceStatusValue = (typeof InvoiceStatus)[keyof typeof InvoiceStatus]\n\n// =============================================================================\n// Payout method constants\n// =============================================================================\n\nexport const PayoutMethod = {\n BankTransfer: 'bank_transfer',\n MobileMoney: 'mobile_money',\n} as const\n\nexport type PayoutMethodValue = (typeof PayoutMethod)[keyof typeof PayoutMethod]\n\n// =============================================================================\n// Events\n// =============================================================================\n\n/** A single usage event sent to the Monigo ingestion pipeline. */\nexport interface IngestEvent {\n /**\n * The name of the event, e.g. `\"api_call\"` or `\"storage.write\"`.\n * Must match the `event_name` on one or more metrics you have configured.\n */\n event_name: string\n /** The Monigo customer UUID this event belongs to. */\n customer_id: string\n /**\n * A unique key for this event. Re-sending the same key is safe — the server\n * will de-duplicate automatically. Use a UUID or any stable ID you control.\n */\n idempotency_key: string\n /**\n * ISO 8601 timestamp for when the event occurred. Backdated events are\n * accepted within the configured replay window. Defaults to now if omitted.\n */\n timestamp?: string | Date\n /**\n * Arbitrary key-value pairs attached to the event. Use these for dimensions\n * such as `{ endpoint: \"/checkout\", region: \"eu-west-1\" }`.\n */\n properties?: Record<string, unknown>\n}\n\n/** Request body for `POST /v1/ingest`. */\nexport interface IngestRequest {\n events: IngestEvent[]\n}\n\n/** Response from `POST /v1/ingest`. */\nexport interface IngestResponse {\n /** Idempotency keys of events that were successfully ingested. */\n ingested: string[]\n /** Idempotency keys that were skipped because they already existed. */\n duplicates: string[]\n}\n\n/** Request body for `POST /v1/events/replay`. */\nexport interface StartReplayRequest {\n /** Start of the replay window (ISO 8601). */\n from: string | Date\n /** End of the replay window (ISO 8601). */\n to: string | Date\n /** Optional event name to replay. Omit to replay all event types. */\n event_name?: string\n}\n\n/** Tracks the progress of an asynchronous event replay job. */\nexport interface EventReplayJob {\n id: string\n org_id: string\n initiated_by: string\n /** `pending` | `processing` | `completed` | `failed` */\n status: string\n from_timestamp: string\n to_timestamp: string\n event_name: string | null\n is_test: boolean\n events_total: number\n events_replayed: number\n error_message: string | null\n started_at: string | null\n completed_at: string | null\n created_at: string\n updated_at: string\n}\n\n// =============================================================================\n// Customers\n// =============================================================================\n\n/** An end-customer record in your Monigo organisation. */\nexport interface Customer {\n id: string\n org_id: string\n /** The ID for this customer in your own system. */\n external_id: string\n name: string\n email: string\n /** Phone number in E.164 international format (e.g. +2348012345678). */\n phone: string\n /** Arbitrary JSON metadata. */\n metadata: Record<string, unknown> | null\n created_at: string\n updated_at: string\n}\n\nexport interface CreateCustomerRequest {\n /** Your internal ID for this customer. */\n external_id: string\n name: string\n email?: string\n /** Phone number in E.164 international format (e.g. +2348012345678). Optional. */\n phone?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface UpdateCustomerRequest {\n name?: string\n email?: string\n /** Phone number in E.164 international format (e.g. +2348012345678). Optional. */\n phone?: string\n metadata?: Record<string, unknown>\n}\n\nexport interface ListCustomersResponse {\n customers: Customer[]\n count: number\n}\n\n// =============================================================================\n// Metrics\n// =============================================================================\n\n/** Defines what usage is counted and how. */\nexport interface Metric {\n id: string\n org_id: string\n name: string\n /** The `event_name` value that this metric tracks. */\n event_name: string\n /** How events are aggregated. Use `Aggregation` constants. */\n aggregation: AggregationType\n /** For sum/max/min/average: the Properties key whose value is used. */\n aggregation_property?: string\n description?: string\n created_at: string\n updated_at: string\n}\n\nexport interface CreateMetricRequest {\n /** Human-readable label, e.g. `\"API Calls\"`. */\n name: string\n /** The `event_name` value to track. */\n event_name: string\n /** How events are aggregated. Use `Aggregation` constants. */\n aggregation: AggregationType\n description?: string\n /** Required for sum/max/min/average aggregations. */\n aggregation_property?: string\n}\n\nexport interface UpdateMetricRequest {\n name?: string\n event_name?: string\n aggregation?: AggregationType\n description?: string\n aggregation_property?: string\n}\n\nexport interface ListMetricsResponse {\n metrics: Metric[]\n count: number\n}\n\n// =============================================================================\n// Plans & Prices\n// =============================================================================\n\n/**\n * One price step in a tiered/volume/weighted_tiered pricing model.\n * Set `up_to` to `null` for the final (infinite) tier.\n */\nexport interface PriceTier {\n up_to: number | null\n /** Price per unit in this tier as a decimal string, e.g. `\"0.50\"`. */\n unit_amount: string\n}\n\n/** Describes a price to attach when creating a plan. */\nexport interface CreatePriceRequest {\n /** UUID of the metric this price is based on. */\n metric_id: string\n /** Pricing model. Use `PricingModel` constants. */\n model: PricingModelType\n /** Flat price per unit as a decimal string (used for flat/overage/package models). */\n unit_price?: string\n /** Price tiers for tiered/volume/weighted_tiered models. */\n tiers?: PriceTier[]\n}\n\n/** Describes an updated price. Include `id` to update an existing price; omit to add a new one. */\nexport interface UpdatePriceRequest {\n id?: string\n metric_id?: string\n model?: PricingModelType\n unit_price?: string\n tiers?: PriceTier[]\n}\n\n/** A pricing rule attached to a plan. */\nexport interface Price {\n id: string\n plan_id: string\n metric_id: string\n model: PricingModelType\n unit_price: string\n tiers: PriceTier[] | null\n created_at: string\n updated_at: string\n}\n\n/** A billing plan that defines pricing for one or more metrics. */\nexport interface Plan {\n id: string\n org_id: string\n name: string\n description?: string\n /** ISO 4217 currency code, e.g. `\"NGN\"`. */\n currency: string\n /** Use `PlanType` constants. */\n plan_type: PlanTypeValue\n /** Use `BillingPeriod` constants. */\n billing_period: BillingPeriodValue\n trial_period_days: number\n prices?: Price[]\n created_at: string\n updated_at: string\n}\n\nexport interface CreatePlanRequest {\n name: string\n description?: string\n /** ISO 4217 currency code. Defaults to `\"NGN\"`. */\n currency?: string\n /** Use `PlanType` constants. Defaults to `\"collection\"`. */\n plan_type?: PlanTypeValue\n /** Use `BillingPeriod` constants. Defaults to `\"monthly\"`. */\n billing_period?: BillingPeriodValue\n /** Trial period in days. Set to `0` for no trial. */\n trial_period_days?: number\n prices?: CreatePriceRequest[]\n}\n\nexport interface UpdatePlanRequest {\n name?: string\n description?: string\n currency?: string\n plan_type?: PlanTypeValue\n billing_period?: BillingPeriodValue\n prices?: UpdatePriceRequest[]\n}\n\nexport interface ListPlansResponse {\n plans: Plan[]\n count: number\n}\n\n// =============================================================================\n// Subscriptions\n// =============================================================================\n\n/** Links a customer to a billing plan. */\nexport interface Subscription {\n id: string\n org_id: string\n customer_id: string\n plan_id: string\n /** Use `SubscriptionStatus` constants. */\n status: SubscriptionStatusValue\n current_period_start: string\n current_period_end: string\n trial_ends_at: string | null\n created_at: string\n updated_at: string\n}\n\nexport interface CreateSubscriptionRequest {\n /** UUID of the customer to subscribe. */\n customer_id: string\n /** UUID of the plan to subscribe the customer to. */\n plan_id: string\n}\n\nexport interface ListSubscriptionsParams {\n /** Filter to a specific customer UUID. */\n customer_id?: string\n /** Filter to a specific plan UUID. */\n plan_id?: string\n /** Filter by status. Use `SubscriptionStatus` constants. */\n status?: SubscriptionStatusValue\n}\n\nexport interface ListSubscriptionsResponse {\n subscriptions: Subscription[]\n count: number\n}\n\n// =============================================================================\n// Payout accounts\n// =============================================================================\n\n/** A bank or mobile-money account that a customer can be paid to. */\nexport interface PayoutAccount {\n id: string\n customer_id: string\n org_id: string\n account_name: string\n bank_name?: string\n bank_code?: string\n account_number?: string\n mobile_money_number?: string\n /** Use `PayoutMethod` constants. */\n payout_method: PayoutMethodValue\n currency: string\n is_default: boolean\n metadata: Record<string, unknown> | null\n created_at: string\n updated_at: string\n}\n\nexport interface CreatePayoutAccountRequest {\n account_name: string\n /** Use `PayoutMethod` constants. */\n payout_method: PayoutMethodValue\n bank_name?: string\n bank_code?: string\n account_number?: string\n mobile_money_number?: string\n currency?: string\n is_default?: boolean\n metadata?: Record<string, unknown>\n}\n\nexport interface UpdatePayoutAccountRequest {\n account_name?: string\n payout_method?: PayoutMethodValue\n bank_name?: string\n account_number?: string\n currency?: string\n is_default?: boolean\n metadata?: Record<string, unknown>\n}\n\nexport interface ListPayoutAccountsResponse {\n payout_accounts: PayoutAccount[]\n count: number\n}\n\n// =============================================================================\n// Invoices\n// =============================================================================\n\n/** One line item on an invoice. */\nexport interface InvoiceLineItem {\n id: string\n invoice_id: string\n metric_id: string\n price_id?: string\n description: string\n quantity: string\n unit_price: string\n /** Amount for this line as a decimal string. */\n amount: string\n created_at: string\n}\n\n/**\n * A billing invoice.\n * All monetary values (`subtotal`, `vat_amount`, `total`) are decimal strings\n * to avoid floating-point precision issues.\n */\nexport interface Invoice {\n id: string\n org_id: string\n customer_id: string\n subscription_id: string\n /** Use `InvoiceStatus` constants. */\n status: InvoiceStatusValue\n currency: string\n subtotal: string\n vat_enabled: boolean\n vat_rate?: string\n vat_amount?: string\n total: string\n period_start: string\n period_end: string\n finalized_at: string | null\n paid_at: string | null\n provider_invoice_id?: string\n line_items?: InvoiceLineItem[]\n created_at: string\n updated_at: string\n}\n\nexport interface ListInvoicesParams {\n /** Filter by status. Use `InvoiceStatus` constants. */\n status?: InvoiceStatusValue\n /** Filter to a specific customer UUID. */\n customer_id?: string\n}\n\nexport interface ListInvoicesResponse {\n invoices: Invoice[]\n count: number\n}\n\n// =============================================================================\n// Usage\n// =============================================================================\n\n/** One aggregated usage record for a (customer, metric, period) tuple. */\nexport interface UsageRollup {\n id: string\n org_id: string\n customer_id: string\n metric_id: string\n period_start: string\n period_end: string\n aggregation: AggregationType\n /** Aggregated value (count, sum, max, etc.). */\n value: number\n event_count: number\n last_event_at: string | null\n is_test: boolean\n created_at: string\n updated_at: string\n}\n\nexport interface UsageQueryParams {\n /** Filter rollups to a specific customer UUID. */\n customer_id?: string\n /** Filter rollups to a specific metric UUID. */\n metric_id?: string\n /**\n * Lower bound for `period_start` (ISO 8601).\n * Defaults to the start of the current billing period.\n */\n from?: string | Date\n /**\n * Exclusive upper bound for `period_start` (ISO 8601).\n * Defaults to the end of the current billing period.\n */\n to?: string | Date\n}\n\nexport interface UsageQueryResult {\n rollups: UsageRollup[]\n count: number\n}\n"],"names":[],"mappings":"AAcO,MAAM,uBAAuB,MAAM;AAAA,EAQxC,YACE,YACA,SACA,SACA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,UAAU;AACf,SAAK,UAAU;AAEf,UAAM,UAAW,MACf,mBACF;AACA,cAAU,MAAM,cAAc;AAAA,EAChC;AAAA;AAAA;AAAA;AAAA,EAMA,IAAI,aAAsB;AACxB,WAAO,KAAK,eAAe;AAAA,EAC7B;AAAA,EAEA,IAAI,iBAA0B;AAC5B,WAAO,KAAK,eAAe;AAAA,EAC7B;AAAA,EAEA,IAAI,cAAuB;AACzB,WAAO,KAAK,eAAe;AAAA,EAC7B;AAAA,EAEA,IAAI,gBAAyB;AAC3B,WAAO,KAAK,eAAe;AAAA,EAC7B;AAAA,EAEA,IAAI,aAAsB;AACxB,WAAO,KAAK,eAAe;AAAA,EAC7B;AAAA,EAEA,IAAI,kBAA2B;AAC7B,WAAO,KAAK,eAAe;AAAA,EAC7B;AAAA,EAEA,IAAI,gBAAyB;AAC3B,WAAO,KAAK,cAAc;AAAA,EAC5B;AAAA;AAAA;AAAA;AAAA,EAMA,OAAO,WAAW,KAAqC;AACrD,WAAO,eAAe,kBAAkB,IAAI,eAAe;AAAA,EAC7D;AAAA,EAEA,OAAO,eAAe,KAAqC;AACzD,WAAO,eAAe,kBAAkB,IAAI,eAAe;AAAA,EAC7D;AAAA,EAEA,OAAO,YAAY,KAAqC;AACtD,WAAO,eAAe,kBAAkB,IAAI,eAAe;AAAA,EAC7D;AAAA,EAEA,OAAO,cAAc,KAAqC;AACxD,WAAO,eAAe,kBAAkB,IAAI,eAAe;AAAA,EAC7D;AAAA,EAEA,OAAO,WAAW,K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,UAAI,eAAe,eAAgB,OAAM;AACzC,UAAI,eAAe,SAAS,IAAI,SAAS,cAAc;AACrD,cAAM,IAAI;AAAA,UACR,4BAA4B,GAAG,oBAAoB,KAAK,QAAQ;AAAA,QAAA;AAAA,MAEpE;AACA,YAAM;AAAA,IACR,UAAA;AACE,mBAAa,SAAS;AAAA,IACxB;AAAA,EACF;AAAA;AAAA,EAGA,OAAO,YAAY,OAA8B;AAC/C,WAAO,iBAAiB,OAAO,MAAM,YAAA,IAAgB;AAAA,EACvD;AACF;ACpNO,MAAM,cAAc;AAAA,EACzB,OAAO;AAAA,EACP,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,SAAS;AAAA,EACT,QAAQ;AACV;AAQO,MAAM,eAAe;AAAA,EAC1B,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,SAAS;AAAA,EACT,gBAAgB;AAClB;AAQO,MAAM,WAAW;AAAA,EACtB,YAAY;AAAA,EACZ,QAAQ;AACV;AAIO,MAAM,gBAAgB;AAAA,EAC3B,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,WAAW;AAAA,EACX,UAAU;AACZ;AAQO,MAAM,qBAAqB;AAAA,EAChC,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,UAAU;AACZ;AAQO,MAAM,gBAAgB;AAAA,EAC3B,OAAO;AAAA,EACP,WAAW;AAAA,EACX,MAAM;AAAA,EACN,MAAM;AACR;AAQO,MAAM,eAAe;AAAA,EAC1B,cAAc;AAAA,EACd,aAAa;AACf;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@monigo/sdk",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "Official Monigo JavaScript / TypeScript SDK — event ingestion, metering, billing, and usage for browser and Node.js",
5
5
  "keywords": [
6
6
  "monigo",