import {z} from 'zod' export type ULID = string; export type Labels = {[key: string]: string}; export type CurrencyCode = string; export type BillingCurrencyCodeCustom = string; export type BillingPriceTier = {up_to_amount?: string | undefined, flat_price?: {type: 'flat', amount: string} | undefined, unit_price?: {type: 'unit', amount: string} | undefined}; export type CreateChargeRequest = {name: string, description?: string | undefined, labels?: Labels | undefined, type: 'flat_fee', currency: CurrencyCode | BillingCurrencyCodeCustom, cost_basis?: ({type: 'dynamic', fiat_currency: string} | {type: 'pinned', fiat_currency: string, cost_basis_id: string} | {type: 'manual', fiat_currency?: string | undefined, rate: string}) | undefined, invoice_at: string, service_period: {from: string, to: string}, unique_reference_id?: string | undefined, settlement_mode: 'credit_then_invoice' | 'credit_only', tax_config?: ({behavior?: ('inclusive' | 'exclusive') | undefined, stripe?: {code: string} | undefined, external_invoicing?: {code: string} | undefined, tax_code_id?: string | undefined, tax_code?: {id: ULID} | undefined}) | undefined, payment_term: 'in_advance' | 'in_arrears', discounts?: ({percentage?: number | undefined}) | undefined, proration_configuration: {mode: 'no_proration' | 'prorate_prices'}, amount_before_proration: {amount: string, currency: CurrencyCode | BillingCurrencyCodeCustom}, feature?: {id: ULID} | undefined, full_service_period?: {from: string, to: string} | undefined, billing_period?: {from: string, to: string} | undefined} | {name: string, description?: string | undefined, labels?: Labels | undefined, type: 'usage_based', currency: CurrencyCode | BillingCurrencyCodeCustom, cost_basis?: ({type: 'dynamic', fiat_currency: string} | {type: 'pinned', fiat_currency: string, cost_basis_id: string} | {type: 'manual', fiat_currency?: string | undefined, rate: string}) | undefined, invoice_at: string, service_period: {from: string, to: string}, unique_reference_id?: string | undefined, settlement_mode: 'credit_then_invoice' | 'credit_only', tax_config?: ({behavior?: ('inclusive' | 'exclusive') | undefined, stripe?: {code: string} | undefined, external_invoicing?: {code: string} | undefined, tax_code_id?: string | undefined, tax_code?: {id: ULID} | undefined}) | undefined, discounts?: ({percentage?: number | undefined, usage?: string | undefined}) | undefined, price: {type: 'unit', amount: string} | {type: 'graduated', tiers: Array} | {type: 'volume', tiers: Array}, commitments?: ({minimum_amount?: string | undefined, maximum_amount?: string | undefined}) | undefined, unit_config?: ({operation: 'divide' | 'multiply', conversion_factor: string, rounding?: ('ceiling' | 'floor' | 'half_up' | 'none') | undefined, precision?: number | undefined, display_unit?: string | undefined}) | undefined, feature: {id: ULID}, full_service_period?: {from: string, to: string} | undefined, billing_period?: {from: string, to: string} | undefined}; export type CreateApiV3OpenmeterCustomersCustomerIdChargesArgs = {customerId: ULID, body: CreateChargeRequest}; export type CreateApiV3OpenmeterCustomersCustomerIdChargesOptions = {baseUrl?: string | undefined, personalAccessToken?: string | undefined, fetch?: typeof fetch | undefined}; export const labels = z.record(z.string(), z.string().min(1).max(63)); export const externalResourceKey = z.string().min(1).max(256); export const usageAttributionSubjectKey = z.string().min(1); export const billingCustomer = z.object({id: z.string(), name: z.string().min(1).max(256), description: z.string().max(1024).optional(), labels: labels.optional(), created_at: z.string(), updated_at: z.string(), deleted_at: z.string().optional(), key: externalResourceKey, usage_attribution: z.object({subject_keys: z.array(usageAttributionSubjectKey)}).optional(), primary_email: z.string().optional(), currency: z.string().min(3).max(3).optional(), billing_address: z.object({country: z.string().min(2).max(2).optional(), postal_code: z.string().optional(), state: z.string().optional(), city: z.string().optional(), line1: z.string().optional(), line2: z.string().optional(), phone_number: z.string().optional()}).optional()}); export const uLID = z.string(); export const customerReference = z.object({id: uLID}); export const billingSubscriptionCostBasisPin = z.object({custom_currency_id: z.string(), invoice_currency: z.string().min(3).max(3), cost_basis_id: z.string()}); export const resourceKey = z.string().min(1).max(64); export const currencyCode = z.string().min(3).max(3); export const billingCurrencyCodeCustom = z.string().min(4).max(24); export const billingPriceTier = z.object({up_to_amount: z.string().optional(), flat_price: z.object({type: z.literal("flat"), amount: z.string()}).optional(), unit_price: z.object({type: z.literal("unit"), amount: z.string()}).optional()}); export const billingSubscriptionItem = z.object({id: z.string(), active_from: z.string(), active_to: z.string().optional(), rate_card: z.object({name: z.string().min(1).max(256), description: z.string().max(1024).optional(), labels: labels.optional(), key: resourceKey, feature: z.object({id: uLID}).optional(), currency: z.union([currencyCode, billingCurrencyCodeCustom]).optional(), billing_cadence: z.string().optional(), price: z.discriminatedUnion("type", [z.object({type: z.literal("free")}), z.object({type: z.literal("flat"), amount: z.string()}), z.object({type: z.literal("unit"), amount: z.string()}), z.object({type: z.literal("graduated"), tiers: z.array(billingPriceTier)}), z.object({type: z.literal("volume"), tiers: z.array(billingPriceTier)})]), unit_config: z.object({operation: z.enum(["divide", "multiply"]), conversion_factor: z.string(), rounding: z.enum(["ceiling", "floor", "half_up", "none"]).optional(), precision: z.number().int().optional(), display_unit: z.string().optional()}).optional(), payment_term: z.enum(["in_advance", "in_arrears"]).optional(), commitments: z.object({minimum_amount: z.string().optional(), maximum_amount: z.string().optional()}).optional(), discounts: z.object({percentage: z.number().gte(0).lte(100).optional(), usage: z.string().optional()}).optional(), tax_config: z.object({behavior: z.enum(["inclusive", "exclusive"]).optional(), code: z.object({id: uLID}).optional()}).optional(), entitlement: z.discriminatedUnion("type", [z.object({type: z.literal("metered"), is_soft_limit: z.boolean().optional(), limit: z.number().gte(0).optional(), usage_period: z.string().optional()}), z.object({type: z.literal("static"), config: z.unknown()}), z.object({type: z.literal("boolean")})]).optional()})}); export const billingSubscriptionPhase = z.object({id: z.string(), name: z.string().min(1).max(256), description: z.string().max(1024).optional(), labels: labels.optional(), created_at: z.string(), updated_at: z.string(), deleted_at: z.string().optional(), key: resourceKey, active_from: z.string(), active_to: z.string().optional(), items: z.array(billingSubscriptionItem)}); export const billingSubscription = z.object({id: z.string(), labels: labels.optional(), created_at: z.string(), updated_at: z.string(), deleted_at: z.string().optional(), name: z.string().min(1).max(256), description: z.string().max(1024).optional(), active_from: z.string(), active_to: z.string().optional(), customer_id: z.string(), plan_id: z.string().optional(), plan: z.object({id: z.string(), key: z.string().min(1).max(64), version: z.number().int().gte(1)}).optional(), invoice_currency: z.string().min(3).max(3), cost_basis_mode: z.enum(["dynamic", "pinned"]), cost_basis_pins: z.array(billingSubscriptionCostBasisPin), billing_cadence: z.string(), pro_rating_config: z.object({enabled: z.boolean(), mode: z.enum(["no_proration", "prorate_prices"])}).optional(), billing_anchor: z.string(), status: z.enum(["active", "inactive", "canceled", "scheduled"]), settlement_mode: z.enum(["credit_then_invoice", "credit_only"]).optional(), current_period: z.object({from: z.string(), to: z.string()}).optional(), phases: z.array(billingSubscriptionPhase)}); export const billingSubscriptionReference = z.object({id: z.string(), name: z.string().optional(), phase: z.object({id: z.string(), item: z.object({id: z.string()})})}); export const billingValidationIssue = z.object({code: z.string(), message: z.string(), attributes: z.record(z.string(), z.unknown()).optional(), severity: z.enum(["critical", "warning"]), field: z.string().optional(), component: z.string().optional()}); export const billingChargeRealizationInvoice = z.object({id: z.string(), description: z.string().max(1024).optional(), labels: labels.optional(), created_at: z.string(), updated_at: z.string(), deleted_at: z.string().optional(), number: z.string().min(1).max(256), currency: z.string().min(3).max(3), supplier: z.object({name: z.string().optional(), tax_id: z.object({code: z.string().min(1).max(32).optional()}).optional(), addresses: z.object({billing_address: z.object({country: z.string().min(2).max(2).optional(), postal_code: z.string().optional(), state: z.string().optional(), city: z.string().optional(), line1: z.string().optional(), line2: z.string().optional(), phone_number: z.string().optional()})}).optional(), id: z.string().optional()}), totals: z.object({amount: z.string(), taxes_total: z.string(), taxes_inclusive_total: z.string(), taxes_exclusive_total: z.string(), charges_total: z.string(), discounts_total: z.string(), credits_total: z.string(), total: z.string()}), service_period: z.object({from: z.string(), to: z.string()}), validation_issues: z.array(billingValidationIssue).optional(), external_references: z.object({invoicing_id: z.string().optional(), payment_id: z.string().optional()}).optional(), type: z.literal("standard"), status: z.enum(["draft", "issuing", "issued", "payment_processing", "overdue", "paid", "uncollectible", "voided"]), status_details: z.object({immutable: z.boolean(), failed: z.boolean(), extended_status: z.string(), available_actions: z.object({advance: z.object({resulting_state: z.string()}).optional(), approve: z.object({resulting_state: z.string()}).optional(), delete: z.object({resulting_state: z.string()}).optional(), retry: z.object({resulting_state: z.string()}).optional(), snapshot_quantities: z.object({resulting_state: z.string()}).optional()})}), issued_at: z.string().optional(), draft_until: z.string().optional(), quantity_snapshotted_at: z.string().optional(), collection_at: z.string().optional(), due_at: z.string().optional(), sent_to_customer_at: z.string().optional(), workflow: z.object({apps: z.object({tax: z.object({id: z.string()}), invoicing: z.object({id: z.string()}), payment: z.object({id: z.string()})}).optional(), source_billing_profile: z.object({id: z.string()}), workflow: z.object({invoicing: z.object({auto_advance: z.boolean().optional(), draft_period: z.string().optional(), due_after: z.string().optional()}).optional(), payment: z.discriminatedUnion("collection_method", [z.object({collection_method: z.literal("charge_automatically")}), z.object({collection_method: z.literal("send_invoice"), due_after: z.string().optional()})]).optional()})})}); export const chargeRealizationInvoiceReference = z.object({id: uLID}); export const billingChargeRealizationDetailedLineCreditApplied = z.object({amount: z.string(), description: z.string().optional(), credit_realization_id: z.string()}); export const billingChargeRealizationAmountDiscount = z.object({amount: z.string(), reason: z.string(), description: z.string().optional(), rounding_amount: z.string().optional(), child_unique_reference_id: z.string()}); export const billingChargeRealizationDetailedLine = z.discriminatedUnion("type", [z.object({id: z.string(), created_at: z.string(), updated_at: z.string(), deleted_at: z.string().optional(), type: z.literal("flat_fee"), service_period: z.object({from: z.string(), to: z.string()}), totals: z.object({amount: z.string(), taxes_total: z.string(), taxes_inclusive_total: z.string(), taxes_exclusive_total: z.string(), charges_total: z.string(), discounts_total: z.string(), credits_total: z.string(), total: z.string()}), category: z.enum(["regular", "commitment"]), credits_applied: z.array(billingChargeRealizationDetailedLineCreditApplied).optional(), unit_price: z.string(), amount_discounts: z.array(billingChargeRealizationAmountDiscount)}), z.object({id: z.string(), created_at: z.string(), updated_at: z.string(), deleted_at: z.string().optional(), type: z.literal("usage_based"), service_period: z.object({from: z.string(), to: z.string()}), totals: z.object({amount: z.string(), taxes_total: z.string(), taxes_inclusive_total: z.string(), taxes_exclusive_total: z.string(), charges_total: z.string(), discounts_total: z.string(), credits_total: z.string(), total: z.string()}), category: z.enum(["regular", "commitment"]), credits_applied: z.array(billingChargeRealizationDetailedLineCreditApplied).optional(), unit_price: z.string(), amount_discounts: z.array(billingChargeRealizationAmountDiscount), quantity: z.string(), corrects_run_id: z.string().optional()})]); export const billingChargeRealization = z.object({id: z.string().optional(), line_id: z.string().optional(), invoice: z.union([billingChargeRealizationInvoice, chargeRealizationInvoiceReference]).optional(), type: z.enum(["final_realization", "partial_invoice", "outstanding", "voided"]), service_period: z.object({from: z.string(), to: z.string()}), usage: z.string().optional(), payment: z.object({status: z.enum(["authorized", "settled"])}).optional(), totals: z.object({amount: z.string(), taxes_total: z.string(), taxes_inclusive_total: z.string(), taxes_exclusive_total: z.string(), charges_total: z.string(), discounts_total: z.string(), credits_total: z.string(), total: z.string()}).optional(), detailed_lines: z.array(billingChargeRealizationDetailedLine).optional()}); export const queryFilterString: z.ZodType = z.object({eq: z.string().optional(), neq: z.string().optional(), in: z.array(z.string()).optional(), nin: z.array(z.string()).optional(), contains: z.string().optional(), ncontains: z.string().optional(), and: z.array(z.lazy(() => queryFilterString)).optional(), or: z.array(z.lazy(() => queryFilterString)).optional()}); export const queryFilterStringMapItem = z.object({exists: z.boolean().optional(), eq: z.string().optional(), neq: z.string().optional(), in: z.array(z.string()).optional(), nin: z.array(z.string()).optional(), contains: z.string().optional(), ncontains: z.string().optional(), and: z.array(queryFilterString).optional(), or: z.array(queryFilterString).optional()}); export const feature = z.object({id: z.string(), name: z.string().min(1).max(256), description: z.string().max(1024).optional(), labels: labels.optional(), created_at: z.string(), updated_at: z.string(), deleted_at: z.string().optional(), key: resourceKey, meter: z.object({id: z.string(), filters: z.record(z.string(), queryFilterStringMapItem).optional()}).optional(), unit_cost: z.discriminatedUnion("type", [z.object({type: z.literal("manual"), amount: z.string()}), z.object({type: z.literal("llm"), provider_property: z.string().optional(), provider: z.string().optional(), model_property: z.string().optional(), model: z.string().optional(), token_type_property: z.string().optional(), token_type: z.enum(["input", "output", "cache_read", "cache_write", "reasoning", "request", "response"]).optional(), pricing: z.object({input_per_token: z.string(), output_per_token: z.string(), cache_read_per_token: z.string().optional(), reasoning_per_token: z.string().optional(), cache_write_per_token: z.string().optional()}).optional()})]).optional()}); export const featureReference = z.object({id: uLID}); export const billingCharge = z.discriminatedUnion("type", [z.object({id: z.string(), name: z.string().min(1).max(256), description: z.string().max(1024).optional(), labels: labels.optional(), created_at: z.string(), updated_at: z.string(), deleted_at: z.string().optional(), type: z.literal("flat_fee"), customer: z.union([billingCustomer, customerReference]), lifecycle_controller: z.enum(["system", "manual"]), subscription: z.union([billingSubscription, billingSubscriptionReference]).optional(), currency: z.union([currencyCode, billingCurrencyCodeCustom]), resolved_cost_basis: z.object({fiat_currency: z.string().min(3).max(3), rate: z.string(), cost_basis_id: z.string().optional(), resolved_at: z.string()}).optional(), status: z.enum(["created", "active", "final", "deleted"]), validation_issues: z.array(billingValidationIssue).optional(), invoice_at: z.string(), service_period: z.object({from: z.string(), to: z.string()}), full_service_period: z.object({from: z.string(), to: z.string()}), billing_period: z.object({from: z.string(), to: z.string()}), advance_after: z.string().optional(), unique_reference_id: z.string().optional(), settlement_mode: z.enum(["credit_then_invoice", "credit_only"]), tax_config: z.object({behavior: z.enum(["inclusive", "exclusive"]).optional(), stripe: z.object({code: z.string()}).optional(), external_invoicing: z.object({code: z.string().max(64)}).optional(), tax_code_id: z.string().optional(), tax_code: z.object({id: uLID}).optional()}).optional(), realizations: z.array(billingChargeRealization), payment_term: z.enum(["in_advance", "in_arrears"]), discounts: z.object({percentage: z.number().gte(0).lte(100).optional()}).optional(), feature: z.union([feature, featureReference]).optional(), proration_configuration: z.object({mode: z.enum(["no_proration", "prorate_prices"])}), amount_after_proration: z.object({amount: z.string(), currency: z.union([currencyCode, billingCurrencyCodeCustom])}), price: z.object({type: z.literal("flat"), amount: z.string()}), system_intent: z.object({name: z.string().min(1).max(256), description: z.string().max(1024).optional(), labels: labels.optional(), invoice_at: z.string(), service_period: z.object({from: z.string(), to: z.string()}), full_service_period: z.object({from: z.string(), to: z.string()}), billing_period: z.object({from: z.string(), to: z.string()}), payment_term: z.enum(["in_advance", "in_arrears"]), discounts: z.object({percentage: z.number().gte(0).lte(100).optional()}).optional(), proration_configuration: z.object({mode: z.enum(["no_proration", "prorate_prices"])}), amount_before_proration: z.object({amount: z.string(), currency: z.union([currencyCode, billingCurrencyCodeCustom])}), deleted_at: z.string().optional()}).optional()}), z.object({id: z.string(), name: z.string().min(1).max(256), description: z.string().max(1024).optional(), labels: labels.optional(), created_at: z.string(), updated_at: z.string(), deleted_at: z.string().optional(), type: z.literal("usage_based"), customer: z.union([billingCustomer, customerReference]), lifecycle_controller: z.enum(["system", "manual"]), subscription: z.union([billingSubscription, billingSubscriptionReference]).optional(), currency: z.union([currencyCode, billingCurrencyCodeCustom]), resolved_cost_basis: z.object({fiat_currency: z.string().min(3).max(3), rate: z.string(), cost_basis_id: z.string().optional(), resolved_at: z.string()}).optional(), status: z.enum(["created", "active", "final", "deleted"]), validation_issues: z.array(billingValidationIssue).optional(), invoice_at: z.string(), service_period: z.object({from: z.string(), to: z.string()}), full_service_period: z.object({from: z.string(), to: z.string()}), billing_period: z.object({from: z.string(), to: z.string()}), advance_after: z.string().optional(), unique_reference_id: z.string().optional(), settlement_mode: z.enum(["credit_then_invoice", "credit_only"]), tax_config: z.object({behavior: z.enum(["inclusive", "exclusive"]).optional(), stripe: z.object({code: z.string()}).optional(), external_invoicing: z.object({code: z.string().max(64)}).optional(), tax_code_id: z.string().optional(), tax_code: z.object({id: uLID}).optional()}).optional(), realizations: z.array(billingChargeRealization), discounts: z.object({percentage: z.number().gte(0).lte(100).optional(), usage: z.string().optional()}).optional(), feature: z.union([feature, featureReference]), totals: z.object({booked: z.object({amount: z.string(), taxes_total: z.string(), taxes_inclusive_total: z.string(), taxes_exclusive_total: z.string(), charges_total: z.string(), discounts_total: z.string(), credits_total: z.string(), total: z.string()}), realtime: z.object({amount: z.string(), taxes_total: z.string(), taxes_inclusive_total: z.string(), taxes_exclusive_total: z.string(), charges_total: z.string(), discounts_total: z.string(), credits_total: z.string(), total: z.string()}).optional()}), usage: z.string().optional(), price: z.discriminatedUnion("type", [z.object({type: z.literal("unit"), amount: z.string()}), z.object({type: z.literal("graduated"), tiers: z.array(billingPriceTier)}), z.object({type: z.literal("volume"), tiers: z.array(billingPriceTier)})]), commitments: z.object({minimum_amount: z.string().optional(), maximum_amount: z.string().optional()}).optional(), unit_config: z.object({operation: z.enum(["divide", "multiply"]), conversion_factor: z.string(), rounding: z.enum(["ceiling", "floor", "half_up", "none"]).optional(), precision: z.number().int().optional(), display_unit: z.string().optional()}).optional(), system_intent: z.object({name: z.string().min(1).max(256), description: z.string().max(1024).optional(), labels: labels.optional(), invoice_at: z.string(), service_period: z.object({from: z.string(), to: z.string()}), full_service_period: z.object({from: z.string(), to: z.string()}), billing_period: z.object({from: z.string(), to: z.string()}), discounts: z.object({percentage: z.number().gte(0).lte(100).optional(), usage: z.string().optional()}).optional(), price: z.discriminatedUnion("type", [z.object({type: z.literal("unit"), amount: z.string()}), z.object({type: z.literal("graduated"), tiers: z.array(billingPriceTier)}), z.object({type: z.literal("volume"), tiers: z.array(billingPriceTier)})]), commitments: z.object({minimum_amount: z.string().optional(), maximum_amount: z.string().optional()}).optional(), unit_config: z.object({operation: z.enum(["divide", "multiply"]), conversion_factor: z.string(), rounding: z.enum(["ceiling", "floor", "half_up", "none"]).optional(), precision: z.number().int().optional(), display_unit: z.string().optional()}).optional(), deleted_at: z.string().optional()}).optional()})]); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Create customer charge * * POST /v3/openmeter/customers/{customerId}/charges * * Also accepts auth: systemAccountAccessToken, konnectAccessToken, serviceAccessToken */ export const createApiV3OpenmeterCustomersCustomerIdCharges = async (args: CreateApiV3OpenmeterCustomersCustomerIdChargesArgs, options?: CreateApiV3OpenmeterCustomersCustomerIdChargesOptions) => { const {baseUrl = "https://global.api.konghq.com", fetch: fetchFn = fetch, personalAccessToken} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (personalAccessToken !== undefined) headers.set('authorization', `Bearer ${personalAccessToken}`) const url = `${baseUrl.replace(/\/+$/, '')}/v3/openmeter/customers/${encodeURIComponent(String(args.customerId))}/charges${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(billingCharge, await res.json()) };