@monigo/sdk 0.1.7 → 0.1.8
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 +235 -0
- package/dist/monigo.cjs +144 -0
- package/dist/monigo.cjs.map +1 -1
- package/dist/monigo.js +145 -1
- package/dist/monigo.js.map +1 -1
- package/package.json +1 -1
package/dist/monigo.cjs.map
CHANGED
|
@@ -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/resources/portal-tokens.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_unit',\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 type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n PortalToken,\n CreatePortalTokenRequest,\n ListPortalTokensResponse,\n} from '../types.js'\n\n/**\n * Manage customer portal access links.\n *\n * Portal tokens grant an end-customer read-only access to their invoices,\n * payout slips, subscriptions, and payout accounts in the Monigo hosted portal.\n * All operations require a write-scoped API key; the organisation is inferred\n * automatically from the key.\n */\nexport class PortalTokensResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Generate a new portal link for a customer.\n *\n * **Requires `write` scope.**\n *\n * The returned `portal_url` is what you share with your customer — embed it\n * in an email, open it in an iframe, or redirect the browser to it directly.\n *\n * @example\n * ```ts\n * const { portal_url } = await monigo.portalTokens.create({\n * customer_external_id: 'usr_abc123',\n * label: 'March 2026 invoice link',\n * })\n * await sendEmail(customer.email, { portalLink: portal_url })\n * ```\n */\n async create(\n request: CreatePortalTokenRequest,\n options?: MutationOptions,\n ): Promise<PortalToken> {\n const wrapper = await this.client._request<{ token: PortalToken }>(\n 'POST',\n '/v1/portal/tokens',\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.token\n }\n\n /**\n * List all portal tokens for a customer.\n *\n * **Requires `read` scope.**\n *\n * @param customerId - The customer's Monigo UUID or their `external_id`.\n */\n async list(customerId: string): Promise<ListPortalTokensResponse> {\n return this.client._request<ListPortalTokensResponse>(\n 'GET',\n '/v1/portal/tokens',\n { query: { customer_id: customerId } },\n )\n }\n\n /**\n * Immediately revoke a portal token.\n *\n * **Requires `write` scope.**\n *\n * Any customer holding the corresponding URL will receive a 401 on their\n * next request. This action is irreversible.\n *\n * @param tokenId - The UUID of the portal token record (not the raw token string).\n */\n async revoke(tokenId: string, options?: MutationOptions): Promise<void> {\n await this.client._request<void>(\n 'DELETE',\n `/v1/portal/tokens/${tokenId}`,\n { idempotencyKey: options?.idempotencyKey },\n )\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'\nimport { PortalTokensResource } from './resources/portal-tokens.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 /** Manage customer portal access links. Requires `read` / `write` scope. */\n readonly portalTokens: PortalTokensResource\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 this.portalTokens = new PortalTokensResource(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 /** Fixed price per unit. Requires `unit_price`. */\n Flat: 'flat_unit',\n /** Alias for `Flat`. */\n PerUnit: 'per_unit',\n /** Graduated tiers — each unit charged at the rate of the tier it falls into.\n * Requires a `PriceTier[]` in the `tiers` field. */\n Tiered: 'tiered',\n /** Charge per bundle of N units. Partial bundles round up.\n * Requires a `PackageConfig` object in the `tiers` field. */\n Package: 'package',\n /** Flat base fee covers an included quota; per-unit rate beyond it.\n * Requires an `OverageConfig` object in the `tiers` field. */\n Overage: 'overage',\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 step in a `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/**\n * Configuration for the `package` pricing model.\n * Pass this as the `tiers` field when `model` is `PricingModel.Package`.\n */\nexport interface PackageConfig {\n /** Number of units per bundle, e.g. `1000` for \"1 000 SMS per bundle\". */\n package_size: number\n /** Price per complete bundle as a decimal string, e.g. `\"500.000000\"`. */\n package_price: string\n /** If `true`, partial bundles are rounded up to the next whole bundle. */\n round_up_partial_block: boolean\n}\n\n/**\n * Configuration for the `overage` pricing model.\n * Pass this as the `tiers` field when `model` is `PricingModel.Overage`.\n */\nexport interface OverageConfig {\n /** Free quota. Usage at or below this threshold is charged `base_price`. */\n included_units: number\n /** Flat fee for usage up to `included_units` as a decimal string.\n * Set to `\"0.000000\"` when there is no base fee. */\n base_price: string\n /** Per-unit rate applied to every unit above `included_units`,\n * as a decimal string, e.g. `\"1.500000\"`. */\n overage_price: 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.\n * Required for `PricingModel.Flat` / `PricingModel.PerUnit`. */\n unit_price?: string\n /**\n * Model-specific configuration:\n * - `PricingModel.Tiered` → `PriceTier[]`\n * - `PricingModel.Package` → `PackageConfig`\n * - `PricingModel.Overage` → `OverageConfig`\n */\n tiers?: PriceTier[] | PackageConfig | OverageConfig\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[] | PackageConfig | OverageConfig\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\n// =============================================================================\n// Portal tokens\n// =============================================================================\n\n/**\n * A portal token grants an end-customer read-only access to their invoices,\n * payout slips, subscriptions, and payout accounts in the Monigo hosted portal.\n */\nexport interface PortalToken {\n id: string\n org_id: string\n customer_id: string\n /** The opaque 64-character hex token embedded in the portal URL. */\n token: string\n label: string\n /** ISO 8601 expiry timestamp, or `null` for a permanent link. */\n expires_at: string | null\n /** ISO 8601 revocation timestamp, or `null` if still active. */\n revoked_at: string | null\n created_at: string\n updated_at: string\n /** Fully-qualified URL to share with the customer, e.g. `https://app.monigo.co/portal/<token>`. */\n portal_url: string\n}\n\n/** Request body for `portalTokens.create()`. */\nexport interface CreatePortalTokenRequest {\n /**\n * The `external_id` you assigned this customer when you called\n * `customers.create()`.\n */\n customer_external_id: string\n /** Optional human-readable label, e.g. `\"Main portal link\"`. */\n label?: string\n /**\n * Optional RFC 3339 expiry timestamp. Omit to create a permanent link.\n * Example: `\"2027-01-01T00:00:00Z\"`\n */\n expires_at?: string\n}\n\nexport interface ListPortalTokensResponse {\n tokens: PortalToken[]\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;AA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gB,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;ACxNO,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;AAAA,EAE1B,MAAM;AAAA;AAAA,EAEN,SAAS;AAAA;AAAA;AAAA,EAGT,QAAQ;AAAA;AAAA;AAAA,EAGR,SAAS;AAAA;AAAA;AAAA,EAGT,SAAS;AACX;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
|
+
{"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/resources/portal-tokens.ts","../src/resources/wallets.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_unit',\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 type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n PortalToken,\n CreatePortalTokenRequest,\n ListPortalTokensResponse,\n} from '../types.js'\n\n/**\n * Manage customer portal access links.\n *\n * Portal tokens grant an end-customer read-only access to their invoices,\n * payout slips, subscriptions, and payout accounts in the Monigo hosted portal.\n * All operations require a write-scoped API key; the organisation is inferred\n * automatically from the key.\n */\nexport class PortalTokensResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Generate a new portal link for a customer.\n *\n * **Requires `write` scope.**\n *\n * The returned `portal_url` is what you share with your customer — embed it\n * in an email, open it in an iframe, or redirect the browser to it directly.\n *\n * @example\n * ```ts\n * const { portal_url } = await monigo.portalTokens.create({\n * customer_external_id: 'usr_abc123',\n * label: 'March 2026 invoice link',\n * })\n * await sendEmail(customer.email, { portalLink: portal_url })\n * ```\n */\n async create(\n request: CreatePortalTokenRequest,\n options?: MutationOptions,\n ): Promise<PortalToken> {\n const wrapper = await this.client._request<{ token: PortalToken }>(\n 'POST',\n '/v1/portal/tokens',\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.token\n }\n\n /**\n * List all portal tokens for a customer.\n *\n * **Requires `read` scope.**\n *\n * @param customerId - The customer's Monigo UUID or their `external_id`.\n */\n async list(customerId: string): Promise<ListPortalTokensResponse> {\n return this.client._request<ListPortalTokensResponse>(\n 'GET',\n '/v1/portal/tokens',\n { query: { customer_id: customerId } },\n )\n }\n\n /**\n * Immediately revoke a portal token.\n *\n * **Requires `write` scope.**\n *\n * Any customer holding the corresponding URL will receive a 401 on their\n * next request. This action is irreversible.\n *\n * @param tokenId - The UUID of the portal token record (not the raw token string).\n */\n async revoke(tokenId: string, options?: MutationOptions): Promise<void> {\n await this.client._request<void>(\n 'DELETE',\n `/v1/portal/tokens/${tokenId}`,\n { idempotencyKey: options?.idempotencyKey },\n )\n }\n}\n","import type { MonigoClient, MutationOptions } from '../client.js'\nimport type {\n CustomerWallet,\n VirtualAccount,\n GetOrCreateWalletRequest,\n CreditWalletRequest,\n DebitWalletRequest,\n CreateVirtualAccountRequest,\n ListWalletsParams,\n ListTransactionsParams,\n ListWalletsResponse,\n WalletWithVirtualAccountsResponse,\n WalletOperationResponse,\n ListTransactionsResponse,\n ListVirtualAccountsResponse,\n} from '../types.js'\n\n/** Manage customer wallets, balance operations, and virtual accounts. */\nexport class WalletsResource {\n constructor(private readonly client: MonigoClient) {}\n\n /**\n * Get an existing wallet or create a new one for the given customer and currency.\n *\n * **Requires `write` scope.**\n */\n async getOrCreate(\n request: GetOrCreateWalletRequest,\n options?: MutationOptions,\n ): Promise<CustomerWallet> {\n const wrapper = await this.client._request<{ wallet: CustomerWallet }>(\n 'POST',\n '/v1/wallets',\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.wallet\n }\n\n /**\n * List all wallets for an organisation.\n *\n * **Requires `read` scope.**\n */\n async list(params: ListWalletsParams): Promise<ListWalletsResponse> {\n return this.client._request<ListWalletsResponse>('GET', '/v1/wallets', {\n query: { org_id: params.org_id },\n })\n }\n\n /**\n * List all wallets belonging to a specific customer.\n *\n * **Requires `read` scope.**\n */\n async listByCustomer(customerId: string): Promise<ListWalletsResponse> {\n return this.client._request<ListWalletsResponse>(\n 'GET',\n `/v1/customers/${customerId}/wallets`,\n )\n }\n\n /**\n * Fetch a single wallet by UUID, including its virtual accounts.\n *\n * **Requires `read` scope.**\n */\n async get(walletId: string): Promise<WalletWithVirtualAccountsResponse> {\n return this.client._request<WalletWithVirtualAccountsResponse>(\n 'GET',\n `/v1/wallets/${walletId}`,\n )\n }\n\n /**\n * Credit (add funds to) a wallet. Returns the updated wallet and ledger entries.\n *\n * **Requires `write` scope.**\n */\n async credit(\n walletId: string,\n request: CreditWalletRequest,\n options?: MutationOptions,\n ): Promise<WalletOperationResponse> {\n return this.client._request<WalletOperationResponse>(\n 'POST',\n `/v1/wallets/${walletId}/credit`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n }\n\n /**\n * Debit (remove funds from) a wallet. Returns the updated wallet and ledger entries.\n * Throws a 402 error if the wallet has insufficient balance.\n *\n * **Requires `write` scope.**\n */\n async debit(\n walletId: string,\n request: DebitWalletRequest,\n options?: MutationOptions,\n ): Promise<WalletOperationResponse> {\n return this.client._request<WalletOperationResponse>(\n 'POST',\n `/v1/wallets/${walletId}/debit`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n }\n\n /**\n * List paginated ledger entries (transactions) for a wallet.\n *\n * **Requires `read` scope.**\n */\n async listTransactions(\n walletId: string,\n params?: ListTransactionsParams,\n ): Promise<ListTransactionsResponse> {\n return this.client._request<ListTransactionsResponse>(\n 'GET',\n `/v1/wallets/${walletId}/transactions`,\n {\n query: {\n limit: params?.limit?.toString(),\n offset: params?.offset?.toString(),\n },\n },\n )\n }\n\n /**\n * Create a dedicated virtual bank account that automatically funds the wallet on deposit.\n *\n * **Requires `write` scope.**\n */\n async createVirtualAccount(\n walletId: string,\n request: CreateVirtualAccountRequest,\n options?: MutationOptions,\n ): Promise<VirtualAccount> {\n const wrapper = await this.client._request<{ virtual_account: VirtualAccount }>(\n 'POST',\n `/v1/wallets/${walletId}/virtual-accounts`,\n { body: request, idempotencyKey: options?.idempotencyKey },\n )\n return wrapper.virtual_account\n }\n\n /**\n * List all virtual accounts linked to a wallet.\n *\n * **Requires `read` scope.**\n */\n async listVirtualAccounts(walletId: string): Promise<ListVirtualAccountsResponse> {\n return this.client._request<ListVirtualAccountsResponse>(\n 'GET',\n `/v1/wallets/${walletId}/virtual-accounts`,\n )\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'\nimport { PortalTokensResource } from './resources/portal-tokens.js'\nimport { WalletsResource } from './resources/wallets.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 /** Manage customer portal access links. Requires `read` / `write` scope. */\n readonly portalTokens: PortalTokensResource\n /** Manage customer wallets, balance operations, and virtual accounts. Requires `read` / `write` scope. */\n readonly wallets: WalletsResource\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 this.portalTokens = new PortalTokensResource(this)\n this.wallets = new WalletsResource(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 /** Fixed price per unit. Requires `unit_price`. */\n Flat: 'flat_unit',\n /** Alias for `Flat`. */\n PerUnit: 'per_unit',\n /** Graduated tiers — each unit charged at the rate of the tier it falls into.\n * Requires a `PriceTier[]` in the `tiers` field. */\n Tiered: 'tiered',\n /** Charge per bundle of N units. Partial bundles round up.\n * Requires a `PackageConfig` object in the `tiers` field. */\n Package: 'package',\n /** Flat base fee covers an included quota; per-unit rate beyond it.\n * Requires an `OverageConfig` object in the `tiers` field. */\n Overage: 'overage',\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// Wallet constants\n// =============================================================================\n\nexport const WalletEntryType = {\n /** Credit from an external funding source. */\n Deposit: 'deposit',\n /** Debit to an external destination. */\n Withdrawal: 'withdrawal',\n /** Automatic debit for metered usage charges. */\n Usage: 'usage',\n /** Credit reversing a previous charge. */\n Refund: 'refund',\n /** Manual balance correction. */\n Adjustment: 'adjustment',\n} as const\n\nexport type WalletEntryTypeValue = (typeof WalletEntryType)[keyof typeof WalletEntryType]\n\nexport const WalletDirection = {\n /** Reduces the wallet balance. */\n Debit: 'debit',\n /** Increases the wallet balance. */\n Credit: 'credit',\n} as const\n\nexport type WalletDirectionValue = (typeof WalletDirection)[keyof typeof WalletDirection]\n\nexport const VirtualAccountProvider = {\n Paystack: 'paystack',\n Flutterwave: 'flutterwave',\n Monnify: 'monnify',\n} as const\n\nexport type VirtualAccountProviderValue = (typeof VirtualAccountProvider)[keyof typeof VirtualAccountProvider]\n\n// =============================================================================\n// Wallets\n// =============================================================================\n\n/** A prepaid balance belonging to a single customer. All monetary values are decimal strings. */\nexport interface CustomerWallet {\n id: string\n customer_id: string\n org_id: string\n currency: string\n /** Current available balance as a decimal string, e.g. `\"500.000000\"`. */\n balance: string\n /** Balance reserved for pending operations. */\n reserved_balance: string\n created_at: string\n updated_at: string\n}\n\n/** A dedicated virtual bank account that funds a customer wallet. */\nexport interface VirtualAccount {\n id: string\n customer_id: string\n wallet_id: string\n org_id: string\n /** Payment provider. Use `VirtualAccountProvider` constants. */\n provider: VirtualAccountProviderValue\n account_number: string\n account_name: string\n bank_name: string\n bank_code: string\n currency: string\n provider_ref: string\n is_active: boolean\n metadata: Record<string, unknown> | null\n created_at: string\n updated_at: string\n}\n\n/** One side of a double-entry accounting record. */\nexport interface LedgerEntry {\n id: string\n org_id: string\n transaction_id: string\n wallet_id: string | null\n /** `customer_wallet`, `provider`, or `revenue`. */\n account_type: string\n account_id: string\n /** Use `WalletDirection` constants. */\n direction: WalletDirectionValue\n /** Amount as a decimal string. */\n amount: string\n currency: string\n balance_before: string\n balance_after: string\n description: string\n /** Use `WalletEntryType` constants. */\n entry_type: WalletEntryTypeValue\n reference_type: string\n reference_id: string\n idempotency_key: string\n metadata: Record<string, unknown> | null\n created_at: string\n}\n\n/** Request body for `wallets.getOrCreate()`. */\nexport interface GetOrCreateWalletRequest {\n org_id: string\n customer_id: string\n currency: string\n}\n\n/** Request body for `wallets.credit()`. */\nexport interface CreditWalletRequest {\n /** Amount as a decimal string, e.g. `\"100.50\"`. */\n amount: string\n currency: string\n description: string\n /** Use `WalletEntryType` constants. */\n entry_type: WalletEntryTypeValue\n reference_type: string\n reference_id: string\n idempotency_key: string\n /** Optional provider account UUID for the other side of double entry. */\n provider_id?: string\n}\n\n/** Request body for `wallets.debit()`. */\nexport interface DebitWalletRequest {\n /** Amount as a decimal string, e.g. `\"50.25\"`. */\n amount: string\n currency: string\n description: string\n /** Use `WalletEntryType` constants. */\n entry_type: WalletEntryTypeValue\n reference_type: string\n reference_id: string\n idempotency_key: string\n}\n\n/** Request body for `wallets.createVirtualAccount()`. */\nexport interface CreateVirtualAccountRequest {\n /** Use `VirtualAccountProvider` constants. */\n provider: VirtualAccountProviderValue\n currency: string\n}\n\nexport interface ListWalletsParams {\n org_id: string\n}\n\nexport interface ListTransactionsParams {\n /** Number of entries to return (1–100). Defaults to 25. */\n limit?: number\n /** Number of entries to skip. Defaults to 0. */\n offset?: number\n}\n\nexport interface ListWalletsResponse {\n wallets: CustomerWallet[]\n count: number\n}\n\nexport interface WalletWithVirtualAccountsResponse {\n wallet: CustomerWallet\n virtual_accounts: VirtualAccount[]\n}\n\nexport interface WalletOperationResponse {\n wallet: CustomerWallet\n ledger_entries: LedgerEntry[]\n}\n\nexport interface ListTransactionsResponse {\n transactions: LedgerEntry[]\n total: number\n limit: number\n offset: number\n}\n\nexport interface ListVirtualAccountsResponse {\n virtual_accounts: VirtualAccount[]\n count: number\n}\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 step in a `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/**\n * Configuration for the `package` pricing model.\n * Pass this as the `tiers` field when `model` is `PricingModel.Package`.\n */\nexport interface PackageConfig {\n /** Number of units per bundle, e.g. `1000` for \"1 000 SMS per bundle\". */\n package_size: number\n /** Price per complete bundle as a decimal string, e.g. `\"500.000000\"`. */\n package_price: string\n /** If `true`, partial bundles are rounded up to the next whole bundle. */\n round_up_partial_block: boolean\n}\n\n/**\n * Configuration for the `overage` pricing model.\n * Pass this as the `tiers` field when `model` is `PricingModel.Overage`.\n */\nexport interface OverageConfig {\n /** Free quota. Usage at or below this threshold is charged `base_price`. */\n included_units: number\n /** Flat fee for usage up to `included_units` as a decimal string.\n * Set to `\"0.000000\"` when there is no base fee. */\n base_price: string\n /** Per-unit rate applied to every unit above `included_units`,\n * as a decimal string, e.g. `\"1.500000\"`. */\n overage_price: 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.\n * Required for `PricingModel.Flat` / `PricingModel.PerUnit`. */\n unit_price?: string\n /**\n * Model-specific configuration:\n * - `PricingModel.Tiered` → `PriceTier[]`\n * - `PricingModel.Package` → `PackageConfig`\n * - `PricingModel.Overage` → `OverageConfig`\n */\n tiers?: PriceTier[] | PackageConfig | OverageConfig\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[] | PackageConfig | OverageConfig\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\n// =============================================================================\n// Portal tokens\n// =============================================================================\n\n/**\n * A portal token grants an end-customer read-only access to their invoices,\n * payout slips, subscriptions, and payout accounts in the Monigo hosted portal.\n */\nexport interface PortalToken {\n id: string\n org_id: string\n customer_id: string\n /** The opaque 64-character hex token embedded in the portal URL. */\n token: string\n label: string\n /** ISO 8601 expiry timestamp, or `null` for a permanent link. */\n expires_at: string | null\n /** ISO 8601 revocation timestamp, or `null` if still active. */\n revoked_at: string | null\n created_at: string\n updated_at: string\n /** Fully-qualified URL to share with the customer, e.g. `https://app.monigo.co/portal/<token>`. */\n portal_url: string\n}\n\n/** Request body for `portalTokens.create()`. */\nexport interface CreatePortalTokenRequest {\n /**\n * The `external_id` you assigned this customer when you called\n * `customers.create()`.\n */\n customer_external_id: string\n /** Optional human-readable label, e.g. `\"Main portal link\"`. */\n label?: string\n /**\n * Optional RFC 3339 expiry timestamp. Omit to create a permanent link.\n * Example: `\"2027-01-01T00:00:00Z\"`\n */\n expires_at?: string\n}\n\nexport interface ListPortalTokensResponse {\n tokens: PortalToken[]\n count: number\n}\n"],"names":[],"mappings":";;AAcO,MAAM,uBAAuB,MAAM;AAAA,EAQ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,kBAAkB;AAAA;AAAA,EAE7B,OAAO;AAAA;AAAA,EAEP,QAAQ;AACV;AAIO,MAAM,yBAAyB;AAAA,EACpC,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AACX;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/dist/monigo.js
CHANGED
|
@@ -722,6 +722,122 @@ class PortalTokensResource {
|
|
|
722
722
|
);
|
|
723
723
|
}
|
|
724
724
|
}
|
|
725
|
+
class WalletsResource {
|
|
726
|
+
constructor(client) {
|
|
727
|
+
this.client = client;
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* Get an existing wallet or create a new one for the given customer and currency.
|
|
731
|
+
*
|
|
732
|
+
* **Requires `write` scope.**
|
|
733
|
+
*/
|
|
734
|
+
async getOrCreate(request, options) {
|
|
735
|
+
const wrapper = await this.client._request(
|
|
736
|
+
"POST",
|
|
737
|
+
"/v1/wallets",
|
|
738
|
+
{ body: request, idempotencyKey: options?.idempotencyKey }
|
|
739
|
+
);
|
|
740
|
+
return wrapper.wallet;
|
|
741
|
+
}
|
|
742
|
+
/**
|
|
743
|
+
* List all wallets for an organisation.
|
|
744
|
+
*
|
|
745
|
+
* **Requires `read` scope.**
|
|
746
|
+
*/
|
|
747
|
+
async list(params) {
|
|
748
|
+
return this.client._request("GET", "/v1/wallets", {
|
|
749
|
+
query: { org_id: params.org_id }
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
/**
|
|
753
|
+
* List all wallets belonging to a specific customer.
|
|
754
|
+
*
|
|
755
|
+
* **Requires `read` scope.**
|
|
756
|
+
*/
|
|
757
|
+
async listByCustomer(customerId) {
|
|
758
|
+
return this.client._request(
|
|
759
|
+
"GET",
|
|
760
|
+
`/v1/customers/${customerId}/wallets`
|
|
761
|
+
);
|
|
762
|
+
}
|
|
763
|
+
/**
|
|
764
|
+
* Fetch a single wallet by UUID, including its virtual accounts.
|
|
765
|
+
*
|
|
766
|
+
* **Requires `read` scope.**
|
|
767
|
+
*/
|
|
768
|
+
async get(walletId) {
|
|
769
|
+
return this.client._request(
|
|
770
|
+
"GET",
|
|
771
|
+
`/v1/wallets/${walletId}`
|
|
772
|
+
);
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* Credit (add funds to) a wallet. Returns the updated wallet and ledger entries.
|
|
776
|
+
*
|
|
777
|
+
* **Requires `write` scope.**
|
|
778
|
+
*/
|
|
779
|
+
async credit(walletId, request, options) {
|
|
780
|
+
return this.client._request(
|
|
781
|
+
"POST",
|
|
782
|
+
`/v1/wallets/${walletId}/credit`,
|
|
783
|
+
{ body: request, idempotencyKey: options?.idempotencyKey }
|
|
784
|
+
);
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* Debit (remove funds from) a wallet. Returns the updated wallet and ledger entries.
|
|
788
|
+
* Throws a 402 error if the wallet has insufficient balance.
|
|
789
|
+
*
|
|
790
|
+
* **Requires `write` scope.**
|
|
791
|
+
*/
|
|
792
|
+
async debit(walletId, request, options) {
|
|
793
|
+
return this.client._request(
|
|
794
|
+
"POST",
|
|
795
|
+
`/v1/wallets/${walletId}/debit`,
|
|
796
|
+
{ body: request, idempotencyKey: options?.idempotencyKey }
|
|
797
|
+
);
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* List paginated ledger entries (transactions) for a wallet.
|
|
801
|
+
*
|
|
802
|
+
* **Requires `read` scope.**
|
|
803
|
+
*/
|
|
804
|
+
async listTransactions(walletId, params) {
|
|
805
|
+
return this.client._request(
|
|
806
|
+
"GET",
|
|
807
|
+
`/v1/wallets/${walletId}/transactions`,
|
|
808
|
+
{
|
|
809
|
+
query: {
|
|
810
|
+
limit: params?.limit?.toString(),
|
|
811
|
+
offset: params?.offset?.toString()
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
);
|
|
815
|
+
}
|
|
816
|
+
/**
|
|
817
|
+
* Create a dedicated virtual bank account that automatically funds the wallet on deposit.
|
|
818
|
+
*
|
|
819
|
+
* **Requires `write` scope.**
|
|
820
|
+
*/
|
|
821
|
+
async createVirtualAccount(walletId, request, options) {
|
|
822
|
+
const wrapper = await this.client._request(
|
|
823
|
+
"POST",
|
|
824
|
+
`/v1/wallets/${walletId}/virtual-accounts`,
|
|
825
|
+
{ body: request, idempotencyKey: options?.idempotencyKey }
|
|
826
|
+
);
|
|
827
|
+
return wrapper.virtual_account;
|
|
828
|
+
}
|
|
829
|
+
/**
|
|
830
|
+
* List all virtual accounts linked to a wallet.
|
|
831
|
+
*
|
|
832
|
+
* **Requires `read` scope.**
|
|
833
|
+
*/
|
|
834
|
+
async listVirtualAccounts(walletId) {
|
|
835
|
+
return this.client._request(
|
|
836
|
+
"GET",
|
|
837
|
+
`/v1/wallets/${walletId}/virtual-accounts`
|
|
838
|
+
);
|
|
839
|
+
}
|
|
840
|
+
}
|
|
725
841
|
const DEFAULT_BASE_URL = "https://api.monigo.co";
|
|
726
842
|
const DEFAULT_TIMEOUT_MS = 3e4;
|
|
727
843
|
class MonigoClient {
|
|
@@ -748,6 +864,7 @@ class MonigoClient {
|
|
|
748
864
|
this.invoices = new InvoicesResource(this);
|
|
749
865
|
this.usage = new UsageResource(this);
|
|
750
866
|
this.portalTokens = new PortalTokensResource(this);
|
|
867
|
+
this.wallets = new WalletsResource(this);
|
|
751
868
|
}
|
|
752
869
|
/**
|
|
753
870
|
* Execute an authenticated HTTP request against the Monigo API.
|
|
@@ -861,6 +978,29 @@ const PayoutMethod = {
|
|
|
861
978
|
BankTransfer: "bank_transfer",
|
|
862
979
|
MobileMoney: "mobile_money"
|
|
863
980
|
};
|
|
981
|
+
const WalletEntryType = {
|
|
982
|
+
/** Credit from an external funding source. */
|
|
983
|
+
Deposit: "deposit",
|
|
984
|
+
/** Debit to an external destination. */
|
|
985
|
+
Withdrawal: "withdrawal",
|
|
986
|
+
/** Automatic debit for metered usage charges. */
|
|
987
|
+
Usage: "usage",
|
|
988
|
+
/** Credit reversing a previous charge. */
|
|
989
|
+
Refund: "refund",
|
|
990
|
+
/** Manual balance correction. */
|
|
991
|
+
Adjustment: "adjustment"
|
|
992
|
+
};
|
|
993
|
+
const WalletDirection = {
|
|
994
|
+
/** Reduces the wallet balance. */
|
|
995
|
+
Debit: "debit",
|
|
996
|
+
/** Increases the wallet balance. */
|
|
997
|
+
Credit: "credit"
|
|
998
|
+
};
|
|
999
|
+
const VirtualAccountProvider = {
|
|
1000
|
+
Paystack: "paystack",
|
|
1001
|
+
Flutterwave: "flutterwave",
|
|
1002
|
+
Monnify: "monnify"
|
|
1003
|
+
};
|
|
864
1004
|
export {
|
|
865
1005
|
Aggregation,
|
|
866
1006
|
BillingPeriod,
|
|
@@ -879,6 +1019,10 @@ export {
|
|
|
879
1019
|
PricingModel,
|
|
880
1020
|
SubscriptionStatus,
|
|
881
1021
|
SubscriptionsResource,
|
|
882
|
-
UsageResource
|
|
1022
|
+
UsageResource,
|
|
1023
|
+
VirtualAccountProvider,
|
|
1024
|
+
WalletDirection,
|
|
1025
|
+
WalletEntryType,
|
|
1026
|
+
WalletsResource
|
|
883
1027
|
};
|
|
884
1028
|
//# sourceMappingURL=monigo.js.map
|