diff --git a/api/spec/packages/aip-client-javascript/.gitignore b/api/spec/packages/aip-client-javascript/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..0e9f501696858e25bae29f8751b71a7dc5f3e27c --- /dev/null +++ b/api/spec/packages/aip-client-javascript/.gitignore @@ -0,0 +1,12 @@ +# Build output +dist/ +tsconfig.tsbuildinfo + +# Test coverage output +coverage/ + +# Dependencies +node_modules/ + +# Generated conformance guards (compile-time only, re-emitted by the generator) +*.assert.ts diff --git a/api/spec/packages/aip-client-javascript/LICENSE b/api/spec/packages/aip-client-javascript/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/api/spec/packages/aip-client-javascript/README.md b/api/spec/packages/aip-client-javascript/README.md new file mode 100644 index 0000000000000000000000000000000000000000..dfb4d60dd73a9ab602b63f3a5d9b267c68dce626 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/README.md @@ -0,0 +1,623 @@ + + +# OpenMeter SDK + +TypeScript client for the OpenMeter API — usage metering and billing for +AI and DevTool companies. This package is generated from the OpenMeter +TypeSpec definitions and ships fully-typed request and response models. + +> **Important:** This SDK is a work in progress. +> +> This SDK targets the [OpenMeter API v3](https://openmeter.io/docs/api/v3), +> a rewrite of the OpenMeter API following AIP (API Improvement Proposal) +> standardization. + +## Table of Contents + +- [Installation](#installation) +- [Initialization](#initialization) +- [Configuration](#configuration) +- [Usage](#usage) +- [Pagination](#pagination) +- [Available Resources and Operations](#available-resources-and-operations) + - [Events](#events) + - [Meters](#meters) + - [Customers](#customers) + - [Entitlements](#entitlements) + - [Subscriptions](#subscriptions) + - [Apps](#apps) + - [Billing](#billing) + - [Tax](#tax) + - [Features](#features) + - [LLMCost](#llmcost) + - [Plans](#plans) + - [Addons](#addons) + - [PlanAddons](#planaddons) + - [Defaults](#defaults) +- [Internal Operations](#internal-operations) + - [Internal Subscriptions](#internal-subscriptions) + - [Internal Invoices](#internal-invoices) + - [Internal Currencies](#internal-currencies) + - [Internal Governance](#internal-governance) +- [Runtime Validation (validate option)](#runtime-validation-validate-option) +- [Zod Schemas (./zod export)](#zod-schemas-zod-export) +- [Error Handling](#error-handling) +- [Standalone Functions](#standalone-functions) + +## Installation + +```bash +npm install @openmeter/client +``` + +Or with your package manager of choice: + +```bash +pnpm add @openmeter/client +yarn add @openmeter/client +``` + +## Initialization + +Create a client with a base URL and an API key. The API key is sent as a +`Bearer` token on every request. + +```typescript +import { OpenMeter } from '@openmeter/client' + +const client = new OpenMeter({ + baseUrl: 'https://openmeter.cloud/api/v3', + apiKey: process.env.OPENMETER_API_KEY, +}) +``` + +Konnect regions are addressed with a server template and a `region` +variable: + +```typescript +import { OpenMeter, ServerList } from '@openmeter/client' + +const client = new OpenMeter({ + baseUrl: ServerList[0], + serverVariables: { region: 'eu' }, + apiKey: process.env.OPENMETER_API_KEY, +}) +``` + +The `apiKey` may also be a function returning a `string` or +`Promise`, so tokens can be refreshed per request. + +## Configuration + +`SDKOptions` extends [ky](https://github.com/sindresorhus/ky)'s +`Options`, so every transport setting ky supports is a top-level client +option: retry policy, per-attempt timeout (ky defaults to 10 seconds), +lifecycle hooks, a custom `fetch`, and so on. + +```typescript +import { OpenMeter } from '@openmeter/client' + +const client = new OpenMeter({ + baseUrl: 'https://openmeter.cloud/api/v3', + apiKey: process.env.OPENMETER_API_KEY, + timeout: 30_000, + hooks: { + beforeRequest: [ + ({ request }) => { + console.log(`-> ${request.method} ${request.url}`) + }, + ], + }, + fetch: async (input, init) => { + const start = Date.now() + const response = await fetch(input, init) + console.log(`${response.status} in ${Date.now() - start}ms`) + return response + }, +}) +``` + +ky only retries the idempotent methods by default — `get`, `put`, +`head`, `delete`, `options`, `trace` — never `post`. That means a +dropped `client.events.ingest` call is not retried on a network error +or a 5xx response unless you opt in explicitly: + +```typescript +import { OpenMeter } from '@openmeter/client' + +const client = new OpenMeter({ + baseUrl: 'https://openmeter.cloud/api/v3', + apiKey: process.env.OPENMETER_API_KEY, + retry: { limit: 3, methods: ['get', 'put', 'head', 'delete', 'post'] }, +}) +``` + +This is safe specifically for event ingestion: the event `id` is its +deduplication key server-side, so resending the same event on retry is +a no-op rather than a duplicate. + +Every method also takes a per-request `RequestOptions` as its second +argument — a curated subset of ky's options (`signal`, `headers`, +`timeout`, `retry`) applied to that call only: + +```typescript +import { OpenMeter } from '@openmeter/client' + +const client = new OpenMeter({ + baseUrl: 'https://openmeter.cloud/api/v3', + apiKey: process.env.OPENMETER_API_KEY, +}) + +const controller = new AbortController() +setTimeout(() => controller.abort(), 5_000) + +const meters = await client.meters.list(undefined, { + signal: controller.signal, + headers: { 'X-Request-Id': 'batch-42' }, +}) +``` + +## Usage + +Every operation is reachable through a fluent, namespaced client and +returns a typed response (or throws an `HTTPError` on a non-2xx status). + +```typescript +import { OpenMeter } from '@openmeter/client' + +const client = new OpenMeter({ + baseUrl: 'https://openmeter.cloud/api/v3', + apiKey: process.env.OPENMETER_API_KEY, +}) + +const meter = await client.meters.create({ + name: 'Tokens', + key: 'tokens', + aggregation: 'sum', + eventType: 'request', + valueProperty: '$.tokens', +}) + +const meters = await client.meters.list() +``` + +Each method takes the request object as its first argument and an optional +per-request options object (`RequestOptions`) as its second. + +Responses return date-time fields as native `Date` objects (every +`createdAt`/`updatedAt`, meter query row windows, …), and requests accept +either a `Date` or an RFC 3339 string — a meter query `from`/`to`, an +ingested event's `time`, filter operands, all alike. + +## Pagination + +Every list operation that returns pages also has an `…All` companion — +`client.meters.listAll(request?)` alongside `client.meters.list(request?)` — +that returns an `AsyncIterable` of items instead of one page. It fetches +each following page lazily, only when the previous page is exhausted, so a +`break` (or a `return`) partway through never fires a request for a page +nothing consumes: + +```typescript +import { OpenMeter } from '@openmeter/client' + +const client = new OpenMeter({ + baseUrl: 'https://openmeter.cloud/api/v3', + apiKey: process.env.OPENMETER_API_KEY, +}) + +for await (const meter of client.meters.listAll()) { + console.log(meter.key) +} +``` + +The request object accepts the same filters, sort, and page size as the +single-page method — only the page cursor/number itself advances between +requests: + +```typescript +for await (const meter of client.meters.listAll({ filter: { key: 'api' } })) { + if (meter.key === 'api-requests') { + break // stops iterating; no further pages are fetched + } +} +``` + +Cursor-paginated resources (`events`, credit transactions) work the same +way: + +```typescript +for await (const event of client.events.listAll()) { + console.log(event.event.id) +} +``` + +Auto-pagination takes the same optional `RequestOptions` as every other +method, so one `AbortSignal` cancels the whole iteration, not just the page +in flight: + +```typescript +const controller = new AbortController() +setTimeout(() => controller.abort(), 30_000) + +for await (const meter of client.meters.listAll(undefined, { + signal: controller.signal, +})) { + console.log(meter.key) +} +``` + +Iteration stops after the server’s last page — an empty or short-of-`size` +page for a page-number resource, or a response with no next cursor for a +cursor resource. A misbehaving server that never signals the end of the +list fails fast instead of looping forever: after 10,000 pages the +iterable throws `PaginationLimitExceededError`. + +## Available Resources and Operations + +Operations are grouped by resource and exposed as methods on the client. +The full call path, HTTP route, and a short description are listed below. + +### Events + +| Method | HTTP | Description | +| ---------------------- | ------------------------ | ---------------------------------------------------------------------------- | +| `client.events.list` | `GET /openmeter/events` | List ingested events. | +| `client.events.ingest` | `POST /openmeter/events` | Ingests an event or batch of events following the CloudEvents specification. | + +### Meters + +| Method | HTTP | Description | +| ------------------------ | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `client.meters.create` | `POST /openmeter/meters` | Create a meter. | +| `client.meters.get` | `GET /openmeter/meters/{meterId}` | Get a meter by ID. | +| `client.meters.list` | `GET /openmeter/meters` | List meters. | +| `client.meters.update` | `PUT /openmeter/meters/{meterId}` | Update a meter. | +| `client.meters.delete` | `DELETE /openmeter/meters/{meterId}` | Delete a meter. | +| `client.meters.query` | `POST /openmeter/meters/{meterId}/query` | Query a meter for usage. Set `Accept: application/json` (the default) to get a structured JSON response. Set `Accept: text/csv` to download the same data as a CSV file suitable for spreadsheets. The CSV columns, in order, are: `from, to, [subject,] [customer_id, customer_key, customer_name,] , value` The `subject` column is emitted only when `subject` is in the query's `group_by_dimensions`. The three `customer_*` columns are emitted together only when `customer_id` is in the query's `group_by_dimensions`. | +| `client.meters.queryCsv` | `POST /openmeter/meters/{meterId}/query` | | + +### Customers + +| Method | HTTP | Description | +| ---------------------------------------------------------- | ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `client.customers.create` | `POST /openmeter/customers` | Create customer | +| `client.customers.get` | `GET /openmeter/customers/{customerId}` | Get customer | +| `client.customers.list` | `GET /openmeter/customers` | List customers | +| `client.customers.upsert` | `PUT /openmeter/customers/{customerId}` | Upsert customer | +| `client.customers.delete` | `DELETE /openmeter/customers/{customerId}` | Delete customer | +| `client.customers.billing.get` | `GET /openmeter/customers/{customerId}/billing` | Get customer billing data | +| `client.customers.billing.update` | `PUT /openmeter/customers/{customerId}/billing` | Update customer billing data | +| `client.customers.billing.updateAppData` | `PUT /openmeter/customers/{customerId}/billing/app-data` | Update customer billing app data | +| `client.customers.billing.createStripeCheckoutSession` | `POST /openmeter/customers/{customerId}/billing/stripe/checkout-sessions` | Create a [Stripe Checkout Session](https://docs.stripe.com/payments/checkout) for the customer. Creates a Checkout Session for collecting payment method information from customers. The session operates in "setup" mode, which collects payment details without charging the customer immediately. The collected payment method can be used for future subscription billing. For hosted checkout sessions, redirect customers to the returned URL. For embedded sessions, use the client_secret to initialize Stripe.js in your application. | +| `client.customers.billing.createStripePortalSession` | `POST /openmeter/customers/{customerId}/billing/stripe/portal-sessions` | Create Stripe Customer Portal Session. Useful to redirect the customer to the Stripe Customer Portal to manage their payment methods, change their billing address and access their invoice history. Only returns URL if the customer billing profile is linked to a stripe app and customer. | +| `client.customers.credits.grants.create` | `POST /openmeter/customers/{customerId}/credits/grants` | Create a new credit grant. A credit grant represents an allocation of prepaid credits to a customer. | +| `client.customers.credits.grants.get` | `GET /openmeter/customers/{customerId}/credits/grants/{creditGrantId}` | Get a credit grant. | +| `client.customers.credits.grants.list` | `GET /openmeter/customers/{customerId}/credits/grants` | List credit grants. | +| `client.customers.credits.balance.get` | `GET /openmeter/customers/{customerId}/credits/balance` | Get a credit balance. | +| `client.customers.credits.adjustments.create` | `POST /openmeter/customers/{customerId}/credits/adjustments` | A credit adjustment can be used to make manual adjustments to a customer's credit balance. Supported use-cases: - Usage correction | +| `client.customers.credits.grants.void` | `POST /openmeter/customers/{customerId}/credits/grants/{creditGrantId}/void` | Void a credit grant, forfeiting the remaining unused balance. Voiding is a forward-looking, irreversible operation. Credits already consumed by usage remain unaffected — only the remaining balance is forfeited. The grant reads as `voided` status afterwards. Payment state is not adjusted when `payment_adjustment` is `none`, so invoice-backed or externally collected payments may still collect the original amount. Only `active` grants can be voided; voiding a pending, expired, or fully consumed grant returns a conflict. Retrying a successful void is an idempotent success. | +| `client.customers.credits.grants.updateExternalSettlement` | `POST /openmeter/customers/{customerId}/credits/grants/{creditGrantId}/settlement/external` | Update the payment settlement status of an externally funded credit grant. Use this endpoint to synchronize the payment state of an external payment with the system so that revenue recognition and credit availability work as expected. | +| `client.customers.credits.transactions.list` | `GET /openmeter/customers/{customerId}/credits/transactions` | List credit transactions for a customer. Returns an immutable, chronological record of credit movements: funded credits and consumed credits. Transactions are returned in reverse chronological order by default. | +| `client.customers.charges.list` | `GET /openmeter/customers/{customerId}/charges` | List customer charges. Returns the customer's charges that are represented as either flat fee or usage-based charges. | +| `client.customers.charges.create` | `POST /openmeter/customers/{customerId}/charges` | Create customer charge. | + +### Entitlements + +| Method | HTTP | Description | +| ---------------------------------------- | ---------------------------------------------------------- | -------------------------------- | +| `client.entitlements.listCustomerAccess` | `GET /openmeter/customers/{customerId}/entitlement-access` | List customer entitlement access | + +### Subscriptions + +| Method | HTTP | Description | +| -------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| `client.subscriptions.create` | `POST /openmeter/subscriptions` | Create subscription | +| `client.subscriptions.list` | `GET /openmeter/subscriptions` | List subscriptions | +| `client.subscriptions.get` | `GET /openmeter/subscriptions/{subscriptionId}` | Get subscription | +| `client.subscriptions.cancel` | `POST /openmeter/subscriptions/{subscriptionId}/cancel` | Cancels the subscription. Will result in a scheduling conflict if there are other subscriptions scheduled to start after the cancelation time. | +| `client.subscriptions.unscheduleCancelation` | `POST /openmeter/subscriptions/{subscriptionId}/unschedule-cancelation` | Unschedules the subscription cancelation. | +| `client.subscriptions.change` | `POST /openmeter/subscriptions/{subscriptionId}/change` | Closes a running subscription and starts a new one according to the specification. Can be used for upgrades, downgrades, and plan changes. | +| `client.subscriptions.listAddons` | `GET /openmeter/subscriptions/{subscriptionId}/addons` | List the add-ons of a subscription. | +| `client.subscriptions.getAddon` | `GET /openmeter/subscriptions/{subscriptionId}/addons/{subscriptionAddonId}` | Get an add-on association for a subscription. | + +### Apps + +| Method | HTTP | Description | +| ---------------------------- | -------------------------------------- | -------------------------------- | +| `client.apps.list` | `GET /openmeter/apps` | List installed apps. | +| `client.apps.get` | `GET /openmeter/apps/{appId}` | Get an installed app. | +| `client.apps.listCatalog` | `GET /openmeter/app-catalog` | List available apps. | +| `client.apps.getCatalogItem` | `GET /openmeter/app-catalog/{appType}` | Get an app catalog item by type. | +| `client.apps.install` | `POST /openmeter/app-catalog/install` | Install an app from the catalog. | + +### Billing + +| Method | HTTP | Description | +| ------------------------------ | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `client.billing.listProfiles` | `GET /openmeter/profiles` | List billing profiles. | +| `client.billing.createProfile` | `POST /openmeter/profiles` | Create a new billing profile. Billing profiles contain the settings for billing and controls invoice generation. An organization can have multiple billing profiles defined. A billing profile is linked to a specific app. This association is established during the billing profile's creation and remains immutable. | +| `client.billing.getProfile` | `GET /openmeter/profiles/{id}` | Get a billing profile. | +| `client.billing.updateProfile` | `PUT /openmeter/profiles/{id}` | Update a billing profile. | +| `client.billing.deleteProfile` | `DELETE /openmeter/profiles/{id}` | Delete a billing profile. Only such billing profiles can be deleted that are: - not the default profile - not pinned to any customer using customer overrides - only have finalized invoices | + +### Tax + +| Method | HTTP | Description | +| ----------------------- | ----------------------------------------- | --------------- | +| `client.tax.createCode` | `POST /openmeter/tax-codes` | Create tax code | +| `client.tax.getCode` | `GET /openmeter/tax-codes/{taxCodeId}` | Get tax code | +| `client.tax.listCodes` | `GET /openmeter/tax-codes` | List tax codes | +| `client.tax.upsertCode` | `PUT /openmeter/tax-codes/{taxCodeId}` | Upsert tax code | +| `client.tax.deleteCode` | `DELETE /openmeter/tax-codes/{taxCodeId}` | Delete tax code | + +### Features + +| Method | HTTP | Description | +| --------------------------- | ------------------------------------------------- | -------------------------------------------------------------------------- | +| `client.features.list` | `GET /openmeter/features` | List all features. | +| `client.features.create` | `POST /openmeter/features` | Create a feature. | +| `client.features.get` | `GET /openmeter/features/{featureId}` | Get a feature by id. | +| `client.features.update` | `PATCH /openmeter/features/{featureId}` | Update a feature by id. Currently only the unit_cost field can be updated. | +| `client.features.delete` | `DELETE /openmeter/features/{featureId}` | Delete a feature by id. | +| `client.features.queryCost` | `POST /openmeter/features/{featureId}/cost/query` | Query the cost of a feature. | + +### LLMCost + +| Method | HTTP | Description | +| ------------------------------- | ------------------------------------------------ | ------------------------------------------------------------------------------------- | +| `client.llmCost.listPrices` | `GET /openmeter/llm-cost/prices` | List global LLM cost prices. Returns prices with overrides applied if any. | +| `client.llmCost.getPrice` | `GET /openmeter/llm-cost/prices/{priceId}` | Get a specific LLM cost price by ID. Returns the price with overrides applied if any. | +| `client.llmCost.listOverrides` | `GET /openmeter/llm-cost/overrides` | List per-namespace price overrides. | +| `client.llmCost.createOverride` | `POST /openmeter/llm-cost/overrides` | Create a per-namespace price override. | +| `client.llmCost.deleteOverride` | `DELETE /openmeter/llm-cost/overrides/{priceId}` | Delete a per-namespace price override. | + +### Plans + +| Method | HTTP | Description | +| ---------------------- | ---------------------------------------- | ----------------------- | +| `client.plans.list` | `GET /openmeter/plans` | List all plans. | +| `client.plans.create` | `POST /openmeter/plans` | Create a new plan. | +| `client.plans.update` | `PUT /openmeter/plans/{planId}` | Update a plan by id. | +| `client.plans.get` | `GET /openmeter/plans/{planId}` | Get a plan by id. | +| `client.plans.delete` | `DELETE /openmeter/plans/{planId}` | Delete a plan by id. | +| `client.plans.archive` | `POST /openmeter/plans/{planId}/archive` | Archive a plan version. | +| `client.plans.publish` | `POST /openmeter/plans/{planId}/publish` | Publish a plan version. | + +### Addons + +| Method | HTTP | Description | +| ----------------------- | ------------------------------------------ | -------------------------- | +| `client.addons.list` | `GET /openmeter/addons` | List all add-ons. | +| `client.addons.create` | `POST /openmeter/addons` | Create a new add-on. | +| `client.addons.update` | `PUT /openmeter/addons/{addonId}` | Update an add-on by id. | +| `client.addons.get` | `GET /openmeter/addons/{addonId}` | Get add-on by id. | +| `client.addons.delete` | `DELETE /openmeter/addons/{addonId}` | Soft delete add-on by id. | +| `client.addons.archive` | `POST /openmeter/addons/{addonId}/archive` | Archive an add-on version. | +| `client.addons.publish` | `POST /openmeter/addons/{addonId}/publish` | Publish an add-on version. | + +### PlanAddons + +| Method | HTTP | Description | +| -------------------------- | ------------------------------------------------------- | ---------------------------------------- | +| `client.planAddons.list` | `GET /openmeter/plans/{planId}/addons` | List add-ons associated with a plan. | +| `client.planAddons.create` | `POST /openmeter/plans/{planId}/addons` | Add an add-on to a plan. | +| `client.planAddons.get` | `GET /openmeter/plans/{planId}/addons/{planAddonId}` | Get an add-on association for a plan. | +| `client.planAddons.update` | `PUT /openmeter/plans/{planId}/addons/{planAddonId}` | Update an add-on association for a plan. | +| `client.planAddons.delete` | `DELETE /openmeter/plans/{planId}/addons/{planAddonId}` | Remove an add-on from a plan. | + +### Defaults + +| Method | HTTP | Description | +| -------------------------------------------- | ----------------------------------- | ------------------------------------- | +| `client.defaults.getOrganizationTaxCodes` | `GET /openmeter/defaults/tax-codes` | Get organization default tax codes | +| `client.defaults.updateOrganizationTaxCodes` | `PUT /openmeter/defaults/tax-codes` | Update organization default tax codes | + +## Internal Operations + +Operations marked internal in the API definition are exposed under +`client.internal.*`, quarantined from the customer surface. They are not +intended for customer use: they may require additional permissions, and +they can change or be removed without notice or semver consideration. + +### Internal Subscriptions + +| Method | HTTP | Description | +| ------------------------------------------- | ------------------------------------------------------- | ----------------------------- | +| `client.internal.subscriptions.createAddon` | `POST /openmeter/subscriptions/{subscriptionId}/addons` | Add add-on to a subscription. | + +### Internal Invoices + +| Method | HTTP | Description | +| --------------------------------------------- | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `client.internal.invoices.list` | `GET /openmeter/billing/invoices` | List billing invoices. Returns a page of invoices. Gathering invoices are never included. Use `filter` to narrow by status, customer, dates, or service period start. Use `sort` to control ordering. | +| `client.internal.invoices.get` | `GET /openmeter/billing/invoices/{invoiceId}` | Get a billing invoice by ID. Returns the full invoice resource including line items, status details, totals, and workflow configuration snapshot. | +| `client.internal.invoices.update` | `PUT /openmeter/billing/invoices/{invoiceId}` | Update a billing invoice. Only the mutable fields of the invoice can be edited: description, labels, supplier, customer, workflow settings, and top-level lines. Top-level lines are matched by `id`; lines without an `id` are created, and existing lines omitted from `lines` are deleted. Detailed (child) lines are always computed and cannot be edited directly. Only invoices in draft status can be updated. | +| `client.internal.invoices.delete` | `DELETE /openmeter/billing/invoices/{invoiceId}` | Delete a billing invoice. Only standard invoices in draft status can be deleted. Deleting an invoice will also delete all associated line items and workflow configuration. | +| `client.internal.invoices.advance` | `POST /openmeter/billing/invoices/{invoiceId}/advance` | Advance a billing invoice. Advances the invoice to the next workflow state. The next state is determined by the invoice's current status and workflow configuration. Only invoices in draft or issued status can be advanced. | +| `client.internal.invoices.approve` | `POST /openmeter/billing/invoices/{invoiceId}/approve` | Approve a billing invoice. This call instantly sends the invoice to the customer using the configured billing profile app. This call is valid in two invoice statuses: - draft: the invoice will be sent to the customer, the invoice state becomes issued - manual_approval_needed: the invoice will be sent to the customer, the invoice state becomes issued | +| `client.internal.invoices.retry` | `POST /openmeter/billing/invoices/{invoiceId}/retry` | Retry sending a billing invoice. Retry advancing the invoice after a failed attempt. The action can be called when the invoice's statusDetails' actions field contain the "retry" action. | +| `client.internal.invoices.snapshotQuantities` | `POST /openmeter/billing/invoices/{invoiceId}/snapshot-quantities` | Snapshot quantities for usage-based line items. This call will snapshot the quantities for all usage based line items in the invoice. This call is only valid in draft.waiting_for_collection status, where the collection period can be skipped using this action. | + +### Internal Currencies + +| Method | HTTP | Description | +| ------------------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | +| `client.internal.currencies.list` | `GET /openmeter/currencies` | List currencies supported by the billing system. | +| `client.internal.currencies.createCustomCurrency` | `POST /openmeter/currencies/custom` | Create a custom currency. This operation allows defining your own custom currency for billing purposes. | +| `client.internal.currencies.listCostBases` | `GET /openmeter/currencies/custom/{currencyId}/cost-bases` | List cost bases for a currency. For custom currencies, there can be multiple cost bases with different `effective_from` dates. | +| `client.internal.currencies.createCostBasis` | `POST /openmeter/currencies/custom/{currencyId}/cost-bases` | Create a cost basis for a currency. | + +### Internal Governance + +| Method | HTTP | Description | +| ---------------------------------------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `client.internal.governance.queryAccess` | `POST /openmeter/governance/query` | Query feature access for a list of customers. The endpoint resolves each provided identifier to a customer and returns the access status for the requested features, plus optional credit balance availability. _Designed to be called on a fixed refresh interval and the query response is intended to be cached._ | + +## Runtime Validation (validate option) + +`validate` is off by default. The SDK's normal request/response mapping +only renames keys and converts dates — it never rejects a payload — so +an additive server-side change (a new response field, a new enum value) +never breaks a client running an older SDK version. + +Set `validate: true` to additionally check the wire payload — the +request body after mapping to snake_case, and the raw response before +mapping back — against the generated `…Wire` schemas. Those schemas are +strict: an unknown field or an unrecognized enum value fails validation +instead of being silently accepted. That makes `validate` a tool for +catching SDK/server contract drift in development or CI, not something +to run in production, where forward compatibility with additive server +changes matters more than strict rejection. + +```typescript +import { OpenMeter, ValidationError } from '@openmeter/client' + +const client = new OpenMeter({ + baseUrl: 'https://openmeter.cloud/api/v3', + apiKey: process.env.OPENMETER_API_KEY, + validate: true, +}) + +try { + await client.meters.get({ meterId: 'meter_123' }) +} catch (error) { + if (error instanceof ValidationError) { + console.error(error.issues) + } +} +``` + +The standalone functions surface the same failure as a `Result` instead +of throwing — check `result.error instanceof ValidationError`. + +## Zod Schemas (./zod export) + +`@openmeter/client/zod` exports every model twice: once shaped like the +SDK's public surface (camelCase keys, `Date` for date-time fields — the +same shape `meter.eventType`/`meter.createdAt` have in TypeScript) and +once as a strict `…Wire` schema shaped like the literal JSON the server +sends and accepts (snake_case keys, RFC 3339 date-time strings, unknown +fields rejected) — the same `…Wire` schemas the `validate` option checks +internally. + +Use the public schemas to validate a payload the SDK did not produce — +a webhook body, a cached record, a test fixture — before trusting its +shape: + +```typescript +import * as schemas from '@openmeter/client/zod' + +const parsed = schemas.meter.safeParse({ + id: '01HZY3W6VXQK6H3NPC6DFA0PJT', + name: 'Tokens', + key: 'tokens', + aggregation: 'sum', + eventType: 'request', + createdAt: new Date(), + updatedAt: new Date(), +}) + +if (parsed.success) { + console.log(parsed.data.eventType) +} +``` + +## Error Handling + +A non-2xx response rejects with an `HTTPError` (`error.name === 'HTTPError'`) +carrying the problem-details fields (`status`, `type`, `title`, `url`) +from the response. + +```typescript +import { OpenMeter, HTTPError } from '@openmeter/client' + +const client = new OpenMeter({ + baseUrl: 'https://openmeter.cloud/api/v3', + apiKey: process.env.OPENMETER_API_KEY, +}) + +try { + await client.meters.get({ meterId: 'unknown' }) +} catch (error) { + if (error instanceof HTTPError) { + console.error(error.status, error.title, error.type) + } +} +``` + +`error.retryAfter` is the delta-seconds form of a numeric `Retry-After` +header (the common case on 429 and 503 responses) and `undefined` +otherwise. A 400 Bad Request additionally carries a typed +`error.invalidParameters` array describing which fields failed +validation; `error.getField(key)` is an untyped escape hatch for any +other problem-details extension member: + +```typescript +import { OpenMeter, HTTPError } from '@openmeter/client' + +const client = new OpenMeter({ + baseUrl: 'https://openmeter.cloud/api/v3', + apiKey: process.env.OPENMETER_API_KEY, +}) + +try { + await client.meters.create({ + name: 'Tokens', + key: 'tokens', + aggregation: 'sum', + eventType: 'request', + }) +} catch (error) { + if (error instanceof HTTPError && error.status === 400) { + for (const param of error.invalidParameters ?? []) { + console.error(param) + } + } +} +``` + +The SDK's other typed errors are `ValidationError` (see +[Runtime Validation (validate option)](#runtime-validation-validate-option)), `UnsafeIntegerError` +(an `int64`/`uint64` value exceeds what JSON can represent without +precision loss), `DepthLimitExceededError` (response data nested deeper +than the mapper's safety limit), and `PaginationLimitExceededError` (an +[Pagination](#pagination) iterable exceeded +its page-count safety limit) — each distinguished the same way, by +`instanceof` or by `.name`. + +## Standalone Functions + +Every method is also available as a standalone, tree-shakeable function +that takes a `Client` and returns a `Result` instead of throwing. + +```typescript +import { Client, funcs } from '@openmeter/client' + +const client = new Client({ + baseUrl: 'https://openmeter.cloud/api/v3', + apiKey: process.env.OPENMETER_API_KEY, +}) + +const result = await funcs.listMeters(client) +if (result.ok) { + console.log(result.value) +} else { + console.error(result.error) +} +``` + +`ok`, `err`, and `unwrap` — the helpers `Result` is built from — are +exported too, so a func call can be unwrapped back into a throwing call +where that is more convenient: + +```typescript +import { Client, funcs, unwrap } from '@openmeter/client' + +const client = new Client({ + baseUrl: 'https://openmeter.cloud/api/v3', + apiKey: process.env.OPENMETER_API_KEY, +}) + +const meters = unwrap(await funcs.listMeters(client)) +``` diff --git a/api/spec/packages/aip-client-javascript/package.json b/api/spec/packages/aip-client-javascript/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6b75789f119ddfaf20628184e13a5eb0202459a4 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/package.json @@ -0,0 +1,59 @@ +{ + "name": "@openmeter/client", + "version": "1.0.0", + "description": "Official TypeScript SDK for the OpenMeter API — usage metering and billing", + "keywords": [ + "openmeter", + "metering", + "billing", + "usage-based-billing", + "entitlements", + "sdk", + "api-client" + ], + "license": "Apache-2.0", + "homepage": "https://openmeter.io", + "repository": { + "type": "git", + "url": "git+https://github.com/openmeterio/openmeter.git", + "directory": "api/spec/packages/aip-client-javascript" + }, + "bugs": "https://github.com/openmeterio/openmeter/issues", + "type": "module", + "engines": { + "node": ">=22" + }, + "sideEffects": false, + "dependencies": { + "ky": "^2.0.2", + "zod": "^4.4.3" + }, + "devDependencies": { + "@types/node": "25.9.2", + "typescript": "5.5.2" + }, + "scripts": { + "build": "tsc", + "prepack": "tsc", + "typecheck": "tsc --noEmit && tsc -p tsconfig.tests.json" + }, + "files": [ + "dist", + "!dist/**/*.assert.*", + "!dist/**/*.map", + "!dist/**/*.tsbuildinfo" + ], + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + "./zod": { + "types": "./dist/models/schemas.d.ts", + "default": "./dist/models/schemas.js" + }, + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + } +} diff --git a/api/spec/packages/aip-client-javascript/src/core.ts b/api/spec/packages/aip-client-javascript/src/core.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a6efc7512a10eddcf17a7232035b52d9a36fcee --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/core.ts @@ -0,0 +1,62 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import ky, { type KyInstance as HTTPClient } from 'ky' +import { type SDKOptions } from './lib/config.js' +import { encodePath } from './lib/encodings.js' +import { SDK_VERSION } from './lib/version.js' + +export class Client { + readonly _options: SDKOptions + readonly _http: HTTPClient + + constructor(options: SDKOptions) { + this._options = options + + let baseUrl = + typeof options.baseUrl === 'string' + ? encodePath(options.baseUrl, options.serverVariables ?? {}) + : String(options.baseUrl) + if (!baseUrl.endsWith('/')) { + baseUrl = `${baseUrl}/` + } + + this._http = ky.create({ + ...options, + baseUrl, + prefix: undefined, + hooks: { + ...options.hooks, + beforeRequest: [ + ...(options.hooks?.beforeRequest ?? []), + async ({ request }) => { + // User-Agent is settable on the web but is not CORS-safelisted, so + // setting it would preflight otherwise-simple cross-origin requests. + // Gate on a positive Node check, not `window`: workers are also + // CORS-bound yet have no `window`. + if ( + typeof process !== 'undefined' && + process.versions?.node != null && + !request.headers.has('User-Agent') + ) { + request.headers.set('User-Agent', `openmeter-node/${SDK_VERSION}`) + } + + const token = + typeof options.apiKey === 'function' + ? await options.apiKey() + : options.apiKey + if (token) { + request.headers.set('Authorization', `Bearer ${token}`) + } + }, + ], + }, + }) + } +} + +export function http(client: Client): HTTPClient { + return client._http +} + +export type { HTTPClient } diff --git a/api/spec/packages/aip-client-javascript/src/funcs/addons.ts b/api/spec/packages/aip-client-javascript/src/funcs/addons.ts new file mode 100644 index 0000000000000000000000000000000000000000..083baaad64c9c3122386a74bb61e2729a9f1127e --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/funcs/addons.ts @@ -0,0 +1,295 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client, http } from '../core.js' +import { type Result, type RequestOptions } from '../lib/types.js' +import { request } from '../lib/request.js' +import { toURLSearchParams, encodeSort } from '../lib/encodings.js' +import { + toWire, + toPathWire, + fromWire, + assertValid, + toSnakeCase, +} from '../lib/wire.js' +import * as schemas from '../models/schemas.js' +import type { + ListAddonsRequest, + ListAddonsResponse, + CreateAddonRequest, + CreateAddonResponse, + UpdateAddonRequest, + UpdateAddonResponse, + GetAddonRequest, + GetAddonResponse, + DeleteAddonRequest, + DeleteAddonResponse, + ArchiveAddonRequest, + ArchiveAddonResponse, + PublishAddonRequest, + PublishAddonResponse, +} from '../models/operations/addons.js' + +/** + * List add-ons + * + * List all add-ons. + * + * GET /openmeter/addons + */ +export function listAddons( + client: Client, + req: ListAddonsRequest = {}, + options?: RequestOptions, +): Promise> { + return request(() => { + if (client._options.validate && req.sort !== undefined) { + assertValid(schemas.listAddonsQueryParams.shape.sort, req.sort) + } + const query = toWire( + { + page: req.page, + sort: encodeSort(req.sort, toSnakeCase), + filter: req.filter, + }, + schemas.listAddonsQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listAddonsQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get('openmeter/addons', { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listAddonsResponseWire, data) + } + return fromWire(data, schemas.listAddonsResponse) + }) + }) +} + +/** + * Create add-on + * + * Create a new add-on. + * + * POST /openmeter/addons + */ +export function createAddon( + client: Client, + req: CreateAddonRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const body = toWire(req, schemas.createAddonBody) + if (client._options.validate) { + assertValid(schemas.createAddonBodyWire, body) + } + return http(client) + .post('openmeter/addons', { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.createAddonResponseWire, data) + } + return fromWire(data, schemas.createAddonResponse) + }) + }) +} + +/** + * Update add-on + * + * Update an add-on by id. + * + * PUT /openmeter/addons/{addonId} + */ +export function updateAddon( + client: Client, + req: UpdateAddonRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + addonId: req.addonId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.updateAddonPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.updateAddonPathParamsWire, pathParams) + } + const path = `openmeter/addons/${(() => { + if (pathParams.addonId === undefined) { + throw new Error('missing path parameter: addonId') + } + return encodeURIComponent(String(pathParams.addonId)) + })()}` + const body = toWire(req.body, schemas.updateAddonBody) + if (client._options.validate) { + assertValid(schemas.updateAddonBodyWire, body) + } + return http(client) + .put(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.updateAddonResponseWire, data) + } + return fromWire(data, schemas.updateAddonResponse) + }) + }) +} + +/** + * Get add-on + * + * Get add-on by id. + * + * GET /openmeter/addons/{addonId} + */ +export function getAddon( + client: Client, + req: GetAddonRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + addonId: req.addonId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.getAddonPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.getAddonPathParamsWire, pathParams) + } + const path = `openmeter/addons/${(() => { + if (pathParams.addonId === undefined) { + throw new Error('missing path parameter: addonId') + } + return encodeURIComponent(String(pathParams.addonId)) + })()}` + return http(client) + .get(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.getAddonResponseWire, data) + } + return fromWire(data, schemas.getAddonResponse) + }) + }) +} + +/** + * Soft delete add-on + * + * Soft delete add-on by id. + * + * DELETE /openmeter/addons/{addonId} + */ +export function deleteAddon( + client: Client, + req: DeleteAddonRequest, + options?: RequestOptions, +): Promise> { + return request(async () => { + const pathParamsInput = { + addonId: req.addonId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.deleteAddonPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.deleteAddonPathParamsWire, pathParams) + } + const path = `openmeter/addons/${(() => { + if (pathParams.addonId === undefined) { + throw new Error('missing path parameter: addonId') + } + return encodeURIComponent(String(pathParams.addonId)) + })()}` + await http(client).delete(path, options) + }) +} + +/** + * Archive add-on version + * + * Archive an add-on version. + * + * POST /openmeter/addons/{addonId}/archive + */ +export function archiveAddon( + client: Client, + req: ArchiveAddonRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + addonId: req.addonId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.archiveAddonPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.archiveAddonPathParamsWire, pathParams) + } + const path = `openmeter/addons/${(() => { + if (pathParams.addonId === undefined) { + throw new Error('missing path parameter: addonId') + } + return encodeURIComponent(String(pathParams.addonId)) + })()}/archive` + return http(client) + .post(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.archiveAddonResponseWire, data) + } + return fromWire(data, schemas.archiveAddonResponse) + }) + }) +} + +/** + * Publish add-on version + * + * Publish an add-on version. + * + * POST /openmeter/addons/{addonId}/publish + */ +export function publishAddon( + client: Client, + req: PublishAddonRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + addonId: req.addonId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.publishAddonPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.publishAddonPathParamsWire, pathParams) + } + const path = `openmeter/addons/${(() => { + if (pathParams.addonId === undefined) { + throw new Error('missing path parameter: addonId') + } + return encodeURIComponent(String(pathParams.addonId)) + })()}/publish` + return http(client) + .post(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.publishAddonResponseWire, data) + } + return fromWire(data, schemas.publishAddonResponse) + }) + }) +} diff --git a/api/spec/packages/aip-client-javascript/src/funcs/apps.ts b/api/spec/packages/aip-client-javascript/src/funcs/apps.ts new file mode 100644 index 0000000000000000000000000000000000000000..f712f8c245f5e4de8fbc1a0c8aa8da825e8cf55b --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/funcs/apps.ts @@ -0,0 +1,199 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client, http } from '../core.js' +import { type Result, type RequestOptions } from '../lib/types.js' +import { request } from '../lib/request.js' +import { toURLSearchParams } from '../lib/encodings.js' +import { toWire, toPathWire, fromWire, assertValid } from '../lib/wire.js' +import * as schemas from '../models/schemas.js' +import type { + ListAppsRequest, + ListAppsResponse, + GetAppRequest, + GetAppResponse, + ListAppCatalogRequest, + ListAppCatalogResponse, + GetAppCatalogItemRequest, + GetAppCatalogItemResponse, + InstallAppRequest, + InstallAppResponse, +} from '../models/operations/apps.js' + +/** + * List apps + * + * List installed apps. + * + * GET /openmeter/apps + */ +export function listApps( + client: Client, + req: ListAppsRequest = {}, + options?: RequestOptions, +): Promise> { + return request(() => { + const query = toWire( + { + page: req.page, + }, + schemas.listAppsQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listAppsQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get('openmeter/apps', { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listAppsResponseWire, data) + } + return fromWire(data, schemas.listAppsResponse) + }) + }) +} + +/** + * Get app + * + * Get an installed app. + * + * GET /openmeter/apps/{appId} + */ +export function getApp( + client: Client, + req: GetAppRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + appId: req.appId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.getAppPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.getAppPathParamsWire, pathParams) + } + const path = `openmeter/apps/${(() => { + if (pathParams.appId === undefined) { + throw new Error('missing path parameter: appId') + } + return encodeURIComponent(String(pathParams.appId)) + })()}` + return http(client) + .get(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.getAppResponseWire, data) + } + return fromWire(data, schemas.getAppResponse) + }) + }) +} + +/** + * List app catalog + * + * List available apps. + * + * GET /openmeter/app-catalog + */ +export function listAppCatalog( + client: Client, + req: ListAppCatalogRequest = {}, + options?: RequestOptions, +): Promise> { + return request(() => { + const query = toWire( + { + page: req.page, + }, + schemas.listAppCatalogQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listAppCatalogQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get('openmeter/app-catalog', { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listAppCatalogResponseWire, data) + } + return fromWire(data, schemas.listAppCatalogResponse) + }) + }) +} + +/** + * Get app catalog item by type + * + * Get an app catalog item by type. + * + * GET /openmeter/app-catalog/{appType} + */ +export function getAppCatalogItem( + client: Client, + req: GetAppCatalogItemRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + appType: req.appType, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.getAppCatalogItemPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.getAppCatalogItemPathParamsWire, pathParams) + } + const path = `openmeter/app-catalog/${(() => { + if (pathParams.appType === undefined) { + throw new Error('missing path parameter: appType') + } + return encodeURIComponent(String(pathParams.appType)) + })()}` + return http(client) + .get(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.getAppCatalogItemResponseWire, data) + } + return fromWire(data, schemas.getAppCatalogItemResponse) + }) + }) +} + +/** + * Install app from the catalog + * + * Install an app from the catalog. + * + * POST /openmeter/app-catalog/install + */ +export function installApp( + client: Client, + req: InstallAppRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const body = toWire(req, schemas.installAppBody) + if (client._options.validate) { + assertValid(schemas.installAppBodyWire, body) + } + return http(client) + .post('openmeter/app-catalog/install', { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.installAppResponseWire, data) + } + return fromWire(data, schemas.installAppResponse) + }) + }) +} diff --git a/api/spec/packages/aip-client-javascript/src/funcs/billing.ts b/api/spec/packages/aip-client-javascript/src/funcs/billing.ts new file mode 100644 index 0000000000000000000000000000000000000000..1edc2cd90e28b1735f427bf4f447bb416753b1f0 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/funcs/billing.ts @@ -0,0 +1,211 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client, http } from '../core.js' +import { type Result, type RequestOptions } from '../lib/types.js' +import { request } from '../lib/request.js' +import { toURLSearchParams } from '../lib/encodings.js' +import { toWire, toPathWire, fromWire, assertValid } from '../lib/wire.js' +import * as schemas from '../models/schemas.js' +import type { + ListBillingProfilesRequest, + ListBillingProfilesResponse, + CreateBillingProfileRequest, + CreateBillingProfileResponse, + GetBillingProfileRequest, + GetBillingProfileResponse, + UpdateBillingProfileRequest, + UpdateBillingProfileResponse, + DeleteBillingProfileRequest, + DeleteBillingProfileResponse, +} from '../models/operations/billing.js' + +/** + * List billing profiles + * + * List billing profiles. + * + * GET /openmeter/profiles + */ +export function listBillingProfiles( + client: Client, + req: ListBillingProfilesRequest = {}, + options?: RequestOptions, +): Promise> { + return request(() => { + const query = toWire( + { + page: req.page, + }, + schemas.listBillingProfilesQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listBillingProfilesQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get('openmeter/profiles', { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listBillingProfilesResponseWire, data) + } + return fromWire(data, schemas.listBillingProfilesResponse) + }) + }) +} + +/** + * Create a new billing profile + * + * Create a new billing profile. + * + * Billing profiles contain the settings for billing and controls invoice + * generation. An organization can have multiple billing profiles defined. A + * billing profile is linked to a specific app. This association is established + * during the billing profile's creation and remains immutable. + * + * POST /openmeter/profiles + */ +export function createBillingProfile( + client: Client, + req: CreateBillingProfileRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const body = toWire(req, schemas.createBillingProfileBody) + if (client._options.validate) { + assertValid(schemas.createBillingProfileBodyWire, body) + } + return http(client) + .post('openmeter/profiles', { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.createBillingProfileResponseWire, data) + } + return fromWire(data, schemas.createBillingProfileResponse) + }) + }) +} + +/** + * Get a billing profile + * + * Get a billing profile. + * + * GET /openmeter/profiles/{id} + */ +export function getBillingProfile( + client: Client, + req: GetBillingProfileRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + id: req.id, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.getBillingProfilePathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.getBillingProfilePathParamsWire, pathParams) + } + const path = `openmeter/profiles/${(() => { + if (pathParams.id === undefined) { + throw new Error('missing path parameter: id') + } + return encodeURIComponent(String(pathParams.id)) + })()}` + return http(client) + .get(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.getBillingProfileResponseWire, data) + } + return fromWire(data, schemas.getBillingProfileResponse) + }) + }) +} + +/** + * Update a billing profile + * + * Update a billing profile. + * + * PUT /openmeter/profiles/{id} + */ +export function updateBillingProfile( + client: Client, + req: UpdateBillingProfileRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + id: req.id, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.updateBillingProfilePathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.updateBillingProfilePathParamsWire, pathParams) + } + const path = `openmeter/profiles/${(() => { + if (pathParams.id === undefined) { + throw new Error('missing path parameter: id') + } + return encodeURIComponent(String(pathParams.id)) + })()}` + const body = toWire(req.body, schemas.updateBillingProfileBody) + if (client._options.validate) { + assertValid(schemas.updateBillingProfileBodyWire, body) + } + return http(client) + .put(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.updateBillingProfileResponseWire, data) + } + return fromWire(data, schemas.updateBillingProfileResponse) + }) + }) +} + +/** + * Delete a billing profile + * + * Delete a billing profile. + * + * Only such billing profiles can be deleted that are: + * + * - not the default profile + * - not pinned to any customer using customer overrides + * - only have finalized invoices + * + * DELETE /openmeter/profiles/{id} + */ +export function deleteBillingProfile( + client: Client, + req: DeleteBillingProfileRequest, + options?: RequestOptions, +): Promise> { + return request(async () => { + const pathParamsInput = { + id: req.id, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.deleteBillingProfilePathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.deleteBillingProfilePathParamsWire, pathParams) + } + const path = `openmeter/profiles/${(() => { + if (pathParams.id === undefined) { + throw new Error('missing path parameter: id') + } + return encodeURIComponent(String(pathParams.id)) + })()}` + await http(client).delete(path, options) + }) +} diff --git a/api/spec/packages/aip-client-javascript/src/funcs/currencies.ts b/api/spec/packages/aip-client-javascript/src/funcs/currencies.ts new file mode 100644 index 0000000000000000000000000000000000000000..d7af41d051cc95e5031ec1f5e0c5ad95eccd45ff --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/funcs/currencies.ts @@ -0,0 +1,190 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client, http } from '../core.js' +import { type Result, type RequestOptions } from '../lib/types.js' +import { request } from '../lib/request.js' +import { toURLSearchParams, encodeSort } from '../lib/encodings.js' +import { + toWire, + toPathWire, + fromWire, + assertValid, + toSnakeCase, +} from '../lib/wire.js' +import * as schemas from '../models/schemas.js' +import type { + ListCurrenciesRequest, + ListCurrenciesResponse, + CreateCustomCurrencyRequest, + CreateCustomCurrencyResponse, + ListCostBasesRequest, + ListCostBasesResponse, + CreateCostBasisRequest, + CreateCostBasisResponse, +} from '../models/operations/currencies.js' + +/** + * List currencies + * + * List currencies supported by the billing system. + * + * GET /openmeter/currencies + */ +export function listCurrencies( + client: Client, + req: ListCurrenciesRequest = {}, + options?: RequestOptions, +): Promise> { + return request(() => { + if (client._options.validate && req.sort !== undefined) { + assertValid(schemas.listCurrenciesQueryParams.shape.sort, req.sort) + } + const query = toWire( + { + page: req.page, + sort: encodeSort(req.sort, toSnakeCase), + filter: req.filter, + }, + schemas.listCurrenciesQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listCurrenciesQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get('openmeter/currencies', { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listCurrenciesResponseWire, data) + } + return fromWire(data, schemas.listCurrenciesResponse) + }) + }) +} + +/** + * Create custom currency + * + * Create a custom currency. This operation allows defining your own custom + * currency for billing purposes. + * + * POST /openmeter/currencies/custom + */ +export function createCustomCurrency( + client: Client, + req: CreateCustomCurrencyRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const body = toWire(req, schemas.createCustomCurrencyBody) + if (client._options.validate) { + assertValid(schemas.createCustomCurrencyBodyWire, body) + } + return http(client) + .post('openmeter/currencies/custom', { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.createCustomCurrencyResponseWire, data) + } + return fromWire(data, schemas.createCustomCurrencyResponse) + }) + }) +} + +/** + * List cost bases + * + * List cost bases for a currency. For custom currencies, there can be multiple + * cost bases with different `effective_from` dates. + * + * GET /openmeter/currencies/custom/{currencyId}/cost-bases + */ +export function listCostBases( + client: Client, + req: ListCostBasesRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + currencyId: req.currencyId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.listCostBasesPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.listCostBasesPathParamsWire, pathParams) + } + const path = `openmeter/currencies/custom/${(() => { + if (pathParams.currencyId === undefined) { + throw new Error('missing path parameter: currencyId') + } + return encodeURIComponent(String(pathParams.currencyId)) + })()}/cost-bases` + const query = toWire( + { + filter: req.filter, + page: req.page, + }, + schemas.listCostBasesQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listCostBasesQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get(path, { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listCostBasesResponseWire, data) + } + return fromWire(data, schemas.listCostBasesResponse) + }) + }) +} + +/** + * Create cost basis + * + * Create a cost basis for a currency. + * + * POST /openmeter/currencies/custom/{currencyId}/cost-bases + */ +export function createCostBasis( + client: Client, + req: CreateCostBasisRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + currencyId: req.currencyId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.createCostBasisPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.createCostBasisPathParamsWire, pathParams) + } + const path = `openmeter/currencies/custom/${(() => { + if (pathParams.currencyId === undefined) { + throw new Error('missing path parameter: currencyId') + } + return encodeURIComponent(String(pathParams.currencyId)) + })()}/cost-bases` + const body = toWire(req.body, schemas.createCostBasisBody) + if (client._options.validate) { + assertValid(schemas.createCostBasisBodyWire, body) + } + return http(client) + .post(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.createCostBasisResponseWire, data) + } + return fromWire(data, schemas.createCostBasisResponse) + }) + }) +} diff --git a/api/spec/packages/aip-client-javascript/src/funcs/customers.ts b/api/spec/packages/aip-client-javascript/src/funcs/customers.ts new file mode 100644 index 0000000000000000000000000000000000000000..a58aef6e7d68e5db3d4c14f2dd23e6b6e926fe56 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/funcs/customers.ts @@ -0,0 +1,1012 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client, http } from '../core.js' +import { type Result, type RequestOptions } from '../lib/types.js' +import { request } from '../lib/request.js' +import { toURLSearchParams, encodeSort } from '../lib/encodings.js' +import { + toWire, + toPathWire, + fromWire, + assertValid, + toSnakeCase, +} from '../lib/wire.js' +import * as schemas from '../models/schemas.js' +import type { + CreateCustomerRequest, + CreateCustomerResponse, + GetCustomerRequest, + GetCustomerResponse, + ListCustomersRequest, + ListCustomersResponse, + UpsertCustomerRequest, + UpsertCustomerResponse, + DeleteCustomerRequest, + DeleteCustomerResponse, + GetCustomerBillingRequest, + GetCustomerBillingResponse, + UpdateCustomerBillingRequest, + UpdateCustomerBillingResponse, + UpdateCustomerBillingAppDataRequest, + UpdateCustomerBillingAppDataResponse, + CreateCustomerStripeCheckoutSessionRequest, + CreateCustomerStripeCheckoutSessionResponse, + CreateCustomerStripePortalSessionRequest, + CreateCustomerStripePortalSessionResponse, + CreateCreditGrantRequest, + CreateCreditGrantResponse, + GetCreditGrantRequest, + GetCreditGrantResponse, + ListCreditGrantsRequest, + ListCreditGrantsResponse, + GetCustomerCreditBalanceRequest, + GetCustomerCreditBalanceResponse, + CreateCreditAdjustmentRequest, + CreateCreditAdjustmentResponse, + VoidCreditGrantRequest, + VoidCreditGrantResponse, + UpdateCreditGrantExternalSettlementRequest, + UpdateCreditGrantExternalSettlementResponse, + ListCreditTransactionsRequest, + ListCreditTransactionsResponse, + ListCustomerChargesRequest, + ListCustomerChargesResponse, + CreateCustomerChargesRequest, + CreateCustomerChargesResponse, +} from '../models/operations/customers.js' + +/** + * Create customer + * + * POST /openmeter/customers + */ +export function createCustomer( + client: Client, + req: CreateCustomerRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const body = toWire(req, schemas.createCustomerBody) + if (client._options.validate) { + assertValid(schemas.createCustomerBodyWire, body) + } + return http(client) + .post('openmeter/customers', { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.createCustomerResponseWire, data) + } + return fromWire(data, schemas.createCustomerResponse) + }) + }) +} + +/** + * Get customer + * + * GET /openmeter/customers/{customerId} + */ +export function getCustomer( + client: Client, + req: GetCustomerRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + customerId: req.customerId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.getCustomerPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.getCustomerPathParamsWire, pathParams) + } + const path = `openmeter/customers/${(() => { + if (pathParams.customerId === undefined) { + throw new Error('missing path parameter: customerId') + } + return encodeURIComponent(String(pathParams.customerId)) + })()}` + return http(client) + .get(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.getCustomerResponseWire, data) + } + return fromWire(data, schemas.getCustomerResponse) + }) + }) +} + +/** + * List customers + * + * GET /openmeter/customers + */ +export function listCustomers( + client: Client, + req: ListCustomersRequest = {}, + options?: RequestOptions, +): Promise> { + return request(() => { + if (client._options.validate && req.sort !== undefined) { + assertValid(schemas.listCustomersQueryParams.shape.sort, req.sort) + } + const query = toWire( + { + page: req.page, + sort: encodeSort(req.sort, toSnakeCase), + filter: req.filter, + }, + schemas.listCustomersQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listCustomersQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get('openmeter/customers', { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listCustomersResponseWire, data) + } + return fromWire(data, schemas.listCustomersResponse) + }) + }) +} + +/** + * Upsert customer + * + * PUT /openmeter/customers/{customerId} + */ +export function upsertCustomer( + client: Client, + req: UpsertCustomerRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + customerId: req.customerId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.upsertCustomerPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.upsertCustomerPathParamsWire, pathParams) + } + const path = `openmeter/customers/${(() => { + if (pathParams.customerId === undefined) { + throw new Error('missing path parameter: customerId') + } + return encodeURIComponent(String(pathParams.customerId)) + })()}` + const body = toWire(req.body, schemas.upsertCustomerBody) + if (client._options.validate) { + assertValid(schemas.upsertCustomerBodyWire, body) + } + return http(client) + .put(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.upsertCustomerResponseWire, data) + } + return fromWire(data, schemas.upsertCustomerResponse) + }) + }) +} + +/** + * Delete customer + * + * DELETE /openmeter/customers/{customerId} + */ +export function deleteCustomer( + client: Client, + req: DeleteCustomerRequest, + options?: RequestOptions, +): Promise> { + return request(async () => { + const pathParamsInput = { + customerId: req.customerId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.deleteCustomerPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.deleteCustomerPathParamsWire, pathParams) + } + const path = `openmeter/customers/${(() => { + if (pathParams.customerId === undefined) { + throw new Error('missing path parameter: customerId') + } + return encodeURIComponent(String(pathParams.customerId)) + })()}` + await http(client).delete(path, options) + }) +} + +/** + * Get customer billing data + * + * GET /openmeter/customers/{customerId}/billing + */ +export function getCustomerBilling( + client: Client, + req: GetCustomerBillingRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + customerId: req.customerId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.getCustomerBillingPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.getCustomerBillingPathParamsWire, pathParams) + } + const path = `openmeter/customers/${(() => { + if (pathParams.customerId === undefined) { + throw new Error('missing path parameter: customerId') + } + return encodeURIComponent(String(pathParams.customerId)) + })()}/billing` + return http(client) + .get(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.getCustomerBillingResponseWire, data) + } + return fromWire(data, schemas.getCustomerBillingResponse) + }) + }) +} + +/** + * Update customer billing data + * + * PUT /openmeter/customers/{customerId}/billing + */ +export function updateCustomerBilling( + client: Client, + req: UpdateCustomerBillingRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + customerId: req.customerId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.updateCustomerBillingPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.updateCustomerBillingPathParamsWire, pathParams) + } + const path = `openmeter/customers/${(() => { + if (pathParams.customerId === undefined) { + throw new Error('missing path parameter: customerId') + } + return encodeURIComponent(String(pathParams.customerId)) + })()}/billing` + const body = toWire(req.body, schemas.updateCustomerBillingBody) + if (client._options.validate) { + assertValid(schemas.updateCustomerBillingBodyWire, body) + } + return http(client) + .put(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.updateCustomerBillingResponseWire, data) + } + return fromWire(data, schemas.updateCustomerBillingResponse) + }) + }) +} + +/** + * Update customer billing app data + * + * PUT /openmeter/customers/{customerId}/billing/app-data + */ +export function updateCustomerBillingAppData( + client: Client, + req: UpdateCustomerBillingAppDataRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + customerId: req.customerId, + } + const pathParams = client._options.validate + ? toPathWire( + pathParamsInput, + schemas.updateCustomerBillingAppDataPathParams, + ) + : pathParamsInput + if (client._options.validate) { + assertValid( + schemas.updateCustomerBillingAppDataPathParamsWire, + pathParams, + ) + } + const path = `openmeter/customers/${(() => { + if (pathParams.customerId === undefined) { + throw new Error('missing path parameter: customerId') + } + return encodeURIComponent(String(pathParams.customerId)) + })()}/billing/app-data` + const body = toWire(req.body, schemas.updateCustomerBillingAppDataBody) + if (client._options.validate) { + assertValid(schemas.updateCustomerBillingAppDataBodyWire, body) + } + return http(client) + .put(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.updateCustomerBillingAppDataResponseWire, data) + } + return fromWire(data, schemas.updateCustomerBillingAppDataResponse) + }) + }) +} + +/** + * Create Stripe Checkout Session + * + * Create a [Stripe Checkout Session](https://docs.stripe.com/payments/checkout) + * for the customer. + * + * Creates a Checkout Session for collecting payment method information from + * customers. The session operates in "setup" mode, which collects payment details + * without charging the customer immediately. The collected payment method can be + * used for future subscription billing. + * + * For hosted checkout sessions, redirect customers to the returned URL. For + * embedded sessions, use the client_secret to initialize Stripe.js in your + * application. + * + * POST /openmeter/customers/{customerId}/billing/stripe/checkout-sessions + */ +export function createCustomerStripeCheckoutSession( + client: Client, + req: CreateCustomerStripeCheckoutSessionRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + customerId: req.customerId, + } + const pathParams = client._options.validate + ? toPathWire( + pathParamsInput, + schemas.createCustomerStripeCheckoutSessionPathParams, + ) + : pathParamsInput + if (client._options.validate) { + assertValid( + schemas.createCustomerStripeCheckoutSessionPathParamsWire, + pathParams, + ) + } + const path = `openmeter/customers/${(() => { + if (pathParams.customerId === undefined) { + throw new Error('missing path parameter: customerId') + } + return encodeURIComponent(String(pathParams.customerId)) + })()}/billing/stripe/checkout-sessions` + const body = toWire( + req.body, + schemas.createCustomerStripeCheckoutSessionBody, + ) + if (client._options.validate) { + assertValid(schemas.createCustomerStripeCheckoutSessionBodyWire, body) + } + return http(client) + .post(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid( + schemas.createCustomerStripeCheckoutSessionResponseWire, + data, + ) + } + return fromWire( + data, + schemas.createCustomerStripeCheckoutSessionResponse, + ) + }) + }) +} + +/** + * Create Stripe customer portal session + * + * Create Stripe Customer Portal Session. + * + * Useful to redirect the customer to the Stripe Customer Portal to manage their + * payment methods, change their billing address and access their invoice history. + * Only returns URL if the customer billing profile is linked to a stripe app and + * customer. + * + * POST /openmeter/customers/{customerId}/billing/stripe/portal-sessions + */ +export function createCustomerStripePortalSession( + client: Client, + req: CreateCustomerStripePortalSessionRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + customerId: req.customerId, + } + const pathParams = client._options.validate + ? toPathWire( + pathParamsInput, + schemas.createCustomerStripePortalSessionPathParams, + ) + : pathParamsInput + if (client._options.validate) { + assertValid( + schemas.createCustomerStripePortalSessionPathParamsWire, + pathParams, + ) + } + const path = `openmeter/customers/${(() => { + if (pathParams.customerId === undefined) { + throw new Error('missing path parameter: customerId') + } + return encodeURIComponent(String(pathParams.customerId)) + })()}/billing/stripe/portal-sessions` + const body = toWire(req.body, schemas.createCustomerStripePortalSessionBody) + if (client._options.validate) { + assertValid(schemas.createCustomerStripePortalSessionBodyWire, body) + } + return http(client) + .post(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid( + schemas.createCustomerStripePortalSessionResponseWire, + data, + ) + } + return fromWire(data, schemas.createCustomerStripePortalSessionResponse) + }) + }) +} + +/** + * Create a new credit grant + * + * Create a new credit grant. A credit grant represents an allocation of prepaid + * credits to a customer. + * + * POST /openmeter/customers/{customerId}/credits/grants + */ +export function createCreditGrant( + client: Client, + req: CreateCreditGrantRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + customerId: req.customerId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.createCreditGrantPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.createCreditGrantPathParamsWire, pathParams) + } + const path = `openmeter/customers/${(() => { + if (pathParams.customerId === undefined) { + throw new Error('missing path parameter: customerId') + } + return encodeURIComponent(String(pathParams.customerId)) + })()}/credits/grants` + const body = toWire(req.body, schemas.createCreditGrantBody) + if (client._options.validate) { + assertValid(schemas.createCreditGrantBodyWire, body) + } + return http(client) + .post(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.createCreditGrantResponseWire, data) + } + return fromWire(data, schemas.createCreditGrantResponse) + }) + }) +} + +/** + * Get a credit grant + * + * Get a credit grant. + * + * GET /openmeter/customers/{customerId}/credits/grants/{creditGrantId} + */ +export function getCreditGrant( + client: Client, + req: GetCreditGrantRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + customerId: req.customerId, + creditGrantId: req.creditGrantId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.getCreditGrantPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.getCreditGrantPathParamsWire, pathParams) + } + const path = `openmeter/customers/${(() => { + if (pathParams.customerId === undefined) { + throw new Error('missing path parameter: customerId') + } + return encodeURIComponent(String(pathParams.customerId)) + })()}/credits/grants/${(() => { + if (pathParams.creditGrantId === undefined) { + throw new Error('missing path parameter: creditGrantId') + } + return encodeURIComponent(String(pathParams.creditGrantId)) + })()}` + return http(client) + .get(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.getCreditGrantResponseWire, data) + } + return fromWire(data, schemas.getCreditGrantResponse) + }) + }) +} + +/** + * List credit grants + * + * List credit grants. + * + * GET /openmeter/customers/{customerId}/credits/grants + */ +export function listCreditGrants( + client: Client, + req: ListCreditGrantsRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + customerId: req.customerId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.listCreditGrantsPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.listCreditGrantsPathParamsWire, pathParams) + } + const path = `openmeter/customers/${(() => { + if (pathParams.customerId === undefined) { + throw new Error('missing path parameter: customerId') + } + return encodeURIComponent(String(pathParams.customerId)) + })()}/credits/grants` + const query = toWire( + { + page: req.page, + filter: req.filter, + }, + schemas.listCreditGrantsQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listCreditGrantsQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get(path, { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listCreditGrantsResponseWire, data) + } + return fromWire(data, schemas.listCreditGrantsResponse) + }) + }) +} + +/** + * Get a customer's credit balance + * + * Get a credit balance. + * + * GET /openmeter/customers/{customerId}/credits/balance + */ +export function getCustomerCreditBalance( + client: Client, + req: GetCustomerCreditBalanceRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + customerId: req.customerId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.getCustomerCreditBalancePathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.getCustomerCreditBalancePathParamsWire, pathParams) + } + const path = `openmeter/customers/${(() => { + if (pathParams.customerId === undefined) { + throw new Error('missing path parameter: customerId') + } + return encodeURIComponent(String(pathParams.customerId)) + })()}/credits/balance` + const query = toWire( + { + timestamp: req.timestamp, + filter: req.filter, + }, + schemas.getCustomerCreditBalanceQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.getCustomerCreditBalanceQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get(path, { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.getCustomerCreditBalanceResponseWire, data) + } + return fromWire(data, schemas.getCustomerCreditBalanceResponse) + }) + }) +} + +/** + * Create a credit adjustment + * + * A credit adjustment can be used to make manual adjustments to a customer's + * credit balance. + * + * Supported use-cases: + * + * - Usage correction + * + * POST /openmeter/customers/{customerId}/credits/adjustments + */ +export function createCreditAdjustment( + client: Client, + req: CreateCreditAdjustmentRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + customerId: req.customerId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.createCreditAdjustmentPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.createCreditAdjustmentPathParamsWire, pathParams) + } + const path = `openmeter/customers/${(() => { + if (pathParams.customerId === undefined) { + throw new Error('missing path parameter: customerId') + } + return encodeURIComponent(String(pathParams.customerId)) + })()}/credits/adjustments` + const body = toWire(req.body, schemas.createCreditAdjustmentBody) + if (client._options.validate) { + assertValid(schemas.createCreditAdjustmentBodyWire, body) + } + return http(client) + .post(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.createCreditAdjustmentResponseWire, data) + } + return fromWire(data, schemas.createCreditAdjustmentResponse) + }) + }) +} + +/** + * Void credit grant + * + * Void a credit grant, forfeiting the remaining unused balance. + * + * Voiding is a forward-looking, irreversible operation. Credits already consumed + * by usage remain unaffected — only the remaining balance is forfeited. The grant + * reads as `voided` status afterwards. Payment state is not adjusted when + * `payment_adjustment` is `none`, so invoice-backed or externally collected + * payments may still collect the original amount. Only `active` grants can be + * voided; voiding a pending, expired, or fully consumed grant returns a conflict. + * Retrying a successful void is an idempotent success. + * + * POST /openmeter/customers/{customerId}/credits/grants/{creditGrantId}/void + */ +export function voidCreditGrant( + client: Client, + req: VoidCreditGrantRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + customerId: req.customerId, + creditGrantId: req.creditGrantId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.voidCreditGrantPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.voidCreditGrantPathParamsWire, pathParams) + } + const path = `openmeter/customers/${(() => { + if (pathParams.customerId === undefined) { + throw new Error('missing path parameter: customerId') + } + return encodeURIComponent(String(pathParams.customerId)) + })()}/credits/grants/${(() => { + if (pathParams.creditGrantId === undefined) { + throw new Error('missing path parameter: creditGrantId') + } + return encodeURIComponent(String(pathParams.creditGrantId)) + })()}/void` + const body = toWire(req.body, schemas.voidCreditGrantBody) + if (client._options.validate) { + assertValid(schemas.voidCreditGrantBodyWire, body) + } + return http(client) + .post(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.voidCreditGrantResponseWire, data) + } + return fromWire(data, schemas.voidCreditGrantResponse) + }) + }) +} + +/** + * Update credit grant external settlement status + * + * Update the payment settlement status of an externally funded credit grant. + * + * Use this endpoint to synchronize the payment state of an external payment with + * the system so that revenue recognition and credit availability work as expected. + * + * POST /openmeter/customers/{customerId}/credits/grants/{creditGrantId}/settlement/external + */ +export function updateCreditGrantExternalSettlement( + client: Client, + req: UpdateCreditGrantExternalSettlementRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + customerId: req.customerId, + creditGrantId: req.creditGrantId, + } + const pathParams = client._options.validate + ? toPathWire( + pathParamsInput, + schemas.updateCreditGrantExternalSettlementPathParams, + ) + : pathParamsInput + if (client._options.validate) { + assertValid( + schemas.updateCreditGrantExternalSettlementPathParamsWire, + pathParams, + ) + } + const path = `openmeter/customers/${(() => { + if (pathParams.customerId === undefined) { + throw new Error('missing path parameter: customerId') + } + return encodeURIComponent(String(pathParams.customerId)) + })()}/credits/grants/${(() => { + if (pathParams.creditGrantId === undefined) { + throw new Error('missing path parameter: creditGrantId') + } + return encodeURIComponent(String(pathParams.creditGrantId)) + })()}/settlement/external` + const body = toWire( + req.body, + schemas.updateCreditGrantExternalSettlementBody, + ) + if (client._options.validate) { + assertValid(schemas.updateCreditGrantExternalSettlementBodyWire, body) + } + return http(client) + .post(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid( + schemas.updateCreditGrantExternalSettlementResponseWire, + data, + ) + } + return fromWire( + data, + schemas.updateCreditGrantExternalSettlementResponse, + ) + }) + }) +} + +/** + * List credit transactions + * + * List credit transactions for a customer. + * + * Returns an immutable, chronological record of credit movements: funded credits + * and consumed credits. Transactions are returned in reverse chronological order + * by default. + * + * GET /openmeter/customers/{customerId}/credits/transactions + */ +export function listCreditTransactions( + client: Client, + req: ListCreditTransactionsRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + customerId: req.customerId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.listCreditTransactionsPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.listCreditTransactionsPathParamsWire, pathParams) + } + const path = `openmeter/customers/${(() => { + if (pathParams.customerId === undefined) { + throw new Error('missing path parameter: customerId') + } + return encodeURIComponent(String(pathParams.customerId)) + })()}/credits/transactions` + const query = toWire( + { + page: req.page, + filter: req.filter, + }, + schemas.listCreditTransactionsQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listCreditTransactionsQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get(path, { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listCreditTransactionsResponseWire, data) + } + return fromWire(data, schemas.listCreditTransactionsResponse) + }) + }) +} + +/** + * List customer charges + * + * List customer charges. + * + * Returns the customer's charges that are represented as either flat fee or + * usage-based charges. + * + * GET /openmeter/customers/{customerId}/charges + */ +export function listCustomerCharges( + client: Client, + req: ListCustomerChargesRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + customerId: req.customerId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.listCustomerChargesPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.listCustomerChargesPathParamsWire, pathParams) + } + const path = `openmeter/customers/${(() => { + if (pathParams.customerId === undefined) { + throw new Error('missing path parameter: customerId') + } + return encodeURIComponent(String(pathParams.customerId)) + })()}/charges` + if (client._options.validate && req.sort !== undefined) { + assertValid(schemas.listCustomerChargesQueryParams.shape.sort, req.sort) + } + const query = toWire( + { + page: req.page, + sort: encodeSort(req.sort, toSnakeCase), + filter: req.filter, + expand: req.expand, + }, + schemas.listCustomerChargesQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listCustomerChargesQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get(path, { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listCustomerChargesResponseWire, data) + } + return fromWire(data, schemas.listCustomerChargesResponse) + }) + }) +} + +/** + * Create customer charge + * + * Create customer charge. + * + * POST /openmeter/customers/{customerId}/charges + */ +export function createCustomerCharges( + client: Client, + req: CreateCustomerChargesRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + customerId: req.customerId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.createCustomerChargesPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.createCustomerChargesPathParamsWire, pathParams) + } + const path = `openmeter/customers/${(() => { + if (pathParams.customerId === undefined) { + throw new Error('missing path parameter: customerId') + } + return encodeURIComponent(String(pathParams.customerId)) + })()}/charges` + const body = toWire(req.body, schemas.createCustomerChargesBody) + if (client._options.validate) { + assertValid(schemas.createCustomerChargesBodyWire, body) + } + return http(client) + .post(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.createCustomerChargesResponseWire, data) + } + return fromWire(data, schemas.createCustomerChargesResponse) + }) + }) +} diff --git a/api/spec/packages/aip-client-javascript/src/funcs/defaults.ts b/api/spec/packages/aip-client-javascript/src/funcs/defaults.ts new file mode 100644 index 0000000000000000000000000000000000000000..97d59b1f44fb34ca67ec53291e2f744e7d231161 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/funcs/defaults.ts @@ -0,0 +1,66 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client, http } from '../core.js' +import { type Result, type RequestOptions } from '../lib/types.js' +import { request } from '../lib/request.js' +import { toWire, fromWire, assertValid } from '../lib/wire.js' +import * as schemas from '../models/schemas.js' +import type { + GetOrganizationDefaultTaxCodesRequest, + GetOrganizationDefaultTaxCodesResponse, + UpdateOrganizationDefaultTaxCodesRequest, + UpdateOrganizationDefaultTaxCodesResponse, +} from '../models/operations/defaults.js' + +/** + * Get organization default tax codes + * + * GET /openmeter/defaults/tax-codes + */ +export function getOrganizationDefaultTaxCodes( + client: Client, + req: GetOrganizationDefaultTaxCodesRequest, + options?: RequestOptions, +): Promise> { + return request(() => + http(client) + .get('openmeter/defaults/tax-codes', options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.getOrganizationDefaultTaxCodesResponseWire, data) + } + return fromWire(data, schemas.getOrganizationDefaultTaxCodesResponse) + }), + ) +} + +/** + * Update organization default tax codes + * + * PUT /openmeter/defaults/tax-codes + */ +export function updateOrganizationDefaultTaxCodes( + client: Client, + req: UpdateOrganizationDefaultTaxCodesRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const body = toWire(req, schemas.updateOrganizationDefaultTaxCodesBody) + if (client._options.validate) { + assertValid(schemas.updateOrganizationDefaultTaxCodesBodyWire, body) + } + return http(client) + .put('openmeter/defaults/tax-codes', { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid( + schemas.updateOrganizationDefaultTaxCodesResponseWire, + data, + ) + } + return fromWire(data, schemas.updateOrganizationDefaultTaxCodesResponse) + }) + }) +} diff --git a/api/spec/packages/aip-client-javascript/src/funcs/entitlements.ts b/api/spec/packages/aip-client-javascript/src/funcs/entitlements.ts new file mode 100644 index 0000000000000000000000000000000000000000..3927baddf2f2127714417494bcfa0cbd752f75ad --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/funcs/entitlements.ts @@ -0,0 +1,55 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client, http } from '../core.js' +import { type Result, type RequestOptions } from '../lib/types.js' +import { request } from '../lib/request.js' +import { toPathWire, fromWire, assertValid } from '../lib/wire.js' +import * as schemas from '../models/schemas.js' +import type { + ListCustomerEntitlementAccessRequest, + ListCustomerEntitlementAccessResponse, +} from '../models/operations/entitlements.js' + +/** + * List customer entitlement access + * + * GET /openmeter/customers/{customerId}/entitlement-access + */ +export function listCustomerEntitlementAccess( + client: Client, + req: ListCustomerEntitlementAccessRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + customerId: req.customerId, + } + const pathParams = client._options.validate + ? toPathWire( + pathParamsInput, + schemas.listCustomerEntitlementAccessPathParams, + ) + : pathParamsInput + if (client._options.validate) { + assertValid( + schemas.listCustomerEntitlementAccessPathParamsWire, + pathParams, + ) + } + const path = `openmeter/customers/${(() => { + if (pathParams.customerId === undefined) { + throw new Error('missing path parameter: customerId') + } + return encodeURIComponent(String(pathParams.customerId)) + })()}/entitlement-access` + return http(client) + .get(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listCustomerEntitlementAccessResponseWire, data) + } + return fromWire(data, schemas.listCustomerEntitlementAccessResponse) + }) + }) +} diff --git a/api/spec/packages/aip-client-javascript/src/funcs/events.ts b/api/spec/packages/aip-client-javascript/src/funcs/events.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee206831690c5f1c041e0735a604b7b7f9e70f2f --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/funcs/events.ts @@ -0,0 +1,75 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client, http } from '../core.js' +import { type Result, type RequestOptions } from '../lib/types.js' +import { request } from '../lib/request.js' +import { toURLSearchParams, encodeSort } from '../lib/encodings.js' +import { toWire, fromWire, assertValid, toSnakeCase } from '../lib/wire.js' +import * as schemas from '../models/schemas.js' +import type { + ListMeteringEventsRequest, + ListMeteringEventsResponse, + IngestMeteringEventsRequest, + IngestMeteringEventsResponse, +} from '../models/operations/events.js' + +/** + * List metering events + * + * List ingested events. + * + * GET /openmeter/events + */ +export function listMeteringEvents( + client: Client, + req: ListMeteringEventsRequest = {}, + options?: RequestOptions, +): Promise> { + return request(() => { + if (client._options.validate && req.sort !== undefined) { + assertValid(schemas.listMeteringEventsQueryParams.shape.sort, req.sort) + } + const query = toWire( + { + page: req.page, + filter: req.filter, + sort: encodeSort(req.sort, toSnakeCase), + }, + schemas.listMeteringEventsQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listMeteringEventsQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get('openmeter/events', { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listMeteringEventsResponseWire, data) + } + return fromWire(data, schemas.listMeteringEventsResponse) + }) + }) +} + +/** + * Ingest metering events + * + * Ingests an event or batch of events following the CloudEvents specification. + * + * POST /openmeter/events + */ +export function ingestMeteringEvents( + client: Client, + req: IngestMeteringEventsRequest, + options?: RequestOptions, +): Promise> { + return request(async () => { + const body = toWire(req, schemas.ingestMeteringEventsBody) + if (client._options.validate) { + assertValid(schemas.ingestMeteringEventsBodyWire, body) + } + await http(client).post('openmeter/events', { ...options, json: body }) + }) +} diff --git a/api/spec/packages/aip-client-javascript/src/funcs/features.ts b/api/spec/packages/aip-client-javascript/src/funcs/features.ts new file mode 100644 index 0000000000000000000000000000000000000000..1817610c6f4a1e598ee281211db22884ff800aa3 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/funcs/features.ts @@ -0,0 +1,257 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client, http } from '../core.js' +import { type Result, type RequestOptions } from '../lib/types.js' +import { request } from '../lib/request.js' +import { toURLSearchParams, encodeSort } from '../lib/encodings.js' +import { + toWire, + toPathWire, + fromWire, + assertValid, + toSnakeCase, +} from '../lib/wire.js' +import * as schemas from '../models/schemas.js' +import type { + ListFeaturesRequest, + ListFeaturesResponse, + CreateFeatureRequest, + CreateFeatureResponse, + GetFeatureRequest, + GetFeatureResponse, + UpdateFeatureRequest, + UpdateFeatureResponse, + DeleteFeatureRequest, + DeleteFeatureResponse, + QueryFeatureCostRequest, + QueryFeatureCostResponse, +} from '../models/operations/features.js' + +/** + * List features + * + * List all features. + * + * GET /openmeter/features + */ +export function listFeatures( + client: Client, + req: ListFeaturesRequest = {}, + options?: RequestOptions, +): Promise> { + return request(() => { + if (client._options.validate && req.sort !== undefined) { + assertValid(schemas.listFeaturesQueryParams.shape.sort, req.sort) + } + const query = toWire( + { + page: req.page, + sort: encodeSort(req.sort, toSnakeCase), + filter: req.filter, + }, + schemas.listFeaturesQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listFeaturesQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get('openmeter/features', { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listFeaturesResponseWire, data) + } + return fromWire(data, schemas.listFeaturesResponse) + }) + }) +} + +/** + * Create feature + * + * Create a feature. + * + * POST /openmeter/features + */ +export function createFeature( + client: Client, + req: CreateFeatureRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const body = toWire(req, schemas.createFeatureBody) + if (client._options.validate) { + assertValid(schemas.createFeatureBodyWire, body) + } + return http(client) + .post('openmeter/features', { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.createFeatureResponseWire, data) + } + return fromWire(data, schemas.createFeatureResponse) + }) + }) +} + +/** + * Get feature + * + * Get a feature by id. + * + * GET /openmeter/features/{featureId} + */ +export function getFeature( + client: Client, + req: GetFeatureRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + featureId: req.featureId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.getFeaturePathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.getFeaturePathParamsWire, pathParams) + } + const path = `openmeter/features/${(() => { + if (pathParams.featureId === undefined) { + throw new Error('missing path parameter: featureId') + } + return encodeURIComponent(String(pathParams.featureId)) + })()}` + return http(client) + .get(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.getFeatureResponseWire, data) + } + return fromWire(data, schemas.getFeatureResponse) + }) + }) +} + +/** + * Update feature + * + * Update a feature by id. Currently only the unit_cost field can be updated. + * + * PATCH /openmeter/features/{featureId} + */ +export function updateFeature( + client: Client, + req: UpdateFeatureRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + featureId: req.featureId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.updateFeaturePathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.updateFeaturePathParamsWire, pathParams) + } + const path = `openmeter/features/${(() => { + if (pathParams.featureId === undefined) { + throw new Error('missing path parameter: featureId') + } + return encodeURIComponent(String(pathParams.featureId)) + })()}` + const body = toWire(req.body, schemas.updateFeatureBody) + if (client._options.validate) { + assertValid(schemas.updateFeatureBodyWire, body) + } + return http(client) + .patch(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.updateFeatureResponseWire, data) + } + return fromWire(data, schemas.updateFeatureResponse) + }) + }) +} + +/** + * Delete feature + * + * Delete a feature by id. + * + * DELETE /openmeter/features/{featureId} + */ +export function deleteFeature( + client: Client, + req: DeleteFeatureRequest, + options?: RequestOptions, +): Promise> { + return request(async () => { + const pathParamsInput = { + featureId: req.featureId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.deleteFeaturePathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.deleteFeaturePathParamsWire, pathParams) + } + const path = `openmeter/features/${(() => { + if (pathParams.featureId === undefined) { + throw new Error('missing path parameter: featureId') + } + return encodeURIComponent(String(pathParams.featureId)) + })()}` + await http(client).delete(path, options) + }) +} + +/** + * Query feature cost + * + * Query the cost of a feature. + * + * POST /openmeter/features/{featureId}/cost/query + */ +export function queryFeatureCost( + client: Client, + req: QueryFeatureCostRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + featureId: req.featureId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.queryFeatureCostPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.queryFeatureCostPathParamsWire, pathParams) + } + const path = `openmeter/features/${(() => { + if (pathParams.featureId === undefined) { + throw new Error('missing path parameter: featureId') + } + return encodeURIComponent(String(pathParams.featureId)) + })()}/cost/query` + const body = toWire(req.body, schemas.queryFeatureCostBody) + if (client._options.validate) { + assertValid(schemas.queryFeatureCostBodyWire, body) + } + return http(client) + .post(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.queryFeatureCostResponseWire, data) + } + return fromWire(data, schemas.queryFeatureCostResponse) + }) + }) +} diff --git a/api/spec/packages/aip-client-javascript/src/funcs/governance.ts b/api/spec/packages/aip-client-javascript/src/funcs/governance.ts new file mode 100644 index 0000000000000000000000000000000000000000..fca8603d442e49982cce668fe5e569448ca068f3 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/funcs/governance.ts @@ -0,0 +1,62 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client, http } from '../core.js' +import { type Result, type RequestOptions } from '../lib/types.js' +import { request } from '../lib/request.js' +import { toURLSearchParams } from '../lib/encodings.js' +import { toWire, fromWire, assertValid } from '../lib/wire.js' +import * as schemas from '../models/schemas.js' +import type { + QueryGovernanceAccessRequest, + QueryGovernanceAccessResponse, +} from '../models/operations/governance.js' + +/** + * Query governance access + * + * Query feature access for a list of customers. + * + * The endpoint resolves each provided identifier to a customer and returns the + * access status for the requested features, plus optional credit balance + * availability. + * + * _Designed to be called on a fixed refresh interval and the query response is + * intended to be cached._ + * + * POST /openmeter/governance/query + */ +export function queryGovernanceAccess( + client: Client, + req: QueryGovernanceAccessRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const body = toWire(req.body, schemas.queryGovernanceAccessBody) + if (client._options.validate) { + assertValid(schemas.queryGovernanceAccessBodyWire, body) + } + const query = toWire( + { + page: req.page, + }, + schemas.queryGovernanceAccessQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.queryGovernanceAccessQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .post('openmeter/governance/query', { + ...options, + searchParams, + json: body, + }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.queryGovernanceAccessResponseWire, data) + } + return fromWire(data, schemas.queryGovernanceAccessResponse) + }) + }) +} diff --git a/api/spec/packages/aip-client-javascript/src/funcs/index.ts b/api/spec/packages/aip-client-javascript/src/funcs/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..ac12b17defc814bb861cb440fe7fa5480f7d6806 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/funcs/index.ts @@ -0,0 +1,19 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +export * from './events.js' +export * from './meters.js' +export * from './customers.js' +export * from './entitlements.js' +export * from './subscriptions.js' +export * from './apps.js' +export * from './billing.js' +export * from './invoices.js' +export * from './tax.js' +export * from './currencies.js' +export * from './features.js' +export * from './llmCost.js' +export * from './plans.js' +export * from './addons.js' +export * from './planAddons.js' +export * from './defaults.js' +export * from './governance.js' diff --git a/api/spec/packages/aip-client-javascript/src/funcs/invoices.ts b/api/spec/packages/aip-client-javascript/src/funcs/invoices.ts new file mode 100644 index 0000000000000000000000000000000000000000..b15de36173ca11c4a0a91c339e5d83480b165a81 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/funcs/invoices.ts @@ -0,0 +1,389 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client, http } from '../core.js' +import { type Result, type RequestOptions } from '../lib/types.js' +import { request } from '../lib/request.js' +import { toURLSearchParams, encodeSort } from '../lib/encodings.js' +import { + toWire, + toPathWire, + fromWire, + assertValid, + toSnakeCase, +} from '../lib/wire.js' +import * as schemas from '../models/schemas.js' +import type { + ListInvoicesRequest, + ListInvoicesResponse, + GetInvoiceRequest, + GetInvoiceResponse, + UpdateInvoiceRequest, + UpdateInvoiceResponse, + DeleteInvoiceRequest, + DeleteInvoiceResponse, + AdvanceInvoiceRequest, + AdvanceInvoiceResponse, + ApproveInvoiceRequest, + ApproveInvoiceResponse, + RetryInvoiceRequest, + RetryInvoiceResponse, + SnapshotQuantitiesInvoiceRequest, + SnapshotQuantitiesInvoiceResponse, +} from '../models/operations/invoices.js' + +/** + * List billing invoices + * + * List billing invoices. + * + * Returns a page of invoices. Gathering invoices are never included. Use `filter` + * to narrow by status, customer, dates, or service period start. Use `sort` to + * control ordering. + * + * GET /openmeter/billing/invoices + */ +export function listInvoices( + client: Client, + req: ListInvoicesRequest = {}, + options?: RequestOptions, +): Promise> { + return request(() => { + if (client._options.validate && req.sort !== undefined) { + assertValid(schemas.listInvoicesQueryParams.shape.sort, req.sort) + } + const query = toWire( + { + page: req.page, + sort: encodeSort(req.sort, toSnakeCase), + filter: req.filter, + }, + schemas.listInvoicesQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listInvoicesQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get('openmeter/billing/invoices', { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listInvoicesResponseWire, data) + } + return fromWire(data, schemas.listInvoicesResponse) + }) + }) +} + +/** + * Get a billing invoice + * + * Get a billing invoice by ID. + * + * Returns the full invoice resource including line items, status details, totals, + * and workflow configuration snapshot. + * + * GET /openmeter/billing/invoices/{invoiceId} + */ +export function getInvoice( + client: Client, + req: GetInvoiceRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + invoiceId: req.invoiceId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.getInvoicePathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.getInvoicePathParamsWire, pathParams) + } + const path = `openmeter/billing/invoices/${(() => { + if (pathParams.invoiceId === undefined) { + throw new Error('missing path parameter: invoiceId') + } + return encodeURIComponent(String(pathParams.invoiceId)) + })()}` + return http(client) + .get(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.getInvoiceResponseWire, data) + } + return fromWire(data, schemas.getInvoiceResponse) + }) + }) +} + +/** + * Update a billing invoice + * + * Update a billing invoice. + * + * Only the mutable fields of the invoice can be edited: description, labels, + * supplier, customer, workflow settings, and top-level lines. Top-level lines are + * matched by `id`; lines without an `id` are created, and existing lines omitted + * from `lines` are deleted. Detailed (child) lines are always computed and cannot + * be edited directly. Only invoices in draft status can be updated. + * + * PUT /openmeter/billing/invoices/{invoiceId} + */ +export function updateInvoice( + client: Client, + req: UpdateInvoiceRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + invoiceId: req.invoiceId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.updateInvoicePathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.updateInvoicePathParamsWire, pathParams) + } + const path = `openmeter/billing/invoices/${(() => { + if (pathParams.invoiceId === undefined) { + throw new Error('missing path parameter: invoiceId') + } + return encodeURIComponent(String(pathParams.invoiceId)) + })()}` + const body = toWire(req.body, schemas.updateInvoiceBody) + if (client._options.validate) { + assertValid(schemas.updateInvoiceBodyWire, body) + } + return http(client) + .put(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.updateInvoiceResponseWire, data) + } + return fromWire(data, schemas.updateInvoiceResponse) + }) + }) +} + +/** + * Delete a billing invoice + * + * Delete a billing invoice. + * + * Only standard invoices in draft status can be deleted. Deleting an invoice will + * also delete all associated line items and workflow configuration. + * + * DELETE /openmeter/billing/invoices/{invoiceId} + */ +export function deleteInvoice( + client: Client, + req: DeleteInvoiceRequest, + options?: RequestOptions, +): Promise> { + return request(async () => { + const pathParamsInput = { + invoiceId: req.invoiceId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.deleteInvoicePathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.deleteInvoicePathParamsWire, pathParams) + } + const path = `openmeter/billing/invoices/${(() => { + if (pathParams.invoiceId === undefined) { + throw new Error('missing path parameter: invoiceId') + } + return encodeURIComponent(String(pathParams.invoiceId)) + })()}` + await http(client).delete(path, options) + }) +} + +/** + * Advance billing invoice's next status + * + * Advance a billing invoice. + * + * Advances the invoice to the next workflow state. The next state is determined by + * the invoice's current status and workflow configuration. Only invoices in draft + * or issued status can be advanced. + * + * POST /openmeter/billing/invoices/{invoiceId}/advance + */ +export function advanceInvoice( + client: Client, + req: AdvanceInvoiceRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + invoiceId: req.invoiceId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.advanceInvoicePathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.advanceInvoicePathParamsWire, pathParams) + } + const path = `openmeter/billing/invoices/${(() => { + if (pathParams.invoiceId === undefined) { + throw new Error('missing path parameter: invoiceId') + } + return encodeURIComponent(String(pathParams.invoiceId)) + })()}/advance` + return http(client) + .post(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.advanceInvoiceResponseWire, data) + } + return fromWire(data, schemas.advanceInvoiceResponse) + }) + }) +} + +/** + * Send the invoice to the customer + * + * Approve a billing invoice. + * + * This call instantly sends the invoice to the customer using the configured + * billing profile app. + * + * This call is valid in two invoice statuses: + * + * - draft: the invoice will be sent to the customer, the invoice state becomes + * issued + * - manual_approval_needed: the invoice will be sent to the customer, the invoice + * state becomes issued + * + * POST /openmeter/billing/invoices/{invoiceId}/approve + */ +export function approveInvoice( + client: Client, + req: ApproveInvoiceRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + invoiceId: req.invoiceId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.approveInvoicePathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.approveInvoicePathParamsWire, pathParams) + } + const path = `openmeter/billing/invoices/${(() => { + if (pathParams.invoiceId === undefined) { + throw new Error('missing path parameter: invoiceId') + } + return encodeURIComponent(String(pathParams.invoiceId)) + })()}/approve` + return http(client) + .post(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.approveInvoiceResponseWire, data) + } + return fromWire(data, schemas.approveInvoiceResponse) + }) + }) +} + +/** + * Retry advancing the invoice after a failed attempt + * + * Retry sending a billing invoice. + * + * Retry advancing the invoice after a failed attempt. + * + * The action can be called when the invoice's statusDetails' actions field contain + * the "retry" action. + * + * POST /openmeter/billing/invoices/{invoiceId}/retry + */ +export function retryInvoice( + client: Client, + req: RetryInvoiceRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + invoiceId: req.invoiceId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.retryInvoicePathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.retryInvoicePathParamsWire, pathParams) + } + const path = `openmeter/billing/invoices/${(() => { + if (pathParams.invoiceId === undefined) { + throw new Error('missing path parameter: invoiceId') + } + return encodeURIComponent(String(pathParams.invoiceId)) + })()}/retry` + return http(client) + .post(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.retryInvoiceResponseWire, data) + } + return fromWire(data, schemas.retryInvoiceResponse) + }) + }) +} + +/** + * Snapshot quantities for usage based line items + * + * Snapshot quantities for usage-based line items. + * + * This call will snapshot the quantities for all usage based line items in the + * invoice. + * + * This call is only valid in draft.waiting_for_collection status, where the + * collection period can be skipped using this action. + * + * POST /openmeter/billing/invoices/{invoiceId}/snapshot-quantities + */ +export function snapshotQuantitiesInvoice( + client: Client, + req: SnapshotQuantitiesInvoiceRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + invoiceId: req.invoiceId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.snapshotQuantitiesInvoicePathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.snapshotQuantitiesInvoicePathParamsWire, pathParams) + } + const path = `openmeter/billing/invoices/${(() => { + if (pathParams.invoiceId === undefined) { + throw new Error('missing path parameter: invoiceId') + } + return encodeURIComponent(String(pathParams.invoiceId)) + })()}/snapshot-quantities` + return http(client) + .post(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.snapshotQuantitiesInvoiceResponseWire, data) + } + return fromWire(data, schemas.snapshotQuantitiesInvoiceResponse) + }) + }) +} diff --git a/api/spec/packages/aip-client-javascript/src/funcs/llmCost.ts b/api/spec/packages/aip-client-javascript/src/funcs/llmCost.ts new file mode 100644 index 0000000000000000000000000000000000000000..ab97b94ab86876a502cab4a1457ad2a71261c6a4 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/funcs/llmCost.ts @@ -0,0 +1,204 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client, http } from '../core.js' +import { type Result, type RequestOptions } from '../lib/types.js' +import { request } from '../lib/request.js' +import { toURLSearchParams, encodeSort } from '../lib/encodings.js' +import { + toWire, + toPathWire, + fromWire, + assertValid, + toSnakeCase, +} from '../lib/wire.js' +import * as schemas from '../models/schemas.js' +import type { + ListLlmCostPricesRequest, + ListLlmCostPricesResponse, + GetLlmCostPriceRequest, + GetLlmCostPriceResponse, + ListLlmCostOverridesRequest, + ListLlmCostOverridesResponse, + CreateLlmCostOverrideRequest, + CreateLlmCostOverrideResponse, + DeleteLlmCostOverrideRequest, + DeleteLlmCostOverrideResponse, +} from '../models/operations/llmCost.js' + +/** + * List LLM cost prices + * + * List global LLM cost prices. Returns prices with overrides applied if any. + * + * GET /openmeter/llm-cost/prices + */ +export function listLlmCostPrices( + client: Client, + req: ListLlmCostPricesRequest = {}, + options?: RequestOptions, +): Promise> { + return request(() => { + if (client._options.validate && req.sort !== undefined) { + assertValid(schemas.listLlmCostPricesQueryParams.shape.sort, req.sort) + } + const query = toWire( + { + filter: req.filter, + sort: encodeSort(req.sort, toSnakeCase), + page: req.page, + }, + schemas.listLlmCostPricesQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listLlmCostPricesQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get('openmeter/llm-cost/prices', { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listLlmCostPricesResponseWire, data) + } + return fromWire(data, schemas.listLlmCostPricesResponse) + }) + }) +} + +/** + * Get LLM cost price + * + * Get a specific LLM cost price by ID. Returns the price with overrides applied if + * any. + * + * GET /openmeter/llm-cost/prices/{priceId} + */ +export function getLlmCostPrice( + client: Client, + req: GetLlmCostPriceRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + priceId: req.priceId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.getLlmCostPricePathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.getLlmCostPricePathParamsWire, pathParams) + } + const path = `openmeter/llm-cost/prices/${(() => { + if (pathParams.priceId === undefined) { + throw new Error('missing path parameter: priceId') + } + return encodeURIComponent(String(pathParams.priceId)) + })()}` + return http(client) + .get(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.getLlmCostPriceResponseWire, data) + } + return fromWire(data, schemas.getLlmCostPriceResponse) + }) + }) +} + +/** + * List LLM cost overrides + * + * List per-namespace price overrides. + * + * GET /openmeter/llm-cost/overrides + */ +export function listLlmCostOverrides( + client: Client, + req: ListLlmCostOverridesRequest = {}, + options?: RequestOptions, +): Promise> { + return request(() => { + const query = toWire( + { + filter: req.filter, + page: req.page, + }, + schemas.listLlmCostOverridesQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listLlmCostOverridesQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get('openmeter/llm-cost/overrides', { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listLlmCostOverridesResponseWire, data) + } + return fromWire(data, schemas.listLlmCostOverridesResponse) + }) + }) +} + +/** + * Create LLM cost override + * + * Create a per-namespace price override. + * + * POST /openmeter/llm-cost/overrides + */ +export function createLlmCostOverride( + client: Client, + req: CreateLlmCostOverrideRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const body = toWire(req, schemas.createLlmCostOverrideBody) + if (client._options.validate) { + assertValid(schemas.createLlmCostOverrideBodyWire, body) + } + return http(client) + .post('openmeter/llm-cost/overrides', { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.createLlmCostOverrideResponseWire, data) + } + return fromWire(data, schemas.createLlmCostOverrideResponse) + }) + }) +} + +/** + * Delete LLM cost override + * + * Delete a per-namespace price override. + * + * DELETE /openmeter/llm-cost/overrides/{priceId} + */ +export function deleteLlmCostOverride( + client: Client, + req: DeleteLlmCostOverrideRequest, + options?: RequestOptions, +): Promise> { + return request(async () => { + const pathParamsInput = { + priceId: req.priceId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.deleteLlmCostOverridePathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.deleteLlmCostOverridePathParamsWire, pathParams) + } + const path = `openmeter/llm-cost/overrides/${(() => { + if (pathParams.priceId === undefined) { + throw new Error('missing path parameter: priceId') + } + return encodeURIComponent(String(pathParams.priceId)) + })()}` + await http(client).delete(path, options) + }) +} diff --git a/api/spec/packages/aip-client-javascript/src/funcs/meters.ts b/api/spec/packages/aip-client-javascript/src/funcs/meters.ts new file mode 100644 index 0000000000000000000000000000000000000000..0df79a8325ca975629614bf065666dfb01adc903 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/funcs/meters.ts @@ -0,0 +1,303 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client, http } from '../core.js' +import { type Result, type RequestOptions } from '../lib/types.js' +import { request } from '../lib/request.js' +import { toURLSearchParams, encodeSort } from '../lib/encodings.js' +import { + toWire, + toPathWire, + fromWire, + assertValid, + toSnakeCase, +} from '../lib/wire.js' +import * as schemas from '../models/schemas.js' +import type { + CreateMeterRequest, + CreateMeterResponse, + GetMeterRequest, + GetMeterResponse, + ListMetersRequest, + ListMetersResponse, + UpdateMeterRequest, + UpdateMeterResponse, + DeleteMeterRequest, + DeleteMeterResponse, + QueryMeterRequest, + QueryMeterResponse, + QueryMeterCsvRequest, + QueryMeterCsvResponse, +} from '../models/operations/meters.js' + +/** + * Create meter + * + * Create a meter. + * + * POST /openmeter/meters + */ +export function createMeter( + client: Client, + req: CreateMeterRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const body = toWire(req, schemas.createMeterBody) + if (client._options.validate) { + assertValid(schemas.createMeterBodyWire, body) + } + return http(client) + .post('openmeter/meters', { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.createMeterResponseWire, data) + } + return fromWire(data, schemas.createMeterResponse) + }) + }) +} + +/** + * Get meter + * + * Get a meter by ID. + * + * GET /openmeter/meters/{meterId} + */ +export function getMeter( + client: Client, + req: GetMeterRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + meterId: req.meterId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.getMeterPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.getMeterPathParamsWire, pathParams) + } + const path = `openmeter/meters/${(() => { + if (pathParams.meterId === undefined) { + throw new Error('missing path parameter: meterId') + } + return encodeURIComponent(String(pathParams.meterId)) + })()}` + return http(client) + .get(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.getMeterResponseWire, data) + } + return fromWire(data, schemas.getMeterResponse) + }) + }) +} + +/** + * List meters + * + * List meters. + * + * GET /openmeter/meters + */ +export function listMeters( + client: Client, + req: ListMetersRequest = {}, + options?: RequestOptions, +): Promise> { + return request(() => { + if (client._options.validate && req.sort !== undefined) { + assertValid(schemas.listMetersQueryParams.shape.sort, req.sort) + } + const query = toWire( + { + page: req.page, + sort: encodeSort(req.sort, toSnakeCase), + filter: req.filter, + }, + schemas.listMetersQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listMetersQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get('openmeter/meters', { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listMetersResponseWire, data) + } + return fromWire(data, schemas.listMetersResponse) + }) + }) +} + +/** + * Update meter + * + * Update a meter. + * + * PUT /openmeter/meters/{meterId} + */ +export function updateMeter( + client: Client, + req: UpdateMeterRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + meterId: req.meterId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.updateMeterPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.updateMeterPathParamsWire, pathParams) + } + const path = `openmeter/meters/${(() => { + if (pathParams.meterId === undefined) { + throw new Error('missing path parameter: meterId') + } + return encodeURIComponent(String(pathParams.meterId)) + })()}` + const body = toWire(req.body, schemas.updateMeterBody) + if (client._options.validate) { + assertValid(schemas.updateMeterBodyWire, body) + } + return http(client) + .put(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.updateMeterResponseWire, data) + } + return fromWire(data, schemas.updateMeterResponse) + }) + }) +} + +/** + * Delete meter + * + * Delete a meter. + * + * DELETE /openmeter/meters/{meterId} + */ +export function deleteMeter( + client: Client, + req: DeleteMeterRequest, + options?: RequestOptions, +): Promise> { + return request(async () => { + const pathParamsInput = { + meterId: req.meterId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.deleteMeterPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.deleteMeterPathParamsWire, pathParams) + } + const path = `openmeter/meters/${(() => { + if (pathParams.meterId === undefined) { + throw new Error('missing path parameter: meterId') + } + return encodeURIComponent(String(pathParams.meterId)) + })()}` + await http(client).delete(path, options) + }) +} + +/** + * Query meter + * + * Query a meter for usage. + * + * Set `Accept: application/json` (the default) to get a structured JSON response. + * Set `Accept: text/csv` to download the same data as a CSV file suitable for + * spreadsheets. The CSV columns, in order, are: + * + * `from, to, [subject,] [customer_id, customer_key, customer_name,] , value` + * + * The `subject` column is emitted only when `subject` is in the query's + * `group_by_dimensions`. The three `customer_*` columns are emitted together only + * when `customer_id` is in the query's `group_by_dimensions`. + * + * POST /openmeter/meters/{meterId}/query + */ +export function queryMeter( + client: Client, + req: QueryMeterRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + meterId: req.meterId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.queryMeterPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.queryMeterPathParamsWire, pathParams) + } + const path = `openmeter/meters/${(() => { + if (pathParams.meterId === undefined) { + throw new Error('missing path parameter: meterId') + } + return encodeURIComponent(String(pathParams.meterId)) + })()}/query` + const body = toWire(req.body, schemas.queryMeterBody) + if (client._options.validate) { + assertValid(schemas.queryMeterBodyWire, body) + } + return http(client) + .post(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.queryMeterResponseWire, data) + } + return fromWire(data, schemas.queryMeterResponse) + }) + }) +} + +/** POST /openmeter/meters/{meterId}/query */ +export function queryMeterCsv( + client: Client, + req: QueryMeterCsvRequest, + options?: RequestOptions, +): Promise> { + const headers = new Headers(options?.headers as HeadersInit | undefined) + headers.set('accept', 'text/csv') + return request(() => { + const pathParamsInput = { + meterId: req.meterId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.queryMeterCsvPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.queryMeterCsvPathParamsWire, pathParams) + } + const path = `openmeter/meters/${(() => { + if (pathParams.meterId === undefined) { + throw new Error('missing path parameter: meterId') + } + return encodeURIComponent(String(pathParams.meterId)) + })()}/query` + const body = toWire(req.body, schemas.queryMeterCsvBody) + if (client._options.validate) { + assertValid(schemas.queryMeterCsvBodyWire, body) + } + return http(client) + .post(path, { ...options, json: body, headers }) + .text() + }) +} diff --git a/api/spec/packages/aip-client-javascript/src/funcs/planAddons.ts b/api/spec/packages/aip-client-javascript/src/funcs/planAddons.ts new file mode 100644 index 0000000000000000000000000000000000000000..dfe7d13a06f580495b72470f93a6431d030f491e --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/funcs/planAddons.ts @@ -0,0 +1,248 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client, http } from '../core.js' +import { type Result, type RequestOptions } from '../lib/types.js' +import { request } from '../lib/request.js' +import { toURLSearchParams } from '../lib/encodings.js' +import { toWire, toPathWire, fromWire, assertValid } from '../lib/wire.js' +import * as schemas from '../models/schemas.js' +import type { + ListPlanAddonsRequest, + ListPlanAddonsResponse, + CreatePlanAddonRequest, + CreatePlanAddonResponse, + GetPlanAddonRequest, + GetPlanAddonResponse, + UpdatePlanAddonRequest, + UpdatePlanAddonResponse, + DeletePlanAddonRequest, + DeletePlanAddonResponse, +} from '../models/operations/planAddons.js' + +/** + * List add-ons for plan + * + * List add-ons associated with a plan. + * + * GET /openmeter/plans/{planId}/addons + */ +export function listPlanAddons( + client: Client, + req: ListPlanAddonsRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + planId: req.planId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.listPlanAddonsPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.listPlanAddonsPathParamsWire, pathParams) + } + const path = `openmeter/plans/${(() => { + if (pathParams.planId === undefined) { + throw new Error('missing path parameter: planId') + } + return encodeURIComponent(String(pathParams.planId)) + })()}/addons` + const query = toWire( + { + page: req.page, + }, + schemas.listPlanAddonsQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listPlanAddonsQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get(path, { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listPlanAddonsResponseWire, data) + } + return fromWire(data, schemas.listPlanAddonsResponse) + }) + }) +} + +/** + * Add add-on to plan + * + * Add an add-on to a plan. + * + * POST /openmeter/plans/{planId}/addons + */ +export function createPlanAddon( + client: Client, + req: CreatePlanAddonRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + planId: req.planId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.createPlanAddonPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.createPlanAddonPathParamsWire, pathParams) + } + const path = `openmeter/plans/${(() => { + if (pathParams.planId === undefined) { + throw new Error('missing path parameter: planId') + } + return encodeURIComponent(String(pathParams.planId)) + })()}/addons` + const body = toWire(req.body, schemas.createPlanAddonBody) + if (client._options.validate) { + assertValid(schemas.createPlanAddonBodyWire, body) + } + return http(client) + .post(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.createPlanAddonResponseWire, data) + } + return fromWire(data, schemas.createPlanAddonResponse) + }) + }) +} + +/** + * Get add-on association for plan + * + * Get an add-on association for a plan. + * + * GET /openmeter/plans/{planId}/addons/{planAddonId} + */ +export function getPlanAddon( + client: Client, + req: GetPlanAddonRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + planId: req.planId, + planAddonId: req.planAddonId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.getPlanAddonPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.getPlanAddonPathParamsWire, pathParams) + } + const path = `openmeter/plans/${(() => { + if (pathParams.planId === undefined) { + throw new Error('missing path parameter: planId') + } + return encodeURIComponent(String(pathParams.planId)) + })()}/addons/${(() => { + if (pathParams.planAddonId === undefined) { + throw new Error('missing path parameter: planAddonId') + } + return encodeURIComponent(String(pathParams.planAddonId)) + })()}` + return http(client) + .get(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.getPlanAddonResponseWire, data) + } + return fromWire(data, schemas.getPlanAddonResponse) + }) + }) +} + +/** + * Update add-on association for plan + * + * Update an add-on association for a plan. + * + * PUT /openmeter/plans/{planId}/addons/{planAddonId} + */ +export function updatePlanAddon( + client: Client, + req: UpdatePlanAddonRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + planId: req.planId, + planAddonId: req.planAddonId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.updatePlanAddonPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.updatePlanAddonPathParamsWire, pathParams) + } + const path = `openmeter/plans/${(() => { + if (pathParams.planId === undefined) { + throw new Error('missing path parameter: planId') + } + return encodeURIComponent(String(pathParams.planId)) + })()}/addons/${(() => { + if (pathParams.planAddonId === undefined) { + throw new Error('missing path parameter: planAddonId') + } + return encodeURIComponent(String(pathParams.planAddonId)) + })()}` + const body = toWire(req.body, schemas.updatePlanAddonBody) + if (client._options.validate) { + assertValid(schemas.updatePlanAddonBodyWire, body) + } + return http(client) + .put(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.updatePlanAddonResponseWire, data) + } + return fromWire(data, schemas.updatePlanAddonResponse) + }) + }) +} + +/** + * Remove add-on from plan + * + * Remove an add-on from a plan. + * + * DELETE /openmeter/plans/{planId}/addons/{planAddonId} + */ +export function deletePlanAddon( + client: Client, + req: DeletePlanAddonRequest, + options?: RequestOptions, +): Promise> { + return request(async () => { + const pathParamsInput = { + planId: req.planId, + planAddonId: req.planAddonId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.deletePlanAddonPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.deletePlanAddonPathParamsWire, pathParams) + } + const path = `openmeter/plans/${(() => { + if (pathParams.planId === undefined) { + throw new Error('missing path parameter: planId') + } + return encodeURIComponent(String(pathParams.planId)) + })()}/addons/${(() => { + if (pathParams.planAddonId === undefined) { + throw new Error('missing path parameter: planAddonId') + } + return encodeURIComponent(String(pathParams.planAddonId)) + })()}` + await http(client).delete(path, options) + }) +} diff --git a/api/spec/packages/aip-client-javascript/src/funcs/plans.ts b/api/spec/packages/aip-client-javascript/src/funcs/plans.ts new file mode 100644 index 0000000000000000000000000000000000000000..edb7891a4972530ee8b0c22281c3a2dc0d4a5a70 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/funcs/plans.ts @@ -0,0 +1,295 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client, http } from '../core.js' +import { type Result, type RequestOptions } from '../lib/types.js' +import { request } from '../lib/request.js' +import { toURLSearchParams, encodeSort } from '../lib/encodings.js' +import { + toWire, + toPathWire, + fromWire, + assertValid, + toSnakeCase, +} from '../lib/wire.js' +import * as schemas from '../models/schemas.js' +import type { + ListPlansRequest, + ListPlansResponse, + CreatePlanRequest, + CreatePlanResponse, + UpdatePlanRequest, + UpdatePlanResponse, + GetPlanRequest, + GetPlanResponse, + DeletePlanRequest, + DeletePlanResponse, + ArchivePlanRequest, + ArchivePlanResponse, + PublishPlanRequest, + PublishPlanResponse, +} from '../models/operations/plans.js' + +/** + * List plans + * + * List all plans. + * + * GET /openmeter/plans + */ +export function listPlans( + client: Client, + req: ListPlansRequest = {}, + options?: RequestOptions, +): Promise> { + return request(() => { + if (client._options.validate && req.sort !== undefined) { + assertValid(schemas.listPlansQueryParams.shape.sort, req.sort) + } + const query = toWire( + { + page: req.page, + sort: encodeSort(req.sort, toSnakeCase), + filter: req.filter, + }, + schemas.listPlansQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listPlansQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get('openmeter/plans', { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listPlansResponseWire, data) + } + return fromWire(data, schemas.listPlansResponse) + }) + }) +} + +/** + * Create plan + * + * Create a new plan. + * + * POST /openmeter/plans + */ +export function createPlan( + client: Client, + req: CreatePlanRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const body = toWire(req, schemas.createPlanBody) + if (client._options.validate) { + assertValid(schemas.createPlanBodyWire, body) + } + return http(client) + .post('openmeter/plans', { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.createPlanResponseWire, data) + } + return fromWire(data, schemas.createPlanResponse) + }) + }) +} + +/** + * Update plan + * + * Update a plan by id. + * + * PUT /openmeter/plans/{planId} + */ +export function updatePlan( + client: Client, + req: UpdatePlanRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + planId: req.planId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.updatePlanPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.updatePlanPathParamsWire, pathParams) + } + const path = `openmeter/plans/${(() => { + if (pathParams.planId === undefined) { + throw new Error('missing path parameter: planId') + } + return encodeURIComponent(String(pathParams.planId)) + })()}` + const body = toWire(req.body, schemas.updatePlanBody) + if (client._options.validate) { + assertValid(schemas.updatePlanBodyWire, body) + } + return http(client) + .put(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.updatePlanResponseWire, data) + } + return fromWire(data, schemas.updatePlanResponse) + }) + }) +} + +/** + * Get plan + * + * Get a plan by id. + * + * GET /openmeter/plans/{planId} + */ +export function getPlan( + client: Client, + req: GetPlanRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + planId: req.planId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.getPlanPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.getPlanPathParamsWire, pathParams) + } + const path = `openmeter/plans/${(() => { + if (pathParams.planId === undefined) { + throw new Error('missing path parameter: planId') + } + return encodeURIComponent(String(pathParams.planId)) + })()}` + return http(client) + .get(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.getPlanResponseWire, data) + } + return fromWire(data, schemas.getPlanResponse) + }) + }) +} + +/** + * Delete plan + * + * Delete a plan by id. + * + * DELETE /openmeter/plans/{planId} + */ +export function deletePlan( + client: Client, + req: DeletePlanRequest, + options?: RequestOptions, +): Promise> { + return request(async () => { + const pathParamsInput = { + planId: req.planId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.deletePlanPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.deletePlanPathParamsWire, pathParams) + } + const path = `openmeter/plans/${(() => { + if (pathParams.planId === undefined) { + throw new Error('missing path parameter: planId') + } + return encodeURIComponent(String(pathParams.planId)) + })()}` + await http(client).delete(path, options) + }) +} + +/** + * Archive plan version + * + * Archive a plan version. + * + * POST /openmeter/plans/{planId}/archive + */ +export function archivePlan( + client: Client, + req: ArchivePlanRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + planId: req.planId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.archivePlanPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.archivePlanPathParamsWire, pathParams) + } + const path = `openmeter/plans/${(() => { + if (pathParams.planId === undefined) { + throw new Error('missing path parameter: planId') + } + return encodeURIComponent(String(pathParams.planId)) + })()}/archive` + return http(client) + .post(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.archivePlanResponseWire, data) + } + return fromWire(data, schemas.archivePlanResponse) + }) + }) +} + +/** + * Publish plan version + * + * Publish a plan version. + * + * POST /openmeter/plans/{planId}/publish + */ +export function publishPlan( + client: Client, + req: PublishPlanRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + planId: req.planId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.publishPlanPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.publishPlanPathParamsWire, pathParams) + } + const path = `openmeter/plans/${(() => { + if (pathParams.planId === undefined) { + throw new Error('missing path parameter: planId') + } + return encodeURIComponent(String(pathParams.planId)) + })()}/publish` + return http(client) + .post(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.publishPlanResponseWire, data) + } + return fromWire(data, schemas.publishPlanResponse) + }) + }) +} diff --git a/api/spec/packages/aip-client-javascript/src/funcs/subscriptions.ts b/api/spec/packages/aip-client-javascript/src/funcs/subscriptions.ts new file mode 100644 index 0000000000000000000000000000000000000000..345c2e09154320d65489197d2a194d3b025d71ac --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/funcs/subscriptions.ts @@ -0,0 +1,414 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client, http } from '../core.js' +import { type Result, type RequestOptions } from '../lib/types.js' +import { request } from '../lib/request.js' +import { toURLSearchParams, encodeSort } from '../lib/encodings.js' +import { + toWire, + toPathWire, + fromWire, + assertValid, + toSnakeCase, +} from '../lib/wire.js' +import * as schemas from '../models/schemas.js' +import type { + CreateSubscriptionRequest, + CreateSubscriptionResponse, + ListSubscriptionsRequest, + ListSubscriptionsResponse, + GetSubscriptionRequest, + GetSubscriptionResponse, + CancelSubscriptionRequest, + CancelSubscriptionResponse, + UnscheduleCancelationRequest, + UnscheduleCancelationResponse, + ChangeSubscriptionRequest, + ChangeSubscriptionResponse, + CreateSubscriptionAddonRequest, + CreateSubscriptionAddonResponse, + ListSubscriptionAddonsRequest, + ListSubscriptionAddonsResponse, + GetSubscriptionAddonRequest, + GetSubscriptionAddonResponse, +} from '../models/operations/subscriptions.js' + +/** + * Create subscription + * + * POST /openmeter/subscriptions + */ +export function createSubscription( + client: Client, + req: CreateSubscriptionRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const body = toWire(req, schemas.createSubscriptionBody) + if (client._options.validate) { + assertValid(schemas.createSubscriptionBodyWire, body) + } + return http(client) + .post('openmeter/subscriptions', { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.createSubscriptionResponseWire, data) + } + return fromWire(data, schemas.createSubscriptionResponse) + }) + }) +} + +/** + * List subscriptions + * + * GET /openmeter/subscriptions + */ +export function listSubscriptions( + client: Client, + req: ListSubscriptionsRequest = {}, + options?: RequestOptions, +): Promise> { + return request(() => { + if (client._options.validate && req.sort !== undefined) { + assertValid(schemas.listSubscriptionsQueryParams.shape.sort, req.sort) + } + const query = toWire( + { + page: req.page, + sort: encodeSort(req.sort, toSnakeCase), + filter: req.filter, + }, + schemas.listSubscriptionsQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listSubscriptionsQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get('openmeter/subscriptions', { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listSubscriptionsResponseWire, data) + } + return fromWire(data, schemas.listSubscriptionsResponse) + }) + }) +} + +/** + * Get subscription + * + * GET /openmeter/subscriptions/{subscriptionId} + */ +export function getSubscription( + client: Client, + req: GetSubscriptionRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + subscriptionId: req.subscriptionId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.getSubscriptionPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.getSubscriptionPathParamsWire, pathParams) + } + const path = `openmeter/subscriptions/${(() => { + if (pathParams.subscriptionId === undefined) { + throw new Error('missing path parameter: subscriptionId') + } + return encodeURIComponent(String(pathParams.subscriptionId)) + })()}` + return http(client) + .get(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.getSubscriptionResponseWire, data) + } + return fromWire(data, schemas.getSubscriptionResponse) + }) + }) +} + +/** + * Cancel subscription + * + * Cancels the subscription. Will result in a scheduling conflict if there are + * other subscriptions scheduled to start after the cancelation time. + * + * POST /openmeter/subscriptions/{subscriptionId}/cancel + */ +export function cancelSubscription( + client: Client, + req: CancelSubscriptionRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + subscriptionId: req.subscriptionId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.cancelSubscriptionPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.cancelSubscriptionPathParamsWire, pathParams) + } + const path = `openmeter/subscriptions/${(() => { + if (pathParams.subscriptionId === undefined) { + throw new Error('missing path parameter: subscriptionId') + } + return encodeURIComponent(String(pathParams.subscriptionId)) + })()}/cancel` + const body = toWire(req.body, schemas.cancelSubscriptionBody) + if (client._options.validate) { + assertValid(schemas.cancelSubscriptionBodyWire, body) + } + return http(client) + .post(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.cancelSubscriptionResponseWire, data) + } + return fromWire(data, schemas.cancelSubscriptionResponse) + }) + }) +} + +/** + * Unschedule subscription cancelation + * + * Unschedules the subscription cancelation. + * + * POST /openmeter/subscriptions/{subscriptionId}/unschedule-cancelation + */ +export function unscheduleCancelation( + client: Client, + req: UnscheduleCancelationRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + subscriptionId: req.subscriptionId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.unscheduleCancelationPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.unscheduleCancelationPathParamsWire, pathParams) + } + const path = `openmeter/subscriptions/${(() => { + if (pathParams.subscriptionId === undefined) { + throw new Error('missing path parameter: subscriptionId') + } + return encodeURIComponent(String(pathParams.subscriptionId)) + })()}/unschedule-cancelation` + return http(client) + .post(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.unscheduleCancelationResponseWire, data) + } + return fromWire(data, schemas.unscheduleCancelationResponse) + }) + }) +} + +/** + * Change subscription + * + * Closes a running subscription and starts a new one according to the + * specification. Can be used for upgrades, downgrades, and plan changes. + * + * POST /openmeter/subscriptions/{subscriptionId}/change + */ +export function changeSubscription( + client: Client, + req: ChangeSubscriptionRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + subscriptionId: req.subscriptionId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.changeSubscriptionPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.changeSubscriptionPathParamsWire, pathParams) + } + const path = `openmeter/subscriptions/${(() => { + if (pathParams.subscriptionId === undefined) { + throw new Error('missing path parameter: subscriptionId') + } + return encodeURIComponent(String(pathParams.subscriptionId)) + })()}/change` + const body = toWire(req.body, schemas.changeSubscriptionBody) + if (client._options.validate) { + assertValid(schemas.changeSubscriptionBodyWire, body) + } + return http(client) + .post(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.changeSubscriptionResponseWire, data) + } + return fromWire(data, schemas.changeSubscriptionResponse) + }) + }) +} + +/** + * Create a new subscription add-on + * + * Add add-on to a subscription. + * + * POST /openmeter/subscriptions/{subscriptionId}/addons + */ +export function createSubscriptionAddon( + client: Client, + req: CreateSubscriptionAddonRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + subscriptionId: req.subscriptionId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.createSubscriptionAddonPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.createSubscriptionAddonPathParamsWire, pathParams) + } + const path = `openmeter/subscriptions/${(() => { + if (pathParams.subscriptionId === undefined) { + throw new Error('missing path parameter: subscriptionId') + } + return encodeURIComponent(String(pathParams.subscriptionId)) + })()}/addons` + const body = toWire(req.body, schemas.createSubscriptionAddonBody) + if (client._options.validate) { + assertValid(schemas.createSubscriptionAddonBodyWire, body) + } + return http(client) + .post(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.createSubscriptionAddonResponseWire, data) + } + return fromWire(data, schemas.createSubscriptionAddonResponse) + }) + }) +} + +/** + * List subscription addons + * + * List the add-ons of a subscription. + * + * GET /openmeter/subscriptions/{subscriptionId}/addons + */ +export function listSubscriptionAddons( + client: Client, + req: ListSubscriptionAddonsRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + subscriptionId: req.subscriptionId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.listSubscriptionAddonsPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.listSubscriptionAddonsPathParamsWire, pathParams) + } + const path = `openmeter/subscriptions/${(() => { + if (pathParams.subscriptionId === undefined) { + throw new Error('missing path parameter: subscriptionId') + } + return encodeURIComponent(String(pathParams.subscriptionId)) + })()}/addons` + if (client._options.validate && req.sort !== undefined) { + assertValid( + schemas.listSubscriptionAddonsQueryParams.shape.sort, + req.sort, + ) + } + const query = toWire( + { + page: req.page, + sort: encodeSort(req.sort, toSnakeCase), + }, + schemas.listSubscriptionAddonsQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listSubscriptionAddonsQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get(path, { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listSubscriptionAddonsResponseWire, data) + } + return fromWire(data, schemas.listSubscriptionAddonsResponse) + }) + }) +} + +/** + * Get add-on association for subscription + * + * Get an add-on association for a subscription. + * + * GET /openmeter/subscriptions/{subscriptionId}/addons/{subscriptionAddonId} + */ +export function getSubscriptionAddon( + client: Client, + req: GetSubscriptionAddonRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + subscriptionId: req.subscriptionId, + subscriptionAddonId: req.subscriptionAddonId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.getSubscriptionAddonPathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.getSubscriptionAddonPathParamsWire, pathParams) + } + const path = `openmeter/subscriptions/${(() => { + if (pathParams.subscriptionId === undefined) { + throw new Error('missing path parameter: subscriptionId') + } + return encodeURIComponent(String(pathParams.subscriptionId)) + })()}/addons/${(() => { + if (pathParams.subscriptionAddonId === undefined) { + throw new Error('missing path parameter: subscriptionAddonId') + } + return encodeURIComponent(String(pathParams.subscriptionAddonId)) + })()}` + return http(client) + .get(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.getSubscriptionAddonResponseWire, data) + } + return fromWire(data, schemas.getSubscriptionAddonResponse) + }) + }) +} diff --git a/api/spec/packages/aip-client-javascript/src/funcs/tax.ts b/api/spec/packages/aip-client-javascript/src/funcs/tax.ts new file mode 100644 index 0000000000000000000000000000000000000000..237613b3e87bf55bf77540fe97d0110a94f86d27 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/funcs/tax.ts @@ -0,0 +1,191 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client, http } from '../core.js' +import { type Result, type RequestOptions } from '../lib/types.js' +import { request } from '../lib/request.js' +import { toURLSearchParams } from '../lib/encodings.js' +import { toWire, toPathWire, fromWire, assertValid } from '../lib/wire.js' +import * as schemas from '../models/schemas.js' +import type { + CreateTaxCodeRequest, + CreateTaxCodeResponse, + GetTaxCodeRequest, + GetTaxCodeResponse, + ListTaxCodesRequest, + ListTaxCodesResponse, + UpsertTaxCodeRequest, + UpsertTaxCodeResponse, + DeleteTaxCodeRequest, + DeleteTaxCodeResponse, +} from '../models/operations/tax.js' + +/** + * Create tax code + * + * POST /openmeter/tax-codes + */ +export function createTaxCode( + client: Client, + req: CreateTaxCodeRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const body = toWire(req, schemas.createTaxCodeBody) + if (client._options.validate) { + assertValid(schemas.createTaxCodeBodyWire, body) + } + return http(client) + .post('openmeter/tax-codes', { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.createTaxCodeResponseWire, data) + } + return fromWire(data, schemas.createTaxCodeResponse) + }) + }) +} + +/** + * Get tax code + * + * GET /openmeter/tax-codes/{taxCodeId} + */ +export function getTaxCode( + client: Client, + req: GetTaxCodeRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + taxCodeId: req.taxCodeId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.getTaxCodePathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.getTaxCodePathParamsWire, pathParams) + } + const path = `openmeter/tax-codes/${(() => { + if (pathParams.taxCodeId === undefined) { + throw new Error('missing path parameter: taxCodeId') + } + return encodeURIComponent(String(pathParams.taxCodeId)) + })()}` + return http(client) + .get(path, options) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.getTaxCodeResponseWire, data) + } + return fromWire(data, schemas.getTaxCodeResponse) + }) + }) +} + +/** + * List tax codes + * + * GET /openmeter/tax-codes + */ +export function listTaxCodes( + client: Client, + req: ListTaxCodesRequest = {}, + options?: RequestOptions, +): Promise> { + return request(() => { + const query = toWire( + { + page: req.page, + includeDeleted: req.includeDeleted, + }, + schemas.listTaxCodesQueryParams, + ) + if (client._options.validate) { + assertValid(schemas.listTaxCodesQueryParamsWire, query) + } + const searchParams = toURLSearchParams(query) + return http(client) + .get('openmeter/tax-codes', { ...options, searchParams }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.listTaxCodesResponseWire, data) + } + return fromWire(data, schemas.listTaxCodesResponse) + }) + }) +} + +/** + * Upsert tax code + * + * PUT /openmeter/tax-codes/{taxCodeId} + */ +export function upsertTaxCode( + client: Client, + req: UpsertTaxCodeRequest, + options?: RequestOptions, +): Promise> { + return request(() => { + const pathParamsInput = { + taxCodeId: req.taxCodeId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.upsertTaxCodePathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.upsertTaxCodePathParamsWire, pathParams) + } + const path = `openmeter/tax-codes/${(() => { + if (pathParams.taxCodeId === undefined) { + throw new Error('missing path parameter: taxCodeId') + } + return encodeURIComponent(String(pathParams.taxCodeId)) + })()}` + const body = toWire(req.body, schemas.upsertTaxCodeBody) + if (client._options.validate) { + assertValid(schemas.upsertTaxCodeBodyWire, body) + } + return http(client) + .put(path, { ...options, json: body }) + .json() + .then((data) => { + if (client._options.validate) { + assertValid(schemas.upsertTaxCodeResponseWire, data) + } + return fromWire(data, schemas.upsertTaxCodeResponse) + }) + }) +} + +/** + * Delete tax code + * + * DELETE /openmeter/tax-codes/{taxCodeId} + */ +export function deleteTaxCode( + client: Client, + req: DeleteTaxCodeRequest, + options?: RequestOptions, +): Promise> { + return request(async () => { + const pathParamsInput = { + taxCodeId: req.taxCodeId, + } + const pathParams = client._options.validate + ? toPathWire(pathParamsInput, schemas.deleteTaxCodePathParams) + : pathParamsInput + if (client._options.validate) { + assertValid(schemas.deleteTaxCodePathParamsWire, pathParams) + } + const path = `openmeter/tax-codes/${(() => { + if (pathParams.taxCodeId === undefined) { + throw new Error('missing path parameter: taxCodeId') + } + return encodeURIComponent(String(pathParams.taxCodeId)) + })()}` + await http(client).delete(path, options) + }) +} diff --git a/api/spec/packages/aip-client-javascript/src/index.ts b/api/spec/packages/aip-client-javascript/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..a6cfe6447b7b0aeb30e3580fe4654320b3aa0269 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/index.ts @@ -0,0 +1,440 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +export { OpenMeter } from './sdk/sdk.js' +export { Events } from './sdk/events.js' +export { Meters } from './sdk/meters.js' +export { Customers } from './sdk/customers.js' +export { Entitlements } from './sdk/entitlements.js' +export { Subscriptions } from './sdk/subscriptions.js' +export { Apps } from './sdk/apps.js' +export { Billing } from './sdk/billing.js' +export { Tax } from './sdk/tax.js' +export { Features } from './sdk/features.js' +export { LLMCost } from './sdk/llmCost.js' +export { Plans } from './sdk/plans.js' +export { Addons } from './sdk/addons.js' +export { PlanAddons } from './sdk/planAddons.js' +export { Defaults } from './sdk/defaults.js' +export { Client } from './core.js' +export { HTTPError } from './models/errors.js' +export { + ValidationError, + DepthLimitExceededError, + UnsafeIntegerError, +} from './lib/wire.js' +export type { AcceptDateStrings, DateString } from './lib/wire.js' +export { PaginationLimitExceededError } from './lib/paginate.js' + +export { ServerList, Regions } from './lib/config.js' +export type { SDKOptions, Region, ServerVariables } from './lib/config.js' +export { unwrap, ok, err } from './lib/types.js' +export type { Result, RequestOptions } from './lib/types.js' + +export { + encodePath, + encodeSort, + querySerializer, + toURLSearchParams, +} from './lib/encodings.js' + +export * as funcs from './funcs/index.js' + +export type * from './models/operations/events.js' +export type * from './models/operations/meters.js' +export type * from './models/operations/customers.js' +export type * from './models/operations/entitlements.js' +export type * from './models/operations/subscriptions.js' +export type * from './models/operations/apps.js' +export type * from './models/operations/billing.js' +export type * from './models/operations/invoices.js' +export type * from './models/operations/tax.js' +export type * from './models/operations/currencies.js' +export type * from './models/operations/features.js' +export type * from './models/operations/llmCost.js' +export type * from './models/operations/plans.js' +export type * from './models/operations/addons.js' +export type * from './models/operations/planAddons.js' +export type * from './models/operations/defaults.js' +export type * from './models/operations/governance.js' + +export type { + Labels, + CursorPaginationQueryPage, + SortQuery, + IngestedEventValidationError, + CursorMetaPage, + BaseError, + PageMeta, + QueryFilterString, + AppStripeCheckoutSessionCustomTextParams, + AppStripeCreateCustomerPortalSessionOptions, + CreateLabels, + TaxConfigStripe, + TaxConfigExternalInvoicing, + ChargeFlatFeeDiscounts, + PriceFree, + RateCardStaticEntitlement, + RateCardBooleanEntitlement, + InstallAppStripeWithApiKey, + InstallAppSandbox, + InstallAppExternalInvoicing, + WorkflowCollectionAlignmentSubscription, + WorkflowPaymentChargeAutomaticallySettings, + WorkflowPaymentSendInvoiceSettings, + InvoiceExternalReferences, + InvoiceAvailableActionDetails, + InvoiceWorkflowInvoicingSettings, + InvoiceLineExternalReferences, + UpdateLabels, + UpdateBillingInvoiceWorkflowInvoicingSettings, + UpdateBillingWorkflowPaymentChargeAutomaticallySettings, + UpdateBillingWorkflowPaymentSendInvoiceSettings, + UpdatePriceFree, + LlmCostProvider, + LlmCostModel, + ProductCatalogValidationError, + GovernanceQueryRequestCustomers, + GovernanceQueryRequestFeatures, + QueryFilterInteger, + QueryFilterFloat, + QueryFilterBoolean, + PagePaginationQuery, + PublicLabels, + SystemAccountAccessToken, + PersonalAccessToken, + KonnectAccessToken, + AppCustomerDataStripe, + AppCustomerDataExternalInvoicing, + CurrencyFiat, + ListCostBasesParamsFilter, + CurrencyAmount, + PriceFlat, + PriceUnit, + RateCardDiscounts, + Totals, + SpendCommitments, + InvoiceLineCreditsApplied, + UpdatePriceFlat, + UpdatePriceUnit, + UpdateDiscounts, + FeatureManualUnitCost, + FeatureLlmUnitCostPricing, + LlmCostModelPricing, + QueryFilterNumeric, + CursorPaginationQuery, + ListMetersParamsFilter, + ListLlmCostPricesParamsFilter, + LabelsFieldFilter, + CustomerReference, + ProfileReference, + CreateResourceReference, + TaxCodeReference, + CreditGrantInvoiceReference, + BillingCustomerReference, + SubscriptionReference, + AddonReference, + FeatureReference, + AppReference, + ChargeReference, + UpdateResourceReference, + Event, + MeterQueryRow, + AppStripeCreateCustomerPortalSessionResult, + ClosedPeriod, + SubscriptionAddonTimelineSegment, + UpdateClosedPeriod, + CostBasis, + FeatureCostQueryRow, + Resource, + ResourceImmutable, + QueryFilterDateTime, + CursorMeta, + InvalidParameterStandard, + InvalidParameterMinimumLength, + InvalidParameterMaximumLength, + InvalidParameterChoiceItem, + InvalidParameterDependentItem, + Unauthorized, + Forbidden, + NotFound, + Gone, + Conflict, + PayloadTooLarge, + UnsupportedMediaType, + UnprocessableContent, + TooManyRequests, + Internal, + NotImplemented, + NotAvailable, + CreateCreditGrantFilters, + CreditGrantFilters, + UpsertPlanAddonRequest, + ResourceWithKey, + Meter, + PaginatedMeta, + QueryFilterStringMapItem, + CustomerKeyReference, + CustomerUsageAttribution, + UpdateCustomerUsageAttribution, + Address, + UpdateAddress, + AppStripeCreateCheckoutSessionCustomerUpdate, + AppStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreement, + AppStripeCreateCheckoutSessionTaxIdCollection, + AppStripeCreateCheckoutSessionResult, + CustomerStripeCreateCustomerPortalSessionRequest, + EntitlementAccessResult, + CreateCreditGrantPurchase, + RateCardMeteredEntitlement, + RecurringPeriod, + CreditGrantPurchase, + ListCreditGrantsParamsFilter, + GetCreditBalanceParamsFilter, + ListChargesParamsFilter, + ListPlansParamsFilter, + SubscriptionCreate, + RateCardProrationConfiguration, + Subscription, + UnitConfig, + TaxCodeAppMapping, + AppCapability, + PartyTaxIdentity, + UpdateBillingPartyTaxIdentity, + WorkflowInvoicingSettings, + InvoiceValidationIssue, + InvoiceAvailableActions, + InvoiceLineAmountDiscount, + InvoiceLineUsageDiscount, + InvoiceLineBaseDiscount, + ListCurrenciesParamsFilter, + CurrencyCustom, + CreateCurrencyCustomRequest, + GovernanceQueryRequest, + GovernanceFeatureAccessReason, + GovernanceQueryError, + AppCustomerData, + UpsertAppCustomerDataRequest, + CreditAdjustment, + CreditBalance, + ListCreditTransactionsParamsFilter, + CreditTransaction, + PriceTier, + ChargeTotals, + UpdatePriceTier, + FeatureLlmUnitCost, + LlmCostPrice, + LlmCostOverrideCreate, + ListCustomersParamsFilter, + ListSubscriptionsParamsFilter, + ListFeatureParamsFilter, + ListAddonsParamsFilter, + CreateCreditGrantTaxConfig, + CreditGrantTaxConfig, + TaxConfig, + RateCardTaxConfig, + OrganizationDefaultTaxCodes, + PlanAddon, + ProfileAppReferences, + InvoiceWorkflowAppsReferences, + UpdateRateCardTaxConfig, + ListEventsParamsFilter, + ListInvoicesParamsFilter, + ResourceFilters, + FieldFilters, + IngestedEvent, + MeterQueryResult, + FeatureCostQueryResult, + MeterPagePaginatedResponse, + CostBasisPagePaginatedResponse, + MeterQueryFilters, + FeatureMeterReference, + Customer, + PartyAddresses, + InvoiceCustomer, + UpdateBillingPartyAddresses, + UpdateInvoiceCustomer, + AppStripeCreateCheckoutSessionConsentCollection, + ListCustomerEntitlementAccessResponseData, + WorkflowCollectionAlignmentAnchored, + ChargeFlatFeeSystemIntent, + SubscriptionPagePaginatedResponse, + SubscriptionChangeResponse, + SubscriptionCancel, + SubscriptionChange, + InvoiceUsageQuantityDetail, + TaxCode, + AppCatalogItem, + InvoiceWorkflow, + InvoiceStatusDetails, + InvoiceLineDiscounts, + UpdateBillingInvoiceWorkflow, + GovernanceFeatureAccess, + CustomerData, + UpsertCustomerBillingDataRequest, + CreditBalances, + CreditTransactionPaginatedResponse, + PriceGraduated, + PriceVolume, + UpdatePriceGraduated, + UpdatePriceVolume, + PricePagePaginatedResponse, + CreditGrant, + CreateChargeFlatFeeRequest, + WorkflowTaxSettings, + PlanAddonPagePaginatedResponse, + IngestedEventPaginatedResponse, + InvalidParameters, + MeterQueryRequest, + CustomerPagePaginatedResponse, + Party, + Supplier, + UpdateSupplier, + AppStripeCreateCheckoutSessionRequestOptions, + TaxCodePagePaginatedResponse, + AppStripe, + AppSandbox, + AppExternalInvoicing, + AppCatalogItemPagePaginatedResponse, + InvoiceWorkflowSettings, + InvoiceDetailedLine, + UpdateInvoiceWorkflowSettings, + CurrencyPagePaginatedResponse, + GovernanceQueryResult, + Feature, + CreditGrantPagePaginatedResponse, + BadRequest, + InvoiceBase, + CustomerStripeCreateCheckoutSessionRequest, + WorkflowCollectionSettings, + GovernanceQueryResponse, + ChargeFlatFee, + ChargeUsageBasedSystemIntent, + CreateChargeUsageBasedRequest, + RateCard, + InvoiceLineRateCard, + UpdateInvoiceLineRateCard, + FeaturePagePaginatedResponse, + Workflow, + AppPagePaginatedResponse, + BillingInstallAppResponse, + ProfileApps, + ChargeUsageBased, + SubscriptionAddonRateCard, + PlanPhase, + Addon, + UpsertAddonRequest, + InvoiceStandardLine, + UpdateInvoiceStandardLine, + Profile, + UpsertBillingProfileRequest, + SubscriptionAddon, + Plan, + UpsertPlanRequest, + AddonPagePaginatedResponse, + ProfilePagePaginatedResponse, + ChargePagePaginatedResponse, + SubscriptionAddonPagePaginatedResponse, + PlanPagePaginatedResponse, + InvoiceStandard, + UpdateInvoiceStandardRequest, + InvoicePagePaginatedResponse, + StringFieldFilter, + MeterAggregation, + MeterQueryGranularity, + StringFieldFilterExact, + PricePaymentTerm, + BillingCurrencyCode, + CreateCurrencyCode, + UlidFieldFilter, + DateTimeFieldFilter, + SubscriptionEditTiming, + WorkflowPaymentSettings, + UpdateBillingWorkflowPaymentSettings, + InvalidParameter, + RateCardEntitlement, + Currency, + FeatureUnitCost, + WorkflowCollectionAlignment, + Price, + UpdatePrice, + App, + CreateChargeRequest, + Charge, + InvoiceLine, + UpdateInvoiceLine, + Invoice, + SortQueryInput, + BaseErrorInput, + WorkflowPaymentSendInvoiceSettingsInput, + InvoiceWorkflowInvoicingSettingsInput, + UpdateBillingInvoiceWorkflowInvoicingSettingsInput, + UpdateBillingWorkflowPaymentSendInvoiceSettingsInput, + EventInput, + UnauthorizedInput, + ForbiddenInput, + NotFoundInput, + GoneInput, + ConflictInput, + PayloadTooLargeInput, + UnsupportedMediaTypeInput, + UnprocessableContentInput, + TooManyRequestsInput, + InternalInput, + NotImplementedInput, + NotAvailableInput, + AppStripeCreateCheckoutSessionCustomerUpdateInput, + AppStripeCreateCheckoutSessionTaxIdCollectionInput, + CreateCreditGrantPurchaseInput, + RateCardMeteredEntitlementInput, + CreditGrantPurchaseInput, + VoidCreditGrantRequestInput, + UnitConfigInput, + WorkflowInvoicingSettingsInput, + GovernanceQueryRequestInput, + IngestedEventInput, + SubscriptionCancelInput, + InvoiceUsageQuantityDetailInput, + InvoiceWorkflowInput, + UpdateBillingInvoiceWorkflowInput, + CreateCreditGrantRequestInput, + CreditGrantInput, + WorkflowTaxSettingsInput, + IngestedEventPaginatedResponseInput, + MeterQueryRequestInput, + AppStripeCreateCheckoutSessionRequestOptionsInput, + InvoiceWorkflowSettingsInput, + InvoiceDetailedLineInput, + UpdateInvoiceWorkflowSettingsInput, + CreditGrantPagePaginatedResponseInput, + BadRequestInput, + CustomerStripeCreateCheckoutSessionRequestInput, + WorkflowCollectionSettingsInput, + RateCardInput, + WorkflowInput, + SubscriptionAddonRateCardInput, + PlanPhaseInput, + AddonInput, + CreateAddonRequestInput, + UpsertAddonRequestInput, + InvoiceStandardLineInput, + ProfileInput, + CreateBillingProfileRequestInput, + UpsertBillingProfileRequestInput, + SubscriptionAddonInput, + PlanInput, + CreatePlanRequestInput, + UpsertPlanRequestInput, + AddonPagePaginatedResponseInput, + ProfilePagePaginatedResponseInput, + SubscriptionAddonPagePaginatedResponseInput, + PlanPagePaginatedResponseInput, + InvoiceStandardInput, + UpdateInvoiceStandardRequestInput, + InvoicePagePaginatedResponseInput, + WorkflowPaymentSettingsInput, + UpdateBillingWorkflowPaymentSettingsInput, + RateCardEntitlementInput, + InvoiceLineInput, + InvoiceInput, + UpdateInvoiceRequestInput, +} from './models/types.js' diff --git a/api/spec/packages/aip-client-javascript/src/lib/config.ts b/api/spec/packages/aip-client-javascript/src/lib/config.ts new file mode 100644 index 0000000000000000000000000000000000000000..ec6453626419c2981a86f1cfc12de01e73203ed9 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/lib/config.ts @@ -0,0 +1,33 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Options } from 'ky' + +export const ServerList = [ + 'https://{region}.api.konghq.com/v3', + 'http://localhost:{port}/api/v3', + 'https://openmeter.cloud/api/v3', +] as const + +export const Regions = ['in', 'me', 'au', 'eu', 'us'] as const + +export type Region = (typeof Regions)[number] + +export type ServerVariables = { + region?: Region + port?: string | number +} + +export interface SDKOptions extends Omit { + baseUrl: (typeof ServerList)[number] | URL | string + serverVariables?: ServerVariables + apiKey?: string | (() => string | Promise) + /** + * Validate request bodies and response payloads against their schemas. Off by + * default: the SDK maps casing but does not validate, so additive server fields + * never break clients. When on, a request body or response that fails its schema + * (missing/wrong-typed field, unknown enum value) returns a failed Result whose + * `error` is a ValidationError (validation runs inside the SDK's request + * handling, so it never rejects/throws). + */ + validate?: boolean +} diff --git a/api/spec/packages/aip-client-javascript/src/lib/encodings.ts b/api/spec/packages/aip-client-javascript/src/lib/encodings.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e093f16c13fcb126d7d60c83aa12fc4dc0f699c --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/lib/encodings.ts @@ -0,0 +1,77 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +export function encodePath( + template: string, + params: Record, +): string { + return template.replace(/\{(\w+)\}/g, (_, key: string) => { + const value = params[key] + if (value === undefined) { + throw new Error(`missing path parameter: ${key}`) + } + return encodeURIComponent(String(value)) + }) +} + +function serializeDeepObject( + prefix: string, + value: unknown, + parts: Array<[string, string]>, +): void { + if (value === null || value === undefined) { + return + } + if (Array.isArray(value)) { + parts.push([prefix, value.map(String).join(',')]) + } else if (typeof value === 'object') { + for (const [k, v] of Object.entries(value)) { + serializeDeepObject(`${prefix}[${k}]`, v, parts) + } + } else { + parts.push([prefix, String(value)]) + } +} + +function serializeParams( + params: Record, +): Array<[string, string]> { + const parts: Array<[string, string]> = [] + for (const [key, value] of Object.entries(params)) { + serializeDeepObject(key, value, parts) + } + return parts +} + +export function querySerializer(params: Record): string { + const parts = serializeParams(params).map( + ([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`, + ) + return parts.length ? `?${parts.join('&')}` : '' +} + +export function toURLSearchParams( + params: Record, +): URLSearchParams { + const search = new URLSearchParams() + for (const [key, value] of serializeParams(params)) { + search.append(key, value) + } + return search +} + +export function encodeSort( + sort: { by?: string; order?: 'asc' | 'desc' } | undefined, + encodeField: (field: string) => string = (field) => field, +): string | undefined { + if (!sort?.by) { + return undefined + } + const by = encodeField(sort.by) + if (sort.order === 'desc') { + return `${by} desc` + } + if (sort.order === 'asc') { + return `${by} asc` + } + return by +} diff --git a/api/spec/packages/aip-client-javascript/src/lib/paginate.ts b/api/spec/packages/aip-client-javascript/src/lib/paginate.ts new file mode 100644 index 0000000000000000000000000000000000000000..8a216d06f26dd40bcf6800ffac998954a9693599 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/lib/paginate.ts @@ -0,0 +1,99 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { unwrap, type RequestOptions, type Result } from './types.js' + +// A misbehaving server — inconsistent `meta.page.total`/`size`, or a +// `meta.page.next` cursor that never resolves to an empty page — would +// otherwise make these generators loop forever. 10,000 pages is far beyond +// any real OpenMeter list, so hitting it means the server's pagination +// contract broke, not that the caller has a legitimately large list. +const MAX_PAGINATION_PAGES = 10_000 + +export class PaginationLimitExceededError extends Error { + constructor(limit: number) { + super( + `pagination exceeded the maximum of ${limit} pages; the server may be returning inconsistent pagination metadata`, + ) + this.name = 'PaginationLimitExceededError' + } +} + +interface PageNumberEnvelope { + data: TItem[] + meta: { page: { number: number; size: number; total: number } } +} + +interface PageNumberRequest { + page?: { number?: number; size?: number } +} + +/** + * Iterates every item of a page-number-paginated list operation, advancing + * `page.number` from wherever the caller's own request starts. Every other + * field on `request` — filters, sort, page.size — is sent unchanged on every + * page fetch; only the page number advances. Stops on a page shorter than + * the server's own reported `size` (including an empty page) or once the + * running item count reaches the server's reported `total`, whichever comes + * first — so a final page that exactly fills `total` does not trigger one + * more, empty request. + */ +export async function* paginatePages( + fetchPage: ( + req: TReq, + options?: RequestOptions, + ) => Promise>>, + request: TReq, + options?: RequestOptions, +): AsyncGenerator { + let req = request + let seen = 0 + for (let page = 0; page < MAX_PAGINATION_PAGES; page++) { + const res = unwrap(await fetchPage(req, options)) + yield* res.data + seen += res.data.length + const { number, size, total } = res.meta.page + if (res.data.length === 0 || res.data.length < size || seen >= total) { + return + } + req = { ...req, page: { ...req.page, number: number + 1 } } as TReq + } + throw new PaginationLimitExceededError(MAX_PAGINATION_PAGES) +} + +interface CursorEnvelope { + data: TItem[] + meta: { page: { next: string | null } } +} + +interface CursorRequest { + page?: { after?: string; before?: string; size?: number } +} + +/** + * Iterates every item of a cursor-paginated list operation, following + * `meta.page.next` until the server stops returning one. Despite carrying a + * `format: uri` annotation in the spec, `next` is the opaque cursor token the + * API expects back verbatim in `page.after` on the following request — not a + * URI to fetch directly. Every other field on `request` is sent unchanged on + * every page fetch; only `page.after` advances. + */ +export async function* paginateCursor( + fetchPage: ( + req: TReq, + options?: RequestOptions, + ) => Promise>>, + request: TReq, + options?: RequestOptions, +): AsyncGenerator { + let req = request + for (let page = 0; page < MAX_PAGINATION_PAGES; page++) { + const res = unwrap(await fetchPage(req, options)) + yield* res.data + const next = res.meta.page.next + if (!next) { + return + } + req = { ...req, page: { ...req.page, after: next } } as TReq + } + throw new PaginationLimitExceededError(MAX_PAGINATION_PAGES) +} diff --git a/api/spec/packages/aip-client-javascript/src/lib/request.ts b/api/spec/packages/aip-client-javascript/src/lib/request.ts new file mode 100644 index 0000000000000000000000000000000000000000..aa6cc533b58a2651f00ac21a1ec6d2bd952edd8d --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/lib/request.ts @@ -0,0 +1,12 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Result, ok, err } from './types.js' +import { toError } from './to-error.js' + +export async function request(fn: () => Promise): Promise> { + try { + return ok(await fn()) + } catch (e) { + return err(await toError(e)) + } +} diff --git a/api/spec/packages/aip-client-javascript/src/lib/to-error.ts b/api/spec/packages/aip-client-javascript/src/lib/to-error.ts new file mode 100644 index 0000000000000000000000000000000000000000..cad387e9a0fdf4ca9175e2a352b733e6954c5dae --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/lib/to-error.ts @@ -0,0 +1,18 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { HTTPError as KyHTTPError } from 'ky' +import * as schemas from '../models/schemas.js' +import { HTTPError } from '../models/errors.js' + +export async function toError(e: unknown): Promise { + if (e instanceof KyHTTPError) { + // ky consumes the body into e.data; e.response.json() would throw. + const parsed = schemas.baseError.safeParse(e.data) + const error = parsed.success ? parsed.data : undefined + return HTTPError.fromResponse({ response: e.response, error }) + } + if (e instanceof Error) { + return e + } + return new Error(String(e)) +} diff --git a/api/spec/packages/aip-client-javascript/src/lib/types.ts b/api/spec/packages/aip-client-javascript/src/lib/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..c553e70429ce1dd994a651ca95a801d4b73359c3 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/lib/types.ts @@ -0,0 +1,27 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import type { Options } from 'ky' + +export type RequestOptions = Pick< + Options, + 'signal' | 'headers' | 'timeout' | 'retry' +> + +export type Result = + | { ok: true; value: T; error?: never } + | { ok: false; value?: never; error: E } + +export function ok(value: T): Result { + return { ok: true, value } +} + +export function err(error: E): Result { + return { ok: false, error } +} + +export function unwrap(result: Result): T { + if (result.ok) { + return result.value + } + throw result.error +} diff --git a/api/spec/packages/aip-client-javascript/src/lib/version.ts b/api/spec/packages/aip-client-javascript/src/lib/version.ts new file mode 100644 index 0000000000000000000000000000000000000000..934202f02c90440ce87d903153389293f80c38c3 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/lib/version.ts @@ -0,0 +1,6 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +// The committed value is a dev placeholder. The publish flow +// (`make -C api/spec publish-aip-sdk`) stamps the real release version here +// before `pnpm publish`, after `pnpm version` updates package.json. +export const SDK_VERSION = '0.0.0' diff --git a/api/spec/packages/aip-client-javascript/src/lib/wire.ts b/api/spec/packages/aip-client-javascript/src/lib/wire.ts new file mode 100644 index 0000000000000000000000000000000000000000..456c5244d63827b9591712c3d60e740c03247fb5 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/lib/wire.ts @@ -0,0 +1,559 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import type { output, ZodType } from 'zod' + +export function toCamelCase(name: string): string { + return name.replace(/_([a-z0-9])/g, (_m, c: string) => c.toUpperCase()) +} + +export function toSnakeCase(name: string): string { + return name.replace(/([A-Z])/g, (_m, c: string) => `_${c.toLowerCase()}`) +} + +type ZodDef = { + type: string + innerType?: ZodType + valueType?: ZodType + element?: ZodType + discriminator?: string + options?: ZodType[] + entries?: Record + defaultValue?: unknown +} + +function def(schema: ZodType | undefined): ZodDef | undefined { + return (schema as { def?: ZodDef } | undefined)?.def +} + +// Unwrap optional/nullable/default to the schema that describes the value's +// shape. These wrappers never change keys, so the walker looks through them +// before classifying a node. +function unwrap(schema: ZodType | undefined): ZodType | undefined { + let current = schema + for (let i = 0; i < 100 && current; i++) { + const d = def(current) + if ( + d && + (d.type === 'optional' || + d.type === 'nullable' || + d.type === 'default') && + d.innerType + ) { + current = d.innerType + continue + } + return current + } + /* v8 ignore next -- loop returns inside; reached only past the cycle guard */ + return current +} + +// The default to write for a field the caller omitted, present only when the +// field is required-with-default in the spec — emitted as `.default(x)` with no +// `.optional()` in the wrapper chain (TypeSpec `field: T = x`, not +// `field?: T = x`). Such fields must be present on the wire (e.g. a CloudEvents +// envelope's `specversion`, which the server's parser rejects when absent), yet +// the generated request type allows omitting them so callers get the documented +// default for free — toWire is the layer that has to reconcile the two. +// Spec-optional fields (`.optional().default(x)`) return undefined and stay off +// the wire: their default is the server's to apply, and materializing them +// client-side would silently overwrite server state on update requests. +function requiredDefault( + schema: ZodType | undefined, +): { value: unknown } | undefined { + let current = schema + let found: { value: unknown } | undefined + for (let i = 0; i < 100 && current; i++) { + const d = def(current) + /* v8 ignore next 3 -- every zod schema carries a def; guards the type only */ + if (!d) { + break + } + if (d.type === 'optional') { + return undefined + } + if (d.type === 'default') { + found ??= { value: d.defaultValue } + } else if (d.type !== 'nullable') { + break + } + current = d.innerType + } + return found +} + +function shapeOf( + schema: ZodType | undefined, +): Record | undefined { + return (schema as { shape?: Record } | undefined)?.shape +} + +// The element schema for array data: the schema's own element when it is an +// array, or the array variant's element when it is a union of T and T[] +// (the single-or-batch body shape). +function arrayElement(schema: ZodType | undefined): ZodType | undefined { + const d = def(schema) + if (d?.type === 'array') { + return d.element + } + if (d?.type === 'union') { + for (const option of d.options ?? []) { + const od = def(unwrap(option)) + if (od?.type === 'array') { + return od.element + } + } + } + return undefined +} + +// Whether a record value schema needs walking: it carries renamable fields +// (object/record/array/union of such) or date-typed values that must map +// between `Date` and the RFC 3339 wire string. Other scalars, literals, +// unknown, and any are left untouched, so user data (labels, dimensions, +// event payloads) is never rewritten. +function needsWalk(schema: ZodType | undefined): boolean { + const s = unwrap(schema) + const d = def(s) + /* v8 ignore next 3 -- a record always has a value schema; defensive only */ + if (!d) { + return false + } + if ( + d.type === 'object' || + d.type === 'record' || + d.type === 'date' || + d.type === 'bigint' + ) { + return true + } + if (d.type === 'array') { + return needsWalk(d.element) + } + if (d.type === 'union') { + return (d.options ?? []).some(needsWalk) + } + return false +} + +// Thrown by toWire when a bigint value (an int64/uint64 field) is outside +// JSON's exactly-representable integer range. The wire carries int64 as a JSON +// number (the server decodes it into a Go int64), so a value beyond 2^53-1 +// cannot be sent without silent precision corruption — a typed, immediate +// failure is the only honest option. request() catches it like any Error and +// surfaces it as Result.error. +export class UnsafeIntegerError extends Error { + constructor(value: bigint) { + super( + `bigint value ${value} exceeds JSON's safe integer range and cannot be sent without precision loss`, + ) + this.name = 'UnsafeIntegerError' + } +} + +// An RFC 3339 string standing in for a `Date` on request input. The +// `Record` intersection keeps a plain string assignable while +// stopping the union simplifier from absorbing sibling string literals — a +// bare `| string` would collapse `'immediate' | 'next_billing_cycle' | Date | +// string` to `string | Date` and kill literal autocomplete. +export type DateString = string & Record + +// The request-side widening of a payload type: every `Date` also accepts its +// RFC 3339 string form. Applied to the generated `…Request` aliases only — +// domain interfaces and response types stay `Date`, so responses always carry +// real `Date`s. At runtime the mapper passes request strings through verbatim +// (never re-parses or normalizes them), so the wire sees exactly what was given +// and the optional wire validation still checks the string against the RFC 3339 +// wire schema. +export type AcceptDateStrings = T extends Date + ? Date | DateString + : T extends (infer E)[] + ? AcceptDateStrings[] + : T extends object + ? { [K in keyof T]: AcceptDateStrings } + : T + +// Literal siblings of `Date` must survive the widening. Checked at compile +// time in both the emitter build and the generated SDK's typecheck, so a +// regression to a bare `| string` arm fails the build. +type _LiteralsSurviveWidening = + 'x' extends Extract, 'x'> + ? true + : { + __error: 'AcceptDateStrings absorbed literal union members into string' + } +const _literalsSurviveWidening: _LiteralsSurviveWidening = true +void _literalsSurviveWidening + +type Direction = { + // The wire→public or public→wire key rename for object fields. + rename: (key: string) => string + // The data key holding a discriminated union's discriminator, given the + // schema's (camelCase) discriminator key. + discriminatorKey: (camelKey: string) => string + // The value mapping at a date-typed node: public `Date` → RFC 3339 wire + // string, wire string → `Date`. Values already in the target form (or not + // convertible) pass through unchanged. + mapDate: (value: unknown) => unknown + // The value mapping at a bigint-typed (int64/uint64) node: public `bigint` → + // JSON number (throwing UnsafeIntegerError beyond 2^53-1, where JSON numbers + // lose integer precision), wire number → `bigint`. Without the public→wire + // mapping, JSON.stringify throws an opaque TypeError on any bigint. Values + // already in the target form (or not convertible) pass through unchanged. + mapBigInt: (value: unknown) => unknown + // Whether absent required-with-default fields are materialized (see + // requiredDefault). True only public→wire: requests must satisfy the wire + // contract, while responses are reported as the server sent them — fromWire + // fabricating fields would mask genuine contract violations. + applyDefaults: boolean + // JSON.stringify omits object properties and record entries whose value is + // undefined. True only public→wire so validation sees the effective JSON + // payload instead of an intermediate object that the transport cannot send. + // Array entries are deliberately unaffected: JSON serializes undefined array + // values as null rather than omitting them. + omitUndefinedObjectEntries: boolean +} + +// A handful of schemas are genuinely self-referential (e.g. the `and`/`or` +// legs of a filter tree), so nesting depth is bounded only by the DATA the +// server sends, not by the schema. Without a limit, a crafted or +// accidentally-deep response recurses until the JS engine throws a raw +// `RangeError: Maximum call stack size exceeded` — still caught by request() +// and surfaced as Result.error, but as an opaque native error instead of a +// typed one. 500 levels is far beyond any real filter/record/array nesting +// in the API today; it exists to fail predictably, not to constrain valid data. +const MAX_WALK_DEPTH = 500 + +export class DepthLimitExceededError extends Error { + constructor() { + super(`wire mapping exceeded maximum nesting depth (${MAX_WALK_DEPTH})`) + this.name = 'DepthLimitExceededError' + } +} + +function walk( + data: unknown, + schema: ZodType | undefined, + dir: Direction, + depth = 0, +): unknown { + if (data === null || data === undefined) { + return data + } + // A Date can only ever mean its wire serialization, wherever it sits — a + // typed date field, a record value, or an unknown-schema position. Wire→ + // public data never contains Date instances (it comes from JSON.parse), so + // this only rewrites public→wire. The same holds for bigint: JSON.parse + // never produces one, and public→wire it must become a JSON number wherever + // it sits. + if (data instanceof Date) { + return dir.mapDate(data) + } + if (typeof data === 'bigint') { + return dir.mapBigInt(data) + } + if (depth > MAX_WALK_DEPTH) { + throw new DepthLimitExceededError() + } + const s = unwrap(schema) + const d = def(s) + // A date-typed node maps between the public `Date` and the RFC 3339 wire + // string (fromWire revives the string; a string handed to toWire by an + // untyped caller passes through as-is). + if (d?.type === 'date') { + return dir.mapDate(data) + } + // A bigint-typed node revives the wire's JSON number into the public + // `bigint` (public→wire bigints were already mapped by the value check + // above, so only fromWire reaches a number here). + if (d?.type === 'bigint') { + return dir.mapBigInt(data) + } + if (Array.isArray(data)) { + // The schema may be the array itself or a union with an array variant + // (e.g. a single-or-batch body `T | T[]`); resolve the element schema from + // whichever applies so array items are still walked with their shape. + const element = arrayElement(s) + return data.map((item) => walk(item, element, dir, depth + 1)) + } + if (typeof data !== 'object') { + // A wire datetime can sit behind a union (`DateTime | null`, + // enum-or-DateTime): revive the string only when the union's date variant + // is its sole plausible owner, so enum literals and plain-string variants + // pass through untouched. + if ( + typeof data === 'string' && + d?.type === 'union' && + unionDateClaims(s, data) + ) { + return dir.mapDate(data) + } + return data + } + const record = data as Record + + if (d?.type === 'record') { + // Record keys are user data (label/dimension names) — preserved verbatim. + // Only the value is walked, and only when it needs mapping. A null + // prototype avoids the `__proto__` key silently reassigning `out`'s own + // prototype instead of becoming a visible entry (user data may contain + // any key, including reserved object-literal property names). The + // prototype is restored once every key is a plain own property, so the + // returned object still behaves normally for consumers (instanceof, + // template literals) — `Object.prototype` itself was never touched. + const valueSchema = needsWalk(d.valueType) ? d.valueType : undefined + const out: Record = Object.create(null) + for (const [key, value] of Object.entries(record)) { + if (dir.omitUndefinedObjectEntries && value === undefined) { + continue + } + out[key] = valueSchema ? walk(value, valueSchema, dir, depth + 1) : value + } + Object.setPrototypeOf(out, Object.prototype) + return out + } + + if (d?.type === 'union') { + const variant = selectVariant(record, s, dir) + if (!variant) { + // No confident match: leave keys untransformed rather than guess. + return data + } + return walk(data, variant, dir, depth + 1) + } + + if (d?.type === 'object') { + const shape = shapeOf(s) ?? {} + // A null prototype avoids two failure modes from data-controlled keys + // like `__proto__`/`constructor`: (1) `fieldFor` below reading an + // inherited Object.prototype member instead of correctly treating the + // key as schema-undeclared, and (2) the assignment at the end of this + // loop reassigning `out`'s own prototype instead of adding a visible key. + const out: Record = Object.create(null) + for (const [key, value] of Object.entries(record)) { + if (dir.omitUndefinedObjectEntries && value === undefined) { + continue + } + const fieldSchema = fieldFor(shape, key) + // Keys the schema does not declare are dropped, so the result matches the + // typed shape exactly (a server-added field has no place in the type). + if (fieldSchema === undefined) { + continue + } + out[dir.rename(key)] = walk(value, fieldSchema, dir, depth + 1) + } + if (dir.applyDefaults) { + // Shape keys are generated camelCase identifiers (never data-controlled), + // so direct indexing into `record` is safe here. Runs after the data loop + // so an explicit `key: undefined` entry is also replaced by the default. + for (const [key, fieldSchema] of Object.entries(shape)) { + if (record[key] !== undefined) { + continue + } + const dflt = requiredDefault(fieldSchema) + if (dflt !== undefined) { + out[dir.rename(key)] = walk(dflt.value, fieldSchema, dir, depth + 1) + } + } + } + Object.setPrototypeOf(out, Object.prototype) + return out + } + + // Scalar or unknown schema: pass through untransformed. + return data +} + +// Resolve a data key to its field schema. The schema is camelCase-keyed; a +// wire→public data key is snake, so it is camelized to index the shape. +// Own-property checks (not `shape[key]`) so a data-controlled key like +// `__proto__` or `constructor` cannot resolve to an inherited +// Object.prototype member and be mistaken for a declared schema field. +function fieldFor( + shape: Record, + dataKey: string, +): ZodType | undefined { + if (Object.hasOwn(shape, dataKey)) { + return shape[dataKey] + } + const camelKey = toCamelCase(dataKey) + return Object.hasOwn(shape, camelKey) ? shape[camelKey] : undefined +} + +function selectVariant( + data: Record, + schema: ZodType | undefined, + dir: Direction, +): ZodType | undefined { + const d = def(schema) + const options = d?.options ?? [] + if (d?.discriminator && schema) { + // O(1) dispatch on the discriminator literal. The data key is the wire-name in + // fromWire (snake) and the public name in toWire (camel); the variant map is + // keyed by the literal value, which is identical in both directions. + const dataKey = dir.discriminatorKey(d.discriminator) + return variantsByDiscriminator(schema, d).get(data[dataKey]) + } + // Non-discriminated union: the codegen gate guarantees at most one object + // variant (it fails the build for a mapped union with two or more), so the single + // object-shaped option is unambiguous. Other variants (scalars, arrays) reach the + // walk through their own data-kind branches, not here. + return options.find((option) => def(unwrap(option))?.type === 'object') +} + +// Memoized literal→variant map for a discriminated union, built once per schema. +const variantMapCache = new WeakMap>() + +function variantsByDiscriminator( + schema: ZodType, + d: ZodDef, +): Map { + const cached = variantMapCache.get(schema) + if (cached) { + return cached + } + const map = new Map() + for (const option of d.options ?? []) { + const shape = shapeOf(unwrap(option)) + const literal = literalValue(shape?.[d.discriminator as string]) + if (literal !== undefined) { + map.set(literal, option) + } + } + variantMapCache.set(schema, map) + return map +} + +function literalValue(schema: ZodType | undefined): unknown { + const s = unwrap(schema) + if (def(s)?.type === 'literal') { + return (s as { value?: unknown }).value + } + /* v8 ignore next -- a discriminated-union variant's discriminator is a literal */ + return undefined +} + +// Whether a union's date variant is the sole plausible owner of a string +// value: the union carries a date option, no string-capable sibling (a plain +// string variant, an enum containing the value, an equal string literal) +// claims it, and the value actually parses as a date. `DateTime | null` +// revives its RFC 3339 string; `'immediate' | DateTime` keeps the enum +// literal a string. Fail-open: an unclaimed string stays a string. +function unionDateClaims(schema: ZodType | undefined, value: string): boolean { + let hasDate = false + for (const option of def(schema)?.options ?? []) { + const od = def(unwrap(option)) + if (od?.type === 'date') { + hasDate = true + } else if (od?.type === 'string') { + return false + } else if ( + od?.type === 'enum' && + Object.values(od.entries ?? {}).includes(value) + ) { + return false + } else if (od?.type === 'literal' && literalValue(option) === value) { + return false + } + } + return hasDate && !Number.isNaN(Date.parse(value)) +} + +const toWireDirection: Direction = { + rename: toSnakeCase, + discriminatorKey: (camelKey) => camelKey, + mapDate: (value) => (value instanceof Date ? value.toISOString() : value), + mapBigInt: (value) => { + if (typeof value !== 'bigint') { + return value + } + if ( + value > BigInt(Number.MAX_SAFE_INTEGER) || + value < -BigInt(Number.MAX_SAFE_INTEGER) + ) { + throw new UnsafeIntegerError(value) + } + return Number(value) + }, + applyDefaults: true, + omitUndefinedObjectEntries: true, +} + +// Path binding names are transport metadata, not JSON object member names, so +// they must remain exactly as declared while their values receive the same +// Date/bigint/default mapping used by request bodies and query parameters. +const toPathWireDirection: Direction = { + ...toWireDirection, + rename: (key) => key, +} + +const fromWireDirection: Direction = { + rename: toCamelCase, + discriminatorKey: (camelKey) => toSnakeCase(camelKey), + mapDate: (value) => (typeof value === 'string' ? new Date(value) : value), + mapBigInt: (value) => + typeof value === 'number' && Number.isInteger(value) + ? BigInt(value) + : value, + applyDefaults: false, + omitUndefinedObjectEntries: false, +} + +// Rewrite a request body or query object from the camelCase public shape to the +// snake_case wire shape, driven by its schema. Record keys (label/dimension names) +// are preserved; `Date` values serialize to RFC 3339 strings; `bigint` values +// (int64 fields) become JSON numbers; omitted required-with-default fields are +// filled with their declared default (see requiredDefault); explicit undefined +// object/record entries are omitted just as JSON.stringify would omit them. The +// return is typed as the input `T` so call sites stay cast-free (the runtime object +// has snake keys and wire-encoded dates, but the value is write-only — it flows +// straight into `json:`/`toURLSearchParams`, both of which accept any object). +export function toWire(data: T, schema: ZodType): T { + return walk(data, schema, toWireDirection) as T +} + +// Rewrite path-parameter values to their transport representation without +// renaming the path binding keys. The returned object is subsequently validated +// against the generated `…PathParamsWire` schema and URL-encoded by the func. +export function toPathWire(data: T, schema: ZodType): T { + return walk(data, schema, toPathWireDirection) as T +} + +// Rewrite a response body from the snake_case wire shape to the camelCase public +// shape: renames keys and revives RFC 3339 strings into `Date`s at date-typed +// nodes — never applies defaults or any other coercion. The result is the +// schema's output shape: `walk` produces exactly the schema's known fields in +// camelCase, so the inferred `output` type describes the runtime value (the +// same wire-trust boundary as a plain `.json()`, with no `.parse()`). +export function fromWire( + data: unknown, + schema: S, +): output { + return walk(data, schema, fromWireDirection) as output +} + +// Thrown by assertValid when the optional `validate` client option is on and data +// fails its schema. request() catches it like any Error and surfaces it as +// Result.error. +export class ValidationError extends Error { + constructor( + message: string, + public readonly issues: unknown, + ) { + super(message) + this.name = 'ValidationError' + } +} + +// Opt-in schema check used by the funcs (when the validate option is on) against +// the snake_case wire payload: the request body after toWire, the raw response +// before fromWire, each against its generated `…Wire` schema. It is a GATE, not a +// transform — the safeParse output (coercions/defaults) is discarded, so validation +// never mutates the payload or return value. Off by default; the SDK does not +// validate by default (additive server fields must not break clients). +export function assertValid(schema: ZodType, data: unknown): void { + const result = schema.safeParse(data) + if (!result.success) { + throw new ValidationError('schema validation failed', result.error.issues) + } +} diff --git a/api/spec/packages/aip-client-javascript/src/models/errors.ts b/api/spec/packages/aip-client-javascript/src/models/errors.ts new file mode 100644 index 0000000000000000000000000000000000000000..17f07dace6c7d339fe7da4041064a9e056206979 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/models/errors.ts @@ -0,0 +1,85 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { z } from 'zod' +import * as schemas from './schemas.js' + +// Retry-After is either delta-seconds (an integer) or an HTTP-date. Only the +// delta-seconds form is parsed; HTTP-date values yield undefined rather than +// a parsed Date, keeping the public type a plain number. +function parseRetryAfter(header: string | null): number | undefined { + if (header === null) { + return undefined + } + const trimmed = header.trim() + return /^\d+$/.test(trimmed) ? Number(trimmed) : undefined +} + +export class HTTPError extends Error { + constructor( + message: string, + public type: string, + public title: string, + public status: number, + public url: string, + public retryAfter: number | undefined, + protected __raw?: Record, + ) { + super(message) + this.name = 'HTTPError' + } + + static fromResponse(resp: { + response: Response + error?: z.infer + }) { + const retryAfter = parseRetryAfter(resp.response.headers.get('Retry-After')) + + if ( + resp.response.headers + .get('Content-Type') + ?.includes('application/problem+json') && + resp.error + ) { + return new HTTPError( + resp.error.detail, + resp.error.type ?? resp.error.title, + resp.error.title, + resp.error.status ?? resp.response.status, + resp.response.url, + retryAfter, + resp.error, + ) + } + + return new HTTPError( + `Request failed: ${resp.response.statusText}`, + resp.response.statusText, + resp.response.statusText, + resp.response.status, + resp.response.url, + retryAfter, + ) + } + + /** + * The `invalid_parameters` problem-detail extension member, present on Bad + * Request (400) responses. Typed from the schema, not runtime-validated + * (like the rest of the SDK, this trusts the server rather than rejecting + * additive fields) — `undefined` when the response didn't carry one. + */ + get invalidParameters(): + | z.infer + | undefined { + return this.__raw?.invalid_parameters as + | z.infer + | undefined + } + + /** + * Escape hatch for problem-detail extension members without a typed + * accessor above. + */ + getField(key: string) { + return this.__raw?.[key] + } +} diff --git a/api/spec/packages/aip-client-javascript/src/models/operations/addons.ts b/api/spec/packages/aip-client-javascript/src/models/operations/addons.ts new file mode 100644 index 0000000000000000000000000000000000000000..79434394f678bb564d40f604770334c5fd417254 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/models/operations/addons.ts @@ -0,0 +1,65 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { z } from 'zod' +import * as schemas from '../schemas.js' +import type { AcceptDateStrings } from '../../lib/wire.js' +import type { + Addon, + AddonPagePaginatedResponse, + CreateAddonRequestInput, + ListAddonsParamsFilter, + SortQueryInput, + UpsertAddonRequestInput, +} from '../types.js' + +export interface ListAddonsQuery { + /** Determines which page of the collection to retrieve. */ + page?: { size?: number; number?: number } + /** + * Sort add-ons returned in the response. Supported sort attributes are: + * + * - `id` + * - `key` + * - `name` + * - `created_at` (default) + * - `updated_at` + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ + sort?: SortQueryInput + /** Filter add-ons returned in the response. */ + filter?: ListAddonsParamsFilter +} + +export type ListAddonsRequest = AcceptDateStrings +export type ListAddonsResponse = AddonPagePaginatedResponse + +export type CreateAddonRequest = AcceptDateStrings +export type CreateAddonResponse = Addon + +export type UpdateAddonRequest = AcceptDateStrings<{ + addonId: string + body: UpsertAddonRequestInput +}> +export type UpdateAddonResponse = Addon + +export type GetAddonRequest = { + addonId: string +} +export type GetAddonResponse = Addon + +export type DeleteAddonRequest = { + addonId: string +} +export type DeleteAddonResponse = void + +export type ArchiveAddonRequest = { + addonId: string +} +export type ArchiveAddonResponse = Addon + +export type PublishAddonRequest = { + addonId: string +} +export type PublishAddonResponse = Addon diff --git a/api/spec/packages/aip-client-javascript/src/models/operations/apps.ts b/api/spec/packages/aip-client-javascript/src/models/operations/apps.ts new file mode 100644 index 0000000000000000000000000000000000000000..f304f7cd83a3b10eaf91f664efdb1e9ef36b56fd --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/models/operations/apps.ts @@ -0,0 +1,42 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { z } from 'zod' +import * as schemas from '../schemas.js' +import type { AcceptDateStrings } from '../../lib/wire.js' +import type { + App, + AppCatalogItem, + AppCatalogItemPagePaginatedResponse, + AppPagePaginatedResponse, + BillingInstallAppResponse, + InstallAppRequest as InstallAppRequestBody, +} from '../types.js' + +export interface ListAppsQuery { + /** Determines which page of the collection to retrieve. */ + page?: { size?: number; number?: number } +} + +export type ListAppsRequest = AcceptDateStrings +export type ListAppsResponse = AppPagePaginatedResponse + +export type GetAppRequest = { + appId: string +} +export type GetAppResponse = App + +export interface ListAppCatalogQuery { + /** Determines which page of the collection to retrieve. */ + page?: { size?: number; number?: number } +} + +export type ListAppCatalogRequest = AcceptDateStrings +export type ListAppCatalogResponse = AppCatalogItemPagePaginatedResponse + +export type GetAppCatalogItemRequest = { + appType: string +} +export type GetAppCatalogItemResponse = AppCatalogItem + +export type InstallAppRequest = AcceptDateStrings +export type InstallAppResponse = BillingInstallAppResponse diff --git a/api/spec/packages/aip-client-javascript/src/models/operations/billing.ts b/api/spec/packages/aip-client-javascript/src/models/operations/billing.ts new file mode 100644 index 0000000000000000000000000000000000000000..93fe43f455e01e33881ccf84d728134d055eeab1 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/models/operations/billing.ts @@ -0,0 +1,40 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { z } from 'zod' +import * as schemas from '../schemas.js' +import type { AcceptDateStrings } from '../../lib/wire.js' +import type { + CreateBillingProfileRequestInput, + Profile, + ProfilePagePaginatedResponse, + UpsertBillingProfileRequestInput, +} from '../types.js' + +export interface ListBillingProfilesQuery { + /** Determines which page of the collection to retrieve. */ + page?: { size?: number; number?: number } +} + +export type ListBillingProfilesRequest = + AcceptDateStrings +export type ListBillingProfilesResponse = ProfilePagePaginatedResponse + +export type CreateBillingProfileRequest = + AcceptDateStrings +export type CreateBillingProfileResponse = Profile + +export type GetBillingProfileRequest = { + id: string +} +export type GetBillingProfileResponse = Profile + +export type UpdateBillingProfileRequest = AcceptDateStrings<{ + id: string + body: UpsertBillingProfileRequestInput +}> +export type UpdateBillingProfileResponse = Profile + +export type DeleteBillingProfileRequest = { + id: string +} +export type DeleteBillingProfileResponse = void diff --git a/api/spec/packages/aip-client-javascript/src/models/operations/currencies.ts b/api/spec/packages/aip-client-javascript/src/models/operations/currencies.ts new file mode 100644 index 0000000000000000000000000000000000000000..00efaf64c08e254348e9da9fadeef509a1b80136 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/models/operations/currencies.ts @@ -0,0 +1,67 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { z } from 'zod' +import * as schemas from '../schemas.js' +import type { AcceptDateStrings } from '../../lib/wire.js' +import type { + CostBasis, + CostBasisPagePaginatedResponse, + CreateCostBasisRequest as CreateCostBasisRequestBody, + CreateCurrencyCustomRequest, + CurrencyCustom, + CurrencyPagePaginatedResponse, + ListCostBasesParamsFilter, + ListCurrenciesParamsFilter, + SortQueryInput, +} from '../types.js' + +export interface ListCurrenciesQuery { + /** Determines which page of the collection to retrieve. */ + page?: { size?: number; number?: number } + /** + * Sort currencies returned in the response. Supported sort attributes are: + * + * - `code` (default) + * - `name` + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ + sort?: SortQueryInput + /** + * Filter currencies returned in the response. + * + * To filter currencies by type add the following query param: filter[type]=custom + */ + filter?: ListCurrenciesParamsFilter +} + +export type ListCurrenciesRequest = AcceptDateStrings +export type ListCurrenciesResponse = CurrencyPagePaginatedResponse + +export type CreateCustomCurrencyRequest = + AcceptDateStrings +export type CreateCustomCurrencyResponse = CurrencyCustom + +export interface ListCostBasesQuery { + /** + * Filter cost bases returned in the response. + * + * To filter cost bases by fiat currency code add the following query param: + * filter[fiat_code]=USD + */ + filter?: ListCostBasesParamsFilter + /** Determines which page of the collection to retrieve. */ + page?: { size?: number; number?: number } +} + +export type ListCostBasesRequest = AcceptDateStrings< + ListCostBasesQuery & { currencyId: string } +> +export type ListCostBasesResponse = CostBasisPagePaginatedResponse + +export type CreateCostBasisRequest = AcceptDateStrings<{ + currencyId: string + body: CreateCostBasisRequestBody +}> +export type CreateCostBasisResponse = CostBasis diff --git a/api/spec/packages/aip-client-javascript/src/models/operations/customers.ts b/api/spec/packages/aip-client-javascript/src/models/operations/customers.ts new file mode 100644 index 0000000000000000000000000000000000000000..01f824aaf098afcaf5f01e1921c3bf62f5ac9fbc --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/models/operations/customers.ts @@ -0,0 +1,225 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { z } from 'zod' +import * as schemas from '../schemas.js' +import type { AcceptDateStrings } from '../../lib/wire.js' +import type { + AppCustomerData, + AppStripeCreateCheckoutSessionResult, + AppStripeCreateCustomerPortalSessionResult, + Charge, + ChargePagePaginatedResponse, + CreateChargeRequest, + CreateCreditAdjustmentRequest as CreateCreditAdjustmentRequestBody, + CreateCreditGrantRequestInput, + CreateCustomerRequest as CreateCustomerRequestBody, + CreditAdjustment, + CreditBalances, + CreditGrant, + CreditGrantPagePaginatedResponse, + CreditTransactionPaginatedResponse, + CursorPaginationQueryPage, + Customer, + CustomerData, + CustomerPagePaginatedResponse, + CustomerStripeCreateCheckoutSessionRequestInput, + CustomerStripeCreateCustomerPortalSessionRequest, + GetCreditBalanceParamsFilter, + ListChargesParamsFilter, + ListCreditGrantsParamsFilter, + ListCreditTransactionsParamsFilter, + ListCustomersParamsFilter, + SortQueryInput, + UpdateCreditGrantExternalSettlementRequest as UpdateCreditGrantExternalSettlementRequestBody, + UpsertAppCustomerDataRequest, + UpsertCustomerBillingDataRequest, + UpsertCustomerRequest as UpsertCustomerRequestBody, + VoidCreditGrantRequestInput, +} from '../types.js' + +export type CreateCustomerRequest = AcceptDateStrings +export type CreateCustomerResponse = Customer + +export type GetCustomerRequest = { + customerId: string +} +export type GetCustomerResponse = Customer + +export interface ListCustomersQuery { + /** Determines which page of the collection to retrieve. */ + page?: { size?: number; number?: number } + /** + * Sort customers returned in the response. Supported sort attributes are: + * + * - `id` + * - `name` (default) + * - `created_at` + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ + sort?: SortQueryInput + /** + * Filter customers returned in the response. + * + * To filter customers by key add the following query param: filter[key]=my-db-id + */ + filter?: ListCustomersParamsFilter +} + +export type ListCustomersRequest = AcceptDateStrings +export type ListCustomersResponse = CustomerPagePaginatedResponse + +export type UpsertCustomerRequest = AcceptDateStrings<{ + customerId: string + body: UpsertCustomerRequestBody +}> +export type UpsertCustomerResponse = Customer + +export type DeleteCustomerRequest = { + customerId: string +} +export type DeleteCustomerResponse = void + +export type GetCustomerBillingRequest = { + customerId: string +} +export type GetCustomerBillingResponse = CustomerData + +export type UpdateCustomerBillingRequest = AcceptDateStrings<{ + customerId: string + body: UpsertCustomerBillingDataRequest +}> +export type UpdateCustomerBillingResponse = CustomerData + +export type UpdateCustomerBillingAppDataRequest = AcceptDateStrings<{ + customerId: string + body: UpsertAppCustomerDataRequest +}> +export type UpdateCustomerBillingAppDataResponse = AppCustomerData + +export type CreateCustomerStripeCheckoutSessionRequest = AcceptDateStrings<{ + customerId: string + body: CustomerStripeCreateCheckoutSessionRequestInput +}> +export type CreateCustomerStripeCheckoutSessionResponse = + AppStripeCreateCheckoutSessionResult + +export type CreateCustomerStripePortalSessionRequest = AcceptDateStrings<{ + customerId: string + body: CustomerStripeCreateCustomerPortalSessionRequest +}> +export type CreateCustomerStripePortalSessionResponse = + AppStripeCreateCustomerPortalSessionResult + +export type CreateCreditGrantRequest = AcceptDateStrings<{ + customerId: string + body: CreateCreditGrantRequestInput +}> +export type CreateCreditGrantResponse = CreditGrant + +export type GetCreditGrantRequest = { + customerId: string + creditGrantId: string +} +export type GetCreditGrantResponse = CreditGrant + +export interface ListCreditGrantsQuery { + /** Determines which page of the collection to retrieve. */ + page?: { size?: number; number?: number } + /** Filter credit grants returned in the response. */ + filter?: ListCreditGrantsParamsFilter +} + +export type ListCreditGrantsRequest = AcceptDateStrings< + ListCreditGrantsQuery & { customerId: string } +> +export type ListCreditGrantsResponse = CreditGrantPagePaginatedResponse + +export interface GetCustomerCreditBalanceQuery { + /** + * Return the credit balance as of this timestamp. + * + * Defaults to the current time. + */ + timestamp?: Date + filter?: GetCreditBalanceParamsFilter +} + +export type GetCustomerCreditBalanceRequest = AcceptDateStrings< + GetCustomerCreditBalanceQuery & { customerId: string } +> +export type GetCustomerCreditBalanceResponse = CreditBalances + +export type CreateCreditAdjustmentRequest = AcceptDateStrings<{ + customerId: string + body: CreateCreditAdjustmentRequestBody +}> +export type CreateCreditAdjustmentResponse = CreditAdjustment + +export type VoidCreditGrantRequest = AcceptDateStrings<{ + customerId: string + creditGrantId: string + body: VoidCreditGrantRequestInput +}> +export type VoidCreditGrantResponse = CreditGrant + +export type UpdateCreditGrantExternalSettlementRequest = AcceptDateStrings<{ + customerId: string + creditGrantId: string + body: UpdateCreditGrantExternalSettlementRequestBody +}> +export type UpdateCreditGrantExternalSettlementResponse = CreditGrant + +export interface ListCreditTransactionsQuery { + page?: CursorPaginationQueryPage + /** Filter credit transactions returned in the response. */ + filter?: ListCreditTransactionsParamsFilter +} + +export type ListCreditTransactionsRequest = AcceptDateStrings< + ListCreditTransactionsQuery & { customerId: string } +> +export type ListCreditTransactionsResponse = CreditTransactionPaginatedResponse + +export interface ListCustomerChargesQuery { + /** Determines which page of the collection to retrieve. */ + page?: { size?: number; number?: number } + /** + * Sort charges returned in the response. + * + * Supported sort attributes are: + * + * - `id` + * - `created_at` + * - `service_period.from` + * - `billing_period.from` + */ + sort?: SortQueryInput + /** + * Filter charges. + * + * To filter charges by status add the following query param: + * `filter[status][oeq]=created,active` + */ + filter?: ListChargesParamsFilter + /** + * Expand full objects for referenced entities. + * + * Supported values are: + * + * - `real_time_usage`: Expand the charge's real-time usage. + */ + expand?: 'real_time_usage'[] +} + +export type ListCustomerChargesRequest = AcceptDateStrings< + ListCustomerChargesQuery & { customerId: string } +> +export type ListCustomerChargesResponse = ChargePagePaginatedResponse + +export type CreateCustomerChargesRequest = AcceptDateStrings<{ + customerId: string + body: CreateChargeRequest +}> +export type CreateCustomerChargesResponse = Charge diff --git a/api/spec/packages/aip-client-javascript/src/models/operations/defaults.ts b/api/spec/packages/aip-client-javascript/src/models/operations/defaults.ts new file mode 100644 index 0000000000000000000000000000000000000000..c1222a5b981c592abc571ec130bff0e52d945b0f --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/models/operations/defaults.ts @@ -0,0 +1,15 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import type { AcceptDateStrings } from '../../lib/wire.js' +import type { + OrganizationDefaultTaxCodes, + UpdateOrganizationDefaultTaxCodesRequest as UpdateOrganizationDefaultTaxCodesRequestBody, +} from '../types.js' + +export type GetOrganizationDefaultTaxCodesRequest = Record +export type GetOrganizationDefaultTaxCodesResponse = OrganizationDefaultTaxCodes + +export type UpdateOrganizationDefaultTaxCodesRequest = + AcceptDateStrings +export type UpdateOrganizationDefaultTaxCodesResponse = + OrganizationDefaultTaxCodes diff --git a/api/spec/packages/aip-client-javascript/src/models/operations/entitlements.ts b/api/spec/packages/aip-client-javascript/src/models/operations/entitlements.ts new file mode 100644 index 0000000000000000000000000000000000000000..c954be5c7155ec3ca88d4cd08d93229b0b2dfbcb --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/models/operations/entitlements.ts @@ -0,0 +1,9 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import type { ListCustomerEntitlementAccessResponseData } from '../types.js' + +export type ListCustomerEntitlementAccessRequest = { + customerId: string +} +export type ListCustomerEntitlementAccessResponse = + ListCustomerEntitlementAccessResponseData diff --git a/api/spec/packages/aip-client-javascript/src/models/operations/events.ts b/api/spec/packages/aip-client-javascript/src/models/operations/events.ts new file mode 100644 index 0000000000000000000000000000000000000000..51b165c03e126311f254c3a4f7bc685cf00764a1 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/models/operations/events.ts @@ -0,0 +1,44 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { z } from 'zod' +import * as schemas from '../schemas.js' +import type { AcceptDateStrings } from '../../lib/wire.js' +import type { + CursorPaginationQueryPage, + EventInput, + IngestedEventPaginatedResponse, + ListEventsParamsFilter, + SortQueryInput, +} from '../types.js' + +export interface ListMeteringEventsQuery { + page?: CursorPaginationQueryPage + /** + * Filter events returned in the response. + * + * To filter events by subject add the following query param: + * filter[subject][eq]=customer-1 + */ + filter?: ListEventsParamsFilter + /** + * Sort events returned in the response. Supported sort attributes are: + * + * - `time` (default) + * - `ingested_at` + * - `stored_at` + * + * When omitted, events are sorted by `time desc` (most recent first). When a sort + * field is provided without a suffix, it sorts descending. Append the `asc` suffix + * to sort ascending, or the `desc` suffix to sort descending. + */ + sort?: SortQueryInput +} + +export type ListMeteringEventsRequest = + AcceptDateStrings +export type ListMeteringEventsResponse = IngestedEventPaginatedResponse + +export type IngestMeteringEventsRequest = AcceptDateStrings< + EventInput | EventInput[] +> +export type IngestMeteringEventsResponse = void diff --git a/api/spec/packages/aip-client-javascript/src/models/operations/features.ts b/api/spec/packages/aip-client-javascript/src/models/operations/features.ts new file mode 100644 index 0000000000000000000000000000000000000000..0e7e0637af9db41e10de111fae6f8540fb924e19 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/models/operations/features.ts @@ -0,0 +1,67 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { z } from 'zod' +import * as schemas from '../schemas.js' +import type { AcceptDateStrings } from '../../lib/wire.js' +import type { + CreateFeatureRequest as CreateFeatureRequestBody, + Feature, + FeatureCostQueryResult, + FeaturePagePaginatedResponse, + ListFeatureParamsFilter, + MeterQueryRequestInput, + SortQueryInput, + UpdateFeatureRequest as UpdateFeatureRequestBody, +} from '../types.js' + +export interface ListFeaturesQuery { + /** Determines which page of the collection to retrieve. */ + page?: { size?: number; number?: number } + /** + * Sort features returned in the response. Supported sort attributes are: + * + * - `key` + * - `name` + * - `created_at` (default) + * - `updated_at` + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ + sort?: SortQueryInput + /** + * Filter features returned in the response. + * + * To filter features by meter_id add the following query param: + * filter[meter_id][oeq]= + */ + filter?: ListFeatureParamsFilter +} + +export type ListFeaturesRequest = AcceptDateStrings +export type ListFeaturesResponse = FeaturePagePaginatedResponse + +export type CreateFeatureRequest = AcceptDateStrings +export type CreateFeatureResponse = Feature + +export type GetFeatureRequest = { + featureId: string +} +export type GetFeatureResponse = Feature + +export type UpdateFeatureRequest = AcceptDateStrings<{ + featureId: string + body: UpdateFeatureRequestBody +}> +export type UpdateFeatureResponse = Feature + +export type DeleteFeatureRequest = { + featureId: string +} +export type DeleteFeatureResponse = void + +export type QueryFeatureCostRequest = AcceptDateStrings<{ + featureId: string + body: MeterQueryRequestInput +}> +export type QueryFeatureCostResponse = FeatureCostQueryResult diff --git a/api/spec/packages/aip-client-javascript/src/models/operations/governance.ts b/api/spec/packages/aip-client-javascript/src/models/operations/governance.ts new file mode 100644 index 0000000000000000000000000000000000000000..792046fc6862cd93f98e6646748e7b93adb74dc9 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/models/operations/governance.ts @@ -0,0 +1,21 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { z } from 'zod' +import * as schemas from '../schemas.js' +import type { AcceptDateStrings } from '../../lib/wire.js' +import type { + CursorPaginationQueryPage, + GovernanceQueryRequestInput, + GovernanceQueryResponse, +} from '../types.js' + +export interface QueryGovernanceAccessQuery { + page?: CursorPaginationQueryPage +} + +export type QueryGovernanceAccessRequest = AcceptDateStrings< + { + body: GovernanceQueryRequestInput + } & QueryGovernanceAccessQuery +> +export type QueryGovernanceAccessResponse = GovernanceQueryResponse diff --git a/api/spec/packages/aip-client-javascript/src/models/operations/invoices.ts b/api/spec/packages/aip-client-javascript/src/models/operations/invoices.ts new file mode 100644 index 0000000000000000000000000000000000000000..c592ff2a97c583585f18bd1f4507b33068781366 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/models/operations/invoices.ts @@ -0,0 +1,77 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { z } from 'zod' +import * as schemas from '../schemas.js' +import type { AcceptDateStrings } from '../../lib/wire.js' +import type { + Invoice, + InvoicePagePaginatedResponse, + ListInvoicesParamsFilter, + SortQueryInput, + UpdateInvoiceRequestInput, +} from '../types.js' + +export interface ListInvoicesQuery { + /** Determines which page of the collection to retrieve. */ + page?: { size?: number; number?: number } + /** + * Sort invoices returned in the response. Supported sort attributes: + * + * - `issued_at` + * - `created_at` (default) + * - `service_period_start` + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ + sort?: SortQueryInput + /** + * Filter invoices returned in the response. + * + * Examples: + * + * - `filter[status][oeq]=draft,issued` + * - `filter[customer_id]=01KPDB8K...` + * - `filter[issued_at][gte]=2024-01-01T00:00:00Z` + */ + filter?: ListInvoicesParamsFilter +} + +export type ListInvoicesRequest = AcceptDateStrings +export type ListInvoicesResponse = InvoicePagePaginatedResponse + +export type GetInvoiceRequest = { + invoiceId: string +} +export type GetInvoiceResponse = Invoice + +export type UpdateInvoiceRequest = AcceptDateStrings<{ + invoiceId: string + body: UpdateInvoiceRequestInput +}> +export type UpdateInvoiceResponse = Invoice + +export type DeleteInvoiceRequest = { + invoiceId: string +} +export type DeleteInvoiceResponse = void + +export type AdvanceInvoiceRequest = { + invoiceId: string +} +export type AdvanceInvoiceResponse = Invoice + +export type ApproveInvoiceRequest = { + invoiceId: string +} +export type ApproveInvoiceResponse = Invoice + +export type RetryInvoiceRequest = { + invoiceId: string +} +export type RetryInvoiceResponse = Invoice + +export type SnapshotQuantitiesInvoiceRequest = { + invoiceId: string +} +export type SnapshotQuantitiesInvoiceResponse = Invoice diff --git a/api/spec/packages/aip-client-javascript/src/models/operations/llmCost.ts b/api/spec/packages/aip-client-javascript/src/models/operations/llmCost.ts new file mode 100644 index 0000000000000000000000000000000000000000..13cc7c8c4afb2d478871e85b5057048c509a6808 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/models/operations/llmCost.ts @@ -0,0 +1,59 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { z } from 'zod' +import * as schemas from '../schemas.js' +import type { AcceptDateStrings } from '../../lib/wire.js' +import type { + ListLlmCostPricesParamsFilter, + LlmCostOverrideCreate, + LlmCostPrice, + PricePagePaginatedResponse, + SortQueryInput, +} from '../types.js' + +export interface ListLlmCostPricesQuery { + /** Filter prices. */ + filter?: ListLlmCostPricesParamsFilter + /** + * Sort prices returned in the response. Supported sort attributes are: + * + * - `id` + * - `provider.id` + * - `model.id` (default) + * - `effective_from` + * - `effective_to` + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ + sort?: SortQueryInput + /** Determines which page of the collection to retrieve. */ + page?: { size?: number; number?: number } +} + +export type ListLlmCostPricesRequest = AcceptDateStrings +export type ListLlmCostPricesResponse = PricePagePaginatedResponse + +export type GetLlmCostPriceRequest = { + priceId: string +} +export type GetLlmCostPriceResponse = LlmCostPrice + +export interface ListLlmCostOverridesQuery { + filter?: ListLlmCostPricesParamsFilter + /** Determines which page of the collection to retrieve. */ + page?: { size?: number; number?: number } +} + +export type ListLlmCostOverridesRequest = + AcceptDateStrings +export type ListLlmCostOverridesResponse = PricePagePaginatedResponse + +export type CreateLlmCostOverrideRequest = + AcceptDateStrings +export type CreateLlmCostOverrideResponse = LlmCostPrice + +export type DeleteLlmCostOverrideRequest = { + priceId: string +} +export type DeleteLlmCostOverrideResponse = void diff --git a/api/spec/packages/aip-client-javascript/src/models/operations/meters.ts b/api/spec/packages/aip-client-javascript/src/models/operations/meters.ts new file mode 100644 index 0000000000000000000000000000000000000000..894abacd967977624738a6ddde0782f133cdcc3c --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/models/operations/meters.ts @@ -0,0 +1,73 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { z } from 'zod' +import * as schemas from '../schemas.js' +import type { AcceptDateStrings } from '../../lib/wire.js' +import type { + CreateMeterRequest as CreateMeterRequestBody, + ListMetersParamsFilter, + Meter, + MeterPagePaginatedResponse, + MeterQueryRequestInput, + MeterQueryResult, + SortQueryInput, + UpdateMeterRequest as UpdateMeterRequestBody, +} from '../types.js' + +export type CreateMeterRequest = AcceptDateStrings +export type CreateMeterResponse = Meter + +export type GetMeterRequest = { + meterId: string +} +export type GetMeterResponse = Meter + +export interface ListMetersQuery { + /** Determines which page of the collection to retrieve. */ + page?: { size?: number; number?: number } + /** + * Sort meters returned in the response. Supported sort attributes are: + * + * - `key` + * - `name` + * - `aggregation` + * - `created_at` (default) + * - `updated_at` + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ + sort?: SortQueryInput + /** + * Filter meters returned in the response. + * + * To filter meters by key add the following query param: filter[key]=my-meter-key + */ + filter?: ListMetersParamsFilter +} + +export type ListMetersRequest = AcceptDateStrings +export type ListMetersResponse = MeterPagePaginatedResponse + +export type UpdateMeterRequest = AcceptDateStrings<{ + meterId: string + body: UpdateMeterRequestBody +}> +export type UpdateMeterResponse = Meter + +export type DeleteMeterRequest = { + meterId: string +} +export type DeleteMeterResponse = void + +export type QueryMeterRequest = AcceptDateStrings<{ + meterId: string + body: MeterQueryRequestInput +}> +export type QueryMeterResponse = MeterQueryResult + +export type QueryMeterCsvRequest = AcceptDateStrings<{ + meterId: string + body: MeterQueryRequestInput +}> +export type QueryMeterCsvResponse = string diff --git a/api/spec/packages/aip-client-javascript/src/models/operations/planAddons.ts b/api/spec/packages/aip-client-javascript/src/models/operations/planAddons.ts new file mode 100644 index 0000000000000000000000000000000000000000..65b3ba9c513fc84ba9f4812662381ef79dbfc2ab --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/models/operations/planAddons.ts @@ -0,0 +1,46 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { z } from 'zod' +import * as schemas from '../schemas.js' +import type { AcceptDateStrings } from '../../lib/wire.js' +import type { + CreatePlanAddonRequest as CreatePlanAddonRequestBody, + PlanAddon, + PlanAddonPagePaginatedResponse, + UpsertPlanAddonRequest, +} from '../types.js' + +export interface ListPlanAddonsQuery { + /** Determines which page of the collection to retrieve. */ + page?: { size?: number; number?: number } +} + +export type ListPlanAddonsRequest = AcceptDateStrings< + ListPlanAddonsQuery & { planId: string } +> +export type ListPlanAddonsResponse = PlanAddonPagePaginatedResponse + +export type CreatePlanAddonRequest = AcceptDateStrings<{ + planId: string + body: CreatePlanAddonRequestBody +}> +export type CreatePlanAddonResponse = PlanAddon + +export type GetPlanAddonRequest = { + planId: string + planAddonId: string +} +export type GetPlanAddonResponse = PlanAddon + +export type UpdatePlanAddonRequest = AcceptDateStrings<{ + planId: string + planAddonId: string + body: UpsertPlanAddonRequest +}> +export type UpdatePlanAddonResponse = PlanAddon + +export type DeletePlanAddonRequest = { + planId: string + planAddonId: string +} +export type DeletePlanAddonResponse = void diff --git a/api/spec/packages/aip-client-javascript/src/models/operations/plans.ts b/api/spec/packages/aip-client-javascript/src/models/operations/plans.ts new file mode 100644 index 0000000000000000000000000000000000000000..367fe525fd18449154ebdc2956a12043cb323e25 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/models/operations/plans.ts @@ -0,0 +1,62 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { z } from 'zod' +import * as schemas from '../schemas.js' +import type { AcceptDateStrings } from '../../lib/wire.js' +import type { + CreatePlanRequestInput, + ListPlansParamsFilter, + Plan, + PlanPagePaginatedResponse, + SortQueryInput, + UpsertPlanRequestInput, +} from '../types.js' + +export interface ListPlansQuery { + /** Determines which page of the collection to retrieve. */ + page?: { size?: number; number?: number } + /** + * Sort plans returned in the response. Supported sort attributes are: + * + * - `id` + * - `key` + * - `version` + * - `created_at` (default) + * - `updated_at` + */ + sort?: SortQueryInput + /** Filter plans returned in the response. */ + filter?: ListPlansParamsFilter +} + +export type ListPlansRequest = AcceptDateStrings +export type ListPlansResponse = PlanPagePaginatedResponse + +export type CreatePlanRequest = AcceptDateStrings +export type CreatePlanResponse = Plan + +export type UpdatePlanRequest = AcceptDateStrings<{ + planId: string + body: UpsertPlanRequestInput +}> +export type UpdatePlanResponse = Plan + +export type GetPlanRequest = { + planId: string +} +export type GetPlanResponse = Plan + +export type DeletePlanRequest = { + planId: string +} +export type DeletePlanResponse = void + +export type ArchivePlanRequest = { + planId: string +} +export type ArchivePlanResponse = Plan + +export type PublishPlanRequest = { + planId: string +} +export type PublishPlanResponse = Plan diff --git a/api/spec/packages/aip-client-javascript/src/models/operations/subscriptions.ts b/api/spec/packages/aip-client-javascript/src/models/operations/subscriptions.ts new file mode 100644 index 0000000000000000000000000000000000000000..7e575cc6f300d9a0cd28e2eccf6f1738044cfc50 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/models/operations/subscriptions.ts @@ -0,0 +1,99 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { z } from 'zod' +import * as schemas from '../schemas.js' +import type { AcceptDateStrings } from '../../lib/wire.js' +import type { + CreateSubscriptionAddonRequest as CreateSubscriptionAddonRequestBody, + ListSubscriptionsParamsFilter, + SortQueryInput, + Subscription, + SubscriptionAddon, + SubscriptionAddonPagePaginatedResponse, + SubscriptionCancelInput, + SubscriptionChange, + SubscriptionChangeResponse, + SubscriptionCreate, + SubscriptionPagePaginatedResponse, +} from '../types.js' + +export type CreateSubscriptionRequest = AcceptDateStrings +export type CreateSubscriptionResponse = Subscription + +export interface ListSubscriptionsQuery { + /** Determines which page of the collection to retrieve. */ + page?: { size?: number; number?: number } + /** + * Sort subscriptions returned in the response. Supported sort attributes are: + * + * - `id` + * - `active_from` (default) + * - `active_to` + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ + sort?: SortQueryInput + /** Filter subscriptions. */ + filter?: ListSubscriptionsParamsFilter +} + +export type ListSubscriptionsRequest = AcceptDateStrings +export type ListSubscriptionsResponse = SubscriptionPagePaginatedResponse + +export type GetSubscriptionRequest = { + subscriptionId: string +} +export type GetSubscriptionResponse = Subscription + +export type CancelSubscriptionRequest = AcceptDateStrings<{ + subscriptionId: string + body: SubscriptionCancelInput +}> +export type CancelSubscriptionResponse = Subscription + +export type UnscheduleCancelationRequest = { + subscriptionId: string +} +export type UnscheduleCancelationResponse = Subscription + +export type ChangeSubscriptionRequest = AcceptDateStrings<{ + subscriptionId: string + body: SubscriptionChange +}> +export type ChangeSubscriptionResponse = SubscriptionChangeResponse + +export type CreateSubscriptionAddonRequest = AcceptDateStrings<{ + subscriptionId: string + body: CreateSubscriptionAddonRequestBody +}> +export type CreateSubscriptionAddonResponse = SubscriptionAddon + +export interface ListSubscriptionAddonsQuery { + /** Determines which page of the collection to retrieve. */ + page?: { size?: number; number?: number } + /** + * Sort subscription addons returned in the response. Supported sort attributes + * are: + * + * - `id` + * - `created_at` (default) + * - `updated_at` + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ + sort?: SortQueryInput +} + +export type ListSubscriptionAddonsRequest = AcceptDateStrings< + ListSubscriptionAddonsQuery & { subscriptionId: string } +> +export type ListSubscriptionAddonsResponse = + SubscriptionAddonPagePaginatedResponse + +export type GetSubscriptionAddonRequest = { + subscriptionId: string + subscriptionAddonId: string +} +export type GetSubscriptionAddonResponse = SubscriptionAddon diff --git a/api/spec/packages/aip-client-javascript/src/models/operations/tax.ts b/api/spec/packages/aip-client-javascript/src/models/operations/tax.ts new file mode 100644 index 0000000000000000000000000000000000000000..b2fb3cd59089617783e84a2cd417476a6b305e07 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/models/operations/tax.ts @@ -0,0 +1,40 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { z } from 'zod' +import * as schemas from '../schemas.js' +import type { AcceptDateStrings } from '../../lib/wire.js' +import type { + CreateTaxCodeRequest as CreateTaxCodeRequestBody, + TaxCode, + TaxCodePagePaginatedResponse, + UpsertTaxCodeRequest as UpsertTaxCodeRequestBody, +} from '../types.js' + +export type CreateTaxCodeRequest = AcceptDateStrings +export type CreateTaxCodeResponse = TaxCode + +export type GetTaxCodeRequest = { + taxCodeId: string +} +export type GetTaxCodeResponse = TaxCode + +export interface ListTaxCodesQuery { + /** Determines which page of the collection to retrieve. */ + page?: { size?: number; number?: number } + /** Include deleted tax codes in the response. */ + includeDeleted?: boolean +} + +export type ListTaxCodesRequest = AcceptDateStrings +export type ListTaxCodesResponse = TaxCodePagePaginatedResponse + +export type UpsertTaxCodeRequest = AcceptDateStrings<{ + taxCodeId: string + body: UpsertTaxCodeRequestBody +}> +export type UpsertTaxCodeResponse = TaxCode + +export type DeleteTaxCodeRequest = { + taxCodeId: string +} +export type DeleteTaxCodeResponse = void diff --git a/api/spec/packages/aip-client-javascript/src/models/schemas.ts b/api/spec/packages/aip-client-javascript/src/models/schemas.ts new file mode 100644 index 0000000000000000000000000000000000000000..03f5ba19d97b2d3d91ddd51238148adfd2b80cc5 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/models/schemas.ts @@ -0,0 +1,13423 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { z } from 'zod' + +export const labels = z + .record(z.string(), z.string()) + + .describe( + 'Labels store metadata of an entity that can be used for filtering an entity list or for searching across entity types. Keys must be of length 1-63 characters, and cannot start with "kong", "konnect", "mesh", "kic", or "\\_".', + ) + +export const currencyCode = z + .string() + .min(3) + .max(3) + .regex(new RegExp('^[A-Z]{3}$')) + + .describe( + 'Three-letter [ISO4217](https://www.iso.org/iso-4217-currency-codes.html) currency code. Custom three-letter currency codes are also supported for convenience.', + ) + +export const numeric = z + .string() + .regex(new RegExp('^\\-?[0-9]+(\\.[0-9]+)?$')) + .describe('Numeric represents an arbitrary precision number.') + +export const cursorPaginationQueryPage = z + .object({ + size: z + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + after: z + .string() + .optional() + + .describe( + 'Request the next page of data, starting with the item after this parameter.', + ), + before: z + .string() + .optional() + + .describe( + 'Request the previous page of data, starting with the item before this parameter.', + ), + }) + .describe('Determines which page of the collection to retrieve.') + +export const stringFieldFilter = z + .union([ + z.string(), + z.object({ + eq: z + .string() + .optional() + .describe('Value strictly equals the given string value.'), + neq: z + .string() + .optional() + .describe('Value does not equal the given string value.'), + contains: z + .string() + .optional() + .describe('Value contains the given string value (fuzzy match).'), + ocontains: z + .array(z.string()) + .optional() + + .describe( + 'Returns entities that fuzzy-match any of the comma-delimited phrases in the filter string.', + ), + oeq: z + .array(z.string()) + .optional() + + .describe( + 'Returns entities that exact match any of the comma-delimited phrases in the filter string.', + ), + gt: z + .string() + .optional() + + .describe( + 'Value is greater than the given string value (lexicographic compare).', + ), + gte: z + .string() + .optional() + + .describe( + 'Value is greater than or equal to the given string value (lexicographic compare).', + ), + lt: z + .string() + .optional() + + .describe( + 'Value is less than the given string value (lexicographic compare).', + ), + lte: z + .string() + .optional() + + .describe( + 'Value is less than or equal to the given string value (lexicographic compare).', + ), + exists: z + .boolean() + .optional() + + .describe( + 'When true, the field must be present (non-null); when false, the field must be absent (null).', + ), + }), + ]) + + .describe( + 'Filters on the given string field value by either exact or fuzzy match. All properties are optional; provide exactly one to specify the comparison.', + ) + +export const ulid = z + .string() + .regex(new RegExp('^[0-7][0-9A-HJKMNP-TV-Z]{25}$')) + .describe('ULID (Universally Unique Lexicographically Sortable Identifier).') + +export const dateTime = z + .date() + + .describe( + '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.', + ) + +export const sortQuery = z + .object({ + by: z.string().describe('The attribute to sort by.'), + order: z + .union([z.literal('asc'), z.literal('desc')]) + .optional() + .default('asc') + .describe('The sort order. `asc` for ascending, `desc` for descending.'), + }) + + .describe( + 'Sort query. The `asc` suffix is optional as the default sort order is ascending. The `desc` suffix is used to specify a descending order.', + ) + +export const ingestedEventValidationError = z + .object({ + code: z.string().describe('The machine readable code of the error.'), + message: z + .string() + .describe('The human readable description of the error.'), + attributes: z + .record(z.string(), z.unknown()) + .optional() + .describe('Additional attributes.'), + }) + .describe('Event validation errors.') + +export const cursorMetaPage = z + .object({ + first: z.string().optional().describe('URI to the first page.'), + last: z.string().optional().describe('URI to the last page.'), + next: z.string().nullable().describe('URI to the next page.'), + previous: z.string().nullable().describe('URI to the previous page.'), + size: z.number().int().describe('Requested page size.'), + }) + .describe('Cursor pagination metadata.') + +export const invalidRules = z + .enum([ + 'required', + 'is_array', + 'is_base64', + 'is_boolean', + 'is_date_time', + 'is_integer', + 'is_null', + 'is_number', + 'is_object', + 'is_string', + 'is_uuid', + 'is_fqdn', + 'is_arn', + 'unknown_property', + 'missing_reference', + 'is_label', + 'matches_regex', + 'invalid', + 'is_supported_network_availability_zone_list', + 'is_supported_network_cidr_block', + 'is_supported_provider_region', + 'type', + ]) + .describe('The validation rule that a parameter failed.') + +export const invalidParameterMinimumRule = z + .enum([ + 'min_length', + 'min_digits', + 'min_lowercase', + 'min_uppercase', + 'min_symbols', + 'min_items', + 'min', + ]) + .describe('Minimum-length (or minimum-value) validation rules.') + +export const invalidParameterMaximumRule = z + .enum(['max_length', 'max_items', 'max']) + .describe('Maximum-length (or maximum-value) validation rules.') + +export const invalidParameterChoiceRule = z + .enum(['enum']) + .describe('The enum validation rule.') + +export const invalidParameterDependentRule = z + .enum(['dependent_fields']) + .describe('The dependent-fields validation rule.') + +export const baseError = z + .intersection( + z.object({ + type: z + .string() + .default('about:blank') + .describe('Type contains a URI that identifies the problem type.'), + status: z + .number() + .int() + + .describe( + 'The HTTP status code generated by the origin server for this occurrence of the problem.', + ), + title: z + .string() + .describe('A a short, human-readable summary of the problem type.'), + detail: z + .string() + + .describe( + 'A human-readable explanation specific to this occurrence of the problem.', + ), + instance: z + .string() + + .describe( + 'A URI reference that identifies the specific occurrence of the problem.', + ), + }), + z.record(z.string(), z.unknown()), + ) + .describe('Standard error response.') + +export const resourceKey = z + .string() + .min(1) + .max(64) + .regex(new RegExp('^[a-z0-9]+(?:_[a-z0-9]+)*$')) + .describe('A key is a unique string that is used to identify a resource.') + +export const meterAggregation = z + .union([ + z.literal('sum'), + z.literal('count'), + z.literal('unique_count'), + z.literal('avg'), + z.literal('min'), + z.literal('max'), + z.literal('latest'), + ]) + .describe('The aggregation type to use for the meter.') + +export const pageMeta = z + .object({ + number: z.number().int().describe('Page number.'), + size: z.number().int().describe('Page size.'), + total: z + .number() + .int() + .describe('Total number of items in the collection.'), + }) + .describe('Pagination information.') + +export const meterQueryGranularity = z + .union([ + z.literal('PT1M'), + z.literal('PT1H'), + z.literal('P1D'), + z.literal('P1M'), + ]) + + .describe( + 'The granularity of the time grouping. Time durations are specified in ISO 8601 format.', + ) + +export const queryFilterString = z + .object({ + eq: z + .string() + .optional() + .describe('The attribute equals the provided value.'), + neq: z + .string() + .optional() + .describe('The attribute does not equal the provided value.'), + in: z + .array(z.string()) + .min(1) + .max(100) + .optional() + .describe('The attribute is one of the provided values.'), + nin: z + .array(z.string()) + .min(1) + .max(100) + .optional() + .describe('The attribute is not one of the provided values.'), + contains: z + .string() + .optional() + .describe('The attribute contains the provided value.'), + ncontains: z + .string() + .optional() + .describe('The attribute does not contain the provided value.'), + get and() { + return z + .array(queryFilterString) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical AND.') + }, + get or() { + return z + .array(queryFilterString) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical OR.') + }, + }) + + .describe( + 'A query filter for a string attribute. Operators are mutually exclusive, only one operator is allowed at a time.', + ) + +export const externalResourceKey = z + .string() + .min(1) + .max(256) + + .describe( + 'ExternalResourceKey is a unique string that is used to identify a resource in an external system.', + ) + +export const usageAttributionSubjectKey = z + .string() + .min(1) + .describe('Subject key.') + +export const countryCode = z + .string() + .min(2) + .max(2) + .regex(new RegExp('^[A-Z]{2}$')) + + .describe( + '[ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 country code. Custom two-letter country codes are also supported for convenience.', + ) + +export const appStripeCreateCheckoutSessionBillingAddressCollection = z + .enum(['auto', 'required']) + + .describe( + "Controls whether Checkout collects the customer's billing address.", + ) + +export const appStripeCreateCheckoutSessionCustomerUpdateBehavior = z + .enum(['auto', 'never']) + .describe('Behavior for updating customer fields from checkout session.') + +export const appStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition = + z + .enum(['auto', 'hidden']) + .describe('Position of payment method reuse agreement in the UI.') + +export const appStripeCreateCheckoutSessionConsentCollectionPromotions = z + .enum(['auto', 'none']) + .describe('Promotional communication consent collection setting.') + +export const appStripeCreateCheckoutSessionConsentCollectionTermsOfService = z + .enum(['none', 'required']) + .describe('Terms of service acceptance requirement.') + +export const appStripeCheckoutSessionCustomTextParams = z + .object({ + afterSubmit: z + .object({ + message: z + .string() + .max(1200) + .optional() + .describe('The custom message text (max 1200 characters).'), + }) + .optional() + .describe('Text displayed after the payment confirmation button.'), + shippingAddress: z + .object({ + message: z + .string() + .max(1200) + .optional() + .describe('The custom message text (max 1200 characters).'), + }) + .optional() + .describe('Text displayed alongside shipping address collection.'), + submit: z + .object({ + message: z + .string() + .max(1200) + .optional() + .describe('The custom message text (max 1200 characters).'), + }) + .optional() + .describe('Text displayed alongside the payment confirmation button.'), + termsOfServiceAcceptance: z + .object({ + message: z + .string() + .max(1200) + .optional() + .describe('The custom message text (max 1200 characters).'), + }) + .optional() + .describe('Text replacing the default terms of service agreement text.'), + }) + .describe('Custom text displayed at various stages of the checkout flow.') + +export const appStripeCheckoutSessionUiMode = z + .enum(['embedded', 'hosted']) + .describe('Checkout Session UI mode.') + +export const appStripeCreateCheckoutSessionRedirectOnCompletion = z + .enum(['always', 'if_required', 'never']) + .describe('Redirect behavior for embedded checkout sessions.') + +export const appStripeCreateCheckoutSessionTaxIdCollectionRequired = z + .enum(['if_supported', 'never']) + .describe('Tax ID collection requirement level.') + +export const appStripeCheckoutSessionMode = z + .enum(['setup']) + + .describe( + 'Stripe Checkout Session mode. Determines the primary purpose of the checkout session.', + ) + +export const appStripeCreateCustomerPortalSessionOptions = z + .object({ + configurationId: z + .string() + .optional() + + .describe( + 'The ID of an existing [Stripe configuration](https://docs.stripe.com/api/customer_portal/configurations) to use for this session, describing its functionality and features. If not specified, the session uses the default configuration.', + ), + locale: z + .string() + .optional() + + .describe( + "The IETF [language tag](https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-locale) of the locale customer portal is displayed in. If blank or `auto`, the customer's preferred_locales or browser's locale is used.", + ), + returnUrl: z + .string() + .optional() + + .describe( + 'The [URL to redirect](https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-return_url) the customer to after they have completed their requested actions.', + ), + }) + .describe('Request to create a Stripe Customer Portal Session.') + +export const entitlementType = z + .enum(['metered', 'static', 'boolean']) + .describe('The type of the entitlement.') + +export const createLabels = z + .record(z.string(), z.string()) + + .describe( + 'Labels store metadata of an entity that can be used for filtering an entity list or for searching across entity types. Keys must be of length 1-63 characters, and cannot start with "kong", "konnect", "mesh", "kic", or "\\_".', + ) + +export const creditFundingMethod = z + .enum(['none', 'invoice', 'external']) + + .describe( + 'The funding method describes how the grant is funded. - `none`: No funding workflow applies, for example promotional grants - `invoice`: The grant is funded by an in-system invoice flow - `external`: The grant is funded outside the system (e.g., wire transfer, external invoice, or manual reconciliation)', + ) + +export const creditAvailabilityPolicy = z + .enum(['on_creation']) + + .describe( + 'When credits become available for consumption. - `on_creation`: Credits are available as soon as the grant is created. - `on_authorization`: Credits are available once the payment is authorized. - `on_settlement`: Credits are available once the payment is settled.', + ) + +export const taxBehavior = z + .enum(['inclusive', 'exclusive']) + + .describe( + 'Tax behavior. This enum is used to specify whether tax is included in the price or excluded from the price.', + ) + +export const iso8601Duration = z + .string() + + .regex( + new RegExp( + '^P(?:\\d+(?:\\.\\d+)?Y)?(?:\\d+(?:\\.\\d+)?M)?(?:\\d+(?:\\.\\d+)?W)?(?:\\d+(?:\\.\\d+)?D)?(?:T(?:\\d+(?:\\.\\d+)?H)?(?:\\d+(?:\\.\\d+)?M)?(?:\\d+(?:\\.\\d+)?S)?)?$', + ), + ) + + .describe( + '[ISO 8601 Duration](https://docs.digi.com/resources/documentation/digidocs/90001488-13/reference/r_iso_8601_duration_format.htm) string.', + ) + +export const creditPurchasePaymentSettlementStatus = z + .enum(['pending', 'authorized', 'settled']) + + .describe( + 'Credit purchase payment settlement status. - `pending`: Payment has been initiated and is not yet authorized. - `authorized`: Payment has been authorized. - `settled`: Payment has been settled.', + ) + +export const creditGrantStatus = z + .enum(['pending', 'active', 'expired', 'voided']) + + .describe( + 'Credit grant lifecycle status. - `pending`: The credit block has been created but is not yet valid. (`effective_at` is in the future or availability_policy is not met) - `active`: The credit block is currently valid and eligible for consumption. (`effective_at` is in the past, `expires_at` is in the future and availability_policy is met) - `expired`: The credit block expired with remaining unused balance, `expires_at` time has passed. - `voided`: The credit block was voided. Remaining balance is forfeited.', + ) + +export const stringFieldFilterExact = z + .union([ + z.string(), + z.object({ + eq: z + .string() + .optional() + .describe('Value strictly equals the given string value.'), + oeq: z + .array(z.string()) + .optional() + + .describe( + 'Returns entities that exact match any of the comma-delimited phrases in the filter string.', + ), + neq: z + .string() + .optional() + .describe('Value does not equal the given string value.'), + }), + ]) + + .describe( + 'Filters on the given string field value by exact match. All properties are optional; provide exactly one to specify the comparison.', + ) + +export const creditGrantVoidPaymentAdjustment = z + .enum(['none']) + + .describe( + 'Describes how voiding a credit grant adjusts related payment state. - `none`: Voiding does not adjust invoices, payment authorization, settlement, payment intents, or external collection state.', + ) + +export const creditTransactionType = z + .enum(['funded', 'consumed', 'expired', 'voided']) + + .describe( + 'The type of the credit transaction. - `funded`: Credit granted and available for consumption. - `consumed`: Credit consumed by usage or fees. - `expired`: Credit removed because it expired before being used. - `voided`: Credit removed because the grant was voided before being used.', + ) + +export const chargesExpand = z + .enum(['real_time_usage']) + + .describe( + "Expands for customer charges. Values: - `real_time_usage`: The charge's real-time usage.", + ) + +export const lifecycleController = z + .enum(['system', 'manual']) + + .describe( + 'Identifies whether a resource lifecycle is controlled by OpenMeter or manually overridden by the API user. Values: - `system`: The resource lifecycle is controlled by OpenMeter. - `manual`: The resource lifecycle was manually overridden by the API user.', + ) + +export const chargeStatus = z + .enum(['created', 'active', 'final', 'deleted']) + + .describe( + 'Lifecycle status of a charge. Values: - `created`: The charge has been created but is not active yet. - `active`: The charge is active. - `final`: The charge is fully finalized and no further changes are expected. - `deleted`: The charge has been deleted.', + ) + +export const settlementMode = z + .enum(['credit_then_invoice', 'credit_only']) + + .describe( + 'Settlement mode for billing. Values: - `credit_then_invoice`: Credits are applied first, then any remainder is invoiced. - `credit_only`: Usage is settled exclusively against credits.', + ) + +export const taxConfigStripe = z + .object({ + code: z + .string() + .regex(new RegExp('^txcd_\\d{8}$')) + .describe('Product [tax code](https://docs.stripe.com/tax/tax-codes).'), + }) + .describe('The tax config for Stripe.') + +export const taxConfigExternalInvoicing = z + .object({ + code: z + .string() + .max(64) + + .describe( + 'The tax code should be interpreted by the external invoicing provider.', + ), + }) + .describe('External invoicing tax config.') + +export const pricePaymentTerm = z + .union([z.literal('in_advance'), z.literal('in_arrears')]) + .describe('The payment term of a flat price.') + +export const chargeFlatFeeDiscounts = z + .object({ + percentage: z + .number() + .nonnegative() + .lte(100) + .optional() + .describe('Percentage discount applied to the price (0–100).'), + }) + + .describe( + 'Discounts applicable to flat fee charges. This is the same as `ProductCatalog.Discounts` but without the `usage` field, which is not applicable to flat fee charges.', + ) + +export const rateCardProrationMode = z + .enum(['no_proration', 'prorate_prices']) + + .describe( + 'The proration mode of the rate card. Values: - `no_proration`: No proration. - `prorate_prices`: Prorate the price based on the time remaining in the billing period.', + ) + +export const priceFree = z + .object({ + type: z.literal('free').describe('The type of the price.'), + }) + .describe('Free price.') + +export const subscriptionStatus = z + .enum(['active', 'inactive', 'canceled', 'scheduled']) + .describe('Subscription status.') + +export const subscriptionEditTimingEnum = z + .enum(['immediate', 'next_billing_cycle']) + + .describe( + 'Subscription edit timing. When immediate, the requested changes take effect immediately. When next_billing_cycle, the requested changes take effect at the next billing cycle.', + ) + +export const unitConfigOperation = z + .enum(['divide', 'multiply']) + + .describe( + 'The arithmetic operation used to convert raw metered units into billing units. - `divide`: Divide the metered quantity by the conversion factor (e.g., bytes ÷ 1e9 = GB). - `multiply`: Multiply the metered quantity by the conversion factor (e.g., cost × 1.2 = cost + 20% margin).', + ) + +export const unitConfigRoundingMode = z + .enum(['ceiling', 'floor', 'half_up', 'none']) + + .describe( + 'The rounding mode applied to the converted quantity for invoicing. Rounding is applied only to the invoiced quantity. Entitlement balance checks use the precise decimal value after conversion. - `ceiling`: Round up to the next integer (typical for package-style billing). - `floor`: Round down to the previous integer. - `half_up`: Round to the nearest integer, with 0.5 rounding up. - `none`: No rounding; the converted value is used as-is.', + ) + +export const rateCardStaticEntitlement = z + .object({ + type: z.literal('static').describe('The type of the entitlement template.'), + config: z + .unknown() + + .describe( + 'The entitlement config as a JSON object. Returned when checking entitlement access; useful for configuring fine-grained access settings implemented in your own system.', + ), + }) + .describe('The entitlement template of a static entitlement.') + +export const rateCardBooleanEntitlement = z + .object({ + type: z + .literal('boolean') + .describe('The type of the entitlement template.'), + }) + .describe('The entitlement template of a boolean entitlement.') + +export const appType = z + .enum(['sandbox', 'stripe', 'external_invoicing']) + .describe('The type of the app.') + +export const appCapabilityType = z + .enum([ + 'report_usage', + 'report_events', + 'calculate_tax', + 'invoice_customers', + 'collect_payments', + ]) + + .describe( + 'Supported capability types for an App. Each capability defines an integration function that an App can perform.', + ) + +export const appInstallMethods = z + .enum(['with_oauth2', 'with_api_key', 'no_credentials_required']) + .describe('Supported installation methods for an app.') + +export const appStatus = z + .enum(['ready', 'unauthorized']) + .describe('Connection status of an installed app.') + +export const installAppStripeWithApiKey = z + .object({ + type: z.literal('stripe').describe('Type of the app.'), + name: z.string().describe('Name of the app.'), + createBillingProfile: z + .boolean() + + .describe( + 'If true, a billing profile will be created for the app. The Stripe app will be also set as the default billing profile if the current default is a Sandbox app.', + ), + apiKey: z.string().describe('API key for the app.'), + }) + .describe('Model for installing an app from the catalog with an API key.') + +export const installAppSandbox = z + .object({ + type: z.literal('sandbox').describe('Type of the app.'), + name: z.string().describe('Name of the app.'), + createBillingProfile: z + .boolean() + + .describe( + 'If true, a billing profile will be created for the app. The Stripe app will be also set as the default billing profile if the current default is a Sandbox app.', + ), + }) + .describe('Base model for installing an app from the catalog.') + +export const installAppExternalInvoicing = z + .object({ + type: z.literal('external_invoicing').describe('Type of the app.'), + name: z.string().describe('Name of the app.'), + createBillingProfile: z + .boolean() + + .describe( + 'If true, a billing profile will be created for the app. The Stripe app will be also set as the default billing profile if the current default is a Sandbox app.', + ), + }) + .describe('Base model for installing an app from the catalog.') + +export const taxIdentificationCode = z + .string() + .min(1) + .max(32) + + .describe( + 'Tax identifier code is a normalized tax code shown on the original identity document.', + ) + +export const workflowCollectionAlignmentSubscription = z + .object({ + type: z.literal('subscription').describe('The type of alignment.'), + }) + + .describe( + 'BillingWorkflowCollectionAlignmentSubscription specifies the alignment for collecting the pending line items into an invoice.', + ) + +export const workflowInvoicingSubscriptionEndProrationMode = z + .enum(['bill_full_period', 'bill_actual_period']) + .describe('Billing workflow subscription end proration mode.') + +export const workflowPaymentChargeAutomaticallySettings = z + .object({ + collectionMethod: z + .literal('charge_automatically') + .describe('The collection method for the invoice.'), + }) + + .describe( + 'Payment settings for a billing workflow when the collection method is charge automatically.', + ) + +export const workflowPaymentSendInvoiceSettings = z + .object({ + collectionMethod: z + .literal('send_invoice') + .describe('The collection method for the invoice.'), + dueAfter: z + .string() + .optional() + .default('P30D') + + .describe( + "The period after which the invoice is due. With some payment solutions it's only applicable for manual collection method.", + ), + }) + + .describe( + 'Payment settings for a billing workflow when the collection method is send invoice.', + ) + +export const invoiceNumber = z + .string() + .min(1) + .max(256) + + .describe( + 'InvoiceNumber is a unique identifier for the invoice, generated by the invoicing app. The uniqueness depends on a lot of factors: - app setting (unique per app or unique per customer) - multiple app scenarios (multiple apps generating invoices with the same prefix)', + ) + +export const invoiceValidationIssueSeverity = z + .enum(['critical', 'warning']) + .describe('Severity level of an invoice validation issue.') + +export const invoiceExternalReferences = z + .object({ + invoicingId: z + .string() + .optional() + + .describe( + 'The ID assigned by the external invoicing app (e.g. Stripe invoice ID).', + ), + paymentId: z + .string() + .optional() + + .describe( + 'The ID assigned by the external payment app (e.g. Stripe payment intent ID).', + ), + }) + + .describe( + 'External identifiers assigned to an invoice by third-party systems.', + ) + +export const invoiceStandardStatus = z + .enum([ + 'draft', + 'issuing', + 'issued', + 'payment_processing', + 'overdue', + 'paid', + 'uncollectible', + 'voided', + ]) + .describe('Lifecycle status of a standard invoice.') + +export const invoiceAvailableActionDetails = z + .object({ + resultingState: z + .string() + + .describe( + 'The extended status the invoice will transition to after performing this action.', + ), + }) + + .describe( + 'Details about an available invoice action including the resulting state.', + ) + +export const invoiceWorkflowInvoicingSettings = z + .object({ + autoAdvance: z + .boolean() + .optional() + .default(true) + + .describe( + 'Whether to automatically issue the invoice after the draft_period has passed.', + ), + draftPeriod: z + .string() + .optional() + .default('P0D') + + .describe( + 'The period for the invoice to be kept in draft status for manual reviews.', + ), + dueAfter: z + .string() + .optional() + + .describe( + 'The period after which the invoice is considered overdue if not paid.', + ), + }) + + .describe( + 'Invoice-level invoicing settings. A subset of BillingWorkflowInvoicingSettings limited to fields that are meaningful per-invoice. progressive_billing is omitted as it is a gather-time / profile-level decision.', + ) + +export const invoiceDiscountReason = z + .enum(['maximum_spend', 'ratecard_percentage', 'ratecard_usage']) + .describe('The reason a discount was applied to an invoice line.') + +export const invoiceLineExternalReferences = z + .object({ + invoicingId: z + .string() + .optional() + .describe('The ID assigned by the external invoicing app.'), + }) + + .describe( + 'External identifiers for an invoice line item assigned by third-party systems.', + ) + +export const invoiceDetailedLineCostCategory = z + .enum(['regular', 'commitment']) + .describe('Cost category of a detailed invoice line item.') + +export const updateLabels = z + .record(z.string(), z.string()) + + .describe( + 'Labels store metadata of an entity that can be used for filtering an entity list or for searching across entity types. Keys must be of length 1-63 characters, and cannot start with "kong", "konnect", "mesh", "kic", or "\\_".', + ) + +export const updateBillingInvoiceWorkflowInvoicingSettings = z + .object({ + autoAdvance: z + .boolean() + .optional() + .default(true) + + .describe( + 'Whether to automatically issue the invoice after the draft_period has passed.', + ), + draftPeriod: z + .string() + .optional() + .default('P0D') + + .describe( + 'The period for the invoice to be kept in draft status for manual reviews.', + ), + }) + + .describe( + 'Invoice-level invoicing settings. A subset of BillingWorkflowInvoicingSettings limited to fields that are meaningful per-invoice. progressive_billing is omitted as it is a gather-time / profile-level decision.', + ) + +export const updateBillingWorkflowPaymentChargeAutomaticallySettings = z + .object({ + collectionMethod: z + .literal('charge_automatically') + .describe('The collection method for the invoice.'), + }) + + .describe( + 'Payment settings for a billing workflow when the collection method is charge automatically.', + ) + +export const updateBillingWorkflowPaymentSendInvoiceSettings = z + .object({ + collectionMethod: z + .literal('send_invoice') + .describe('The collection method for the invoice.'), + dueAfter: z + .string() + .optional() + .default('P30D') + + .describe( + "The period after which the invoice is due. With some payment solutions it's only applicable for manual collection method.", + ), + }) + + .describe( + 'Payment settings for a billing workflow when the collection method is send invoice.', + ) + +export const updatePriceFree = z + .object({ + type: z.literal('free').describe('The type of the price.'), + }) + .describe('Free price.') + +export const currencyType = z + .enum(['fiat', 'custom']) + + .describe( + 'Currency type for custom currencies. It should be a unique code but not conflicting with any existing standard currency codes.', + ) + +export const currencyCodeCustom = z + .string() + .min(3) + .max(24) + + .describe( + 'Custom currency code. It should be a unique code but not conflicting with any existing fiat currency codes.', + ) + +export const featureLlmTokenType = z + .enum([ + 'input', + 'output', + 'cache_read', + 'cache_write', + 'reasoning', + 'request', + 'response', + ]) + .describe('Token type for LLM cost lookup.') + +export const llmCostProvider = z + .object({ + id: z + .string() + .describe('Identifier of the provider, e.g., "openai", "anthropic".'), + name: z + .string() + .describe('Name of the provider, e.g., "OpenAI", "Anthropic".'), + }) + .describe('LLM Provider') + +export const llmCostModel = z + .object({ + id: z + .string() + + .describe('Identifier of the model, e.g., "gpt-4", "claude-3-5-sonnet".'), + name: z + .string() + .describe('Name of the model, e.g., "GPT-4", "Claude 3.5 Sonnet".'), + }) + .describe('LLM Model') + +export const llmCostPriceSource = z + .enum(['manual', 'system']) + .describe('Identifies where an LLM cost price came from.') + +export const planStatus = z + .enum(['draft', 'active', 'archived', 'scheduled']) + + .describe( + 'The status of a plan. - `draft`: The plan has not yet been published and can be edited. - `active`: The plan is published and can be used in subscriptions. - `archived`: The plan is no longer available for use. - `scheduled`: The plan is scheduled to be published at a future date.', + ) + +export const productCatalogValidationError = z + .object({ + code: z.string().describe('Machine-readable error code.'), + message: z.string().describe('Human-readable description of the error.'), + attributes: z + .record(z.string(), z.unknown()) + .optional() + .describe('Additional structured context.'), + field: z.string().describe('The path to the field.'), + }) + .describe('Validation errors providing detailed description of the issue.') + +export const addonInstanceType = z + .enum(['single', 'multiple']) + + .describe( + 'The instanceType of the add-on. - `single`: Can be added to a subscription only once. - `multiple`: Can be added to a subscription more than once.', + ) + +export const addonStatus = z + .enum(['draft', 'active', 'archived']) + + .describe( + 'The status of the add-on defined by the `effective_from` and `effective_to` properties. - `draft`: The add-on has not yet been published and can be edited. - `active`: The add-on is published and available for use. - `archived`: The add-on is no longer available for use.', + ) + +export const governanceQueryRequestCustomers = z + .object({ + keys: z + .array(z.string()) + .min(1) + .max(100) + + .describe( + 'Each entry can be a customer `key` or a usage-attribution subject `key`. Identifiers that cannot be resolved to a customer are reported in the response `errors` array.', + ), + }) + .describe('List of customer identifiers to evaluate access for.') + +export const governanceQueryRequestFeatures = z + .object({ + keys: z + .array(z.string()) + .min(1) + .max(100) + .describe('List of feature keys to evaluate access for.'), + }) + + .describe( + 'Optional list of feature keys to evaluate access for. If omitted, all features available in the organization are returned. Providing this list is recommended to reduce the response size and the load on the backend services.', + ) + +export const governanceFeatureAccessReasonCode = z + .enum([ + 'unknown', + 'usage_limit_reached', + 'feature_unavailable', + 'feature_not_found', + 'no_credit_available', + ]) + .describe('Machine-readable reason code for denied feature access.') + +export const governanceQueryErrorCode = z + .enum(['unknown', 'customer_not_found']) + .describe('Error code for a governance query failure.') + +export const queryFilterInteger = z + .object({ + eq: z + .number() + .int() + .optional() + .describe('The attribute equals the provided value.'), + neq: z + .number() + .int() + .optional() + .describe('The attribute does not equal the provided value.'), + in: z + .array(z.number().int()) + .min(1) + .max(100) + .optional() + .describe('The attribute is one of the provided values.'), + nin: z + .array(z.number().int()) + .min(1) + .max(100) + .optional() + .describe('The attribute is not one of the provided values.'), + gt: z + .number() + .int() + .optional() + .describe('The attribute is greater than the provided value.'), + gte: z + .number() + .int() + .optional() + + .describe( + 'The attribute is greater than or equal to the provided value.', + ), + lt: z + .number() + .int() + .optional() + .describe('The attribute is less than the provided value.'), + lte: z + .number() + .int() + .optional() + .describe('The attribute is less than or equal to the provided value.'), + get and() { + return z + .array(queryFilterInteger) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical AND.') + }, + get or() { + return z + .array(queryFilterInteger) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical OR.') + }, + }) + + .describe( + 'A query filter for an integer attribute. Operators are mutually exclusive, only one operator is allowed at a time.', + ) + +export const queryFilterFloat = z + .object({ + gt: z + .number() + .optional() + .describe('The attribute is greater than the provided value.'), + gte: z + .number() + .optional() + + .describe( + 'The attribute is greater than or equal to the provided value.', + ), + lt: z + .number() + .optional() + .describe('The attribute is less than the provided value.'), + lte: z + .number() + .optional() + .describe('The attribute is less than or equal to the provided value.'), + get and() { + return z + .array(queryFilterFloat) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical AND.') + }, + get or() { + return z + .array(queryFilterFloat) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical OR.') + }, + }) + + .describe( + 'A query filter for a float attribute. Operators are mutually exclusive, only one operator is allowed at a time.', + ) + +export const queryFilterBoolean = z + .object({ + eq: z + .boolean() + .optional() + .describe('The attribute equals the provided value.'), + }) + + .describe( + 'A query filter for a boolean attribute. Operators are mutually exclusive, only one operator is allowed at a time.', + ) + +export const pagePaginationQuery = z + .object({ + page: z + .object({ + size: z + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + }) + .describe('Page pagination query.') + +export const publicLabels = z + .record(z.string(), z.string()) + + .describe( + 'Public labels store information about an entity that can be used for filtering a list of objects.', + ) + +export const booleanFieldFilter = z + .union([ + z.boolean(), + z.object({ + eq: z + .boolean() + .describe('Value strictly equals the given boolean value.'), + }), + ]) + .describe('Filter by a boolean value (true/false).') + +export const numericFieldFilter = z + .union([ + z.number(), + z.object({ + eq: z + .number() + .optional() + .describe('Value strictly equals the given numeric value.'), + neq: z + .number() + .optional() + .describe('Value does not equal the given numeric value.'), + oeq: z + .array(z.number()) + .optional() + + .describe( + 'Returns entities that match any of the comma-delimited numeric values.', + ), + lt: z + .number() + .optional() + .describe('Value is less than the given numeric value.'), + lte: z + .number() + .optional() + .describe('Value is less than or equal to the given numeric value.'), + gt: z + .number() + .optional() + .describe('Value is greater than the given numeric value.'), + gte: z + .number() + .optional() + .describe('Value is greater than or equal to the given numeric value.'), + }), + ]) + + .describe( + 'Filter by a numeric value. All properties are optional; provide exactly one to specify the comparison.', + ) + +export const chargeType = z + .enum(['flat_fee', 'usage_based']) + + .describe( + 'Type of a charge. Values: - `flat_fee`: A fixed-amount charge. - `usage_based`: A usage-priced charge.', + ) + +export const invoiceType = z + .enum(['standard']) + .describe('The type of a billing invoice.') + +export const invoiceLineType = z + .enum(['standard_line']) + .describe('Line item type discriminator.') + +export const priceType = z + .enum(['free', 'flat', 'unit', 'graduated', 'volume']) + + .describe( + "The type of the price. - `free`: No charge, the rate card is included at no cost. - `flat`: A fixed amount charged once per billing period, regardless of usage. - `unit`: A fixed rate charged per billing unit consumed. - `graduated`: Tiered pricing where each tier's rate applies only to usage within that tier. - `volume`: Tiered pricing where the rate for the highest tier reached applies to all units in the period.", + ) + +export const collectionAlignment = z + .enum(['subscription', 'anchored']) + + .describe( + 'BillingCollectionAlignment specifies when the pending line items should be collected into an invoice.', + ) + +export const collectionMethod = z + .enum(['charge_automatically', 'send_invoice']) + + .describe( + 'Collection method specifies how the invoice should be collected (automatic or manual).', + ) + +export const featureUnitCostType = z + .enum(['llm', 'manual']) + .describe('The type of unit cost.') + +export const systemAccountAccessToken = z + .object({ + type: z.literal('http').describe('Http authentication'), + scheme: z.literal('Bearer').describe('bearer auth scheme'), + }) + + .describe( + 'The system account access token is meant for automations and integrations that are not directly associated with a human identity.', + ) + +export const personalAccessToken = z + .object({ + type: z.literal('http').describe('Http authentication'), + scheme: z.literal('Bearer').describe('bearer auth scheme'), + }) + + .describe( + 'The personal access token is meant to be used as an alternative to basic-auth when accessing Konnect via APIs.', + ) + +export const konnectAccessToken = z + .object({ + type: z.literal('http').describe('Http authentication'), + scheme: z.literal('Bearer').describe('bearer auth scheme'), + }) + + .describe( + 'The Konnect access token is meant to be used by the Konnect dashboard and the decK CLI authenticate with.', + ) + +export const updateMeterRequest = z + .object({ + name: z + .string() + .min(1) + .max(256) + .optional() + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + dimensions: z + .record(z.string(), z.string()) + .optional() + + .describe( + 'Named JSONPath expressions to extract the group by values from the event data. Keys must be unique and consist only alphanumeric and underscore characters.', + ), + }) + .describe('Meter update request.') + +export const appCustomerDataStripe = z + .object({ + customerId: z.string().optional().describe('The Stripe customer ID used.'), + defaultPaymentMethodId: z + .string() + .optional() + .describe('The Stripe default payment method ID.'), + labels: labels.optional(), + }) + .describe('Stripe customer data.') + +export const appCustomerDataExternalInvoicing = z + .object({ + labels: labels.optional(), + }) + .describe('External invoicing customer data.') + +export const billingCurrencyCode = z + .union([currencyCode]) + .describe('Fiat or custom currency code.') + +export const createCurrencyCode = z + .union([currencyCode]) + .describe('Fiat or custom currency code.') + +export const currencyFiat = z + .object({ + type: z.literal('fiat').describe('The type of the currency.'), + name: z + .string() + .min(1) + .max(256) + + .describe( + 'The name of the currency. It should be a human-readable string that represents the name of the currency, such as "US Dollar" or "Euro".', + ), + symbol: z + .string() + .min(1) + .optional() + + .describe( + 'The symbol of the currency. It should be a string that represents the symbol of the currency, such as "$" for US Dollar or "€" for Euro.', + ), + code: currencyCode, + }) + .describe('Currency describes a currency supported by the billing system.') + +export const listCostBasesParamsFilter = z + .object({ + fiatCode: currencyCode.optional(), + }) + .describe('Filter options for listing cost bases.') + +export const currencyAmount = z + .object({ + amount: numeric, + currency: currencyCode, + }) + .describe('Monetary amount in a specific currency.') + +export const priceFlat = z + .object({ + type: z.literal('flat').describe('The type of the price.'), + amount: numeric, + }) + .describe('Flat price.') + +export const priceUnit = z + .object({ + type: z.literal('unit').describe('The type of the price.'), + amount: numeric, + }) + + .describe( + 'Unit price. Charges a fixed rate per billing unit. When UnitConfig is present on the rate card, billing units are the converted quantities (e.g. GB instead of bytes).', + ) + +export const rateCardDiscounts = z + .object({ + percentage: z + .number() + .nonnegative() + .lte(100) + .optional() + .describe('Percentage discount applied to the price (0–100).'), + usage: numeric.optional(), + }) + .describe('Discount configuration for a rate card.') + +export const totals = z + .object({ + amount: numeric, + taxesTotal: numeric, + taxesInclusiveTotal: numeric, + taxesExclusiveTotal: numeric, + chargesTotal: numeric, + discountsTotal: numeric, + creditsTotal: numeric, + total: numeric, + }) + + .describe( + 'Totals contains the summaries of all calculations for a billing resource.', + ) + +export const spendCommitments = z + .object({ + minimumAmount: numeric.optional(), + maximumAmount: numeric.optional(), + }) + + .describe( + 'Spend commitments for a rate card. The customer is committed to spend at least the minimum amount and at most the maximum amount.', + ) + +export const invoiceLineCreditsApplied = z + .object({ + amount: numeric, + description: z + .string() + .optional() + + .describe( + 'Optional human-readable description of the credit allocation.', + ), + }) + .describe('A credit allocation applied to an invoice line item.') + +export const updatePriceFlat = z + .object({ + type: z.literal('flat').describe('The type of the price.'), + amount: numeric, + }) + .describe('Flat price.') + +export const updatePriceUnit = z + .object({ + type: z.literal('unit').describe('The type of the price.'), + amount: numeric, + }) + + .describe( + 'Unit price. Charges a fixed rate per billing unit. When UnitConfig is present on the rate card, billing units are the converted quantities (e.g. GB instead of bytes).', + ) + +export const updateDiscounts = z + .object({ + percentage: z + .number() + .nonnegative() + .lte(100) + .optional() + .describe('Percentage discount applied to the price (0–100).'), + usage: numeric.optional(), + }) + .describe('Discount configuration for a rate card.') + +export const featureManualUnitCost = z + .object({ + type: z + .literal('manual') + .describe('The type discriminator for manual unit cost.'), + amount: numeric, + }) + .describe('A fixed per-unit cost amount.') + +export const featureLlmUnitCostPricing = z + .object({ + inputPerToken: numeric, + outputPerToken: numeric, + cacheReadPerToken: numeric.optional(), + reasoningPerToken: numeric.optional(), + cacheWritePerToken: numeric.optional(), + }) + .describe('Resolved per-token pricing from the LLM cost database.') + +export const llmCostModelPricing = z + .object({ + inputPerToken: numeric, + outputPerToken: numeric, + cacheReadPerToken: numeric.optional(), + cacheWritePerToken: numeric.optional(), + reasoningPerToken: numeric.optional(), + }) + .describe('Token pricing for an LLM model, denominated per token.') + +export const queryFilterNumeric = z + .object({ + gt: numeric.optional(), + gte: numeric.optional(), + lt: numeric.optional(), + lte: numeric.optional(), + get and() { + return z + .array(queryFilterNumeric) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical AND.') + }, + get or() { + return z + .array(queryFilterNumeric) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical OR.') + }, + }) + + .describe( + 'A query filter for a numeric attribute. Operators are mutually exclusive, only one operator is allowed at a time.', + ) + +export const cursorPaginationQuery = z + .object({ + page: cursorPaginationQueryPage.optional(), + }) + .describe('Cursor page query.') + +export const listMetersParamsFilter = z + .object({ + key: stringFieldFilter.optional(), + name: stringFieldFilter.optional(), + }) + .describe('Filter options for listing meters.') + +export const listLlmCostPricesParamsFilter = z + .object({ + provider: stringFieldFilter.optional(), + modelId: stringFieldFilter.optional(), + modelName: stringFieldFilter.optional(), + currency: stringFieldFilter.optional(), + source: stringFieldFilter.optional(), + }) + .describe('Filter options for listing LLM cost prices.') + +export const labelsFieldFilter = z + .record(z.string(), stringFieldFilter) + + .describe( + "Filters on the resource's `labels` field. The schema is a map keyed by the label name; each value is a `StringFieldFilter`. Both deepObject forms are accepted: `filter[labels][key]=value` (nested) and `filter[labels.key]=value` (dot-notation).", + ) + +export const ulidFieldFilter = z + .union([ + ulid, + z.object({ + eq: ulid.optional(), + oeq: z + .array(ulid) + .optional() + + .describe( + 'Returns entities that exact match any of the comma-delimited ULIDs in the filter string.', + ), + neq: ulid.optional(), + }), + ]) + + .describe( + 'Filters on the given ULID field value by exact match. All properties are optional; provide exactly one to specify the comparison.', + ) + +export const customerReference = z + .object({ + id: ulid, + }) + .describe('Customer reference.') + +export const profileReference = z + .object({ + id: ulid, + }) + .describe('Billing profile reference.') + +export const createResourceReference = z + .object({ + id: ulid, + }) + .describe('TaxCode reference.') + +export const taxCodeReference = z + .object({ + id: ulid, + }) + .describe('TaxCode reference.') + +export const creditGrantInvoiceReference = z + .object({ + id: ulid.optional(), + line: z + .object({ + id: ulid, + }) + .optional() + .describe('Identifier of the invoice line associated with the grant.'), + }) + .describe('Invoice references for the grant.') + +export const billingCustomerReference = z + .object({ + id: ulid, + }) + .describe('Customer reference.') + +export const subscriptionReference = z + .object({ + id: ulid, + phase: z + .object({ + id: ulid, + item: z + .object({ + id: ulid, + }) + .describe('The item of the phase.'), + }) + .describe('The phase of the subscription.'), + }) + + .describe( + 'Subscription reference represents a reference to the specific subscription item this entity represents.', + ) + +export const addonReference = z + .object({ + id: ulid, + }) + .describe('Addon reference.') + +export const featureReference = z + .object({ + id: ulid, + }) + .describe('Feature reference.') + +export const appReference = z + .object({ + id: ulid, + }) + .describe('App reference.') + +export const chargeReference = z + .object({ + id: ulid, + }) + .describe('Reference to a charge associated with an invoice line.') + +export const updateResourceReference = z + .object({ + id: ulid, + }) + .describe('TaxCode reference.') + +export const dateTimeFieldFilter = z + .union([ + dateTime, + z.object({ + eq: dateTime.optional(), + lt: dateTime.optional(), + lte: dateTime.optional(), + gt: dateTime.optional(), + gte: dateTime.optional(), + }), + ]) + + .describe( + 'Filters on the given datetime (RFC-3339) field value. All properties are optional; provide exactly one to specify the comparison.', + ) + +export const event = z + .object({ + id: z.string().min(1).describe('Identifies the event.'), + source: z + .string() + .min(1) + .describe('Identifies the context in which an event happened.'), + specversion: z + .string() + .min(1) + .default('1.0') + + .describe( + 'The version of the CloudEvents specification which the event uses.', + ), + type: z + .string() + .min(1) + + .describe( + 'Contains a value describing the type of event related to the originating occurrence.', + ), + datacontenttype: z + .literal('application/json') + .nullable() + .optional() + + .describe( + 'Content type of the CloudEvents data value. Only the value "application/json" is allowed over HTTP.', + ), + dataschema: z + .string() + .nullable() + .optional() + .describe('Identifies the schema that data adheres to.'), + subject: z + .string() + .min(1) + + .describe( + 'Describes the subject of the event in the context of the event producer (identified by source).', + ), + time: dateTime + .nullable() + .optional() + + .describe( + 'Timestamp of when the occurrence happened. Must adhere to RFC 3339.', + ), + data: z + .record(z.string(), z.unknown()) + .nullable() + .optional() + + .describe( + 'The event payload. Optional, if present it must be a JSON object.', + ), + }) + .describe('Metering event following the CloudEvents specification.') + +export const meterQueryRow = z + .object({ + value: numeric, + from: dateTime, + to: dateTime, + dimensions: z + .record(z.string(), z.string()) + + .describe( + 'The dimensions the value is aggregated over. `subject` and `customer_id` are reserved dimensions.', + ), + }) + .describe('A row in the result of a meter query.') + +export const appStripeCreateCustomerPortalSessionResult = z + .object({ + id: z + .string() + + .describe( + 'The ID of the customer portal session. See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-id', + ), + stripeCustomerId: z.string().describe('The ID of the stripe customer.'), + configurationId: z + .string() + + .describe( + 'Configuration used to customize the customer portal. See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-configuration', + ), + livemode: z + .boolean() + + .describe( + 'Livemode. See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-livemode', + ), + createdAt: dateTime, + returnUrl: z + .string() + + .describe( + 'Return URL. See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-return_url', + ), + locale: z + .string() + + .describe( + 'The IETF language tag of the locale customer portal is displayed in. See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-locale', + ), + url: z + .string() + + .describe( + 'The URL to redirect the customer to after they have completed their requested actions.', + ), + }) + + .describe( + 'Result of creating a [Stripe Customer Portal Session](https://docs.stripe.com/api/customer_portal/sessions/object). Contains all the information needed to redirect the customer to the Stripe Customer Portal.', + ) + +export const closedPeriod = z + .object({ + from: dateTime, + to: dateTime, + }) + + .describe( + 'A period with defined start and end dates. The period is always inclusive at the start and exclusive at the end.', + ) + +export const subscriptionAddonTimelineSegment = z + .object({ + activeFrom: dateTime, + activeTo: dateTime.optional(), + quantity: z + .number() + .int() + .nonnegative() + .describe('The quantity of the add-on for the given period.'), + }) + .describe('A subscription add-on event.') + +export const updateClosedPeriod = z + .object({ + from: dateTime, + to: dateTime, + }) + + .describe( + 'A period with defined start and end dates. The period is always inclusive at the start and exclusive at the end.', + ) + +export const costBasis = z + .object({ + id: ulid, + fiatCode: currencyCode, + rate: numeric, + effectiveFrom: dateTime.optional(), + effectiveTo: dateTime.optional(), + createdAt: dateTime, + }) + .describe('Describes currency basis supported by billing system.') + +export const createCostBasisRequest = z + .object({ + fiatCode: currencyCode, + rate: numeric, + effectiveFrom: dateTime.optional(), + effectiveTo: dateTime.optional(), + }) + .describe('CostBasis create request.') + +export const featureCostQueryRow = z + .object({ + usage: numeric, + cost: numeric + .nullable() + + .describe( + 'The computed cost amount (usage × unit cost). Null when pricing is not available for the given combination of dimensions.', + ), + currency: currencyCode, + detail: z + .string() + .optional() + + .describe( + 'Detail message when cost amount is null, explaining why the cost could not be resolved.', + ), + from: dateTime, + to: dateTime, + dimensions: z + .record(z.string(), z.string()) + + .describe( + 'The dimensions the value is aggregated over. `subject` and `customer_id` are reserved dimensions.', + ), + }) + .describe('A row in the result of a feature cost query.') + +export const resource = z + .object({ + id: ulid, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + }) + .describe('Represents common fields of resources.') + +export const resourceImmutable = z + .object({ + id: ulid, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + }) + .describe('Represents common fields of immutable resources.') + +export const queryFilterDateTime = z + .object({ + gt: dateTime.optional(), + gte: dateTime.optional(), + lt: dateTime.optional(), + lte: dateTime.optional(), + get and() { + return z + .array(queryFilterDateTime) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical AND.') + }, + get or() { + return z + .array(queryFilterDateTime) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical OR.') + }, + }) + + .describe( + 'A query filter for a time attribute. Operators are mutually exclusive, only one operator is allowed at a time.', + ) + +export const cursorMeta = z + .object({ + page: cursorMetaPage, + }) + .describe('Cursor pagination metadata.') + +export const invalidParameterStandard = z + .object({ + field: z.string().describe('The name of the field that failed validation.'), + rule: invalidRules.optional(), + source: z + .string() + .optional() + + .describe( + 'The part of the request the field came from (e.g. `body`, `query`).', + ), + reason: z + .string() + + .describe( + 'A human readable explanation of why the field failed validation.', + ), + }) + .describe('A parameter that failed a standard validation rule.') + +export const invalidParameterMinimumLength = z + .object({ + field: z.string().describe('The name of the field that failed validation.'), + rule: invalidParameterMinimumRule, + minimum: z.number().int().describe('The minimum allowed value or length.'), + source: z + .string() + .optional() + + .describe( + 'The part of the request the field came from (e.g. `body`, `query`).', + ), + reason: z + .string() + + .describe( + 'A human readable explanation of why the field failed validation.', + ), + }) + + .describe( + 'A parameter that failed a minimum-length (or minimum-value) validation rule.', + ) + +export const invalidParameterMaximumLength = z + .object({ + field: z.string().describe('The name of the field that failed validation.'), + rule: invalidParameterMaximumRule, + maximum: z.number().int().describe('The maximum allowed value or length.'), + source: z + .string() + .optional() + + .describe( + 'The part of the request the field came from (e.g. `body`, `query`).', + ), + reason: z + .string() + + .describe( + 'A human readable explanation of why the field failed validation.', + ), + }) + + .describe( + 'A parameter that failed a maximum-length (or maximum-value) validation rule.', + ) + +export const invalidParameterChoiceItem = z + .object({ + field: z.string().describe('The name of the field that failed validation.'), + rule: invalidParameterChoiceRule, + reason: z + .string() + + .describe( + 'A human readable explanation of why the field failed validation.', + ), + choices: z + .array(z.unknown()) + .min(1) + .describe('The allowed choices for the field.'), + source: z + .string() + .optional() + + .describe( + 'The part of the request the field came from (e.g. `body`, `query`).', + ), + }) + .describe('A parameter whose value was not one of the allowed choices.') + +export const invalidParameterDependentItem = z + .object({ + field: z.string().describe('The name of the field that failed validation.'), + rule: invalidParameterDependentRule, + reason: z + .string() + + .describe( + 'A human readable explanation of why the field failed validation.', + ), + dependents: z + .array(z.unknown()) + .describe('The fields that this field depends on.'), + source: z + .string() + .optional() + + .describe( + 'The part of the request the field came from (e.g. `body`, `query`).', + ), + }) + .describe('A parameter that failed a dependent-fields validation rule.') + +export const unauthorized = baseError.describe('Unauthorized.') + +export const forbidden = baseError.describe('Forbidden.') + +export const notFound = baseError.describe('Not Found.') + +export const gone = baseError.describe('Gone.') + +export const conflict = baseError.describe('Conflict.') + +export const payloadTooLarge = baseError.describe('Payload Too Large.') + +export const unsupportedMediaType = baseError.describe( + 'Unsupported Media Type.', +) + +export const unprocessableContent = baseError.describe('Unprocessable Content.') + +export const tooManyRequests = baseError.describe('Too Many Requests.') + +export const internal = baseError.describe('Internal Server Error.') + +export const notImplemented = baseError.describe('Not Implemented.') + +export const notAvailable = baseError.describe('Not Available.') + +export const createCreditGrantFilters = z + .object({ + features: z + .array(resourceKey) + .optional() + + .describe( + 'Limit the credit grant to specific features. If no features are specified, the credit grant can be used for any feature.', + ), + }) + .describe('Filters for the credit grant.') + +export const creditGrantFilters = z + .object({ + features: z + .array(resourceKey) + .optional() + + .describe( + 'Limit the credit grant to specific features. If no features are specified, the credit grant can be used for any feature.', + ), + }) + .describe('Filters for the credit grant.') + +export const upsertPlanAddonRequest = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + fromPlanPhase: resourceKey, + maxQuantity: z + .number() + .int() + .gte(1) + .optional() + + .describe( + 'The maximum number of times the add-on can be purchased for the plan. For single-instance add-ons this field must be omitted. For multi-instance add-ons when omitted, unlimited quantity can be purchased.', + ), + }) + .describe('PlanAddon upsert request.') + +export const resourceWithKey = z + .object({ + id: ulid, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + key: resourceKey, + }) + .describe('Represents common fields of resources with a key.') + +export const ulidOrResourceKey = z + .union([ulid, resourceKey]) + .describe('ULID ID or Resource Key.') + +export const createMeterRequest = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + key: resourceKey, + aggregation: meterAggregation, + eventType: z + .string() + .min(1) + .describe('The event type to include in the aggregation.'), + eventsFrom: dateTime.optional(), + valueProperty: z + .string() + .min(1) + .optional() + + .describe( + "JSONPath expression to extract the value from the ingested event's data property. The ingested value for sum, avg, min, and max aggregations is a number or a string that can be parsed to a number. For unique_count aggregation, the ingested value must be a string. For count aggregation the value_property is ignored.", + ), + dimensions: z + .record(z.string(), z.string()) + .optional() + + .describe( + 'Named JSONPath expressions to extract the group by values from the event data. Keys must be unique and consist only alphanumeric and underscore characters.', + ), + }) + .describe('Meter create request.') + +export const meter = z + .object({ + id: ulid, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + key: resourceKey, + aggregation: meterAggregation, + eventType: z + .string() + .min(1) + .describe('The event type to include in the aggregation.'), + eventsFrom: dateTime.optional(), + valueProperty: z + .string() + .min(1) + .optional() + + .describe( + "JSONPath expression to extract the value from the ingested event's data property. The ingested value for sum, avg, min, and max aggregations is a number or a string that can be parsed to a number. For unique_count aggregation, the ingested value must be a string. For count aggregation the value_property is ignored.", + ), + dimensions: z + .record(z.string(), z.string()) + .optional() + + .describe( + 'Named JSONPath expressions to extract the group by values from the event data. Keys must be unique and consist only alphanumeric and underscore characters.', + ), + }) + + .describe( + 'A meter is a configuration that defines how to match and aggregate events.', + ) + +export const paginatedMeta = z + .object({ + page: pageMeta, + }) + .describe('Pagination metadata.') + +export const queryFilterStringMapItem = z + .object({ + exists: z.boolean().optional().describe('The attribute exists.'), + eq: z + .string() + .optional() + .describe('The attribute equals the provided value.'), + neq: z + .string() + .optional() + .describe('The attribute does not equal the provided value.'), + in: z + .array(z.string()) + .min(1) + .max(100) + .optional() + .describe('The attribute is one of the provided values.'), + nin: z + .array(z.string()) + .min(1) + .max(100) + .optional() + .describe('The attribute is not one of the provided values.'), + contains: z + .string() + .optional() + .describe('The attribute contains the provided value.'), + ncontains: z + .string() + .optional() + .describe('The attribute does not contain the provided value.'), + and: z + .array(queryFilterString) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical AND.'), + or: z + .array(queryFilterString) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical OR.'), + }) + + .describe( + 'A query filter for an item in a string map attribute. Operators are mutually exclusive, only one operator is allowed at a time.', + ) + +export const ulidOrExternalResourceKey = z + .union([ulid, externalResourceKey]) + .describe('ULID ID or External Resource Key.') + +export const customerKeyReference = z + .object({ + key: externalResourceKey, + }) + .describe('Customer reference by external key.') + +export const customerUsageAttribution = z + .object({ + subjectKeys: z + .array(usageAttributionSubjectKey) + + .describe( + 'The subjects that are attributed to the customer. Can be empty when no usage event subjects are associated with the customer.', + ), + }) + + .describe( + 'Mapping to attribute metered usage to the customer. One customer can have zero or more subjects, but one subject can only belong to one customer.', + ) + +export const updateCustomerUsageAttribution = z + .object({ + subjectKeys: z + .array(usageAttributionSubjectKey) + + .describe( + 'The subjects that are attributed to the customer. Can be empty when no usage event subjects are associated with the customer.', + ), + }) + + .describe( + 'Mapping to attribute metered usage to the customer. One customer can have zero or more subjects, but one subject can only belong to one customer.', + ) + +export const address = z + .object({ + country: countryCode.optional(), + postalCode: z.string().optional().describe('Postal code.'), + state: z.string().optional().describe('State or province.'), + city: z.string().optional().describe('City.'), + line1: z.string().optional().describe('First line of the address.'), + line2: z.string().optional().describe('Second line of the address.'), + phoneNumber: z.string().optional().describe('Phone number.'), + }) + .describe('Address') + +export const updateAddress = z + .object({ + country: countryCode.optional(), + postalCode: z.string().optional().describe('Postal code.'), + state: z.string().optional().describe('State or province.'), + city: z.string().optional().describe('City.'), + line1: z.string().optional().describe('First line of the address.'), + line2: z.string().optional().describe('Second line of the address.'), + phoneNumber: z.string().optional().describe('Phone number.'), + }) + .describe('Address') + +export const appStripeCreateCheckoutSessionCustomerUpdate = z + .object({ + address: appStripeCreateCheckoutSessionCustomerUpdateBehavior + .optional() + .default('never'), + name: appStripeCreateCheckoutSessionCustomerUpdateBehavior + .optional() + .default('never'), + shipping: appStripeCreateCheckoutSessionCustomerUpdateBehavior + .optional() + .default('never'), + }) + + .describe( + 'Controls which customer fields can be updated by the checkout session.', + ) + +export const appStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreement = + z + .object({ + position: + appStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition.optional(), + }) + .describe('Payment method reuse agreement configuration.') + +export const appStripeCreateCheckoutSessionTaxIdCollection = z + .object({ + enabled: z + .boolean() + .optional() + .default(false) + .describe('Enable tax ID collection during checkout. Defaults to false.'), + required: appStripeCreateCheckoutSessionTaxIdCollectionRequired + .optional() + .default('never'), + }) + .describe('Tax ID collection configuration for checkout sessions.') + +export const appStripeCreateCheckoutSessionResult = z + .object({ + customerId: ulid, + stripeCustomerId: z.string().describe('The Stripe customer ID.'), + sessionId: z.string().describe('The Stripe checkout session ID.'), + setupIntentId: z + .string() + + .describe( + 'The setup intent ID created for collecting the payment method.', + ), + clientSecret: z + .string() + .optional() + + .describe( + 'Client secret for initializing Stripe.js on the client side. Required for embedded checkout sessions. See: https://docs.stripe.com/payments/checkout/custom-success-page', + ), + clientReferenceId: z + .string() + .optional() + + .describe( + 'The client reference ID provided in the request. Useful for reconciling the session with your internal systems.', + ), + customerEmail: z + .string() + .optional() + .describe("Customer's email address if provided to Stripe."), + currency: currencyCode.optional(), + createdAt: dateTime, + expiresAt: dateTime.optional(), + metadata: z + .record(z.string(), z.string()) + .optional() + .describe('Metadata attached to the checkout session.'), + status: z + .string() + .optional() + + .describe( + 'The status of the checkout session. See: https://docs.stripe.com/api/checkout/sessions/object#checkout_session_object-status', + ), + url: z + .string() + .optional() + + .describe( + 'URL to redirect customers to the checkout page (for hosted mode).', + ), + mode: appStripeCheckoutSessionMode, + cancelUrl: z + .string() + .optional() + + .describe( + 'The cancel URL where customers are redirected if they cancel.', + ), + successUrl: z + .string() + .optional() + + .describe( + 'The success URL where customers are redirected after completion.', + ), + returnUrl: z + .string() + .optional() + .describe('The return URL for embedded sessions after authentication.'), + }) + + .describe( + 'Result of creating a Stripe Checkout Session. Contains all the information needed to redirect customers to the checkout or initialize an embedded checkout flow.', + ) + +export const customerStripeCreateCustomerPortalSessionRequest = z + .object({ + stripeOptions: appStripeCreateCustomerPortalSessionOptions, + }) + + .describe( + 'Request to create a Stripe Customer Portal Session for the customer. Useful to redirect the customer to the Stripe Customer Portal to manage their payment methods, change their billing address and access their invoice history. Only returns URL if the customer billing profile is linked to a stripe app and customer.', + ) + +export const entitlementAccessResult = z + .object({ + type: entitlementType, + featureKey: resourceKey, + hasAccess: z + .boolean() + + .describe( + 'Whether the customer has access to the feature. Always true for `boolean` and `static` entitlements. Depends on balance for `metered` entitlements.', + ), + config: z + .string() + .optional() + + .describe( + 'Only available for static entitlements. Config is the JSON parsable configuration of the entitlement. Useful to describe per customer configuration.', + ), + }) + .describe('Entitlement access result.') + +export const createCreditGrantPurchase = z + .object({ + currency: currencyCode, + perUnitCostBasis: numeric.optional().default('1.0'), + availabilityPolicy: creditAvailabilityPolicy + .optional() + .default('on_creation'), + }) + .describe('Purchase and payment terms of the grant.') + +export const rateCardMeteredEntitlement = z + .object({ + type: z + .literal('metered') + .describe('The type of the entitlement template.'), + isSoftLimit: z + .boolean() + .optional() + .default(false) + + .describe( + 'If soft limit is true, the subject can use the feature even if the entitlement is exhausted; access remains granted.', + ), + limit: z + .number() + .nonnegative() + .optional() + + .describe( + "The amount of usage granted each usage period, in the feature's unit. Usage is counted against this allowance and the balance resets every usage period. When `is_soft_limit` is true the subject keeps access after the limit is reached; otherwise access is denied once the allowance is exhausted.", + ), + usagePeriod: iso8601Duration.optional(), + }) + .describe('The entitlement template of a metered entitlement.') + +export const recurringPeriod = z + .object({ + anchor: dateTime, + interval: iso8601Duration, + }) + .describe('Recurring period with an anchor and an interval.') + +export const creditGrantPurchase = z + .object({ + currency: currencyCode, + perUnitCostBasis: numeric.optional().default('1.0'), + amount: numeric, + availabilityPolicy: creditAvailabilityPolicy + .optional() + .default('on_creation'), + settlementStatus: creditPurchasePaymentSettlementStatus.optional(), + }) + .describe('Purchase and payment terms of the grant.') + +export const updateCreditGrantExternalSettlementRequest = z + .object({ + status: creditPurchasePaymentSettlementStatus, + }) + + .describe( + 'Request body for updating the external payment settlement status of a credit grant.', + ) + +export const listCreditGrantsParamsFilter = z + .object({ + status: creditGrantStatus.optional(), + currency: currencyCode.optional(), + key: stringFieldFilter.optional(), + }) + .describe('Filter options for listing credit grants.') + +export const getCreditBalanceParamsFilter = z + .object({ + currency: stringFieldFilterExact.optional(), + featureKey: stringFieldFilter.optional(), + }) + .describe('Filter options for getting a credit balance.') + +export const listChargesParamsFilter = z + .object({ + status: stringFieldFilterExact.optional(), + }) + .describe('Filter options for listing charges.') + +export const listPlansParamsFilter = z + .object({ + key: stringFieldFilter.optional(), + name: stringFieldFilter.optional(), + status: stringFieldFilterExact.optional(), + currency: stringFieldFilterExact.optional(), + }) + .describe('Filter options for listing plans.') + +export const voidCreditGrantRequest = z + .object({ + paymentAdjustment: creditGrantVoidPaymentAdjustment + .optional() + .default('none'), + }) + .describe('Request body for voiding a credit grant.') + +export const subscriptionCreate = z + .object({ + labels: labels.optional(), + settlementMode: settlementMode.optional(), + customer: z + .object({ + id: ulid.optional(), + key: externalResourceKey.optional(), + }) + .describe('The customer to create the subscription for.'), + plan: z + .object({ + id: ulid.optional(), + key: resourceKey.optional(), + version: z + .number() + .int() + .optional() + + .describe( + 'The plan version of the subscription, if any. If not provided, the latest version of the plan will be used.', + ), + }) + .describe('The plan reference of the subscription.'), + billingAnchor: dateTime.optional(), + }) + .describe('Subscription create request.') + +export const rateCardProrationConfiguration = z + .object({ + mode: rateCardProrationMode, + }) + .describe('The proration configuration of the rate card.') + +export const subscription = z + .object({ + id: ulid, + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + customerId: ulid, + planId: ulid.optional(), + billingAnchor: dateTime, + status: subscriptionStatus, + settlementMode: settlementMode.optional(), + }) + .describe('Subscription.') + +export const subscriptionEditTiming = z + .union([subscriptionEditTimingEnum, dateTime]) + + .describe( + 'Subscription edit timing defined when the changes should take effect. If the provided configuration is not supported by the subscription, an error will be returned.', + ) + +export const unitConfig = z + .object({ + operation: unitConfigOperation, + conversionFactor: numeric, + rounding: unitConfigRoundingMode.optional().default('none'), + precision: z + .number() + .int() + .optional() + .default(0) + + .describe( + 'The number of decimal places to retain after rounding. Only meaningful when rounding is not "none". Defaults to 0 (round to whole numbers).', + ), + displayUnit: z + .string() + .optional() + + .describe( + 'A human-readable label for the converted unit shown on invoices and in the customer portal (e.g., "GB", "hours", "M tokens"). Optional. When omitted, no unit label is rendered.', + ), + }) + + .describe( + 'Unit conversion configuration. Transforms raw metered quantities into billing-ready units before pricing and entitlement evaluation. Applied at the rate card level so the same feature can be billed in different units across plans. Examples: - Meter bytes, bill GB: operation=divide, conversionFactor=1e9, rounding=ceiling, displayUnit="GB" - Meter seconds, bill hours: operation=divide, conversionFactor=3600, rounding=ceiling, displayUnit="hours" - Cost + 20% margin: operation=multiply, conversionFactor=1.2 - Bill per million tokens: operation=divide, conversionFactor=1e6, rounding=ceiling, displayUnit="M" v1 equivalents: - DynamicPrice(multiplier): operation=multiply, conversionFactor=multiplier + UnitPrice(amount=1) - PackagePrice(amount, quantityPerPkg): operation=divide, conversionFactor=quantityPerPkg, rounding=ceiling + UnitPrice(amount)', + ) + +export const taxCodeAppMapping = z + .object({ + appType: appType, + taxCode: z.string().describe('Tax code.'), + }) + .describe('Mapping of app types to tax codes.') + +export const appCapability = z + .object({ + type: appCapabilityType, + key: resourceKey, + name: z.string().describe('Name of the capability.'), + description: z.string().describe('Description of the capability.'), + }) + .describe('App capability describes a function that an App can perform.') + +export const installAppRequest = z + .discriminatedUnion('type', [ + installAppStripeWithApiKey, + installAppSandbox, + installAppExternalInvoicing, + ]) + .describe('Request to install an app from the catalog.') + +export const partyTaxIdentity = z + .object({ + code: taxIdentificationCode.optional(), + }) + + .describe( + 'Identity stores the details required to identify an entity for tax purposes in a specific country.', + ) + +export const updateBillingPartyTaxIdentity = z + .object({ + code: taxIdentificationCode.optional(), + }) + + .describe( + 'Identity stores the details required to identify an entity for tax purposes in a specific country.', + ) + +export const workflowInvoicingSettings = z + .object({ + autoAdvance: z + .boolean() + .optional() + .default(true) + + .describe( + 'Whether to automatically issue the invoice after the draftPeriod has passed.', + ), + draftPeriod: z + .string() + .optional() + .default('P0D') + + .describe( + 'The period for the invoice to be kept in draft status for manual reviews.', + ), + progressiveBilling: z + .boolean() + .optional() + .default(true) + .describe('Should progressive billing be allowed for this workflow?'), + subscriptionEndProrationMode: workflowInvoicingSubscriptionEndProrationMode + .optional() + .default('bill_actual_period'), + }) + .describe('Invoice settings for a billing workflow.') + +export const workflowPaymentSettings = z + .discriminatedUnion('collectionMethod', [ + workflowPaymentChargeAutomaticallySettings, + workflowPaymentSendInvoiceSettings, + ]) + .describe('Payment settings for a billing workflow.') + +export const invoiceValidationIssue = z + .object({ + code: z.string().describe('Machine-readable error code.'), + message: z.string().describe('Human-readable description of the error.'), + attributes: z + .record(z.string(), z.unknown()) + .optional() + .describe('Additional structured context.'), + severity: invoiceValidationIssueSeverity, + field: z + .string() + .optional() + + .describe( + 'JSON path to the field that caused this validation issue, if applicable. For example: `lines/0/rate_card/price`.', + ), + }) + + .describe( + 'A validation issue found during invoice processing. Converges on the same structure used by plan and subscription validation errors: a machine-readable `code`, a human-readable `message`, optional structured `attributes`, plus a `severity` and optional `field` path.', + ) + +export const invoiceAvailableActions = z + .object({ + advance: invoiceAvailableActionDetails.optional(), + approve: invoiceAvailableActionDetails.optional(), + delete: invoiceAvailableActionDetails.optional(), + retry: invoiceAvailableActionDetails.optional(), + snapshotQuantities: invoiceAvailableActionDetails.optional(), + }) + + .describe( + 'The set of state-transition actions available for an invoice in its current status. A field is present only when that action is permitted from the current state.', + ) + +export const invoiceLineAmountDiscount = z + .object({ + id: ulid, + reason: invoiceDiscountReason, + description: z + .string() + .optional() + .describe('Optional human-readable description of the discount.'), + externalReferences: invoiceLineExternalReferences.optional(), + amount: numeric, + }) + .describe('A monetary amount discount applied to an invoice line item.') + +export const invoiceLineUsageDiscount = z + .object({ + id: ulid, + reason: invoiceDiscountReason, + description: z + .string() + .optional() + .describe('Optional human-readable description of the discount.'), + externalReferences: invoiceLineExternalReferences.optional(), + quantity: numeric, + }) + .describe('A usage quantity discount applied to an invoice line item.') + +export const invoiceLineBaseDiscount = z + .object({ + id: ulid, + reason: invoiceDiscountReason, + description: z + .string() + .optional() + .describe('Optional human-readable description of the discount.'), + externalReferences: invoiceLineExternalReferences.optional(), + }) + .describe('Base fields shared by all invoice line item discounts.') + +export const updateBillingWorkflowPaymentSettings = z + .discriminatedUnion('collectionMethod', [ + updateBillingWorkflowPaymentChargeAutomaticallySettings, + updateBillingWorkflowPaymentSendInvoiceSettings, + ]) + .describe('Payment settings for a billing workflow.') + +export const listCurrenciesParamsFilter = z + .object({ + type: currencyType.optional(), + code: stringFieldFilter.optional(), + }) + .describe('Filter options for listing currencies.') + +export const currencyCustom = z + .object({ + type: z.literal('custom').describe('The type of the currency.'), + name: z + .string() + .min(1) + .max(256) + + .describe( + 'The name of the currency. It should be a human-readable string that represents the name of the currency, such as "US Dollar" or "Euro".', + ), + symbol: z + .string() + .min(1) + .optional() + + .describe( + 'The symbol of the currency. It should be a string that represents the symbol of the currency, such as "$" for US Dollar or "€" for Euro.', + ), + id: ulid, + code: currencyCodeCustom, + createdAt: dateTime, + }) + .describe('Describes custom currency.') + +export const createCurrencyCustomRequest = z + .object({ + name: z + .string() + .min(1) + .max(256) + + .describe( + 'The name of the currency. It should be a human-readable string that represents the name of the currency, such as "US Dollar" or "Euro".', + ), + symbol: z + .string() + .min(1) + .optional() + + .describe( + 'The symbol of the currency. It should be a string that represents the symbol of the currency, such as "$" for US Dollar or "€" for Euro.', + ), + code: currencyCodeCustom, + }) + .describe('CurrencyCustom create request.') + +export const governanceQueryRequest = z + .object({ + includeCredits: z + .boolean() + .optional() + .default(false) + + .describe( + 'Whether to include credit balance availability for each resolved customer. When true, each feature evaluation includes credit balance checks. Defaults to `false`.', + ), + customer: governanceQueryRequestCustomers, + feature: governanceQueryRequestFeatures.optional(), + }) + .describe('Query to evaluate feature access for a list of customers.') + +export const governanceFeatureAccessReason = z + .object({ + code: governanceFeatureAccessReasonCode, + message: z.string().describe('Human-readable description of the error.'), + attributes: z + .record(z.string(), z.unknown()) + .optional() + .describe('Additional structured context.'), + }) + .describe('Reason a feature is not accessible to a customer.') + +export const governanceQueryError = z + .object({ + code: governanceQueryErrorCode, + message: z.string().describe('Human-readable description of the error.'), + attributes: z + .record(z.string(), z.unknown()) + .optional() + .describe('Additional structured context.'), + customer: z + .string() + .optional() + + .describe( + 'The customer identifier from the request that produced this error.', + ), + }) + + .describe( + 'Query error within a partially successful governance query response.', + ) + +export const appCustomerData = z + .object({ + stripe: appCustomerDataStripe.optional(), + externalInvoicing: appCustomerDataExternalInvoicing.optional(), + }) + .describe('App customer data.') + +export const upsertAppCustomerDataRequest = z + .object({ + stripe: appCustomerDataStripe.optional(), + externalInvoicing: appCustomerDataExternalInvoicing.optional(), + }) + .describe('AppCustomerData upsert request.') + +export const creditAdjustment = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + }) + + .describe( + "A credit adjustment can be used to make manual adjustments to a customer's credit balance. Supported use-cases: - Usage correction", + ) + +export const creditBalance = z + .object({ + currency: billingCurrencyCode, + live: numeric, + settled: numeric, + pending: numeric, + }) + .describe('The credit balance by currency.') + +export const createCreditAdjustmentRequest = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + currency: billingCurrencyCode, + amount: numeric, + }) + .describe('CreditAdjustment create request.') + +export const listCreditTransactionsParamsFilter = z + .object({ + type: creditTransactionType.optional(), + currency: billingCurrencyCode.optional(), + featureKey: stringFieldFilter.optional(), + }) + .describe('Filter options for listing credit transactions.') + +export const creditTransaction = z + .object({ + id: ulid, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + bookedAt: dateTime, + type: creditTransactionType, + currency: billingCurrencyCode, + amount: numeric, + availableBalance: z + .object({ + before: numeric, + after: numeric, + }) + .describe('The available balance before and after the transaction.'), + }) + + .describe( + "A credit transaction represents a single credit movement on the customer's balance. Credit transactions are immutable.", + ) + +export const priceTier = z + .object({ + upToAmount: numeric.optional(), + flatPrice: priceFlat.optional(), + unitPrice: priceUnit.optional(), + }) + + .describe( + 'A price tier used in graduated and volume pricing. At least one price component (flat_price or unit_price) must be set. When UnitConfig is present on the rate card, up_to_amount is expressed in converted billing units.', + ) + +export const chargeTotals = z + .object({ + booked: totals, + realtime: totals.optional(), + }) + + .describe( + 'The totals of a change. RealTime is only expanded when the `real_time_usage` expand is used.', + ) + +export const updatePriceTier = z + .object({ + upToAmount: numeric.optional(), + flatPrice: updatePriceFlat.optional(), + unitPrice: updatePriceUnit.optional(), + }) + + .describe( + 'A price tier used in graduated and volume pricing. At least one price component (flat_price or unit_price) must be set. When UnitConfig is present on the rate card, up_to_amount is expressed in converted billing units.', + ) + +export const featureLlmUnitCost = z + .object({ + type: z + .literal('llm') + .describe('The type discriminator for LLM unit cost.'), + providerProperty: z + .string() + .optional() + + .describe( + 'Meter group-by property that holds the LLM provider. Use this when the meter has a group-by dimension for provider. Mutually exclusive with `provider`.', + ), + provider: z + .string() + .optional() + + .describe( + 'Static LLM provider value (e.g., "openai", "anthropic"). Use this when the feature tracks a single provider. Mutually exclusive with `provider_property`.', + ), + modelProperty: z + .string() + .optional() + + .describe( + 'Meter group-by property that holds the model ID. Use this when the meter has a group-by dimension for model. Mutually exclusive with `model`.', + ), + model: z + .string() + .optional() + + .describe( + 'Static model ID value (e.g., "gpt-4", "claude-3-5-sonnet"). Use this when the feature tracks a single model. Mutually exclusive with `model_property`.', + ), + tokenTypeProperty: z + .string() + .optional() + + .describe( + 'Meter group-by property that holds the token type. Use this when the meter has a group-by dimension for token type. Mutually exclusive with `token_type`.', + ), + tokenType: featureLlmTokenType.optional(), + pricing: featureLlmUnitCostPricing.optional(), + }) + + .describe( + 'LLM cost lookup configuration. Each dimension (provider, model, token type) can be specified as either a static value or a meter group-by property name (mutually exclusive).', + ) + +export const llmCostPrice = z + .object({ + id: ulid, + provider: llmCostProvider, + model: llmCostModel, + pricing: llmCostModelPricing, + currency: currencyCode, + source: llmCostPriceSource, + effectiveFrom: dateTime, + effectiveTo: dateTime.optional(), + createdAt: dateTime, + updatedAt: dateTime, + }) + + .describe( + 'An LLM cost price record, representing the cost per token for a specific model from a specific provider.', + ) + +export const llmCostOverrideCreate = z + .object({ + provider: z.string().describe('Provider/vendor of the model.'), + modelId: z.string().describe('Canonical model identifier.'), + modelName: z.string().optional().describe('Human-readable model name.'), + pricing: llmCostModelPricing, + currency: currencyCode, + effectiveFrom: dateTime, + effectiveTo: dateTime.optional(), + }) + + .describe( + 'Input for creating a per-namespace price override. Unique per provider, model and currency. If an override already exists for the given provider, model and currency, it will be updated. If an override does not exist, it will be created.', + ) + +export const listCustomersParamsFilter = z + .object({ + key: stringFieldFilter.optional(), + name: stringFieldFilter.optional(), + primaryEmail: stringFieldFilter.optional(), + usageAttributionSubjectKey: stringFieldFilter.optional(), + planKey: stringFieldFilter.optional(), + billingProfileId: ulidFieldFilter.optional(), + }) + .describe('Filter options for listing customers.') + +export const listSubscriptionsParamsFilter = z + .object({ + id: ulidFieldFilter.optional(), + customerId: ulidFieldFilter.optional(), + status: stringFieldFilterExact.optional(), + planId: ulidFieldFilter.optional(), + planKey: stringFieldFilterExact.optional(), + }) + .describe('Filter options for listing subscriptions.') + +export const listFeatureParamsFilter = z + .object({ + meterId: ulidFieldFilter.optional(), + key: stringFieldFilter.optional(), + name: stringFieldFilter.optional(), + }) + .describe('Filter options for listing features.') + +export const listAddonsParamsFilter = z + .object({ + id: ulidFieldFilter.optional(), + key: stringFieldFilter.optional(), + name: stringFieldFilter.optional(), + status: stringFieldFilterExact.optional(), + currency: stringFieldFilterExact.optional(), + }) + .describe('Filter options for listing add-ons.') + +export const createCreditGrantTaxConfig = z + .object({ + behavior: taxBehavior.optional(), + taxCode: createResourceReference.optional(), + }) + + .describe( + 'Tax configuration for a credit grant. Tax configuration should be provided to ensure correct revenue recognition, including for externally funded grants.', + ) + +export const creditGrantTaxConfig = z + .object({ + behavior: taxBehavior.optional(), + taxCode: taxCodeReference.optional(), + }) + + .describe( + 'Tax configuration for a credit grant. Tax configuration should be provided to ensure correct revenue recognition, including for externally funded grants.', + ) + +export const taxConfig = z + .object({ + behavior: taxBehavior.optional(), + stripe: taxConfigStripe.optional(), + externalInvoicing: taxConfigExternalInvoicing.optional(), + taxCodeId: ulid.optional(), + taxCode: taxCodeReference.optional(), + }) + .describe('Set of provider specific tax configs.') + +export const rateCardTaxConfig = z + .object({ + behavior: taxBehavior.optional(), + code: taxCodeReference, + }) + .describe('The tax config of the rate card.') + +export const organizationDefaultTaxCodes = z + .object({ + invoicingTaxCode: taxCodeReference, + creditGrantTaxCode: taxCodeReference, + createdAt: dateTime, + updatedAt: dateTime, + }) + + .describe( + 'Organization-level default tax code references. Stores the default tax codes applied to specific billing contexts for this organization. Provisioned automatically when the organization is created.', + ) + +export const updateOrganizationDefaultTaxCodesRequest = z + .object({ + invoicingTaxCode: taxCodeReference.optional(), + creditGrantTaxCode: taxCodeReference.optional(), + }) + .describe('OrganizationDefaultTaxCodes update request.') + +export const planAddon = z + .object({ + id: ulid, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + addon: addonReference, + fromPlanPhase: resourceKey, + maxQuantity: z + .number() + .int() + .gte(1) + .optional() + + .describe( + 'The maximum number of times the add-on can be purchased for the plan. For single-instance add-ons this field must be omitted. For multi-instance add-ons when omitted, unlimited quantity can be purchased.', + ), + validationErrors: z + .array(productCatalogValidationError) + .optional() + .describe('List of validation errors.'), + }) + + .describe( + 'PlanAddon represents an association between a plan and an add-on, controlling which add-ons are available for purchase within a plan.', + ) + +export const createPlanAddonRequest = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + addon: addonReference, + fromPlanPhase: resourceKey, + maxQuantity: z + .number() + .int() + .gte(1) + .optional() + + .describe( + 'The maximum number of times the add-on can be purchased for the plan. For single-instance add-ons this field must be omitted. For multi-instance add-ons when omitted, unlimited quantity can be purchased.', + ), + }) + .describe('PlanAddon create request.') + +export const profileAppReferences = z + .object({ + tax: appReference, + invoicing: appReference, + payment: appReference, + }) + .describe('References to the applications used by a billing profile.') + +export const invoiceWorkflowAppsReferences = z + .object({ + tax: appReference, + invoicing: appReference, + payment: appReference, + }) + + .describe( + 'BillingInvoiceWorkflowAppsReferences represents the references (id) to the apps used by a billing profile', + ) + +export const updateRateCardTaxConfig = z + .object({ + behavior: taxBehavior.optional(), + code: updateResourceReference, + }) + .describe('The tax config of the rate card.') + +export const listEventsParamsFilter = z + .object({ + id: stringFieldFilter.optional(), + source: stringFieldFilter.optional(), + subject: stringFieldFilter.optional(), + type: stringFieldFilter.optional(), + customerId: ulidFieldFilter.optional(), + time: dateTimeFieldFilter.optional(), + ingestedAt: dateTimeFieldFilter.optional(), + storedAt: dateTimeFieldFilter.optional(), + }) + .describe('Filter options for listing ingested events.') + +export const listInvoicesParamsFilter = z + .object({ + status: stringFieldFilterExact.optional(), + customerId: ulidFieldFilter.optional(), + issuedAt: dateTimeFieldFilter.optional(), + servicePeriodStart: dateTimeFieldFilter.optional(), + createdAt: dateTimeFieldFilter.optional(), + }) + .describe('Filter options for listing invoices.') + +export const resourceFilters = z + .object({ + name: stringFieldFilter.optional(), + labels: labelsFieldFilter.optional(), + publicLabels: labelsFieldFilter.optional(), + createdAt: dateTimeFieldFilter.optional(), + updatedAt: dateTimeFieldFilter.optional(), + deletedAt: dateTimeFieldFilter.optional(), + }) + .describe('Resource filters.') + +export const fieldFilters = z + .object({ + boolean: booleanFieldFilter.optional(), + numeric: numericFieldFilter.optional(), + string: stringFieldFilter.optional(), + stringExact: stringFieldFilterExact.optional(), + ulid: ulidFieldFilter.optional(), + datetime: dateTimeFieldFilter.optional(), + labels: labelsFieldFilter.optional(), + }) + .describe('Field filters with all supported types.') + +export const ingestedEvent = z + .object({ + event: event, + customer: customerReference.optional(), + ingestedAt: dateTime, + storedAt: dateTime, + validationErrors: z + .array(ingestedEventValidationError) + .optional() + .describe('The validation errors of the ingested event.'), + }) + .describe('An ingested metering event with ingestion metadata.') + +export const meterQueryResult = z + .object({ + from: dateTime.optional(), + to: dateTime.optional(), + data: z + .array(meterQueryRow) + + .describe( + 'The usage data. If no data is available, an empty array is returned.', + ), + }) + .describe('Meter query result.') + +export const featureCostQueryResult = z + .object({ + from: dateTime.optional(), + to: dateTime.optional(), + data: z.array(featureCostQueryRow).describe('The cost data rows.'), + }) + .describe('Result of a feature cost query.') + +export const invalidParameter = z + .union([ + invalidParameterStandard, + invalidParameterMinimumLength, + invalidParameterMaximumLength, + invalidParameterChoiceItem, + invalidParameterDependentItem, + ]) + .describe('A parameter that failed validation.') + +export const meterPagePaginatedResponse = z + .object({ + data: z.array(meter), + meta: paginatedMeta, + }) + .describe('Page paginated response.') + +export const costBasisPagePaginatedResponse = z + .object({ + data: z.array(costBasis), + meta: paginatedMeta, + }) + .describe('Page paginated response.') + +export const meterQueryFilters = z + .object({ + dimensions: z + .record(z.string(), queryFilterStringMapItem) + .optional() + + .describe( + 'Filters to apply to the dimensions of the query. For `subject` and `customer_id` only equals ("eq", "in") comparisons are supported.', + ), + }) + .describe('Filters to apply to a meter query.') + +export const featureMeterReference = z + .object({ + id: ulid, + filters: z + .record(z.string(), queryFilterStringMapItem) + .optional() + .describe('Filters to apply to the dimensions of the meter.'), + }) + .describe('Reference to a meter associated with a feature.') + +export const createCustomerRequest = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + key: externalResourceKey, + usageAttribution: customerUsageAttribution.optional(), + primaryEmail: z + .string() + .optional() + .describe('The primary email address of the customer.'), + currency: currencyCode.optional(), + billingAddress: address.optional(), + }) + .describe('Customer create request.') + +export const customer = z + .object({ + id: ulid, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + key: externalResourceKey, + usageAttribution: customerUsageAttribution.optional(), + primaryEmail: z + .string() + .optional() + .describe('The primary email address of the customer.'), + currency: currencyCode.optional(), + billingAddress: address.optional(), + }) + + .describe( + 'Customers can be individuals or organizations that can subscribe to plans and have access to features.', + ) + +export const upsertCustomerRequest = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + usageAttribution: customerUsageAttribution.optional(), + primaryEmail: z + .string() + .optional() + .describe('The primary email address of the customer.'), + currency: currencyCode.optional(), + billingAddress: address.optional(), + }) + .describe('Customer upsert request.') + +export const partyAddresses = z + .object({ + billingAddress: address, + }) + .describe('A collection of addresses for the party.') + +export const invoiceCustomer = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + usageAttribution: customerUsageAttribution.optional(), + billingAddress: address.optional(), + id: ulid, + key: externalResourceKey.optional(), + }) + + .describe( + "Snapshot of the customer's information at the time the invoice was issued.", + ) + +export const updateBillingPartyAddresses = z + .object({ + billingAddress: updateAddress, + }) + .describe('A collection of addresses for the party.') + +export const updateInvoiceCustomer = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + usageAttribution: updateCustomerUsageAttribution.optional(), + billingAddress: updateAddress.optional(), + id: ulid, + key: externalResourceKey.optional(), + }) + + .describe( + "Snapshot of the customer's information at the time the invoice was issued.", + ) + +export const appStripeCreateCheckoutSessionConsentCollection = z + .object({ + paymentMethodReuseAgreement: + appStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreement.optional(), + promotions: + appStripeCreateCheckoutSessionConsentCollectionPromotions.optional(), + termsOfService: + appStripeCreateCheckoutSessionConsentCollectionTermsOfService.optional(), + }) + .describe('Checkout Session consent collection configuration.') + +export const listCustomerEntitlementAccessResponseData = z + .object({ + data: z + .array(entitlementAccessResult) + .describe('The list of entitlement access results.'), + }) + .describe('List customer entitlement access response data.') + +export const rateCardEntitlement = z + .discriminatedUnion('type', [ + rateCardMeteredEntitlement, + rateCardStaticEntitlement, + rateCardBooleanEntitlement, + ]) + + .describe( + 'Entitlement template configured on a rate card. The feature is taken from the rate card itself, so it is omitted here.', + ) + +export const workflowCollectionAlignmentAnchored = z + .object({ + type: z.literal('anchored').describe('The type of alignment.'), + recurringPeriod: recurringPeriod, + }) + + .describe( + 'BillingWorkflowCollectionAlignmentAnchored specifies the alignment for collecting the pending line items into an invoice.', + ) + +export const chargeFlatFeeSystemIntent = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + invoiceAt: dateTime, + servicePeriod: closedPeriod, + fullServicePeriod: closedPeriod, + billingPeriod: closedPeriod, + paymentTerm: pricePaymentTerm, + discounts: chargeFlatFeeDiscounts.optional(), + prorationConfiguration: rateCardProrationConfiguration, + amountBeforeProration: currencyAmount, + deletedAt: dateTime.optional(), + }) + + .describe( + 'Flat fee intent fields from the system lifecycle controller shadowed by a manual override.', + ) + +export const subscriptionPagePaginatedResponse = z + .object({ + data: z.array(subscription), + meta: paginatedMeta, + }) + .describe('Page paginated response.') + +export const subscriptionChangeResponse = z + .object({ + current: subscription, + next: subscription, + }) + .describe('Response for changing a subscription.') + +export const subscriptionCancel = z + .object({ + timing: subscriptionEditTiming.optional().default('immediate'), + }) + .describe('Request for canceling a subscription.') + +export const subscriptionChange = z + .object({ + labels: labels.optional(), + settlementMode: settlementMode.optional(), + customer: z + .object({ + id: ulid.optional(), + key: externalResourceKey.optional(), + }) + .describe('The customer to create the subscription for.'), + plan: z + .object({ + id: ulid.optional(), + key: resourceKey.optional(), + version: z + .number() + .int() + .optional() + + .describe( + 'The plan version of the subscription, if any. If not provided, the latest version of the plan will be used.', + ), + }) + .describe('The plan reference of the subscription.'), + billingAnchor: dateTime.optional(), + timing: subscriptionEditTiming, + }) + .describe('Request for changing a subscription.') + +export const createSubscriptionAddonRequest = z + .object({ + labels: labels.optional(), + addon: addonReference, + quantity: z + .number() + .int() + .gte(1) + + .describe( + 'The quantity of the add-on. Always 1 for single instance add-ons.', + ), + timing: subscriptionEditTiming, + }) + .describe('SubscriptionAddon create request.') + +export const invoiceUsageQuantityDetail = z + .object({ + rawQuantity: numeric, + convertedQuantity: numeric, + invoicedQuantity: numeric, + displayUnit: z + .string() + .optional() + + .describe('The display unit label (e.g., "GB", "hours", "M tokens").'), + appliedUnitConfig: unitConfig, + }) + + .describe( + 'Usage quantity details on an invoice line item when UnitConfig is in effect. Provides the full audit trail from raw meter output to the invoiced amount.', + ) + +export const createTaxCodeRequest = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + key: resourceKey, + appMappings: z + .array(taxCodeAppMapping) + .describe('Mapping of app types to tax codes.'), + }) + .describe('TaxCode create request.') + +export const taxCode = z + .object({ + id: ulid, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + key: resourceKey, + appMappings: z + .array(taxCodeAppMapping) + .describe('Mapping of app types to tax codes.'), + }) + .describe('Tax codes by provider.') + +export const upsertTaxCodeRequest = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + appMappings: z + .array(taxCodeAppMapping) + .describe('Mapping of app types to tax codes.'), + }) + .describe('TaxCode upsert request.') + +export const appCatalogItem = z + .object({ + type: appType, + name: z.string().describe('Name of the app.'), + description: z.string().describe('Description of the app.'), + capabilities: z.array(appCapability).describe('Capabilities of the app.'), + installMethods: z + .array(appInstallMethods) + .describe('Available install methods of the app.'), + }) + + .describe( + 'Available apps for billing integrations to connect with third-party services. Apps can have various capabilities like syncing data from or to external systems, integrating with third-party services for tax calculation, delivery of invoices, collection of payments, etc.', + ) + +export const invoiceWorkflow = z + .object({ + invoicing: invoiceWorkflowInvoicingSettings.optional(), + payment: workflowPaymentSettings.optional(), + }) + + .describe( + 'Invoice-level snapshot of the workflow configuration. Contains only the settings that are meaningful for an already-created invoice: invoicing behaviour and payment settings. Collection alignment and tax policy are gather-time / profile-wide concerns and are not included.', + ) + +export const invoiceStatusDetails = z + .object({ + immutable: z + .boolean() + + .describe( + 'Whether the invoice is immutable (i.e. cannot be modified or deleted).', + ), + failed: z.boolean().describe('Whether the invoice is in a failed state.'), + extendedStatus: z + .string() + + .describe( + 'Fine-grained internal status string providing additional workflow detail beyond the top-level status enum.', + ), + availableActions: invoiceAvailableActions, + }) + .describe('Detailed status information for a standard invoice.') + +export const invoiceLineDiscounts = z + .object({ + amount: z + .array(invoiceLineAmountDiscount) + .optional() + + .describe( + 'Monetary amount discounts (e.g. from maximum spend commitments).', + ), + usage: z + .array(invoiceLineUsageDiscount) + .optional() + .describe('Usage quantity discounts (e.g. free tier usage allowances).'), + }) + .describe('Discounts applied to an invoice line item.') + +export const updateBillingInvoiceWorkflow = z + .object({ + invoicing: updateBillingInvoiceWorkflowInvoicingSettings.optional(), + payment: updateBillingWorkflowPaymentSettings.optional(), + }) + + .describe( + 'Invoice-level snapshot of the workflow configuration. Contains only the settings that are meaningful for an already-created invoice: invoicing behaviour and payment settings. Collection alignment and tax policy are gather-time / profile-wide concerns and are not included.', + ) + +export const currency = z + .discriminatedUnion('type', [currencyFiat, currencyCustom]) + .describe('Fiat or custom currency.') + +export const governanceFeatureAccess = z + .object({ + hasAccess: z + .boolean() + + .describe( + 'Whether the customer currently has access to the feature. `true` for boolean and static entitlements that are available, and for metered entitlements with remaining balance. `false` when the feature is unavailable, the usage limit has been reached, or (when applicable) credits have been exhausted.', + ), + reason: governanceFeatureAccessReason.optional(), + }) + .describe('Access status for a single feature.') + +export const customerData = z + .object({ + billingProfile: profileReference.optional(), + appData: appCustomerData.optional(), + }) + .describe('Billing customer data.') + +export const upsertCustomerBillingDataRequest = z + .object({ + billingProfile: profileReference.optional(), + appData: appCustomerData.optional(), + }) + .describe('CustomerBillingData upsert request.') + +export const creditBalances = z + .object({ + retrievedAt: dateTime, + balances: z.array(creditBalance).describe('The balances by currencies.'), + }) + .describe('The balances of the credits of a customer.') + +export const creditTransactionPaginatedResponse = z + .object({ + data: z.array(creditTransaction), + meta: cursorMeta, + }) + .describe('Cursor paginated response.') + +export const priceGraduated = z + .object({ + type: z.literal('graduated').describe('The type of the price.'), + tiers: z + .array(priceTier) + .min(1) + + .describe( + 'The tiers of the graduated price. At least one tier is required.', + ), + }) + + .describe( + "Graduated tiered price. Each tier's rate applies only to the usage within that tier. Pricing can change as cumulative usage crosses tier boundaries. When UnitConfig is present on the rate card, tier boundaries (up_to_amount) are expressed in converted billing units.", + ) + +export const priceVolume = z + .object({ + type: z.literal('volume').describe('The type of the price.'), + tiers: z + .array(priceTier) + .min(1) + + .describe( + 'The tiers of the volume price. At least one tier is required.', + ), + }) + + .describe( + 'Volume tiered price. The maximum quantity within a period determines the per-unit price for all units in that period. When UnitConfig is present on the rate card, tier boundaries (up_to_amount) are expressed in converted billing units.', + ) + +export const updatePriceGraduated = z + .object({ + type: z.literal('graduated').describe('The type of the price.'), + tiers: z + .array(updatePriceTier) + .min(1) + + .describe( + 'The tiers of the graduated price. At least one tier is required.', + ), + }) + + .describe( + "Graduated tiered price. Each tier's rate applies only to the usage within that tier. Pricing can change as cumulative usage crosses tier boundaries. When UnitConfig is present on the rate card, tier boundaries (up_to_amount) are expressed in converted billing units.", + ) + +export const updatePriceVolume = z + .object({ + type: z.literal('volume').describe('The type of the price.'), + tiers: z + .array(updatePriceTier) + .min(1) + + .describe( + 'The tiers of the volume price. At least one tier is required.', + ), + }) + + .describe( + 'Volume tiered price. The maximum quantity within a period determines the per-unit price for all units in that period. When UnitConfig is present on the rate card, tier boundaries (up_to_amount) are expressed in converted billing units.', + ) + +export const featureUnitCost = z + .discriminatedUnion('type', [featureManualUnitCost, featureLlmUnitCost]) + + .describe( + 'Per-unit cost configuration for a feature. Either a fixed manual amount or a dynamic LLM cost lookup.', + ) + +export const pricePagePaginatedResponse = z + .object({ + data: z.array(llmCostPrice), + meta: paginatedMeta, + }) + .describe('Page paginated response.') + +export const createCreditGrantRequest = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: createLabels.optional(), + fundingMethod: creditFundingMethod, + currency: createCurrencyCode, + amount: numeric, + purchase: createCreditGrantPurchase.optional(), + taxConfig: createCreditGrantTaxConfig.optional(), + filters: createCreditGrantFilters.optional(), + priority: z + .number() + .int() + .gte(1) + .lte(1000) + .optional() + .default(10) + + .describe( + 'Draw-down priority of the grant. Lower values have higher priority.', + ), + effectiveAt: dateTime.optional(), + expiresAfter: iso8601Duration.optional(), + key: externalResourceKey.optional(), + }) + .describe('CreditGrant create request.') + +export const creditGrant = z + .object({ + id: ulid, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + fundingMethod: creditFundingMethod, + currency: billingCurrencyCode, + amount: numeric, + purchase: creditGrantPurchase.optional(), + taxConfig: creditGrantTaxConfig.optional(), + invoice: creditGrantInvoiceReference.optional(), + filters: creditGrantFilters.optional(), + priority: z + .number() + .int() + .gte(1) + .lte(1000) + .optional() + .default(10) + + .describe( + 'Draw-down priority of the grant. Lower values have higher priority.', + ), + effectiveAt: dateTime.optional(), + key: externalResourceKey.optional(), + expiresAt: dateTime.optional(), + voidedAt: dateTime.optional(), + status: creditGrantStatus, + }) + + .describe( + 'A credit grant allocates credits to a customer. Credits are drawn down against charges according to the settlement mode configured on the rate card.', + ) + +export const createChargeFlatFeeRequest = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + type: z.literal('flat_fee').describe('The type of the charge.'), + currency: currencyCode, + invoiceAt: dateTime, + servicePeriod: closedPeriod, + uniqueReferenceId: z + .string() + .optional() + .describe('Unique reference ID of the charge.'), + settlementMode: settlementMode, + taxConfig: taxConfig.optional(), + paymentTerm: pricePaymentTerm, + discounts: chargeFlatFeeDiscounts.optional(), + featureKey: z + .string() + .optional() + .describe('The feature associated with the charge, when applicable.'), + prorationConfiguration: rateCardProrationConfiguration, + amountBeforeProration: currencyAmount, + fullServicePeriod: closedPeriod.optional(), + billingPeriod: closedPeriod.optional(), + }) + .describe('Flat fee charge create request.') + +export const workflowTaxSettings = z + .object({ + enabled: z + .boolean() + .optional() + .default(true) + + .describe( + 'Enable automatic tax calculation when tax is supported by the app. For example, with Stripe Invoicing when enabled, tax is calculated via Stripe Tax.', + ), + enforced: z + .boolean() + .optional() + .default(false) + + .describe( + 'Enforce tax calculation when tax is supported by the app. When enabled, the billing system will not allow to create an invoice without tax calculation. Enforcement is different per apps, for example, Stripe app requires customer to have a tax location when starting a paid subscription.', + ), + defaultTaxConfig: taxConfig.optional(), + }) + .describe('Tax settings for a billing workflow.') + +export const planAddonPagePaginatedResponse = z + .object({ + data: z.array(planAddon), + meta: paginatedMeta, + }) + .describe('Page paginated response.') + +export const ingestedEventPaginatedResponse = z + .object({ + data: z.array(ingestedEvent), + meta: cursorMeta, + }) + .describe('Cursor paginated response.') + +export const invalidParameters = z + .array(invalidParameter) + .min(1) + .describe('The list of parameters that failed validation.') + +export const meterQueryRequest = z + .object({ + from: dateTime.optional(), + to: dateTime.optional(), + granularity: meterQueryGranularity.optional(), + timeZone: z + .string() + .optional() + .default('UTC') + + .describe( + 'The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones). The time zone is used to determine the start and end of the time buckets. If not specified, the UTC timezone will be used.', + ), + groupByDimensions: z + .array(z.string()) + .max(100) + .optional() + .describe('The dimensions to group the results by.'), + filters: meterQueryFilters.optional(), + }) + .describe('A meter query request.') + +export const customerPagePaginatedResponse = z + .object({ + data: z.array(customer), + meta: paginatedMeta, + }) + .describe('Page paginated response.') + +export const party = z + .object({ + id: z.string().optional().describe('Unique identifier for the party.'), + key: externalResourceKey.optional(), + name: z + .string() + .optional() + .describe('Legal name or representation of the party.'), + taxId: partyTaxIdentity.optional(), + addresses: partyAddresses.optional(), + }) + .describe('Party represents a person or business entity.') + +export const supplier = z + .object({ + name: z + .string() + .optional() + .describe('Legal name or representation of the party.'), + taxId: partyTaxIdentity.optional(), + addresses: partyAddresses.optional(), + id: z.string().optional().describe('Unique identifier for the party.'), + }) + + .describe( + "Snapshot of the supplier's information at the time the invoice was issued. Structurally a read-only subset of `BillingParty` (the type configured on the billing profile), so the snapshot stays aligned with the source. `key` is omitted because it is not part of the snapshotted supplier data.", + ) + +export const updateSupplier = z + .object({ + name: z + .string() + .optional() + .describe('Legal name or representation of the party.'), + taxId: updateBillingPartyTaxIdentity.optional(), + addresses: updateBillingPartyAddresses.optional(), + id: z.string().optional().describe('Unique identifier for the party.'), + }) + + .describe( + "Snapshot of the supplier's information at the time the invoice was issued. Structurally a read-only subset of `BillingParty` (the type configured on the billing profile), so the snapshot stays aligned with the source. `key` is omitted because it is not part of the snapshotted supplier data.", + ) + +export const appStripeCreateCheckoutSessionRequestOptions = z + .object({ + billingAddressCollection: + appStripeCreateCheckoutSessionBillingAddressCollection + .optional() + .default('auto'), + cancelUrl: z + .string() + .optional() + + .describe( + 'URL to redirect customers who cancel the checkout session. Not allowed when ui_mode is "embedded".', + ), + clientReferenceId: z + .string() + .optional() + + .describe( + 'Unique reference string for reconciling sessions with internal systems. Can be a customer ID, cart ID, or any other identifier.', + ), + customerUpdate: appStripeCreateCheckoutSessionCustomerUpdate.optional(), + consentCollection: + appStripeCreateCheckoutSessionConsentCollection.optional(), + currency: currencyCode.optional(), + customText: appStripeCheckoutSessionCustomTextParams.optional(), + expiresAt: z.coerce + .bigint() + .gte(-9223372036854775808n) + .lte(9223372036854775807n) + .optional() + + .describe( + 'Unix timestamp when the checkout session expires. Can be 30 minutes to 24 hours from creation. Defaults to 24 hours.', + ), + locale: z + .string() + .optional() + + .describe( + 'IETF language tag for the checkout UI locale. If blank or "auto", uses the browser\'s locale. Example: "en", "fr", "de".', + ), + metadata: z + .record(z.string(), z.string()) + .optional() + + .describe( + 'Set of key-value pairs to attach to the checkout session. Useful for storing additional structured information.', + ), + returnUrl: z + .string() + .optional() + + .describe( + 'Return URL for embedded checkout sessions after payment authentication. Required if ui_mode is "embedded" and redirect-based payment methods are enabled.', + ), + successUrl: z + .string() + .optional() + + .describe( + 'Success URL to redirect customers after completing payment or setup. Not allowed when ui_mode is "embedded". See: https://docs.stripe.com/payments/checkout/custom-success-page', + ), + uiMode: appStripeCheckoutSessionUiMode.optional().default('hosted'), + paymentMethodTypes: z + .array(z.string()) + .optional() + + .describe( + 'List of payment method types to enable (e.g., "card", "us_bank_account"). If not specified, Stripe enables all relevant payment methods.', + ), + redirectOnCompletion: + appStripeCreateCheckoutSessionRedirectOnCompletion.optional(), + taxIdCollection: appStripeCreateCheckoutSessionTaxIdCollection.optional(), + }) + + .describe( + "Configuration options for creating a Stripe Checkout Session. Based on Stripe's [Checkout Session API parameters](https://docs.stripe.com/api/checkout/sessions/create).", + ) + +export const workflowCollectionAlignment = z + .discriminatedUnion('type', [ + workflowCollectionAlignmentSubscription, + workflowCollectionAlignmentAnchored, + ]) + + .describe( + 'The alignment for collecting the pending line items into an invoice. Defaults to subscription, which means that we are to create a new invoice every time the a subscription period starts (for in advance items) or ends (for in arrears items).', + ) + +export const taxCodePagePaginatedResponse = z + .object({ + data: z.array(taxCode), + meta: paginatedMeta, + }) + .describe('Page paginated response.') + +export const appStripe = z + .object({ + id: ulid, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + type: z.literal('stripe').describe('The app type.'), + definition: appCatalogItem, + status: appStatus, + accountId: z + .string() + + .describe( + 'The Stripe account ID associated with the connected Stripe account.', + ), + livemode: z + .boolean() + + .describe( + 'Indicates whether the app is connected to a live Stripe account.', + ), + maskedApiKey: z + .string() + + .describe( + 'The masked Stripe API key that only exposes the first and last few characters.', + ), + }) + .describe('Stripe app.') + +export const appSandbox = z + .object({ + id: ulid, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + type: z.literal('sandbox').describe('The app type.'), + definition: appCatalogItem, + status: appStatus, + }) + .describe('Sandbox app can be used for testing billing features.') + +export const appExternalInvoicing = z + .object({ + id: ulid, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + type: z.literal('external_invoicing').describe('The app type.'), + definition: appCatalogItem, + status: appStatus, + enableDraftSyncHook: z + .boolean() + + .describe( + 'Enable draft synchronization hook. When enabled, invoices will pause at the draft state and wait for the integration to call the draft synchronized endpoint before progressing to the issuing state. This allows the external system to validate and prepare the invoice data. When disabled, invoices automatically progress through the draft state based on the configured workflow timing.', + ), + enableIssuingSyncHook: z + .boolean() + + .describe( + 'Enable issuing synchronization hook. When enabled, invoices will pause at the issuing state and wait for the integration to call the issuing synchronized endpoint before progressing to the issued state. This ensures the external invoicing system has successfully created and finalized the invoice before it is marked as issued. When disabled, invoices automatically progress through the issuing state and are immediately marked as issued.', + ), + }) + + .describe( + 'External Invoicing app enables integration with third-party invoicing or payment system. The app supports a bi-directional synchronization pattern where OpenMeter Billing manages the invoice lifecycle while the external system handles invoice presentation and payment collection. Integration workflow: 1. The billing system creates invoices and transitions them through lifecycle states (draft → issuing → issued) 2. The integration receives webhook notifications about invoice state changes 3. The integration calls back to provide external system IDs and metadata 4. The integration reports payment events back via the payment status API State synchronization is controlled by hooks that pause invoice progression until the external system confirms synchronization via API callbacks.', + ) + +export const appCatalogItemPagePaginatedResponse = z + .object({ + data: z.array(appCatalogItem), + meta: paginatedMeta, + }) + .describe('Page paginated response.') + +export const invoiceWorkflowSettings = z + .object({ + apps: invoiceWorkflowAppsReferences.optional(), + sourceBillingProfile: profileReference, + workflow: invoiceWorkflow, + }) + + .describe( + 'Snapshot of the billing workflow configuration captured at invoice creation.', + ) + +export const invoiceDetailedLine = z + .object({ + id: ulid, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + servicePeriod: closedPeriod, + totals: totals, + category: invoiceDetailedLineCostCategory.default('regular'), + discounts: invoiceLineDiscounts.optional(), + creditsApplied: z + .array(invoiceLineCreditsApplied) + .optional() + .describe('Credit applied to this detailed line.'), + externalReferences: invoiceLineExternalReferences.optional(), + quantity: numeric, + unitPrice: numeric, + }) + + .describe( + 'A detailed (child) sub-line belonging to a parent invoice line. Detailed lines represent the individual flat-fee components that make up a usage-based parent line after quantity snapshotting.', + ) + +export const updateInvoiceWorkflowSettings = z + .object({ + workflow: updateBillingInvoiceWorkflow, + }) + + .describe( + 'Snapshot of the billing workflow configuration captured at invoice creation.', + ) + +export const currencyPagePaginatedResponse = z + .object({ + data: z.array(currency), + meta: paginatedMeta, + }) + .describe('Page paginated response.') + +export const governanceQueryResult = z + .object({ + matched: z + .array(z.string()) + + .describe( + 'The list of identifiers from the request that resolved to this customer. Each entry is either the customer `key` or one of its usage-attribution subject `key`s. Duplicate or aliased identifiers that resolve to the same customer collapse to a single result entry, with every requested identifier listed here.', + ), + customer: customer, + features: z + .record(z.string(), governanceFeatureAccess) + + .describe( + 'Map of features with their access status. Map keys are the feature keys requested in `feature.keys`, or every feature `key` available in the organization when the feature filter was omitted.', + ), + updatedAt: dateTime, + }) + .describe('Access evaluation result for a single resolved customer.') + +export const price = z + .discriminatedUnion('type', [ + priceFree, + priceFlat, + priceUnit, + priceGraduated, + priceVolume, + ]) + .describe('Price.') + +export const priceUsageBased = z + .discriminatedUnion('type', [priceUnit, priceGraduated, priceVolume]) + + .describe( + 'Usage-based price types that can appear on a usage-based rate card. When UnitConfig is present on the rate card, these price types operate on billing units (i.e. post-conversion quantities), not raw metered units.', + ) + +export const updatePrice = z + .discriminatedUnion('type', [ + updatePriceFree, + updatePriceFlat, + updatePriceUnit, + updatePriceGraduated, + updatePriceVolume, + ]) + .describe('Price.') + +export const feature = z + .object({ + id: ulid, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + key: resourceKey, + meter: featureMeterReference.optional(), + unitCost: featureUnitCost.optional(), + }) + .describe('A capability or billable dimension offered by a provider.') + +export const createFeatureRequest = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + key: resourceKey, + meter: featureMeterReference.optional(), + unitCost: featureUnitCost.optional(), + }) + .describe('Feature create request.') + +export const updateFeatureRequest = z + .object({ + unitCost: featureUnitCost + .nullable() + .optional() + + .describe( + 'Optional per-unit cost configuration. Use "manual" for a fixed per-unit cost, or "llm" to look up cost from the LLM cost database based on meter group-by properties. Set to `null` to clear the existing unit cost; omit to leave it unchanged.', + ), + }) + + .describe( + 'Request body for updating a feature. Currently only the unit_cost field can be updated.', + ) + +export const creditGrantPagePaginatedResponse = z + .object({ + data: z.array(creditGrant), + meta: paginatedMeta, + }) + .describe('Page paginated response.') + +export const badRequest = z + .intersection( + baseError, + z.object({ + invalidParameters: invalidParameters, + }), + ) + .describe('Bad Request.') + +export const invoiceBase = z + .object({ + id: ulid, + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + number: invoiceNumber, + currency: currencyCode, + supplier: supplier, + customer: invoiceCustomer, + totals: totals, + servicePeriod: closedPeriod, + validationIssues: z + .array(invoiceValidationIssue) + .optional() + + .describe( + 'Validation issues found during invoice processing. Present only when there are one or more validation findings. An empty list is omitted.', + ), + externalReferences: invoiceExternalReferences.optional(), + }) + + .describe( + 'Base fields shared by all invoice types. Spread this model into each concrete invoice variant.', + ) + +export const customerStripeCreateCheckoutSessionRequest = z + .object({ + stripeOptions: appStripeCreateCheckoutSessionRequestOptions, + }) + + .describe( + 'Request to create a Stripe Checkout Session for the customer. Checkout Sessions are used to collect payment method information from customers in a secure, Stripe-hosted interface. This integration uses setup mode to collect payment methods that can be charged later for subscription billing.', + ) + +export const workflowCollectionSettings = z + .object({ + alignment: workflowCollectionAlignment.optional().default({ + type: 'subscription', + }), + interval: z + .string() + .optional() + .default('PT1H') + + .describe( + 'This grace period can be used to delay the collection of the pending line items specified in alignment. This is useful, in case of multiple subscriptions having slightly different billing periods.', + ), + }) + + .describe( + 'Workflow collection specifies how to collect the pending line items for an invoice.', + ) + +export const app = z + .discriminatedUnion('type', [appStripe, appSandbox, appExternalInvoicing]) + .describe('Installed application.') + +export const governanceQueryResponse = z + .object({ + data: z + .array(governanceQueryResult) + .describe('Access evaluation results, one entry per resolved customer.'), + errors: z + .array(governanceQueryError) + .describe('Partial errors encountered while processing the request.'), + meta: cursorMeta, + }) + .describe('Response of the governance query.') + +export const chargeFlatFee = z + .object({ + id: ulid, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + type: z.literal('flat_fee').describe('The type of the charge.'), + customer: billingCustomerReference, + lifecycleController: lifecycleController, + subscription: subscriptionReference.optional(), + currency: currencyCode, + status: chargeStatus, + invoiceAt: dateTime, + servicePeriod: closedPeriod, + fullServicePeriod: closedPeriod, + billingPeriod: closedPeriod, + advanceAfter: dateTime.optional(), + uniqueReferenceId: z + .string() + .optional() + .describe('Unique reference ID of the charge.'), + settlementMode: settlementMode, + taxConfig: taxConfig.optional(), + paymentTerm: pricePaymentTerm, + discounts: chargeFlatFeeDiscounts.optional(), + featureKey: z + .string() + .optional() + .describe('The feature associated with the charge, when applicable.'), + prorationConfiguration: rateCardProrationConfiguration, + amountAfterProration: currencyAmount, + price: price, + systemIntent: chargeFlatFeeSystemIntent.optional(), + }) + .describe('A flat fee charge for a customer.') + +export const chargeUsageBasedSystemIntent = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + invoiceAt: dateTime, + servicePeriod: closedPeriod, + fullServicePeriod: closedPeriod, + billingPeriod: closedPeriod, + discounts: rateCardDiscounts.optional(), + price: price, + deletedAt: dateTime.optional(), + }) + + .describe( + 'Usage-based intent fields from the system lifecycle controller shadowed by a manual override.', + ) + +export const createChargeUsageBasedRequest = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + type: z.literal('usage_based').describe('The type of the charge.'), + currency: currencyCode, + invoiceAt: dateTime, + servicePeriod: closedPeriod, + uniqueReferenceId: z + .string() + .optional() + .describe('Unique reference ID of the charge.'), + settlementMode: settlementMode, + taxConfig: taxConfig.optional(), + discounts: rateCardDiscounts.optional(), + featureKey: z.string().describe('The feature associated with the charge.'), + price: price, + fullServicePeriod: closedPeriod.optional(), + billingPeriod: closedPeriod.optional(), + }) + .describe('Usage-based charge create request.') + +export const rateCard = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + key: resourceKey, + feature: featureReference.optional(), + billingCadence: iso8601Duration.optional(), + price: price, + unitConfig: unitConfig.optional(), + paymentTerm: pricePaymentTerm.optional().default('in_arrears'), + commitments: spendCommitments.optional(), + discounts: rateCardDiscounts.optional(), + taxConfig: rateCardTaxConfig.optional(), + entitlement: rateCardEntitlement.optional(), + }) + + .describe( + 'A rate card defines the pricing and entitlement of a feature or service.', + ) + +export const invoiceLineRateCard = z + .object({ + price: price, + taxConfig: rateCardTaxConfig.optional(), + featureKey: resourceKey.optional(), + discounts: rateCardDiscounts.optional(), + }) + .describe('Rate card configuration snapshot for a usage-based invoice line.') + +export const updateInvoiceLineRateCard = z + .object({ + price: updatePrice, + taxConfig: updateRateCardTaxConfig.optional(), + featureKey: resourceKey.optional(), + discounts: updateDiscounts.optional(), + }) + .describe('Rate card configuration snapshot for a usage-based invoice line.') + +export const featurePagePaginatedResponse = z + .object({ + data: z.array(feature), + meta: paginatedMeta, + }) + .describe('Page paginated response.') + +export const workflow = z + .object({ + collection: workflowCollectionSettings.optional(), + invoicing: workflowInvoicingSettings.optional(), + payment: workflowPaymentSettings.optional(), + tax: workflowTaxSettings.optional(), + }) + .describe('Billing workflow settings.') + +export const appPagePaginatedResponse = z + .object({ + data: z.array(app), + meta: paginatedMeta, + }) + .describe('Page paginated response.') + +export const billingInstallAppResponse = z + .object({ + app: app, + defaultForCapabilityTypes: z.array(appCapabilityType), + }) + .describe('Response of the app install.') + +export const profileApps = z + .object({ + tax: app, + invoicing: app, + payment: app, + }) + .describe('Applications used by a billing profile.') + +export const chargeUsageBased = z + .object({ + id: ulid, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + type: z.literal('usage_based').describe('The type of the charge.'), + customer: billingCustomerReference, + lifecycleController: lifecycleController, + subscription: subscriptionReference.optional(), + currency: currencyCode, + status: chargeStatus, + invoiceAt: dateTime, + servicePeriod: closedPeriod, + fullServicePeriod: closedPeriod, + billingPeriod: closedPeriod, + advanceAfter: dateTime.optional(), + uniqueReferenceId: z + .string() + .optional() + .describe('Unique reference ID of the charge.'), + settlementMode: settlementMode, + taxConfig: taxConfig.optional(), + discounts: rateCardDiscounts.optional(), + featureKey: z.string().describe('The feature associated with the charge.'), + totals: chargeTotals, + price: price, + systemIntent: chargeUsageBasedSystemIntent.optional(), + }) + .describe('A usage-based charge for a customer.') + +export const createChargeRequest = z + .discriminatedUnion('type', [ + createChargeFlatFeeRequest, + createChargeUsageBasedRequest, + ]) + .describe('Customer charge.') + +export const subscriptionAddonRateCard = z + .object({ + rateCard: rateCard, + affectedSubscriptionItemIds: z + .array(ulid) + + .describe( + 'The IDs of the subscription items that this rate card belongs to.', + ), + }) + .describe('A rate card for a subscription add-on.') + +export const planPhase = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + key: resourceKey, + duration: iso8601Duration.optional(), + rateCards: z.array(rateCard).describe('The rate cards of the plan.'), + }) + + .describe( + "The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses.", + ) + +export const addon = z + .object({ + id: ulid, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + key: resourceKey, + version: z + .number() + .int() + .gte(1) + .default(1) + + .describe( + 'Version of the add-on. Incremented when the add-on is updated.', + ), + instanceType: addonInstanceType, + currency: billingCurrencyCode, + effectiveFrom: dateTime.optional(), + effectiveTo: dateTime.optional(), + status: addonStatus, + rateCards: z.array(rateCard).describe('The rate cards of the add-on.'), + validationErrors: z + .array(productCatalogValidationError) + .optional() + .describe('List of validation errors.'), + }) + + .describe( + 'Add-on allows extending subscriptions with compatible plans with additional ratecards.', + ) + +export const createAddonRequest = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + key: resourceKey, + instanceType: addonInstanceType, + currency: billingCurrencyCode, + rateCards: z.array(rateCard).describe('The rate cards of the add-on.'), + }) + .describe('Addon create request.') + +export const upsertAddonRequest = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + instanceType: addonInstanceType, + rateCards: z.array(rateCard).describe('The rate cards of the add-on.'), + }) + .describe('Addon upsert request.') + +export const invoiceStandardLine = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + id: ulid.optional(), + type: z + .literal('standard_line') + .describe('The type of charge this line item represents.'), + lifecycleController: lifecycleController, + servicePeriod: closedPeriod, + totals: totals, + discounts: invoiceLineDiscounts.optional(), + creditsApplied: z + .array(invoiceLineCreditsApplied) + .optional() + .describe('Credit applied to this line item.'), + externalReferences: invoiceLineExternalReferences.optional(), + subscription: subscriptionReference.optional(), + rateCard: invoiceLineRateCard, + detailedLines: z + .array(invoiceDetailedLine) + + .describe( + 'Detailed sub-lines that this line has been broken down into. Present when line has individual details.', + ), + charge: chargeReference.optional(), + }) + + .describe( + 'A top-level line item on an invoice. Each line represents a single charge, typically associated with a rate card from a subscription. Detailed (child) lines are nested under `detailed_lines` when present.', + ) + +export const updateInvoiceStandardLine = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: updateLabels.optional(), + id: ulid.optional(), + type: z + .literal('standard_line') + .describe('The type of charge this line item represents.'), + servicePeriod: updateClosedPeriod, + rateCard: updateInvoiceLineRateCard, + }) + + .describe( + 'A top-level line item on an invoice. Each line represents a single charge, typically associated with a rate card from a subscription. Detailed (child) lines are nested under `detailed_lines` when present.', + ) + +export const profile = z + .object({ + id: ulid, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + supplier: party, + workflow: workflow, + apps: profileAppReferences, + default: z.boolean().describe('Whether this is the default profile.'), + }) + + .describe( + 'Billing profiles contain the settings for billing and controls invoice generation.', + ) + +export const createBillingProfileRequest = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + supplier: party, + workflow: workflow, + apps: profileAppReferences, + default: z.boolean().describe('Whether this is the default profile.'), + }) + .describe('BillingProfile create request.') + +export const upsertBillingProfileRequest = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + supplier: party, + workflow: workflow, + default: z.boolean().describe('Whether this is the default profile.'), + }) + .describe('BillingProfile upsert request.') + +export const charge = z + .discriminatedUnion('type', [chargeFlatFee, chargeUsageBased]) + .describe('Customer charge.') + +export const subscriptionAddon = z + .object({ + id: ulid, + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + addon: addonReference, + quantity: z + .number() + .int() + .gte(1) + + .describe( + 'The quantity of the add-on. Always 1 for single instance add-ons.', + ), + quantityAt: dateTime, + activeFrom: dateTime, + activeTo: dateTime.optional(), + timeline: z + .array(subscriptionAddonTimelineSegment) + + .describe( + 'The timeline of the add-on. The returned periods are sorted and continuous.', + ), + rateCards: z + .array(subscriptionAddonRateCard) + .describe('The rate cards of the add-on.'), + }) + .describe('Addon purchased with a subscription.') + +export const plan = z + .object({ + id: ulid, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + key: resourceKey, + version: z + .number() + .int() + .gte(1) + .default(1) + + .describe( + 'Plans are versioned to allow you to make changes without affecting running subscriptions.', + ), + currency: currencyCode, + billingCadence: iso8601Duration, + proRatingEnabled: z + .boolean() + .optional() + .default(true) + .describe('Whether pro-rating is enabled for this plan.'), + effectiveFrom: dateTime.optional(), + effectiveTo: dateTime.optional(), + status: planStatus, + phases: z + .array(planPhase) + .min(1) + + .describe( + 'The plan phases define the pricing ramp for a subscription. A phase switch occurs only at the end of a billing period. At least one phase is required.', + ), + settlementMode: settlementMode.optional().default('credit_then_invoice'), + validationErrors: z + .array(productCatalogValidationError) + .optional() + + .describe( + 'List of validation errors in `draft` state that prevent the plan from being published.', + ), + }) + .describe('Plans provide a template for subscriptions.') + +export const createPlanRequest = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + key: resourceKey, + currency: currencyCode, + billingCadence: iso8601Duration, + proRatingEnabled: z + .boolean() + .optional() + .default(true) + .describe('Whether pro-rating is enabled for this plan.'), + phases: z + .array(planPhase) + .min(1) + + .describe( + 'The plan phases define the pricing ramp for a subscription. A phase switch occurs only at the end of a billing period. At least one phase is required.', + ), + }) + .describe('Plan create request.') + +export const upsertPlanRequest = z + .object({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + proRatingEnabled: z + .boolean() + .optional() + .default(true) + .describe('Whether pro-rating is enabled for this plan.'), + phases: z + .array(planPhase) + .min(1) + + .describe( + 'The plan phases define the pricing ramp for a subscription. A phase switch occurs only at the end of a billing period. At least one phase is required.', + ), + }) + .describe('Plan upsert request.') + +export const addonPagePaginatedResponse = z + .object({ + data: z.array(addon), + meta: paginatedMeta, + }) + .describe('Page paginated response.') + +export const invoiceLine = z + .discriminatedUnion('type', [invoiceStandardLine]) + + .describe( + 'A top-level line item on an invoice. Each line represents a single charge, typically associated with a rate card from a subscription. Detailed (child) lines are nested under `detailed_lines` when present.', + ) + +export const updateInvoiceLine = z + .discriminatedUnion('type', [updateInvoiceStandardLine]) + + .describe( + 'A top-level line item on an invoice. Each line represents a single charge, typically associated with a rate card from a subscription. Detailed (child) lines are nested under `detailed_lines` when present.', + ) + +export const profilePagePaginatedResponse = z + .object({ + data: z.array(profile), + meta: paginatedMeta, + }) + .describe('Page paginated response.') + +export const chargePagePaginatedResponse = z + .object({ + data: z.array(charge), + meta: paginatedMeta, + }) + .describe('Page paginated response.') + +export const subscriptionAddonPagePaginatedResponse = z + .object({ + data: z.array(subscriptionAddon), + meta: paginatedMeta, + }) + .describe('Page paginated response.') + +export const planPagePaginatedResponse = z + .object({ + data: z.array(plan), + meta: paginatedMeta, + }) + .describe('Page paginated response.') + +export const invoiceStandard = z + .object({ + id: ulid, + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labels.optional(), + createdAt: dateTime, + updatedAt: dateTime, + deletedAt: dateTime.optional(), + number: invoiceNumber, + currency: currencyCode, + supplier: supplier, + customer: invoiceCustomer, + totals: totals, + servicePeriod: closedPeriod, + validationIssues: z + .array(invoiceValidationIssue) + .optional() + + .describe( + 'Validation issues found during invoice processing. Present only when there are one or more validation findings. An empty list is omitted.', + ), + externalReferences: invoiceExternalReferences.optional(), + type: z + .literal('standard') + .describe('Discriminator field identifying this as a standard invoice.'), + status: invoiceStandardStatus, + statusDetails: invoiceStatusDetails, + issuedAt: dateTime.optional(), + draftUntil: dateTime.optional(), + quantitySnapshottedAt: dateTime.optional(), + collectionAt: dateTime.optional(), + dueAt: dateTime.optional(), + sentToCustomerAt: dateTime.optional(), + workflow: invoiceWorkflowSettings, + lines: z + .array(invoiceLine) + .optional() + + .describe( + 'Line items on this invoice. Always returned on single-resource GET; omitted on list endpoints unless explicitly expanded. Editable via update: existing lines are matched by `id`, lines without an `id` are created, and lines present on the invoice but omitted from the update request are deleted. Detailed (child) lines are always computed and cannot be edited directly.', + ), + }) + .describe('A standard invoice for charges owed by the customer.') + +export const updateInvoiceStandardRequest = z + .object({ + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: updateLabels.optional(), + supplier: updateSupplier, + customer: updateInvoiceCustomer, + type: z + .literal('standard') + .describe('Discriminator field identifying this as a standard invoice.'), + workflow: updateInvoiceWorkflowSettings, + lines: z + .array(updateInvoiceLine) + .optional() + + .describe( + 'Line items on this invoice. Always returned on single-resource GET; omitted on list endpoints unless explicitly expanded. Editable via update: existing lines are matched by `id`, lines without an `id` are created, and lines present on the invoice but omitted from the update request are deleted. Detailed (child) lines are always computed and cannot be edited directly.', + ), + }) + .describe('InvoiceStandard update request.') + +export const invoice = z + .discriminatedUnion('type', [invoiceStandard]) + + .describe( + 'An invoice issued to a customer. The `type` field determines the concrete variant: - `standard`: a standard invoice for charges owed.', + ) + +export const updateInvoiceRequest = z + .discriminatedUnion('type', [updateInvoiceStandardRequest]) + .describe('UpdateInvoiceRequest update request.') + +export const invoicePagePaginatedResponse = z + .object({ + data: z.array(invoice), + meta: paginatedMeta, + }) + .describe('Page paginated response.') + +export const listMeteringEventsQueryParams = z.object({ + page: cursorPaginationQueryPage.optional(), + filter: listEventsParamsFilter.optional(), + sort: sortQuery.optional(), +}) + +export const listMeteringEventsResponse = z.object({ + data: z.array(ingestedEvent), + meta: cursorMeta, +}) + +export const ingestMeteringEventsBody = z.union([event, z.array(event)]) + +export const createMeterBody = createMeterRequest + +export const createMeterResponse = meter + +export const getMeterPathParams = z.object({ + meterId: ulid, +}) + +export const getMeterResponse = meter + +export const listMetersQueryParams = z.object({ + page: z + .object({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + sort: sortQuery.optional(), + filter: listMetersParamsFilter.optional(), +}) + +export const listMetersResponse = z.object({ + data: z.array(meter), + meta: paginatedMeta, +}) + +export const updateMeterPathParams = z.object({ + meterId: ulid, +}) + +export const updateMeterBody = updateMeterRequest + +export const updateMeterResponse = meter + +export const deleteMeterPathParams = z.object({ + meterId: ulid, +}) + +export const queryMeterPathParams = z.object({ + meterId: ulid, +}) + +export const queryMeterBody = meterQueryRequest + +export const queryMeterResponse = meterQueryResult + +export const queryMeterCsvPathParams = z.object({ + meterId: ulid, +}) + +export const queryMeterCsvBody = meterQueryRequest + +export const queryMeterCsvResponse = z.string() + +export const createCustomerBody = createCustomerRequest + +export const createCustomerResponse = customer + +export const getCustomerPathParams = z.object({ + customerId: ulid, +}) + +export const getCustomerResponse = customer + +export const listCustomersQueryParams = z.object({ + page: z + .object({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + sort: sortQuery.optional(), + filter: listCustomersParamsFilter.optional(), +}) + +export const listCustomersResponse = z.object({ + data: z.array(customer), + meta: paginatedMeta, +}) + +export const upsertCustomerPathParams = z.object({ + customerId: ulid, +}) + +export const upsertCustomerBody = upsertCustomerRequest + +export const upsertCustomerResponse = customer + +export const deleteCustomerPathParams = z.object({ + customerId: ulid, +}) + +export const getCustomerBillingPathParams = z.object({ + customerId: ulid, +}) + +export const getCustomerBillingResponse = customerData + +export const updateCustomerBillingPathParams = z.object({ + customerId: ulid, +}) + +export const updateCustomerBillingBody = upsertCustomerBillingDataRequest + +export const updateCustomerBillingResponse = customerData + +export const updateCustomerBillingAppDataPathParams = z.object({ + customerId: ulid, +}) + +export const updateCustomerBillingAppDataBody = upsertAppCustomerDataRequest + +export const updateCustomerBillingAppDataResponse = appCustomerData + +export const createCustomerStripeCheckoutSessionPathParams = z.object({ + customerId: ulid, +}) + +export const createCustomerStripeCheckoutSessionBody = + customerStripeCreateCheckoutSessionRequest + +export const createCustomerStripeCheckoutSessionResponse = + appStripeCreateCheckoutSessionResult + +export const createCustomerStripePortalSessionPathParams = z.object({ + customerId: ulid, +}) + +export const createCustomerStripePortalSessionBody = + customerStripeCreateCustomerPortalSessionRequest + +export const createCustomerStripePortalSessionResponse = + appStripeCreateCustomerPortalSessionResult + +export const listCustomerEntitlementAccessPathParams = z.object({ + customerId: ulid, +}) + +export const listCustomerEntitlementAccessResponse = + listCustomerEntitlementAccessResponseData + +export const createCreditGrantPathParams = z.object({ + customerId: ulid, +}) + +export const createCreditGrantBody = createCreditGrantRequest + +export const createCreditGrantResponse = creditGrant + +export const getCreditGrantPathParams = z.object({ + customerId: ulid, + creditGrantId: ulid, +}) + +export const getCreditGrantResponse = creditGrant + +export const listCreditGrantsPathParams = z.object({ + customerId: ulid, +}) + +export const listCreditGrantsQueryParams = z.object({ + page: z + .object({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + filter: listCreditGrantsParamsFilter.optional(), +}) + +export const listCreditGrantsResponse = z.object({ + data: z.array(creditGrant), + meta: paginatedMeta, +}) + +export const getCustomerCreditBalancePathParams = z.object({ + customerId: ulid, +}) + +export const getCustomerCreditBalanceQueryParams = z.object({ + timestamp: dateTime.optional(), + filter: getCreditBalanceParamsFilter.optional(), +}) + +export const getCustomerCreditBalanceResponse = creditBalances + +export const createCreditAdjustmentPathParams = z.object({ + customerId: ulid, +}) + +export const createCreditAdjustmentBody = createCreditAdjustmentRequest + +export const createCreditAdjustmentResponse = creditAdjustment + +export const voidCreditGrantPathParams = z.object({ + customerId: ulid, + creditGrantId: ulid, +}) + +export const voidCreditGrantBody = voidCreditGrantRequest + +export const voidCreditGrantResponse = creditGrant + +export const updateCreditGrantExternalSettlementPathParams = z.object({ + customerId: ulid, + creditGrantId: ulid, +}) + +export const updateCreditGrantExternalSettlementBody = + updateCreditGrantExternalSettlementRequest + +export const updateCreditGrantExternalSettlementResponse = creditGrant + +export const listCreditTransactionsPathParams = z.object({ + customerId: ulid, +}) + +export const listCreditTransactionsQueryParams = z.object({ + page: cursorPaginationQueryPage.optional(), + filter: listCreditTransactionsParamsFilter.optional(), +}) + +export const listCreditTransactionsResponse = z.object({ + data: z.array(creditTransaction), + meta: cursorMeta, +}) + +export const listCustomerChargesPathParams = z.object({ + customerId: ulid, +}) + +export const listCustomerChargesQueryParams = z.object({ + page: z + .object({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + sort: sortQuery.optional(), + filter: listChargesParamsFilter.optional(), + expand: z + .array(chargesExpand) + .optional() + + .describe( + "Expand full objects for referenced entities. Supported values are: - `real_time_usage`: Expand the charge's real-time usage.", + ), +}) + +export const listCustomerChargesResponse = z.object({ + data: z.array(charge), + meta: paginatedMeta, +}) + +export const createCustomerChargesPathParams = z.object({ + customerId: ulid, +}) + +export const createCustomerChargesBody = createChargeRequest + +export const createCustomerChargesResponse = charge + +export const createSubscriptionBody = subscriptionCreate + +export const createSubscriptionResponse = subscription + +export const listSubscriptionsQueryParams = z.object({ + page: z + .object({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + sort: sortQuery.optional(), + filter: listSubscriptionsParamsFilter.optional(), +}) + +export const listSubscriptionsResponse = z.object({ + data: z.array(subscription), + meta: paginatedMeta, +}) + +export const getSubscriptionPathParams = z.object({ + subscriptionId: ulid, +}) + +export const getSubscriptionResponse = subscription + +export const cancelSubscriptionPathParams = z.object({ + subscriptionId: ulid, +}) + +export const cancelSubscriptionBody = subscriptionCancel + +export const cancelSubscriptionResponse = subscription + +export const unscheduleCancelationPathParams = z.object({ + subscriptionId: ulid, +}) + +export const unscheduleCancelationResponse = subscription + +export const changeSubscriptionPathParams = z.object({ + subscriptionId: ulid, +}) + +export const changeSubscriptionBody = subscriptionChange + +export const changeSubscriptionResponse = subscriptionChangeResponse + +export const createSubscriptionAddonPathParams = z.object({ + subscriptionId: ulid, +}) + +export const createSubscriptionAddonBody = createSubscriptionAddonRequest + +export const createSubscriptionAddonResponse = subscriptionAddon + +export const listSubscriptionAddonsPathParams = z.object({ + subscriptionId: ulid, +}) + +export const listSubscriptionAddonsQueryParams = z.object({ + page: z + .object({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + sort: sortQuery.optional(), +}) + +export const listSubscriptionAddonsResponse = z.object({ + data: z.array(subscriptionAddon), + meta: paginatedMeta, +}) + +export const getSubscriptionAddonPathParams = z.object({ + subscriptionId: ulid, + subscriptionAddonId: ulid, +}) + +export const getSubscriptionAddonResponse = subscriptionAddon + +export const listAppsQueryParams = z.object({ + page: z + .object({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), +}) + +export const listAppsResponse = z.object({ + data: z.array(app), + meta: paginatedMeta, +}) + +export const getAppPathParams = z.object({ + appId: ulid, +}) + +export const getAppResponse = app + +export const listAppCatalogQueryParams = z.object({ + page: z + .object({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), +}) + +export const listAppCatalogResponse = z.object({ + data: z.array(appCatalogItem), + meta: paginatedMeta, +}) + +export const getAppCatalogItemPathParams = z.object({ + appType: appType, +}) + +export const getAppCatalogItemResponse = appCatalogItem + +export const installAppBody = installAppRequest + +export const installAppResponse = billingInstallAppResponse + +export const listBillingProfilesQueryParams = z.object({ + page: z + .object({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), +}) + +export const listBillingProfilesResponse = z.object({ + data: z.array(profile), + meta: paginatedMeta, +}) + +export const createBillingProfileBody = createBillingProfileRequest + +export const createBillingProfileResponse = profile + +export const getBillingProfilePathParams = z.object({ + id: ulid, +}) + +export const getBillingProfileResponse = profile + +export const updateBillingProfilePathParams = z.object({ + id: ulid, +}) + +export const updateBillingProfileBody = upsertBillingProfileRequest + +export const updateBillingProfileResponse = profile + +export const deleteBillingProfilePathParams = z.object({ + id: ulid, +}) + +export const listInvoicesQueryParams = z.object({ + page: z + .object({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + sort: sortQuery.optional(), + filter: listInvoicesParamsFilter.optional(), +}) + +export const listInvoicesResponse = z.object({ + data: z.array(invoice), + meta: paginatedMeta, +}) + +export const getInvoicePathParams = z.object({ + invoiceId: ulid, +}) + +export const getInvoiceResponse = invoice + +export const updateInvoicePathParams = z.object({ + invoiceId: ulid, +}) + +export const updateInvoiceBody = updateInvoiceRequest + +export const updateInvoiceResponse = invoice + +export const deleteInvoicePathParams = z.object({ + invoiceId: ulid, +}) + +export const advanceInvoicePathParams = z.object({ + invoiceId: ulid, +}) + +export const advanceInvoiceResponse = invoice + +export const approveInvoicePathParams = z.object({ + invoiceId: ulid, +}) + +export const approveInvoiceResponse = invoice + +export const retryInvoicePathParams = z.object({ + invoiceId: ulid, +}) + +export const retryInvoiceResponse = invoice + +export const snapshotQuantitiesInvoicePathParams = z.object({ + invoiceId: ulid, +}) + +export const snapshotQuantitiesInvoiceResponse = invoice + +export const createTaxCodeBody = createTaxCodeRequest + +export const createTaxCodeResponse = taxCode + +export const getTaxCodePathParams = z.object({ + taxCodeId: ulid, +}) + +export const getTaxCodeResponse = taxCode + +export const listTaxCodesQueryParams = z.object({ + page: z + .object({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + includeDeleted: z.coerce + .boolean() + .optional() + .describe('Include deleted tax codes in the response.'), +}) + +export const listTaxCodesResponse = z.object({ + data: z.array(taxCode), + meta: paginatedMeta, +}) + +export const upsertTaxCodePathParams = z.object({ + taxCodeId: ulid, +}) + +export const upsertTaxCodeBody = upsertTaxCodeRequest + +export const upsertTaxCodeResponse = taxCode + +export const deleteTaxCodePathParams = z.object({ + taxCodeId: ulid, +}) + +export const listCurrenciesQueryParams = z.object({ + page: z + .object({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + sort: sortQuery.optional(), + filter: listCurrenciesParamsFilter.optional(), +}) + +export const listCurrenciesResponse = z.object({ + data: z.array(currency), + meta: paginatedMeta, +}) + +export const createCustomCurrencyBody = createCurrencyCustomRequest + +export const createCustomCurrencyResponse = currencyCustom + +export const listCostBasesPathParams = z.object({ + currencyId: ulid, +}) + +export const listCostBasesQueryParams = z.object({ + filter: listCostBasesParamsFilter.optional(), + page: z + .object({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), +}) + +export const listCostBasesResponse = z.object({ + data: z.array(costBasis), + meta: paginatedMeta, +}) + +export const createCostBasisPathParams = z.object({ + currencyId: ulid, +}) + +export const createCostBasisBody = createCostBasisRequest + +export const createCostBasisResponse = costBasis + +export const listFeaturesQueryParams = z.object({ + page: z + .object({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + sort: sortQuery.optional(), + filter: listFeatureParamsFilter.optional(), +}) + +export const listFeaturesResponse = z.object({ + data: z.array(feature), + meta: paginatedMeta, +}) + +export const createFeatureBody = createFeatureRequest + +export const createFeatureResponse = feature + +export const getFeaturePathParams = z.object({ + featureId: ulid, +}) + +export const getFeatureResponse = feature + +export const updateFeaturePathParams = z.object({ + featureId: ulid, +}) + +export const updateFeatureBody = updateFeatureRequest + +export const updateFeatureResponse = feature + +export const deleteFeaturePathParams = z.object({ + featureId: ulid, +}) + +export const queryFeatureCostPathParams = z.object({ + featureId: ulid, +}) + +export const queryFeatureCostBody = meterQueryRequest + +export const queryFeatureCostResponse = featureCostQueryResult + +export const listLlmCostPricesQueryParams = z.object({ + filter: listLlmCostPricesParamsFilter.optional(), + sort: sortQuery.optional(), + page: z + .object({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), +}) + +export const listLlmCostPricesResponse = z.object({ + data: z.array(llmCostPrice), + meta: paginatedMeta, +}) + +export const getLlmCostPricePathParams = z.object({ + priceId: ulid, +}) + +export const getLlmCostPriceResponse = llmCostPrice + +export const listLlmCostOverridesQueryParams = z.object({ + filter: listLlmCostPricesParamsFilter.optional(), + page: z + .object({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), +}) + +export const listLlmCostOverridesResponse = z.object({ + data: z.array(llmCostPrice), + meta: paginatedMeta, +}) + +export const createLlmCostOverrideBody = llmCostOverrideCreate + +export const createLlmCostOverrideResponse = llmCostPrice + +export const deleteLlmCostOverridePathParams = z.object({ + priceId: ulid, +}) + +export const listPlansQueryParams = z.object({ + page: z + .object({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + sort: sortQuery.optional(), + filter: listPlansParamsFilter.optional(), +}) + +export const listPlansResponse = z.object({ + data: z.array(plan), + meta: paginatedMeta, +}) + +export const createPlanBody = createPlanRequest + +export const createPlanResponse = plan + +export const updatePlanPathParams = z.object({ + planId: ulid, +}) + +export const updatePlanBody = upsertPlanRequest + +export const updatePlanResponse = plan + +export const getPlanPathParams = z.object({ + planId: ulid, +}) + +export const getPlanResponse = plan + +export const deletePlanPathParams = z.object({ + planId: ulid, +}) + +export const archivePlanPathParams = z.object({ + planId: ulid, +}) + +export const archivePlanResponse = plan + +export const publishPlanPathParams = z.object({ + planId: ulid, +}) + +export const publishPlanResponse = plan + +export const listAddonsQueryParams = z.object({ + page: z + .object({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + sort: sortQuery.optional(), + filter: listAddonsParamsFilter.optional(), +}) + +export const listAddonsResponse = z.object({ + data: z.array(addon), + meta: paginatedMeta, +}) + +export const createAddonBody = createAddonRequest + +export const createAddonResponse = addon + +export const updateAddonPathParams = z.object({ + addonId: ulid, +}) + +export const updateAddonBody = upsertAddonRequest + +export const updateAddonResponse = addon + +export const getAddonPathParams = z.object({ + addonId: ulid, +}) + +export const getAddonResponse = addon + +export const deleteAddonPathParams = z.object({ + addonId: ulid, +}) + +export const archiveAddonPathParams = z.object({ + addonId: ulid, +}) + +export const archiveAddonResponse = addon + +export const publishAddonPathParams = z.object({ + addonId: ulid, +}) + +export const publishAddonResponse = addon + +export const listPlanAddonsPathParams = z.object({ + planId: ulid, +}) + +export const listPlanAddonsQueryParams = z.object({ + page: z + .object({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), +}) + +export const listPlanAddonsResponse = z.object({ + data: z.array(planAddon), + meta: paginatedMeta, +}) + +export const createPlanAddonPathParams = z.object({ + planId: ulid, +}) + +export const createPlanAddonBody = createPlanAddonRequest + +export const createPlanAddonResponse = planAddon + +export const getPlanAddonPathParams = z.object({ + planId: ulid, + planAddonId: ulid, +}) + +export const getPlanAddonResponse = planAddon + +export const updatePlanAddonPathParams = z.object({ + planId: ulid, + planAddonId: ulid, +}) + +export const updatePlanAddonBody = upsertPlanAddonRequest + +export const updatePlanAddonResponse = planAddon + +export const deletePlanAddonPathParams = z.object({ + planId: ulid, + planAddonId: ulid, +}) + +export const getOrganizationDefaultTaxCodesResponse = + organizationDefaultTaxCodes + +export const updateOrganizationDefaultTaxCodesBody = + updateOrganizationDefaultTaxCodesRequest + +export const updateOrganizationDefaultTaxCodesResponse = + organizationDefaultTaxCodes + +export const queryGovernanceAccessQueryParams = z.object({ + page: cursorPaginationQueryPage.optional(), +}) + +export const queryGovernanceAccessBody = governanceQueryRequest + +export const queryGovernanceAccessResponse = governanceQueryResponse + +export const labelsWire = z + .record(z.string(), z.string()) + + .describe( + 'Labels store metadata of an entity that can be used for filtering an entity list or for searching across entity types. Keys must be of length 1-63 characters, and cannot start with "kong", "konnect", "mesh", "kic", or "\\_".', + ) + +export const currencyCodeWire = z + .string() + .min(3) + .max(3) + .regex(new RegExp('^[A-Z]{3}$')) + + .describe( + 'Three-letter [ISO4217](https://www.iso.org/iso-4217-currency-codes.html) currency code. Custom three-letter currency codes are also supported for convenience.', + ) + +export const numericWire = z + .string() + .regex(new RegExp('^\\-?[0-9]+(\\.[0-9]+)?$')) + .describe('Numeric represents an arbitrary precision number.') + +export const cursorPaginationQueryPageWire = z + .strictObject({ + size: z + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + after: z + .string() + .optional() + + .describe( + 'Request the next page of data, starting with the item after this parameter.', + ), + before: z + .string() + .optional() + + .describe( + 'Request the previous page of data, starting with the item before this parameter.', + ), + }) + .describe('Determines which page of the collection to retrieve.') + +export const stringFieldFilterWire = z + .union([ + z.string(), + z.strictObject({ + eq: z + .string() + .optional() + .describe('Value strictly equals the given string value.'), + neq: z + .string() + .optional() + .describe('Value does not equal the given string value.'), + contains: z + .string() + .optional() + .describe('Value contains the given string value (fuzzy match).'), + ocontains: z + .array(z.string()) + .optional() + + .describe( + 'Returns entities that fuzzy-match any of the comma-delimited phrases in the filter string.', + ), + oeq: z + .array(z.string()) + .optional() + + .describe( + 'Returns entities that exact match any of the comma-delimited phrases in the filter string.', + ), + gt: z + .string() + .optional() + + .describe( + 'Value is greater than the given string value (lexicographic compare).', + ), + gte: z + .string() + .optional() + + .describe( + 'Value is greater than or equal to the given string value (lexicographic compare).', + ), + lt: z + .string() + .optional() + + .describe( + 'Value is less than the given string value (lexicographic compare).', + ), + lte: z + .string() + .optional() + + .describe( + 'Value is less than or equal to the given string value (lexicographic compare).', + ), + exists: z + .boolean() + .optional() + + .describe( + 'When true, the field must be present (non-null); when false, the field must be absent (null).', + ), + }), + ]) + + .describe( + 'Filters on the given string field value by either exact or fuzzy match. All properties are optional; provide exactly one to specify the comparison.', + ) + +export const ulidWire = z + .string() + .regex(new RegExp('^[0-7][0-9A-HJKMNP-TV-Z]{25}$')) + .describe('ULID (Universally Unique Lexicographically Sortable Identifier).') + +export const dateTimeWire = z + .string() + .datetime() + + .describe( + '[RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in UTC.', + ) + +export const sortQueryWire = z + .strictObject({ + by: z.string().describe('The attribute to sort by.'), + order: z + .union([z.literal('asc'), z.literal('desc')]) + .optional() + .describe('The sort order. `asc` for ascending, `desc` for descending.'), + }) + + .describe( + 'Sort query. The `asc` suffix is optional as the default sort order is ascending. The `desc` suffix is used to specify a descending order.', + ) + +export const ingestedEventValidationErrorWire = z + .strictObject({ + code: z.string().describe('The machine readable code of the error.'), + message: z + .string() + .describe('The human readable description of the error.'), + attributes: z + .record(z.string(), z.unknown()) + .optional() + .describe('Additional attributes.'), + }) + .describe('Event validation errors.') + +export const cursorMetaPageWire = z + .strictObject({ + first: z.string().optional().describe('URI to the first page.'), + last: z.string().optional().describe('URI to the last page.'), + next: z.string().nullable().describe('URI to the next page.'), + previous: z.string().nullable().describe('URI to the previous page.'), + size: z.number().int().describe('Requested page size.'), + }) + .describe('Cursor pagination metadata.') + +export const invalidRulesWire = z + .enum([ + 'required', + 'is_array', + 'is_base64', + 'is_boolean', + 'is_date_time', + 'is_integer', + 'is_null', + 'is_number', + 'is_object', + 'is_string', + 'is_uuid', + 'is_fqdn', + 'is_arn', + 'unknown_property', + 'missing_reference', + 'is_label', + 'matches_regex', + 'invalid', + 'is_supported_network_availability_zone_list', + 'is_supported_network_cidr_block', + 'is_supported_provider_region', + 'type', + ]) + .describe('The validation rule that a parameter failed.') + +export const invalidParameterMinimumRuleWire = z + .enum([ + 'min_length', + 'min_digits', + 'min_lowercase', + 'min_uppercase', + 'min_symbols', + 'min_items', + 'min', + ]) + .describe('Minimum-length (or minimum-value) validation rules.') + +export const invalidParameterMaximumRuleWire = z + .enum(['max_length', 'max_items', 'max']) + .describe('Maximum-length (or maximum-value) validation rules.') + +export const invalidParameterChoiceRuleWire = z + .enum(['enum']) + .describe('The enum validation rule.') + +export const invalidParameterDependentRuleWire = z + .enum(['dependent_fields']) + .describe('The dependent-fields validation rule.') + +export const baseErrorWire = z + .intersection( + z.object({ + type: z + .string() + .describe('Type contains a URI that identifies the problem type.'), + status: z + .number() + .int() + + .describe( + 'The HTTP status code generated by the origin server for this occurrence of the problem.', + ), + title: z + .string() + .describe('A a short, human-readable summary of the problem type.'), + detail: z + .string() + + .describe( + 'A human-readable explanation specific to this occurrence of the problem.', + ), + instance: z + .string() + + .describe( + 'A URI reference that identifies the specific occurrence of the problem.', + ), + }), + z.record(z.string(), z.unknown()), + ) + .describe('Standard error response.') + +export const resourceKeyWire = z + .string() + .min(1) + .max(64) + .regex(new RegExp('^[a-z0-9]+(?:_[a-z0-9]+)*$')) + .describe('A key is a unique string that is used to identify a resource.') + +export const meterAggregationWire = z + .union([ + z.literal('sum'), + z.literal('count'), + z.literal('unique_count'), + z.literal('avg'), + z.literal('min'), + z.literal('max'), + z.literal('latest'), + ]) + .describe('The aggregation type to use for the meter.') + +export const pageMetaWire = z + .strictObject({ + number: z.number().int().describe('Page number.'), + size: z.number().int().describe('Page size.'), + total: z + .number() + .int() + .describe('Total number of items in the collection.'), + }) + .describe('Pagination information.') + +export const meterQueryGranularityWire = z + .union([ + z.literal('PT1M'), + z.literal('PT1H'), + z.literal('P1D'), + z.literal('P1M'), + ]) + + .describe( + 'The granularity of the time grouping. Time durations are specified in ISO 8601 format.', + ) + +export const queryFilterStringWire = z + .strictObject({ + eq: z + .string() + .optional() + .describe('The attribute equals the provided value.'), + neq: z + .string() + .optional() + .describe('The attribute does not equal the provided value.'), + in: z + .array(z.string()) + .min(1) + .max(100) + .optional() + .describe('The attribute is one of the provided values.'), + nin: z + .array(z.string()) + .min(1) + .max(100) + .optional() + .describe('The attribute is not one of the provided values.'), + contains: z + .string() + .optional() + .describe('The attribute contains the provided value.'), + ncontains: z + .string() + .optional() + .describe('The attribute does not contain the provided value.'), + get and() { + return z + .array(queryFilterStringWire) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical AND.') + }, + get or() { + return z + .array(queryFilterStringWire) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical OR.') + }, + }) + + .describe( + 'A query filter for a string attribute. Operators are mutually exclusive, only one operator is allowed at a time.', + ) + +export const externalResourceKeyWire = z + .string() + .min(1) + .max(256) + + .describe( + 'ExternalResourceKey is a unique string that is used to identify a resource in an external system.', + ) + +export const usageAttributionSubjectKeyWire = z + .string() + .min(1) + .describe('Subject key.') + +export const countryCodeWire = z + .string() + .min(2) + .max(2) + .regex(new RegExp('^[A-Z]{2}$')) + + .describe( + '[ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 country code. Custom two-letter country codes are also supported for convenience.', + ) + +export const appStripeCreateCheckoutSessionBillingAddressCollectionWire = z + .enum(['auto', 'required']) + + .describe( + "Controls whether Checkout collects the customer's billing address.", + ) + +export const appStripeCreateCheckoutSessionCustomerUpdateBehaviorWire = z + .enum(['auto', 'never']) + .describe('Behavior for updating customer fields from checkout session.') + +export const appStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPositionWire = + z + .enum(['auto', 'hidden']) + .describe('Position of payment method reuse agreement in the UI.') + +export const appStripeCreateCheckoutSessionConsentCollectionPromotionsWire = z + .enum(['auto', 'none']) + .describe('Promotional communication consent collection setting.') + +export const appStripeCreateCheckoutSessionConsentCollectionTermsOfServiceWire = + z + .enum(['none', 'required']) + .describe('Terms of service acceptance requirement.') + +export const appStripeCheckoutSessionCustomTextParamsWire = z + .strictObject({ + after_submit: z + .strictObject({ + message: z + .string() + .max(1200) + .optional() + .describe('The custom message text (max 1200 characters).'), + }) + .optional() + .describe('Text displayed after the payment confirmation button.'), + shipping_address: z + .strictObject({ + message: z + .string() + .max(1200) + .optional() + .describe('The custom message text (max 1200 characters).'), + }) + .optional() + .describe('Text displayed alongside shipping address collection.'), + submit: z + .strictObject({ + message: z + .string() + .max(1200) + .optional() + .describe('The custom message text (max 1200 characters).'), + }) + .optional() + .describe('Text displayed alongside the payment confirmation button.'), + terms_of_service_acceptance: z + .strictObject({ + message: z + .string() + .max(1200) + .optional() + .describe('The custom message text (max 1200 characters).'), + }) + .optional() + .describe('Text replacing the default terms of service agreement text.'), + }) + .describe('Custom text displayed at various stages of the checkout flow.') + +export const appStripeCheckoutSessionUiModeWire = z + .enum(['embedded', 'hosted']) + .describe('Checkout Session UI mode.') + +export const appStripeCreateCheckoutSessionRedirectOnCompletionWire = z + .enum(['always', 'if_required', 'never']) + .describe('Redirect behavior for embedded checkout sessions.') + +export const appStripeCreateCheckoutSessionTaxIdCollectionRequiredWire = z + .enum(['if_supported', 'never']) + .describe('Tax ID collection requirement level.') + +export const appStripeCheckoutSessionModeWire = z + .enum(['setup']) + + .describe( + 'Stripe Checkout Session mode. Determines the primary purpose of the checkout session.', + ) + +export const appStripeCreateCustomerPortalSessionOptionsWire = z + .strictObject({ + configuration_id: z + .string() + .optional() + + .describe( + 'The ID of an existing [Stripe configuration](https://docs.stripe.com/api/customer_portal/configurations) to use for this session, describing its functionality and features. If not specified, the session uses the default configuration.', + ), + locale: z + .string() + .optional() + + .describe( + "The IETF [language tag](https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-locale) of the locale customer portal is displayed in. If blank or `auto`, the customer's preferred_locales or browser's locale is used.", + ), + return_url: z + .string() + .optional() + + .describe( + 'The [URL to redirect](https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-return_url) the customer to after they have completed their requested actions.', + ), + }) + .describe('Request to create a Stripe Customer Portal Session.') + +export const entitlementTypeWire = z + .enum(['metered', 'static', 'boolean']) + .describe('The type of the entitlement.') + +export const createLabelsWire = z + .record(z.string(), z.string()) + + .describe( + 'Labels store metadata of an entity that can be used for filtering an entity list or for searching across entity types. Keys must be of length 1-63 characters, and cannot start with "kong", "konnect", "mesh", "kic", or "\\_".', + ) + +export const creditFundingMethodWire = z + .enum(['none', 'invoice', 'external']) + + .describe( + 'The funding method describes how the grant is funded. - `none`: No funding workflow applies, for example promotional grants - `invoice`: The grant is funded by an in-system invoice flow - `external`: The grant is funded outside the system (e.g., wire transfer, external invoice, or manual reconciliation)', + ) + +export const creditAvailabilityPolicyWire = z + .enum(['on_creation']) + + .describe( + 'When credits become available for consumption. - `on_creation`: Credits are available as soon as the grant is created. - `on_authorization`: Credits are available once the payment is authorized. - `on_settlement`: Credits are available once the payment is settled.', + ) + +export const taxBehaviorWire = z + .enum(['inclusive', 'exclusive']) + + .describe( + 'Tax behavior. This enum is used to specify whether tax is included in the price or excluded from the price.', + ) + +export const iso8601DurationWire = z + .string() + + .regex( + new RegExp( + '^P(?:\\d+(?:\\.\\d+)?Y)?(?:\\d+(?:\\.\\d+)?M)?(?:\\d+(?:\\.\\d+)?W)?(?:\\d+(?:\\.\\d+)?D)?(?:T(?:\\d+(?:\\.\\d+)?H)?(?:\\d+(?:\\.\\d+)?M)?(?:\\d+(?:\\.\\d+)?S)?)?$', + ), + ) + + .describe( + '[ISO 8601 Duration](https://docs.digi.com/resources/documentation/digidocs/90001488-13/reference/r_iso_8601_duration_format.htm) string.', + ) + +export const creditPurchasePaymentSettlementStatusWire = z + .enum(['pending', 'authorized', 'settled']) + + .describe( + 'Credit purchase payment settlement status. - `pending`: Payment has been initiated and is not yet authorized. - `authorized`: Payment has been authorized. - `settled`: Payment has been settled.', + ) + +export const creditGrantStatusWire = z + .enum(['pending', 'active', 'expired', 'voided']) + + .describe( + 'Credit grant lifecycle status. - `pending`: The credit block has been created but is not yet valid. (`effective_at` is in the future or availability_policy is not met) - `active`: The credit block is currently valid and eligible for consumption. (`effective_at` is in the past, `expires_at` is in the future and availability_policy is met) - `expired`: The credit block expired with remaining unused balance, `expires_at` time has passed. - `voided`: The credit block was voided. Remaining balance is forfeited.', + ) + +export const stringFieldFilterExactWire = z + .union([ + z.string(), + z.strictObject({ + eq: z + .string() + .optional() + .describe('Value strictly equals the given string value.'), + oeq: z + .array(z.string()) + .optional() + + .describe( + 'Returns entities that exact match any of the comma-delimited phrases in the filter string.', + ), + neq: z + .string() + .optional() + .describe('Value does not equal the given string value.'), + }), + ]) + + .describe( + 'Filters on the given string field value by exact match. All properties are optional; provide exactly one to specify the comparison.', + ) + +export const creditGrantVoidPaymentAdjustmentWire = z + .enum(['none']) + + .describe( + 'Describes how voiding a credit grant adjusts related payment state. - `none`: Voiding does not adjust invoices, payment authorization, settlement, payment intents, or external collection state.', + ) + +export const creditTransactionTypeWire = z + .enum(['funded', 'consumed', 'expired', 'voided']) + + .describe( + 'The type of the credit transaction. - `funded`: Credit granted and available for consumption. - `consumed`: Credit consumed by usage or fees. - `expired`: Credit removed because it expired before being used. - `voided`: Credit removed because the grant was voided before being used.', + ) + +export const chargesExpandWire = z + .enum(['real_time_usage']) + + .describe( + "Expands for customer charges. Values: - `real_time_usage`: The charge's real-time usage.", + ) + +export const lifecycleControllerWire = z + .enum(['system', 'manual']) + + .describe( + 'Identifies whether a resource lifecycle is controlled by OpenMeter or manually overridden by the API user. Values: - `system`: The resource lifecycle is controlled by OpenMeter. - `manual`: The resource lifecycle was manually overridden by the API user.', + ) + +export const chargeStatusWire = z + .enum(['created', 'active', 'final', 'deleted']) + + .describe( + 'Lifecycle status of a charge. Values: - `created`: The charge has been created but is not active yet. - `active`: The charge is active. - `final`: The charge is fully finalized and no further changes are expected. - `deleted`: The charge has been deleted.', + ) + +export const settlementModeWire = z + .enum(['credit_then_invoice', 'credit_only']) + + .describe( + 'Settlement mode for billing. Values: - `credit_then_invoice`: Credits are applied first, then any remainder is invoiced. - `credit_only`: Usage is settled exclusively against credits.', + ) + +export const taxConfigStripeWire = z + .strictObject({ + code: z + .string() + .regex(new RegExp('^txcd_\\d{8}$')) + .describe('Product [tax code](https://docs.stripe.com/tax/tax-codes).'), + }) + .describe('The tax config for Stripe.') + +export const taxConfigExternalInvoicingWire = z + .strictObject({ + code: z + .string() + .max(64) + + .describe( + 'The tax code should be interpreted by the external invoicing provider.', + ), + }) + .describe('External invoicing tax config.') + +export const pricePaymentTermWire = z + .union([z.literal('in_advance'), z.literal('in_arrears')]) + .describe('The payment term of a flat price.') + +export const chargeFlatFeeDiscountsWire = z + .strictObject({ + percentage: z + .number() + .nonnegative() + .lte(100) + .optional() + .describe('Percentage discount applied to the price (0–100).'), + }) + + .describe( + 'Discounts applicable to flat fee charges. This is the same as `ProductCatalog.Discounts` but without the `usage` field, which is not applicable to flat fee charges.', + ) + +export const rateCardProrationModeWire = z + .enum(['no_proration', 'prorate_prices']) + + .describe( + 'The proration mode of the rate card. Values: - `no_proration`: No proration. - `prorate_prices`: Prorate the price based on the time remaining in the billing period.', + ) + +export const priceFreeWire = z + .strictObject({ + type: z.literal('free').describe('The type of the price.'), + }) + .describe('Free price.') + +export const subscriptionStatusWire = z + .enum(['active', 'inactive', 'canceled', 'scheduled']) + .describe('Subscription status.') + +export const subscriptionEditTimingEnumWire = z + .enum(['immediate', 'next_billing_cycle']) + + .describe( + 'Subscription edit timing. When immediate, the requested changes take effect immediately. When next_billing_cycle, the requested changes take effect at the next billing cycle.', + ) + +export const unitConfigOperationWire = z + .enum(['divide', 'multiply']) + + .describe( + 'The arithmetic operation used to convert raw metered units into billing units. - `divide`: Divide the metered quantity by the conversion factor (e.g., bytes ÷ 1e9 = GB). - `multiply`: Multiply the metered quantity by the conversion factor (e.g., cost × 1.2 = cost + 20% margin).', + ) + +export const unitConfigRoundingModeWire = z + .enum(['ceiling', 'floor', 'half_up', 'none']) + + .describe( + 'The rounding mode applied to the converted quantity for invoicing. Rounding is applied only to the invoiced quantity. Entitlement balance checks use the precise decimal value after conversion. - `ceiling`: Round up to the next integer (typical for package-style billing). - `floor`: Round down to the previous integer. - `half_up`: Round to the nearest integer, with 0.5 rounding up. - `none`: No rounding; the converted value is used as-is.', + ) + +export const rateCardStaticEntitlementWire = z + .strictObject({ + type: z.literal('static').describe('The type of the entitlement template.'), + config: z + .unknown() + + .describe( + 'The entitlement config as a JSON object. Returned when checking entitlement access; useful for configuring fine-grained access settings implemented in your own system.', + ), + }) + .describe('The entitlement template of a static entitlement.') + +export const rateCardBooleanEntitlementWire = z + .strictObject({ + type: z + .literal('boolean') + .describe('The type of the entitlement template.'), + }) + .describe('The entitlement template of a boolean entitlement.') + +export const appTypeWire = z + .enum(['sandbox', 'stripe', 'external_invoicing']) + .describe('The type of the app.') + +export const appCapabilityTypeWire = z + .enum([ + 'report_usage', + 'report_events', + 'calculate_tax', + 'invoice_customers', + 'collect_payments', + ]) + + .describe( + 'Supported capability types for an App. Each capability defines an integration function that an App can perform.', + ) + +export const appInstallMethodsWire = z + .enum(['with_oauth2', 'with_api_key', 'no_credentials_required']) + .describe('Supported installation methods for an app.') + +export const appStatusWire = z + .enum(['ready', 'unauthorized']) + .describe('Connection status of an installed app.') + +export const installAppStripeWithApiKeyWire = z + .strictObject({ + type: z.literal('stripe').describe('Type of the app.'), + name: z.string().describe('Name of the app.'), + create_billing_profile: z + .boolean() + + .describe( + 'If true, a billing profile will be created for the app. The Stripe app will be also set as the default billing profile if the current default is a Sandbox app.', + ), + api_key: z.string().describe('API key for the app.'), + }) + .describe('Model for installing an app from the catalog with an API key.') + +export const installAppSandboxWire = z + .strictObject({ + type: z.literal('sandbox').describe('Type of the app.'), + name: z.string().describe('Name of the app.'), + create_billing_profile: z + .boolean() + + .describe( + 'If true, a billing profile will be created for the app. The Stripe app will be also set as the default billing profile if the current default is a Sandbox app.', + ), + }) + .describe('Base model for installing an app from the catalog.') + +export const installAppExternalInvoicingWire = z + .strictObject({ + type: z.literal('external_invoicing').describe('Type of the app.'), + name: z.string().describe('Name of the app.'), + create_billing_profile: z + .boolean() + + .describe( + 'If true, a billing profile will be created for the app. The Stripe app will be also set as the default billing profile if the current default is a Sandbox app.', + ), + }) + .describe('Base model for installing an app from the catalog.') + +export const taxIdentificationCodeWire = z + .string() + .min(1) + .max(32) + + .describe( + 'Tax identifier code is a normalized tax code shown on the original identity document.', + ) + +export const workflowCollectionAlignmentSubscriptionWire = z + .strictObject({ + type: z.literal('subscription').describe('The type of alignment.'), + }) + + .describe( + 'BillingWorkflowCollectionAlignmentSubscription specifies the alignment for collecting the pending line items into an invoice.', + ) + +export const workflowInvoicingSubscriptionEndProrationModeWire = z + .enum(['bill_full_period', 'bill_actual_period']) + .describe('Billing workflow subscription end proration mode.') + +export const workflowPaymentChargeAutomaticallySettingsWire = z + .strictObject({ + collection_method: z + .literal('charge_automatically') + .describe('The collection method for the invoice.'), + }) + + .describe( + 'Payment settings for a billing workflow when the collection method is charge automatically.', + ) + +export const workflowPaymentSendInvoiceSettingsWire = z + .strictObject({ + collection_method: z + .literal('send_invoice') + .describe('The collection method for the invoice.'), + due_after: z + .string() + .optional() + + .describe( + "The period after which the invoice is due. With some payment solutions it's only applicable for manual collection method.", + ), + }) + + .describe( + 'Payment settings for a billing workflow when the collection method is send invoice.', + ) + +export const invoiceNumberWire = z + .string() + .min(1) + .max(256) + + .describe( + 'InvoiceNumber is a unique identifier for the invoice, generated by the invoicing app. The uniqueness depends on a lot of factors: - app setting (unique per app or unique per customer) - multiple app scenarios (multiple apps generating invoices with the same prefix)', + ) + +export const invoiceValidationIssueSeverityWire = z + .enum(['critical', 'warning']) + .describe('Severity level of an invoice validation issue.') + +export const invoiceExternalReferencesWire = z + .strictObject({ + invoicing_id: z + .string() + .optional() + + .describe( + 'The ID assigned by the external invoicing app (e.g. Stripe invoice ID).', + ), + payment_id: z + .string() + .optional() + + .describe( + 'The ID assigned by the external payment app (e.g. Stripe payment intent ID).', + ), + }) + + .describe( + 'External identifiers assigned to an invoice by third-party systems.', + ) + +export const invoiceStandardStatusWire = z + .enum([ + 'draft', + 'issuing', + 'issued', + 'payment_processing', + 'overdue', + 'paid', + 'uncollectible', + 'voided', + ]) + .describe('Lifecycle status of a standard invoice.') + +export const invoiceAvailableActionDetailsWire = z + .strictObject({ + resulting_state: z + .string() + + .describe( + 'The extended status the invoice will transition to after performing this action.', + ), + }) + + .describe( + 'Details about an available invoice action including the resulting state.', + ) + +export const invoiceWorkflowInvoicingSettingsWire = z + .strictObject({ + auto_advance: z + .boolean() + .optional() + + .describe( + 'Whether to automatically issue the invoice after the draft_period has passed.', + ), + draft_period: z + .string() + .optional() + + .describe( + 'The period for the invoice to be kept in draft status for manual reviews.', + ), + due_after: z + .string() + .optional() + + .describe( + 'The period after which the invoice is considered overdue if not paid.', + ), + }) + + .describe( + 'Invoice-level invoicing settings. A subset of BillingWorkflowInvoicingSettings limited to fields that are meaningful per-invoice. progressive_billing is omitted as it is a gather-time / profile-level decision.', + ) + +export const invoiceDiscountReasonWire = z + .enum(['maximum_spend', 'ratecard_percentage', 'ratecard_usage']) + .describe('The reason a discount was applied to an invoice line.') + +export const invoiceLineExternalReferencesWire = z + .strictObject({ + invoicing_id: z + .string() + .optional() + .describe('The ID assigned by the external invoicing app.'), + }) + + .describe( + 'External identifiers for an invoice line item assigned by third-party systems.', + ) + +export const invoiceDetailedLineCostCategoryWire = z + .enum(['regular', 'commitment']) + .describe('Cost category of a detailed invoice line item.') + +export const updateLabelsWire = z + .record(z.string(), z.string()) + + .describe( + 'Labels store metadata of an entity that can be used for filtering an entity list or for searching across entity types. Keys must be of length 1-63 characters, and cannot start with "kong", "konnect", "mesh", "kic", or "\\_".', + ) + +export const updateBillingInvoiceWorkflowInvoicingSettingsWire = z + .strictObject({ + auto_advance: z + .boolean() + .optional() + + .describe( + 'Whether to automatically issue the invoice after the draft_period has passed.', + ), + draft_period: z + .string() + .optional() + + .describe( + 'The period for the invoice to be kept in draft status for manual reviews.', + ), + }) + + .describe( + 'Invoice-level invoicing settings. A subset of BillingWorkflowInvoicingSettings limited to fields that are meaningful per-invoice. progressive_billing is omitted as it is a gather-time / profile-level decision.', + ) + +export const updateBillingWorkflowPaymentChargeAutomaticallySettingsWire = z + .strictObject({ + collection_method: z + .literal('charge_automatically') + .describe('The collection method for the invoice.'), + }) + + .describe( + 'Payment settings for a billing workflow when the collection method is charge automatically.', + ) + +export const updateBillingWorkflowPaymentSendInvoiceSettingsWire = z + .strictObject({ + collection_method: z + .literal('send_invoice') + .describe('The collection method for the invoice.'), + due_after: z + .string() + .optional() + + .describe( + "The period after which the invoice is due. With some payment solutions it's only applicable for manual collection method.", + ), + }) + + .describe( + 'Payment settings for a billing workflow when the collection method is send invoice.', + ) + +export const updatePriceFreeWire = z + .strictObject({ + type: z.literal('free').describe('The type of the price.'), + }) + .describe('Free price.') + +export const currencyTypeWire = z + .enum(['fiat', 'custom']) + + .describe( + 'Currency type for custom currencies. It should be a unique code but not conflicting with any existing standard currency codes.', + ) + +export const currencyCodeCustomWire = z + .string() + .min(3) + .max(24) + + .describe( + 'Custom currency code. It should be a unique code but not conflicting with any existing fiat currency codes.', + ) + +export const featureLlmTokenTypeWire = z + .enum([ + 'input', + 'output', + 'cache_read', + 'cache_write', + 'reasoning', + 'request', + 'response', + ]) + .describe('Token type for LLM cost lookup.') + +export const llmCostProviderWire = z + .strictObject({ + id: z + .string() + .describe('Identifier of the provider, e.g., "openai", "anthropic".'), + name: z + .string() + .describe('Name of the provider, e.g., "OpenAI", "Anthropic".'), + }) + .describe('LLM Provider') + +export const llmCostModelWire = z + .strictObject({ + id: z + .string() + + .describe('Identifier of the model, e.g., "gpt-4", "claude-3-5-sonnet".'), + name: z + .string() + .describe('Name of the model, e.g., "GPT-4", "Claude 3.5 Sonnet".'), + }) + .describe('LLM Model') + +export const llmCostPriceSourceWire = z + .enum(['manual', 'system']) + .describe('Identifies where an LLM cost price came from.') + +export const planStatusWire = z + .enum(['draft', 'active', 'archived', 'scheduled']) + + .describe( + 'The status of a plan. - `draft`: The plan has not yet been published and can be edited. - `active`: The plan is published and can be used in subscriptions. - `archived`: The plan is no longer available for use. - `scheduled`: The plan is scheduled to be published at a future date.', + ) + +export const productCatalogValidationErrorWire = z + .strictObject({ + code: z.string().describe('Machine-readable error code.'), + message: z.string().describe('Human-readable description of the error.'), + attributes: z + .record(z.string(), z.unknown()) + .optional() + .describe('Additional structured context.'), + field: z.string().describe('The path to the field.'), + }) + .describe('Validation errors providing detailed description of the issue.') + +export const addonInstanceTypeWire = z + .enum(['single', 'multiple']) + + .describe( + 'The instanceType of the add-on. - `single`: Can be added to a subscription only once. - `multiple`: Can be added to a subscription more than once.', + ) + +export const addonStatusWire = z + .enum(['draft', 'active', 'archived']) + + .describe( + 'The status of the add-on defined by the `effective_from` and `effective_to` properties. - `draft`: The add-on has not yet been published and can be edited. - `active`: The add-on is published and available for use. - `archived`: The add-on is no longer available for use.', + ) + +export const governanceQueryRequestCustomersWire = z + .strictObject({ + keys: z + .array(z.string()) + .min(1) + .max(100) + + .describe( + 'Each entry can be a customer `key` or a usage-attribution subject `key`. Identifiers that cannot be resolved to a customer are reported in the response `errors` array.', + ), + }) + .describe('List of customer identifiers to evaluate access for.') + +export const governanceQueryRequestFeaturesWire = z + .strictObject({ + keys: z + .array(z.string()) + .min(1) + .max(100) + .describe('List of feature keys to evaluate access for.'), + }) + + .describe( + 'Optional list of feature keys to evaluate access for. If omitted, all features available in the organization are returned. Providing this list is recommended to reduce the response size and the load on the backend services.', + ) + +export const governanceFeatureAccessReasonCodeWire = z + .enum([ + 'unknown', + 'usage_limit_reached', + 'feature_unavailable', + 'feature_not_found', + 'no_credit_available', + ]) + .describe('Machine-readable reason code for denied feature access.') + +export const governanceQueryErrorCodeWire = z + .enum(['unknown', 'customer_not_found']) + .describe('Error code for a governance query failure.') + +export const queryFilterIntegerWire = z + .strictObject({ + eq: z + .number() + .int() + .optional() + .describe('The attribute equals the provided value.'), + neq: z + .number() + .int() + .optional() + .describe('The attribute does not equal the provided value.'), + in: z + .array(z.number().int()) + .min(1) + .max(100) + .optional() + .describe('The attribute is one of the provided values.'), + nin: z + .array(z.number().int()) + .min(1) + .max(100) + .optional() + .describe('The attribute is not one of the provided values.'), + gt: z + .number() + .int() + .optional() + .describe('The attribute is greater than the provided value.'), + gte: z + .number() + .int() + .optional() + + .describe( + 'The attribute is greater than or equal to the provided value.', + ), + lt: z + .number() + .int() + .optional() + .describe('The attribute is less than the provided value.'), + lte: z + .number() + .int() + .optional() + .describe('The attribute is less than or equal to the provided value.'), + get and() { + return z + .array(queryFilterIntegerWire) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical AND.') + }, + get or() { + return z + .array(queryFilterIntegerWire) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical OR.') + }, + }) + + .describe( + 'A query filter for an integer attribute. Operators are mutually exclusive, only one operator is allowed at a time.', + ) + +export const queryFilterFloatWire = z + .strictObject({ + gt: z + .number() + .optional() + .describe('The attribute is greater than the provided value.'), + gte: z + .number() + .optional() + + .describe( + 'The attribute is greater than or equal to the provided value.', + ), + lt: z + .number() + .optional() + .describe('The attribute is less than the provided value.'), + lte: z + .number() + .optional() + .describe('The attribute is less than or equal to the provided value.'), + get and() { + return z + .array(queryFilterFloatWire) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical AND.') + }, + get or() { + return z + .array(queryFilterFloatWire) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical OR.') + }, + }) + + .describe( + 'A query filter for a float attribute. Operators are mutually exclusive, only one operator is allowed at a time.', + ) + +export const queryFilterBooleanWire = z + .strictObject({ + eq: z + .boolean() + .optional() + .describe('The attribute equals the provided value.'), + }) + + .describe( + 'A query filter for a boolean attribute. Operators are mutually exclusive, only one operator is allowed at a time.', + ) + +export const pagePaginationQueryWire = z + .strictObject({ + page: z + .strictObject({ + size: z + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + }) + .describe('Page pagination query.') + +export const publicLabelsWire = z + .record(z.string(), z.string()) + + .describe( + 'Public labels store information about an entity that can be used for filtering a list of objects.', + ) + +export const booleanFieldFilterWire = z + .union([ + z.boolean(), + z.strictObject({ + eq: z + .boolean() + .describe('Value strictly equals the given boolean value.'), + }), + ]) + .describe('Filter by a boolean value (true/false).') + +export const numericFieldFilterWire = z + .union([ + z.number(), + z.strictObject({ + eq: z + .number() + .optional() + .describe('Value strictly equals the given numeric value.'), + neq: z + .number() + .optional() + .describe('Value does not equal the given numeric value.'), + oeq: z + .array(z.number()) + .optional() + + .describe( + 'Returns entities that match any of the comma-delimited numeric values.', + ), + lt: z + .number() + .optional() + .describe('Value is less than the given numeric value.'), + lte: z + .number() + .optional() + .describe('Value is less than or equal to the given numeric value.'), + gt: z + .number() + .optional() + .describe('Value is greater than the given numeric value.'), + gte: z + .number() + .optional() + .describe('Value is greater than or equal to the given numeric value.'), + }), + ]) + + .describe( + 'Filter by a numeric value. All properties are optional; provide exactly one to specify the comparison.', + ) + +export const chargeTypeWire = z + .enum(['flat_fee', 'usage_based']) + + .describe( + 'Type of a charge. Values: - `flat_fee`: A fixed-amount charge. - `usage_based`: A usage-priced charge.', + ) + +export const invoiceTypeWire = z + .enum(['standard']) + .describe('The type of a billing invoice.') + +export const invoiceLineTypeWire = z + .enum(['standard_line']) + .describe('Line item type discriminator.') + +export const priceTypeWire = z + .enum(['free', 'flat', 'unit', 'graduated', 'volume']) + + .describe( + "The type of the price. - `free`: No charge, the rate card is included at no cost. - `flat`: A fixed amount charged once per billing period, regardless of usage. - `unit`: A fixed rate charged per billing unit consumed. - `graduated`: Tiered pricing where each tier's rate applies only to usage within that tier. - `volume`: Tiered pricing where the rate for the highest tier reached applies to all units in the period.", + ) + +export const collectionAlignmentWire = z + .enum(['subscription', 'anchored']) + + .describe( + 'BillingCollectionAlignment specifies when the pending line items should be collected into an invoice.', + ) + +export const collectionMethodWire = z + .enum(['charge_automatically', 'send_invoice']) + + .describe( + 'Collection method specifies how the invoice should be collected (automatic or manual).', + ) + +export const featureUnitCostTypeWire = z + .enum(['llm', 'manual']) + .describe('The type of unit cost.') + +export const systemAccountAccessTokenWire = z + .strictObject({ + type: z.literal('http').describe('Http authentication'), + scheme: z.literal('Bearer').describe('bearer auth scheme'), + }) + + .describe( + 'The system account access token is meant for automations and integrations that are not directly associated with a human identity.', + ) + +export const personalAccessTokenWire = z + .strictObject({ + type: z.literal('http').describe('Http authentication'), + scheme: z.literal('Bearer').describe('bearer auth scheme'), + }) + + .describe( + 'The personal access token is meant to be used as an alternative to basic-auth when accessing Konnect via APIs.', + ) + +export const konnectAccessTokenWire = z + .strictObject({ + type: z.literal('http').describe('Http authentication'), + scheme: z.literal('Bearer').describe('bearer auth scheme'), + }) + + .describe( + 'The Konnect access token is meant to be used by the Konnect dashboard and the decK CLI authenticate with.', + ) + +export const updateMeterRequestWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .optional() + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + dimensions: z + .record(z.string(), z.string()) + .optional() + + .describe( + 'Named JSONPath expressions to extract the group by values from the event data. Keys must be unique and consist only alphanumeric and underscore characters.', + ), + }) + .describe('Meter update request.') + +export const appCustomerDataStripeWire = z + .strictObject({ + customer_id: z.string().optional().describe('The Stripe customer ID used.'), + default_payment_method_id: z + .string() + .optional() + .describe('The Stripe default payment method ID.'), + labels: labelsWire.optional(), + }) + .describe('Stripe customer data.') + +export const appCustomerDataExternalInvoicingWire = z + .strictObject({ + labels: labelsWire.optional(), + }) + .describe('External invoicing customer data.') + +export const billingCurrencyCodeWire = z + .union([currencyCodeWire]) + .describe('Fiat or custom currency code.') + +export const createCurrencyCodeWire = z + .union([currencyCodeWire]) + .describe('Fiat or custom currency code.') + +export const currencyFiatWire = z + .strictObject({ + type: z.literal('fiat').describe('The type of the currency.'), + name: z + .string() + .min(1) + .max(256) + + .describe( + 'The name of the currency. It should be a human-readable string that represents the name of the currency, such as "US Dollar" or "Euro".', + ), + symbol: z + .string() + .min(1) + .optional() + + .describe( + 'The symbol of the currency. It should be a string that represents the symbol of the currency, such as "$" for US Dollar or "€" for Euro.', + ), + code: currencyCodeWire, + }) + .describe('Currency describes a currency supported by the billing system.') + +export const listCostBasesParamsFilterWire = z + .strictObject({ + fiat_code: currencyCodeWire.optional(), + }) + .describe('Filter options for listing cost bases.') + +export const currencyAmountWire = z + .strictObject({ + amount: numericWire, + currency: currencyCodeWire, + }) + .describe('Monetary amount in a specific currency.') + +export const priceFlatWire = z + .strictObject({ + type: z.literal('flat').describe('The type of the price.'), + amount: numericWire, + }) + .describe('Flat price.') + +export const priceUnitWire = z + .strictObject({ + type: z.literal('unit').describe('The type of the price.'), + amount: numericWire, + }) + + .describe( + 'Unit price. Charges a fixed rate per billing unit. When UnitConfig is present on the rate card, billing units are the converted quantities (e.g. GB instead of bytes).', + ) + +export const rateCardDiscountsWire = z + .strictObject({ + percentage: z + .number() + .nonnegative() + .lte(100) + .optional() + .describe('Percentage discount applied to the price (0–100).'), + usage: numericWire.optional(), + }) + .describe('Discount configuration for a rate card.') + +export const totalsWire = z + .strictObject({ + amount: numericWire, + taxes_total: numericWire, + taxes_inclusive_total: numericWire, + taxes_exclusive_total: numericWire, + charges_total: numericWire, + discounts_total: numericWire, + credits_total: numericWire, + total: numericWire, + }) + + .describe( + 'Totals contains the summaries of all calculations for a billing resource.', + ) + +export const spendCommitmentsWire = z + .strictObject({ + minimum_amount: numericWire.optional(), + maximum_amount: numericWire.optional(), + }) + + .describe( + 'Spend commitments for a rate card. The customer is committed to spend at least the minimum amount and at most the maximum amount.', + ) + +export const invoiceLineCreditsAppliedWire = z + .strictObject({ + amount: numericWire, + description: z + .string() + .optional() + + .describe( + 'Optional human-readable description of the credit allocation.', + ), + }) + .describe('A credit allocation applied to an invoice line item.') + +export const updatePriceFlatWire = z + .strictObject({ + type: z.literal('flat').describe('The type of the price.'), + amount: numericWire, + }) + .describe('Flat price.') + +export const updatePriceUnitWire = z + .strictObject({ + type: z.literal('unit').describe('The type of the price.'), + amount: numericWire, + }) + + .describe( + 'Unit price. Charges a fixed rate per billing unit. When UnitConfig is present on the rate card, billing units are the converted quantities (e.g. GB instead of bytes).', + ) + +export const updateDiscountsWire = z + .strictObject({ + percentage: z + .number() + .nonnegative() + .lte(100) + .optional() + .describe('Percentage discount applied to the price (0–100).'), + usage: numericWire.optional(), + }) + .describe('Discount configuration for a rate card.') + +export const featureManualUnitCostWire = z + .strictObject({ + type: z + .literal('manual') + .describe('The type discriminator for manual unit cost.'), + amount: numericWire, + }) + .describe('A fixed per-unit cost amount.') + +export const featureLlmUnitCostPricingWire = z + .strictObject({ + input_per_token: numericWire, + output_per_token: numericWire, + cache_read_per_token: numericWire.optional(), + reasoning_per_token: numericWire.optional(), + cache_write_per_token: numericWire.optional(), + }) + .describe('Resolved per-token pricing from the LLM cost database.') + +export const llmCostModelPricingWire = z + .strictObject({ + input_per_token: numericWire, + output_per_token: numericWire, + cache_read_per_token: numericWire.optional(), + cache_write_per_token: numericWire.optional(), + reasoning_per_token: numericWire.optional(), + }) + .describe('Token pricing for an LLM model, denominated per token.') + +export const queryFilterNumericWire = z + .strictObject({ + gt: numericWire.optional(), + gte: numericWire.optional(), + lt: numericWire.optional(), + lte: numericWire.optional(), + get and() { + return z + .array(queryFilterNumericWire) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical AND.') + }, + get or() { + return z + .array(queryFilterNumericWire) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical OR.') + }, + }) + + .describe( + 'A query filter for a numeric attribute. Operators are mutually exclusive, only one operator is allowed at a time.', + ) + +export const cursorPaginationQueryWire = z + .strictObject({ + page: cursorPaginationQueryPageWire.optional(), + }) + .describe('Cursor page query.') + +export const listMetersParamsFilterWire = z + .strictObject({ + key: stringFieldFilterWire.optional(), + name: stringFieldFilterWire.optional(), + }) + .describe('Filter options for listing meters.') + +export const listLlmCostPricesParamsFilterWire = z + .strictObject({ + provider: stringFieldFilterWire.optional(), + model_id: stringFieldFilterWire.optional(), + model_name: stringFieldFilterWire.optional(), + currency: stringFieldFilterWire.optional(), + source: stringFieldFilterWire.optional(), + }) + .describe('Filter options for listing LLM cost prices.') + +export const labelsFieldFilterWire = z + .record(z.string(), stringFieldFilterWire) + + .describe( + "Filters on the resource's `labels` field. The schema is a map keyed by the label name; each value is a `StringFieldFilter`. Both deepObject forms are accepted: `filter[labels][key]=value` (nested) and `filter[labels.key]=value` (dot-notation).", + ) + +export const ulidFieldFilterWire = z + .union([ + ulidWire, + z.strictObject({ + eq: ulidWire.optional(), + oeq: z + .array(ulidWire) + .optional() + + .describe( + 'Returns entities that exact match any of the comma-delimited ULIDs in the filter string.', + ), + neq: ulidWire.optional(), + }), + ]) + + .describe( + 'Filters on the given ULID field value by exact match. All properties are optional; provide exactly one to specify the comparison.', + ) + +export const customerReferenceWire = z + .strictObject({ + id: ulidWire, + }) + .describe('Customer reference.') + +export const profileReferenceWire = z + .strictObject({ + id: ulidWire, + }) + .describe('Billing profile reference.') + +export const createResourceReferenceWire = z + .strictObject({ + id: ulidWire, + }) + .describe('TaxCode reference.') + +export const taxCodeReferenceWire = z + .strictObject({ + id: ulidWire, + }) + .describe('TaxCode reference.') + +export const creditGrantInvoiceReferenceWire = z + .strictObject({ + id: ulidWire.optional(), + line: z + .strictObject({ + id: ulidWire, + }) + .optional() + .describe('Identifier of the invoice line associated with the grant.'), + }) + .describe('Invoice references for the grant.') + +export const billingCustomerReferenceWire = z + .strictObject({ + id: ulidWire, + }) + .describe('Customer reference.') + +export const subscriptionReferenceWire = z + .strictObject({ + id: ulidWire, + phase: z + .strictObject({ + id: ulidWire, + item: z + .strictObject({ + id: ulidWire, + }) + .describe('The item of the phase.'), + }) + .describe('The phase of the subscription.'), + }) + + .describe( + 'Subscription reference represents a reference to the specific subscription item this entity represents.', + ) + +export const addonReferenceWire = z + .strictObject({ + id: ulidWire, + }) + .describe('Addon reference.') + +export const featureReferenceWire = z + .strictObject({ + id: ulidWire, + }) + .describe('Feature reference.') + +export const appReferenceWire = z + .strictObject({ + id: ulidWire, + }) + .describe('App reference.') + +export const chargeReferenceWire = z + .strictObject({ + id: ulidWire, + }) + .describe('Reference to a charge associated with an invoice line.') + +export const updateResourceReferenceWire = z + .strictObject({ + id: ulidWire, + }) + .describe('TaxCode reference.') + +export const dateTimeFieldFilterWire = z + .union([ + dateTimeWire, + z.strictObject({ + eq: dateTimeWire.optional(), + lt: dateTimeWire.optional(), + lte: dateTimeWire.optional(), + gt: dateTimeWire.optional(), + gte: dateTimeWire.optional(), + }), + ]) + + .describe( + 'Filters on the given datetime (RFC-3339) field value. All properties are optional; provide exactly one to specify the comparison.', + ) + +export const eventWire = z + .strictObject({ + id: z.string().min(1).describe('Identifies the event.'), + source: z + .string() + .min(1) + .describe('Identifies the context in which an event happened.'), + specversion: z + .string() + .min(1) + + .describe( + 'The version of the CloudEvents specification which the event uses.', + ), + type: z + .string() + .min(1) + + .describe( + 'Contains a value describing the type of event related to the originating occurrence.', + ), + datacontenttype: z + .literal('application/json') + .nullable() + .optional() + + .describe( + 'Content type of the CloudEvents data value. Only the value "application/json" is allowed over HTTP.', + ), + dataschema: z + .string() + .nullable() + .optional() + .describe('Identifies the schema that data adheres to.'), + subject: z + .string() + .min(1) + + .describe( + 'Describes the subject of the event in the context of the event producer (identified by source).', + ), + time: dateTimeWire + .nullable() + .optional() + + .describe( + 'Timestamp of when the occurrence happened. Must adhere to RFC 3339.', + ), + data: z + .record(z.string(), z.unknown()) + .nullable() + .optional() + + .describe( + 'The event payload. Optional, if present it must be a JSON object.', + ), + }) + .describe('Metering event following the CloudEvents specification.') + +export const meterQueryRowWire = z + .strictObject({ + value: numericWire, + from: dateTimeWire, + to: dateTimeWire, + dimensions: z + .record(z.string(), z.string()) + + .describe( + 'The dimensions the value is aggregated over. `subject` and `customer_id` are reserved dimensions.', + ), + }) + .describe('A row in the result of a meter query.') + +export const appStripeCreateCustomerPortalSessionResultWire = z + .strictObject({ + id: z + .string() + + .describe( + 'The ID of the customer portal session. See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-id', + ), + stripe_customer_id: z.string().describe('The ID of the stripe customer.'), + configuration_id: z + .string() + + .describe( + 'Configuration used to customize the customer portal. See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-configuration', + ), + livemode: z + .boolean() + + .describe( + 'Livemode. See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-livemode', + ), + created_at: dateTimeWire, + return_url: z + .string() + + .describe( + 'Return URL. See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-return_url', + ), + locale: z + .string() + + .describe( + 'The IETF language tag of the locale customer portal is displayed in. See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-locale', + ), + url: z + .string() + + .describe( + 'The URL to redirect the customer to after they have completed their requested actions.', + ), + }) + + .describe( + 'Result of creating a [Stripe Customer Portal Session](https://docs.stripe.com/api/customer_portal/sessions/object). Contains all the information needed to redirect the customer to the Stripe Customer Portal.', + ) + +export const closedPeriodWire = z + .strictObject({ + from: dateTimeWire, + to: dateTimeWire, + }) + + .describe( + 'A period with defined start and end dates. The period is always inclusive at the start and exclusive at the end.', + ) + +export const subscriptionAddonTimelineSegmentWire = z + .strictObject({ + active_from: dateTimeWire, + active_to: dateTimeWire.optional(), + quantity: z + .number() + .int() + .nonnegative() + .describe('The quantity of the add-on for the given period.'), + }) + .describe('A subscription add-on event.') + +export const updateClosedPeriodWire = z + .strictObject({ + from: dateTimeWire, + to: dateTimeWire, + }) + + .describe( + 'A period with defined start and end dates. The period is always inclusive at the start and exclusive at the end.', + ) + +export const costBasisWire = z + .strictObject({ + id: ulidWire, + fiat_code: currencyCodeWire, + rate: numericWire, + effective_from: dateTimeWire.optional(), + effective_to: dateTimeWire.optional(), + created_at: dateTimeWire, + }) + .describe('Describes currency basis supported by billing system.') + +export const createCostBasisRequestWire = z + .strictObject({ + fiat_code: currencyCodeWire, + rate: numericWire, + effective_from: dateTimeWire.optional(), + effective_to: dateTimeWire.optional(), + }) + .describe('CostBasis create request.') + +export const featureCostQueryRowWire = z + .strictObject({ + usage: numericWire, + cost: numericWire + .nullable() + + .describe( + 'The computed cost amount (usage × unit cost). Null when pricing is not available for the given combination of dimensions.', + ), + currency: currencyCodeWire, + detail: z + .string() + .optional() + + .describe( + 'Detail message when cost amount is null, explaining why the cost could not be resolved.', + ), + from: dateTimeWire, + to: dateTimeWire, + dimensions: z + .record(z.string(), z.string()) + + .describe( + 'The dimensions the value is aggregated over. `subject` and `customer_id` are reserved dimensions.', + ), + }) + .describe('A row in the result of a feature cost query.') + +export const resourceWire = z + .strictObject({ + id: ulidWire, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + }) + .describe('Represents common fields of resources.') + +export const resourceImmutableWire = z + .strictObject({ + id: ulidWire, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + }) + .describe('Represents common fields of immutable resources.') + +export const queryFilterDateTimeWire = z + .strictObject({ + gt: dateTimeWire.optional(), + gte: dateTimeWire.optional(), + lt: dateTimeWire.optional(), + lte: dateTimeWire.optional(), + get and() { + return z + .array(queryFilterDateTimeWire) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical AND.') + }, + get or() { + return z + .array(queryFilterDateTimeWire) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical OR.') + }, + }) + + .describe( + 'A query filter for a time attribute. Operators are mutually exclusive, only one operator is allowed at a time.', + ) + +export const cursorMetaWire = z + .strictObject({ + page: cursorMetaPageWire, + }) + .describe('Cursor pagination metadata.') + +export const invalidParameterStandardWire = z + .strictObject({ + field: z.string().describe('The name of the field that failed validation.'), + rule: invalidRulesWire.optional(), + source: z + .string() + .optional() + + .describe( + 'The part of the request the field came from (e.g. `body`, `query`).', + ), + reason: z + .string() + + .describe( + 'A human readable explanation of why the field failed validation.', + ), + }) + .describe('A parameter that failed a standard validation rule.') + +export const invalidParameterMinimumLengthWire = z + .strictObject({ + field: z.string().describe('The name of the field that failed validation.'), + rule: invalidParameterMinimumRuleWire, + minimum: z.number().int().describe('The minimum allowed value or length.'), + source: z + .string() + .optional() + + .describe( + 'The part of the request the field came from (e.g. `body`, `query`).', + ), + reason: z + .string() + + .describe( + 'A human readable explanation of why the field failed validation.', + ), + }) + + .describe( + 'A parameter that failed a minimum-length (or minimum-value) validation rule.', + ) + +export const invalidParameterMaximumLengthWire = z + .strictObject({ + field: z.string().describe('The name of the field that failed validation.'), + rule: invalidParameterMaximumRuleWire, + maximum: z.number().int().describe('The maximum allowed value or length.'), + source: z + .string() + .optional() + + .describe( + 'The part of the request the field came from (e.g. `body`, `query`).', + ), + reason: z + .string() + + .describe( + 'A human readable explanation of why the field failed validation.', + ), + }) + + .describe( + 'A parameter that failed a maximum-length (or maximum-value) validation rule.', + ) + +export const invalidParameterChoiceItemWire = z + .strictObject({ + field: z.string().describe('The name of the field that failed validation.'), + rule: invalidParameterChoiceRuleWire, + reason: z + .string() + + .describe( + 'A human readable explanation of why the field failed validation.', + ), + choices: z + .array(z.unknown()) + .min(1) + .describe('The allowed choices for the field.'), + source: z + .string() + .optional() + + .describe( + 'The part of the request the field came from (e.g. `body`, `query`).', + ), + }) + .describe('A parameter whose value was not one of the allowed choices.') + +export const invalidParameterDependentItemWire = z + .strictObject({ + field: z.string().describe('The name of the field that failed validation.'), + rule: invalidParameterDependentRuleWire, + reason: z + .string() + + .describe( + 'A human readable explanation of why the field failed validation.', + ), + dependents: z + .array(z.unknown()) + .describe('The fields that this field depends on.'), + source: z + .string() + .optional() + + .describe( + 'The part of the request the field came from (e.g. `body`, `query`).', + ), + }) + .describe('A parameter that failed a dependent-fields validation rule.') + +export const unauthorizedWire = baseErrorWire.describe('Unauthorized.') + +export const forbiddenWire = baseErrorWire.describe('Forbidden.') + +export const notFoundWire = baseErrorWire.describe('Not Found.') + +export const goneWire = baseErrorWire.describe('Gone.') + +export const conflictWire = baseErrorWire.describe('Conflict.') + +export const payloadTooLargeWire = baseErrorWire.describe('Payload Too Large.') + +export const unsupportedMediaTypeWire = baseErrorWire.describe( + 'Unsupported Media Type.', +) + +export const unprocessableContentWire = baseErrorWire.describe( + 'Unprocessable Content.', +) + +export const tooManyRequestsWire = baseErrorWire.describe('Too Many Requests.') + +export const internalWire = baseErrorWire.describe('Internal Server Error.') + +export const notImplementedWire = baseErrorWire.describe('Not Implemented.') + +export const notAvailableWire = baseErrorWire.describe('Not Available.') + +export const createCreditGrantFiltersWire = z + .strictObject({ + features: z + .array(resourceKeyWire) + .optional() + + .describe( + 'Limit the credit grant to specific features. If no features are specified, the credit grant can be used for any feature.', + ), + }) + .describe('Filters for the credit grant.') + +export const creditGrantFiltersWire = z + .strictObject({ + features: z + .array(resourceKeyWire) + .optional() + + .describe( + 'Limit the credit grant to specific features. If no features are specified, the credit grant can be used for any feature.', + ), + }) + .describe('Filters for the credit grant.') + +export const upsertPlanAddonRequestWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + from_plan_phase: resourceKeyWire, + max_quantity: z + .number() + .int() + .gte(1) + .optional() + + .describe( + 'The maximum number of times the add-on can be purchased for the plan. For single-instance add-ons this field must be omitted. For multi-instance add-ons when omitted, unlimited quantity can be purchased.', + ), + }) + .describe('PlanAddon upsert request.') + +export const resourceWithKeyWire = z + .strictObject({ + id: ulidWire, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + key: resourceKeyWire, + }) + .describe('Represents common fields of resources with a key.') + +export const ulidOrResourceKeyWire = z + .union([ulidWire, resourceKeyWire]) + .describe('ULID ID or Resource Key.') + +export const createMeterRequestWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + key: resourceKeyWire, + aggregation: meterAggregationWire, + event_type: z + .string() + .min(1) + .describe('The event type to include in the aggregation.'), + events_from: dateTimeWire.optional(), + value_property: z + .string() + .min(1) + .optional() + + .describe( + "JSONPath expression to extract the value from the ingested event's data property. The ingested value for sum, avg, min, and max aggregations is a number or a string that can be parsed to a number. For unique_count aggregation, the ingested value must be a string. For count aggregation the value_property is ignored.", + ), + dimensions: z + .record(z.string(), z.string()) + .optional() + + .describe( + 'Named JSONPath expressions to extract the group by values from the event data. Keys must be unique and consist only alphanumeric and underscore characters.', + ), + }) + .describe('Meter create request.') + +export const meterWire = z + .strictObject({ + id: ulidWire, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + key: resourceKeyWire, + aggregation: meterAggregationWire, + event_type: z + .string() + .min(1) + .describe('The event type to include in the aggregation.'), + events_from: dateTimeWire.optional(), + value_property: z + .string() + .min(1) + .optional() + + .describe( + "JSONPath expression to extract the value from the ingested event's data property. The ingested value for sum, avg, min, and max aggregations is a number or a string that can be parsed to a number. For unique_count aggregation, the ingested value must be a string. For count aggregation the value_property is ignored.", + ), + dimensions: z + .record(z.string(), z.string()) + .optional() + + .describe( + 'Named JSONPath expressions to extract the group by values from the event data. Keys must be unique and consist only alphanumeric and underscore characters.', + ), + }) + + .describe( + 'A meter is a configuration that defines how to match and aggregate events.', + ) + +export const paginatedMetaWire = z + .strictObject({ + page: pageMetaWire, + }) + .describe('Pagination metadata.') + +export const queryFilterStringMapItemWire = z + .strictObject({ + exists: z.boolean().optional().describe('The attribute exists.'), + eq: z + .string() + .optional() + .describe('The attribute equals the provided value.'), + neq: z + .string() + .optional() + .describe('The attribute does not equal the provided value.'), + in: z + .array(z.string()) + .min(1) + .max(100) + .optional() + .describe('The attribute is one of the provided values.'), + nin: z + .array(z.string()) + .min(1) + .max(100) + .optional() + .describe('The attribute is not one of the provided values.'), + contains: z + .string() + .optional() + .describe('The attribute contains the provided value.'), + ncontains: z + .string() + .optional() + .describe('The attribute does not contain the provided value.'), + and: z + .array(queryFilterStringWire) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical AND.'), + or: z + .array(queryFilterStringWire) + .min(1) + .max(10) + .optional() + .describe('Combines the provided filters with a logical OR.'), + }) + + .describe( + 'A query filter for an item in a string map attribute. Operators are mutually exclusive, only one operator is allowed at a time.', + ) + +export const ulidOrExternalResourceKeyWire = z + .union([ulidWire, externalResourceKeyWire]) + .describe('ULID ID or External Resource Key.') + +export const customerKeyReferenceWire = z + .strictObject({ + key: externalResourceKeyWire, + }) + .describe('Customer reference by external key.') + +export const customerUsageAttributionWire = z + .strictObject({ + subject_keys: z + .array(usageAttributionSubjectKeyWire) + + .describe( + 'The subjects that are attributed to the customer. Can be empty when no usage event subjects are associated with the customer.', + ), + }) + + .describe( + 'Mapping to attribute metered usage to the customer. One customer can have zero or more subjects, but one subject can only belong to one customer.', + ) + +export const updateCustomerUsageAttributionWire = z + .strictObject({ + subject_keys: z + .array(usageAttributionSubjectKeyWire) + + .describe( + 'The subjects that are attributed to the customer. Can be empty when no usage event subjects are associated with the customer.', + ), + }) + + .describe( + 'Mapping to attribute metered usage to the customer. One customer can have zero or more subjects, but one subject can only belong to one customer.', + ) + +export const addressWire = z + .strictObject({ + country: countryCodeWire.optional(), + postal_code: z.string().optional().describe('Postal code.'), + state: z.string().optional().describe('State or province.'), + city: z.string().optional().describe('City.'), + line1: z.string().optional().describe('First line of the address.'), + line2: z.string().optional().describe('Second line of the address.'), + phone_number: z.string().optional().describe('Phone number.'), + }) + .describe('Address') + +export const updateAddressWire = z + .strictObject({ + country: countryCodeWire.optional(), + postal_code: z.string().optional().describe('Postal code.'), + state: z.string().optional().describe('State or province.'), + city: z.string().optional().describe('City.'), + line1: z.string().optional().describe('First line of the address.'), + line2: z.string().optional().describe('Second line of the address.'), + phone_number: z.string().optional().describe('Phone number.'), + }) + .describe('Address') + +export const appStripeCreateCheckoutSessionCustomerUpdateWire = z + .strictObject({ + address: + appStripeCreateCheckoutSessionCustomerUpdateBehaviorWire.optional(), + name: appStripeCreateCheckoutSessionCustomerUpdateBehaviorWire.optional(), + shipping: + appStripeCreateCheckoutSessionCustomerUpdateBehaviorWire.optional(), + }) + + .describe( + 'Controls which customer fields can be updated by the checkout session.', + ) + +export const appStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreementWire = + z + .strictObject({ + position: + appStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPositionWire.optional(), + }) + .describe('Payment method reuse agreement configuration.') + +export const appStripeCreateCheckoutSessionTaxIdCollectionWire = z + .strictObject({ + enabled: z + .boolean() + .optional() + .describe('Enable tax ID collection during checkout. Defaults to false.'), + required: + appStripeCreateCheckoutSessionTaxIdCollectionRequiredWire.optional(), + }) + .describe('Tax ID collection configuration for checkout sessions.') + +export const appStripeCreateCheckoutSessionResultWire = z + .strictObject({ + customer_id: ulidWire, + stripe_customer_id: z.string().describe('The Stripe customer ID.'), + session_id: z.string().describe('The Stripe checkout session ID.'), + setup_intent_id: z + .string() + + .describe( + 'The setup intent ID created for collecting the payment method.', + ), + client_secret: z + .string() + .optional() + + .describe( + 'Client secret for initializing Stripe.js on the client side. Required for embedded checkout sessions. See: https://docs.stripe.com/payments/checkout/custom-success-page', + ), + client_reference_id: z + .string() + .optional() + + .describe( + 'The client reference ID provided in the request. Useful for reconciling the session with your internal systems.', + ), + customer_email: z + .string() + .optional() + .describe("Customer's email address if provided to Stripe."), + currency: currencyCodeWire.optional(), + created_at: dateTimeWire, + expires_at: dateTimeWire.optional(), + metadata: z + .record(z.string(), z.string()) + .optional() + .describe('Metadata attached to the checkout session.'), + status: z + .string() + .optional() + + .describe( + 'The status of the checkout session. See: https://docs.stripe.com/api/checkout/sessions/object#checkout_session_object-status', + ), + url: z + .string() + .optional() + + .describe( + 'URL to redirect customers to the checkout page (for hosted mode).', + ), + mode: appStripeCheckoutSessionModeWire, + cancel_url: z + .string() + .optional() + + .describe( + 'The cancel URL where customers are redirected if they cancel.', + ), + success_url: z + .string() + .optional() + + .describe( + 'The success URL where customers are redirected after completion.', + ), + return_url: z + .string() + .optional() + .describe('The return URL for embedded sessions after authentication.'), + }) + + .describe( + 'Result of creating a Stripe Checkout Session. Contains all the information needed to redirect customers to the checkout or initialize an embedded checkout flow.', + ) + +export const customerStripeCreateCustomerPortalSessionRequestWire = z + .strictObject({ + stripe_options: appStripeCreateCustomerPortalSessionOptionsWire, + }) + + .describe( + 'Request to create a Stripe Customer Portal Session for the customer. Useful to redirect the customer to the Stripe Customer Portal to manage their payment methods, change their billing address and access their invoice history. Only returns URL if the customer billing profile is linked to a stripe app and customer.', + ) + +export const entitlementAccessResultWire = z + .strictObject({ + type: entitlementTypeWire, + feature_key: resourceKeyWire, + has_access: z + .boolean() + + .describe( + 'Whether the customer has access to the feature. Always true for `boolean` and `static` entitlements. Depends on balance for `metered` entitlements.', + ), + config: z + .string() + .optional() + + .describe( + 'Only available for static entitlements. Config is the JSON parsable configuration of the entitlement. Useful to describe per customer configuration.', + ), + }) + .describe('Entitlement access result.') + +export const createCreditGrantPurchaseWire = z + .strictObject({ + currency: currencyCodeWire, + per_unit_cost_basis: numericWire.optional(), + availability_policy: creditAvailabilityPolicyWire.optional(), + }) + .describe('Purchase and payment terms of the grant.') + +export const rateCardMeteredEntitlementWire = z + .strictObject({ + type: z + .literal('metered') + .describe('The type of the entitlement template.'), + is_soft_limit: z + .boolean() + .optional() + + .describe( + 'If soft limit is true, the subject can use the feature even if the entitlement is exhausted; access remains granted.', + ), + limit: z + .number() + .nonnegative() + .optional() + + .describe( + "The amount of usage granted each usage period, in the feature's unit. Usage is counted against this allowance and the balance resets every usage period. When `is_soft_limit` is true the subject keeps access after the limit is reached; otherwise access is denied once the allowance is exhausted.", + ), + usage_period: iso8601DurationWire.optional(), + }) + .describe('The entitlement template of a metered entitlement.') + +export const recurringPeriodWire = z + .strictObject({ + anchor: dateTimeWire, + interval: iso8601DurationWire, + }) + .describe('Recurring period with an anchor and an interval.') + +export const creditGrantPurchaseWire = z + .strictObject({ + currency: currencyCodeWire, + per_unit_cost_basis: numericWire.optional(), + amount: numericWire, + availability_policy: creditAvailabilityPolicyWire.optional(), + settlement_status: creditPurchasePaymentSettlementStatusWire.optional(), + }) + .describe('Purchase and payment terms of the grant.') + +export const updateCreditGrantExternalSettlementRequestWire = z + .strictObject({ + status: creditPurchasePaymentSettlementStatusWire, + }) + + .describe( + 'Request body for updating the external payment settlement status of a credit grant.', + ) + +export const listCreditGrantsParamsFilterWire = z + .strictObject({ + status: creditGrantStatusWire.optional(), + currency: currencyCodeWire.optional(), + key: stringFieldFilterWire.optional(), + }) + .describe('Filter options for listing credit grants.') + +export const getCreditBalanceParamsFilterWire = z + .strictObject({ + currency: stringFieldFilterExactWire.optional(), + feature_key: stringFieldFilterWire.optional(), + }) + .describe('Filter options for getting a credit balance.') + +export const listChargesParamsFilterWire = z + .strictObject({ + status: stringFieldFilterExactWire.optional(), + }) + .describe('Filter options for listing charges.') + +export const listPlansParamsFilterWire = z + .strictObject({ + key: stringFieldFilterWire.optional(), + name: stringFieldFilterWire.optional(), + status: stringFieldFilterExactWire.optional(), + currency: stringFieldFilterExactWire.optional(), + }) + .describe('Filter options for listing plans.') + +export const voidCreditGrantRequestWire = z + .strictObject({ + payment_adjustment: creditGrantVoidPaymentAdjustmentWire.optional(), + }) + .describe('Request body for voiding a credit grant.') + +export const subscriptionCreateWire = z + .strictObject({ + labels: labelsWire.optional(), + settlement_mode: settlementModeWire.optional(), + customer: z + .strictObject({ + id: ulidWire.optional(), + key: externalResourceKeyWire.optional(), + }) + .describe('The customer to create the subscription for.'), + plan: z + .strictObject({ + id: ulidWire.optional(), + key: resourceKeyWire.optional(), + version: z + .number() + .int() + .optional() + + .describe( + 'The plan version of the subscription, if any. If not provided, the latest version of the plan will be used.', + ), + }) + .describe('The plan reference of the subscription.'), + billing_anchor: dateTimeWire.optional(), + }) + .describe('Subscription create request.') + +export const rateCardProrationConfigurationWire = z + .strictObject({ + mode: rateCardProrationModeWire, + }) + .describe('The proration configuration of the rate card.') + +export const subscriptionWire = z + .strictObject({ + id: ulidWire, + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + customer_id: ulidWire, + plan_id: ulidWire.optional(), + billing_anchor: dateTimeWire, + status: subscriptionStatusWire, + settlement_mode: settlementModeWire.optional(), + }) + .describe('Subscription.') + +export const subscriptionEditTimingWire = z + .union([subscriptionEditTimingEnumWire, dateTimeWire]) + + .describe( + 'Subscription edit timing defined when the changes should take effect. If the provided configuration is not supported by the subscription, an error will be returned.', + ) + +export const unitConfigWire = z + .strictObject({ + operation: unitConfigOperationWire, + conversion_factor: numericWire, + rounding: unitConfigRoundingModeWire.optional(), + precision: z + .number() + .int() + .optional() + + .describe( + 'The number of decimal places to retain after rounding. Only meaningful when rounding is not "none". Defaults to 0 (round to whole numbers).', + ), + display_unit: z + .string() + .optional() + + .describe( + 'A human-readable label for the converted unit shown on invoices and in the customer portal (e.g., "GB", "hours", "M tokens"). Optional. When omitted, no unit label is rendered.', + ), + }) + + .describe( + 'Unit conversion configuration. Transforms raw metered quantities into billing-ready units before pricing and entitlement evaluation. Applied at the rate card level so the same feature can be billed in different units across plans. Examples: - Meter bytes, bill GB: operation=divide, conversionFactor=1e9, rounding=ceiling, displayUnit="GB" - Meter seconds, bill hours: operation=divide, conversionFactor=3600, rounding=ceiling, displayUnit="hours" - Cost + 20% margin: operation=multiply, conversionFactor=1.2 - Bill per million tokens: operation=divide, conversionFactor=1e6, rounding=ceiling, displayUnit="M" v1 equivalents: - DynamicPrice(multiplier): operation=multiply, conversionFactor=multiplier + UnitPrice(amount=1) - PackagePrice(amount, quantityPerPkg): operation=divide, conversionFactor=quantityPerPkg, rounding=ceiling + UnitPrice(amount)', + ) + +export const taxCodeAppMappingWire = z + .strictObject({ + app_type: appTypeWire, + tax_code: z.string().describe('Tax code.'), + }) + .describe('Mapping of app types to tax codes.') + +export const appCapabilityWire = z + .strictObject({ + type: appCapabilityTypeWire, + key: resourceKeyWire, + name: z.string().describe('Name of the capability.'), + description: z.string().describe('Description of the capability.'), + }) + .describe('App capability describes a function that an App can perform.') + +export const installAppRequestWire = z + .discriminatedUnion('type', [ + installAppStripeWithApiKeyWire, + installAppSandboxWire, + installAppExternalInvoicingWire, + ]) + .describe('Request to install an app from the catalog.') + +export const partyTaxIdentityWire = z + .strictObject({ + code: taxIdentificationCodeWire.optional(), + }) + + .describe( + 'Identity stores the details required to identify an entity for tax purposes in a specific country.', + ) + +export const updateBillingPartyTaxIdentityWire = z + .strictObject({ + code: taxIdentificationCodeWire.optional(), + }) + + .describe( + 'Identity stores the details required to identify an entity for tax purposes in a specific country.', + ) + +export const workflowInvoicingSettingsWire = z + .strictObject({ + auto_advance: z + .boolean() + .optional() + + .describe( + 'Whether to automatically issue the invoice after the draftPeriod has passed.', + ), + draft_period: z + .string() + .optional() + + .describe( + 'The period for the invoice to be kept in draft status for manual reviews.', + ), + progressive_billing: z + .boolean() + .optional() + .describe('Should progressive billing be allowed for this workflow?'), + subscription_end_proration_mode: + workflowInvoicingSubscriptionEndProrationModeWire.optional(), + }) + .describe('Invoice settings for a billing workflow.') + +export const workflowPaymentSettingsWire = z + .discriminatedUnion('collection_method', [ + workflowPaymentChargeAutomaticallySettingsWire, + workflowPaymentSendInvoiceSettingsWire, + ]) + .describe('Payment settings for a billing workflow.') + +export const invoiceValidationIssueWire = z + .strictObject({ + code: z.string().describe('Machine-readable error code.'), + message: z.string().describe('Human-readable description of the error.'), + attributes: z + .record(z.string(), z.unknown()) + .optional() + .describe('Additional structured context.'), + severity: invoiceValidationIssueSeverityWire, + field: z + .string() + .optional() + + .describe( + 'JSON path to the field that caused this validation issue, if applicable. For example: `lines/0/rate_card/price`.', + ), + }) + + .describe( + 'A validation issue found during invoice processing. Converges on the same structure used by plan and subscription validation errors: a machine-readable `code`, a human-readable `message`, optional structured `attributes`, plus a `severity` and optional `field` path.', + ) + +export const invoiceAvailableActionsWire = z + .strictObject({ + advance: invoiceAvailableActionDetailsWire.optional(), + approve: invoiceAvailableActionDetailsWire.optional(), + delete: invoiceAvailableActionDetailsWire.optional(), + retry: invoiceAvailableActionDetailsWire.optional(), + snapshot_quantities: invoiceAvailableActionDetailsWire.optional(), + }) + + .describe( + 'The set of state-transition actions available for an invoice in its current status. A field is present only when that action is permitted from the current state.', + ) + +export const invoiceLineAmountDiscountWire = z + .strictObject({ + id: ulidWire, + reason: invoiceDiscountReasonWire, + description: z + .string() + .optional() + .describe('Optional human-readable description of the discount.'), + external_references: invoiceLineExternalReferencesWire.optional(), + amount: numericWire, + }) + .describe('A monetary amount discount applied to an invoice line item.') + +export const invoiceLineUsageDiscountWire = z + .strictObject({ + id: ulidWire, + reason: invoiceDiscountReasonWire, + description: z + .string() + .optional() + .describe('Optional human-readable description of the discount.'), + external_references: invoiceLineExternalReferencesWire.optional(), + quantity: numericWire, + }) + .describe('A usage quantity discount applied to an invoice line item.') + +export const invoiceLineBaseDiscountWire = z + .strictObject({ + id: ulidWire, + reason: invoiceDiscountReasonWire, + description: z + .string() + .optional() + .describe('Optional human-readable description of the discount.'), + external_references: invoiceLineExternalReferencesWire.optional(), + }) + .describe('Base fields shared by all invoice line item discounts.') + +export const updateBillingWorkflowPaymentSettingsWire = z + .discriminatedUnion('collection_method', [ + updateBillingWorkflowPaymentChargeAutomaticallySettingsWire, + updateBillingWorkflowPaymentSendInvoiceSettingsWire, + ]) + .describe('Payment settings for a billing workflow.') + +export const listCurrenciesParamsFilterWire = z + .strictObject({ + type: currencyTypeWire.optional(), + code: stringFieldFilterWire.optional(), + }) + .describe('Filter options for listing currencies.') + +export const currencyCustomWire = z + .strictObject({ + type: z.literal('custom').describe('The type of the currency.'), + name: z + .string() + .min(1) + .max(256) + + .describe( + 'The name of the currency. It should be a human-readable string that represents the name of the currency, such as "US Dollar" or "Euro".', + ), + symbol: z + .string() + .min(1) + .optional() + + .describe( + 'The symbol of the currency. It should be a string that represents the symbol of the currency, such as "$" for US Dollar or "€" for Euro.', + ), + id: ulidWire, + code: currencyCodeCustomWire, + created_at: dateTimeWire, + }) + .describe('Describes custom currency.') + +export const createCurrencyCustomRequestWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + + .describe( + 'The name of the currency. It should be a human-readable string that represents the name of the currency, such as "US Dollar" or "Euro".', + ), + symbol: z + .string() + .min(1) + .optional() + + .describe( + 'The symbol of the currency. It should be a string that represents the symbol of the currency, such as "$" for US Dollar or "€" for Euro.', + ), + code: currencyCodeCustomWire, + }) + .describe('CurrencyCustom create request.') + +export const governanceQueryRequestWire = z + .strictObject({ + include_credits: z + .boolean() + .optional() + + .describe( + 'Whether to include credit balance availability for each resolved customer. When true, each feature evaluation includes credit balance checks. Defaults to `false`.', + ), + customer: governanceQueryRequestCustomersWire, + feature: governanceQueryRequestFeaturesWire.optional(), + }) + .describe('Query to evaluate feature access for a list of customers.') + +export const governanceFeatureAccessReasonWire = z + .strictObject({ + code: governanceFeatureAccessReasonCodeWire, + message: z.string().describe('Human-readable description of the error.'), + attributes: z + .record(z.string(), z.unknown()) + .optional() + .describe('Additional structured context.'), + }) + .describe('Reason a feature is not accessible to a customer.') + +export const governanceQueryErrorWire = z + .strictObject({ + code: governanceQueryErrorCodeWire, + message: z.string().describe('Human-readable description of the error.'), + attributes: z + .record(z.string(), z.unknown()) + .optional() + .describe('Additional structured context.'), + customer: z + .string() + .optional() + + .describe( + 'The customer identifier from the request that produced this error.', + ), + }) + + .describe( + 'Query error within a partially successful governance query response.', + ) + +export const appCustomerDataWire = z + .strictObject({ + stripe: appCustomerDataStripeWire.optional(), + external_invoicing: appCustomerDataExternalInvoicingWire.optional(), + }) + .describe('App customer data.') + +export const upsertAppCustomerDataRequestWire = z + .strictObject({ + stripe: appCustomerDataStripeWire.optional(), + external_invoicing: appCustomerDataExternalInvoicingWire.optional(), + }) + .describe('AppCustomerData upsert request.') + +export const creditAdjustmentWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + }) + + .describe( + "A credit adjustment can be used to make manual adjustments to a customer's credit balance. Supported use-cases: - Usage correction", + ) + +export const creditBalanceWire = z + .strictObject({ + currency: billingCurrencyCodeWire, + live: numericWire, + settled: numericWire, + pending: numericWire, + }) + .describe('The credit balance by currency.') + +export const createCreditAdjustmentRequestWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + currency: billingCurrencyCodeWire, + amount: numericWire, + }) + .describe('CreditAdjustment create request.') + +export const listCreditTransactionsParamsFilterWire = z + .strictObject({ + type: creditTransactionTypeWire.optional(), + currency: billingCurrencyCodeWire.optional(), + feature_key: stringFieldFilterWire.optional(), + }) + .describe('Filter options for listing credit transactions.') + +export const creditTransactionWire = z + .strictObject({ + id: ulidWire, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + booked_at: dateTimeWire, + type: creditTransactionTypeWire, + currency: billingCurrencyCodeWire, + amount: numericWire, + available_balance: z + .strictObject({ + before: numericWire, + after: numericWire, + }) + .describe('The available balance before and after the transaction.'), + }) + + .describe( + "A credit transaction represents a single credit movement on the customer's balance. Credit transactions are immutable.", + ) + +export const priceTierWire = z + .strictObject({ + up_to_amount: numericWire.optional(), + flat_price: priceFlatWire.optional(), + unit_price: priceUnitWire.optional(), + }) + + .describe( + 'A price tier used in graduated and volume pricing. At least one price component (flat_price or unit_price) must be set. When UnitConfig is present on the rate card, up_to_amount is expressed in converted billing units.', + ) + +export const chargeTotalsWire = z + .strictObject({ + booked: totalsWire, + realtime: totalsWire.optional(), + }) + + .describe( + 'The totals of a change. RealTime is only expanded when the `real_time_usage` expand is used.', + ) + +export const updatePriceTierWire = z + .strictObject({ + up_to_amount: numericWire.optional(), + flat_price: updatePriceFlatWire.optional(), + unit_price: updatePriceUnitWire.optional(), + }) + + .describe( + 'A price tier used in graduated and volume pricing. At least one price component (flat_price or unit_price) must be set. When UnitConfig is present on the rate card, up_to_amount is expressed in converted billing units.', + ) + +export const featureLlmUnitCostWire = z + .strictObject({ + type: z + .literal('llm') + .describe('The type discriminator for LLM unit cost.'), + provider_property: z + .string() + .optional() + + .describe( + 'Meter group-by property that holds the LLM provider. Use this when the meter has a group-by dimension for provider. Mutually exclusive with `provider`.', + ), + provider: z + .string() + .optional() + + .describe( + 'Static LLM provider value (e.g., "openai", "anthropic"). Use this when the feature tracks a single provider. Mutually exclusive with `provider_property`.', + ), + model_property: z + .string() + .optional() + + .describe( + 'Meter group-by property that holds the model ID. Use this when the meter has a group-by dimension for model. Mutually exclusive with `model`.', + ), + model: z + .string() + .optional() + + .describe( + 'Static model ID value (e.g., "gpt-4", "claude-3-5-sonnet"). Use this when the feature tracks a single model. Mutually exclusive with `model_property`.', + ), + token_type_property: z + .string() + .optional() + + .describe( + 'Meter group-by property that holds the token type. Use this when the meter has a group-by dimension for token type. Mutually exclusive with `token_type`.', + ), + token_type: featureLlmTokenTypeWire.optional(), + pricing: featureLlmUnitCostPricingWire.optional(), + }) + + .describe( + 'LLM cost lookup configuration. Each dimension (provider, model, token type) can be specified as either a static value or a meter group-by property name (mutually exclusive).', + ) + +export const llmCostPriceWire = z + .strictObject({ + id: ulidWire, + provider: llmCostProviderWire, + model: llmCostModelWire, + pricing: llmCostModelPricingWire, + currency: currencyCodeWire, + source: llmCostPriceSourceWire, + effective_from: dateTimeWire, + effective_to: dateTimeWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + }) + + .describe( + 'An LLM cost price record, representing the cost per token for a specific model from a specific provider.', + ) + +export const llmCostOverrideCreateWire = z + .strictObject({ + provider: z.string().describe('Provider/vendor of the model.'), + model_id: z.string().describe('Canonical model identifier.'), + model_name: z.string().optional().describe('Human-readable model name.'), + pricing: llmCostModelPricingWire, + currency: currencyCodeWire, + effective_from: dateTimeWire, + effective_to: dateTimeWire.optional(), + }) + + .describe( + 'Input for creating a per-namespace price override. Unique per provider, model and currency. If an override already exists for the given provider, model and currency, it will be updated. If an override does not exist, it will be created.', + ) + +export const listCustomersParamsFilterWire = z + .strictObject({ + key: stringFieldFilterWire.optional(), + name: stringFieldFilterWire.optional(), + primary_email: stringFieldFilterWire.optional(), + usage_attribution_subject_key: stringFieldFilterWire.optional(), + plan_key: stringFieldFilterWire.optional(), + billing_profile_id: ulidFieldFilterWire.optional(), + }) + .describe('Filter options for listing customers.') + +export const listSubscriptionsParamsFilterWire = z + .strictObject({ + id: ulidFieldFilterWire.optional(), + customer_id: ulidFieldFilterWire.optional(), + status: stringFieldFilterExactWire.optional(), + plan_id: ulidFieldFilterWire.optional(), + plan_key: stringFieldFilterExactWire.optional(), + }) + .describe('Filter options for listing subscriptions.') + +export const listFeatureParamsFilterWire = z + .strictObject({ + meter_id: ulidFieldFilterWire.optional(), + key: stringFieldFilterWire.optional(), + name: stringFieldFilterWire.optional(), + }) + .describe('Filter options for listing features.') + +export const listAddonsParamsFilterWire = z + .strictObject({ + id: ulidFieldFilterWire.optional(), + key: stringFieldFilterWire.optional(), + name: stringFieldFilterWire.optional(), + status: stringFieldFilterExactWire.optional(), + currency: stringFieldFilterExactWire.optional(), + }) + .describe('Filter options for listing add-ons.') + +export const createCreditGrantTaxConfigWire = z + .strictObject({ + behavior: taxBehaviorWire.optional(), + tax_code: createResourceReferenceWire.optional(), + }) + + .describe( + 'Tax configuration for a credit grant. Tax configuration should be provided to ensure correct revenue recognition, including for externally funded grants.', + ) + +export const creditGrantTaxConfigWire = z + .strictObject({ + behavior: taxBehaviorWire.optional(), + tax_code: taxCodeReferenceWire.optional(), + }) + + .describe( + 'Tax configuration for a credit grant. Tax configuration should be provided to ensure correct revenue recognition, including for externally funded grants.', + ) + +export const taxConfigWire = z + .strictObject({ + behavior: taxBehaviorWire.optional(), + stripe: taxConfigStripeWire.optional(), + external_invoicing: taxConfigExternalInvoicingWire.optional(), + tax_code_id: ulidWire.optional(), + tax_code: taxCodeReferenceWire.optional(), + }) + .describe('Set of provider specific tax configs.') + +export const rateCardTaxConfigWire = z + .strictObject({ + behavior: taxBehaviorWire.optional(), + code: taxCodeReferenceWire, + }) + .describe('The tax config of the rate card.') + +export const organizationDefaultTaxCodesWire = z + .strictObject({ + invoicing_tax_code: taxCodeReferenceWire, + credit_grant_tax_code: taxCodeReferenceWire, + created_at: dateTimeWire, + updated_at: dateTimeWire, + }) + + .describe( + 'Organization-level default tax code references. Stores the default tax codes applied to specific billing contexts for this organization. Provisioned automatically when the organization is created.', + ) + +export const updateOrganizationDefaultTaxCodesRequestWire = z + .strictObject({ + invoicing_tax_code: taxCodeReferenceWire.optional(), + credit_grant_tax_code: taxCodeReferenceWire.optional(), + }) + .describe('OrganizationDefaultTaxCodes update request.') + +export const planAddonWire = z + .strictObject({ + id: ulidWire, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + addon: addonReferenceWire, + from_plan_phase: resourceKeyWire, + max_quantity: z + .number() + .int() + .gte(1) + .optional() + + .describe( + 'The maximum number of times the add-on can be purchased for the plan. For single-instance add-ons this field must be omitted. For multi-instance add-ons when omitted, unlimited quantity can be purchased.', + ), + validation_errors: z + .array(productCatalogValidationErrorWire) + .optional() + .describe('List of validation errors.'), + }) + + .describe( + 'PlanAddon represents an association between a plan and an add-on, controlling which add-ons are available for purchase within a plan.', + ) + +export const createPlanAddonRequestWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + addon: addonReferenceWire, + from_plan_phase: resourceKeyWire, + max_quantity: z + .number() + .int() + .gte(1) + .optional() + + .describe( + 'The maximum number of times the add-on can be purchased for the plan. For single-instance add-ons this field must be omitted. For multi-instance add-ons when omitted, unlimited quantity can be purchased.', + ), + }) + .describe('PlanAddon create request.') + +export const profileAppReferencesWire = z + .strictObject({ + tax: appReferenceWire, + invoicing: appReferenceWire, + payment: appReferenceWire, + }) + .describe('References to the applications used by a billing profile.') + +export const invoiceWorkflowAppsReferencesWire = z + .strictObject({ + tax: appReferenceWire, + invoicing: appReferenceWire, + payment: appReferenceWire, + }) + + .describe( + 'BillingInvoiceWorkflowAppsReferences represents the references (id) to the apps used by a billing profile', + ) + +export const updateRateCardTaxConfigWire = z + .strictObject({ + behavior: taxBehaviorWire.optional(), + code: updateResourceReferenceWire, + }) + .describe('The tax config of the rate card.') + +export const listEventsParamsFilterWire = z + .strictObject({ + id: stringFieldFilterWire.optional(), + source: stringFieldFilterWire.optional(), + subject: stringFieldFilterWire.optional(), + type: stringFieldFilterWire.optional(), + customer_id: ulidFieldFilterWire.optional(), + time: dateTimeFieldFilterWire.optional(), + ingested_at: dateTimeFieldFilterWire.optional(), + stored_at: dateTimeFieldFilterWire.optional(), + }) + .describe('Filter options for listing ingested events.') + +export const listInvoicesParamsFilterWire = z + .strictObject({ + status: stringFieldFilterExactWire.optional(), + customer_id: ulidFieldFilterWire.optional(), + issued_at: dateTimeFieldFilterWire.optional(), + service_period_start: dateTimeFieldFilterWire.optional(), + created_at: dateTimeFieldFilterWire.optional(), + }) + .describe('Filter options for listing invoices.') + +export const resourceFiltersWire = z + .strictObject({ + name: stringFieldFilterWire.optional(), + labels: labelsFieldFilterWire.optional(), + public_labels: labelsFieldFilterWire.optional(), + created_at: dateTimeFieldFilterWire.optional(), + updated_at: dateTimeFieldFilterWire.optional(), + deleted_at: dateTimeFieldFilterWire.optional(), + }) + .describe('Resource filters.') + +export const fieldFiltersWire = z + .strictObject({ + boolean: booleanFieldFilterWire.optional(), + numeric: numericFieldFilterWire.optional(), + string: stringFieldFilterWire.optional(), + string_exact: stringFieldFilterExactWire.optional(), + ulid: ulidFieldFilterWire.optional(), + datetime: dateTimeFieldFilterWire.optional(), + labels: labelsFieldFilterWire.optional(), + }) + .describe('Field filters with all supported types.') + +export const ingestedEventWire = z + .strictObject({ + event: eventWire, + customer: customerReferenceWire.optional(), + ingested_at: dateTimeWire, + stored_at: dateTimeWire, + validation_errors: z + .array(ingestedEventValidationErrorWire) + .optional() + .describe('The validation errors of the ingested event.'), + }) + .describe('An ingested metering event with ingestion metadata.') + +export const meterQueryResultWire = z + .strictObject({ + from: dateTimeWire.optional(), + to: dateTimeWire.optional(), + data: z + .array(meterQueryRowWire) + + .describe( + 'The usage data. If no data is available, an empty array is returned.', + ), + }) + .describe('Meter query result.') + +export const featureCostQueryResultWire = z + .strictObject({ + from: dateTimeWire.optional(), + to: dateTimeWire.optional(), + data: z.array(featureCostQueryRowWire).describe('The cost data rows.'), + }) + .describe('Result of a feature cost query.') + +export const invalidParameterWire = z + .union([ + invalidParameterStandardWire, + invalidParameterMinimumLengthWire, + invalidParameterMaximumLengthWire, + invalidParameterChoiceItemWire, + invalidParameterDependentItemWire, + ]) + .describe('A parameter that failed validation.') + +export const meterPagePaginatedResponseWire = z + .strictObject({ + data: z.array(meterWire), + meta: paginatedMetaWire, + }) + .describe('Page paginated response.') + +export const costBasisPagePaginatedResponseWire = z + .strictObject({ + data: z.array(costBasisWire), + meta: paginatedMetaWire, + }) + .describe('Page paginated response.') + +export const meterQueryFiltersWire = z + .strictObject({ + dimensions: z + .record(z.string(), queryFilterStringMapItemWire) + .optional() + + .describe( + 'Filters to apply to the dimensions of the query. For `subject` and `customer_id` only equals ("eq", "in") comparisons are supported.', + ), + }) + .describe('Filters to apply to a meter query.') + +export const featureMeterReferenceWire = z + .strictObject({ + id: ulidWire, + filters: z + .record(z.string(), queryFilterStringMapItemWire) + .optional() + .describe('Filters to apply to the dimensions of the meter.'), + }) + .describe('Reference to a meter associated with a feature.') + +export const createCustomerRequestWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + key: externalResourceKeyWire, + usage_attribution: customerUsageAttributionWire.optional(), + primary_email: z + .string() + .optional() + .describe('The primary email address of the customer.'), + currency: currencyCodeWire.optional(), + billing_address: addressWire.optional(), + }) + .describe('Customer create request.') + +export const customerWire = z + .strictObject({ + id: ulidWire, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + key: externalResourceKeyWire, + usage_attribution: customerUsageAttributionWire.optional(), + primary_email: z + .string() + .optional() + .describe('The primary email address of the customer.'), + currency: currencyCodeWire.optional(), + billing_address: addressWire.optional(), + }) + + .describe( + 'Customers can be individuals or organizations that can subscribe to plans and have access to features.', + ) + +export const upsertCustomerRequestWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + usage_attribution: customerUsageAttributionWire.optional(), + primary_email: z + .string() + .optional() + .describe('The primary email address of the customer.'), + currency: currencyCodeWire.optional(), + billing_address: addressWire.optional(), + }) + .describe('Customer upsert request.') + +export const partyAddressesWire = z + .strictObject({ + billing_address: addressWire, + }) + .describe('A collection of addresses for the party.') + +export const invoiceCustomerWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + usage_attribution: customerUsageAttributionWire.optional(), + billing_address: addressWire.optional(), + id: ulidWire, + key: externalResourceKeyWire.optional(), + }) + + .describe( + "Snapshot of the customer's information at the time the invoice was issued.", + ) + +export const updateBillingPartyAddressesWire = z + .strictObject({ + billing_address: updateAddressWire, + }) + .describe('A collection of addresses for the party.') + +export const updateInvoiceCustomerWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + usage_attribution: updateCustomerUsageAttributionWire.optional(), + billing_address: updateAddressWire.optional(), + id: ulidWire, + key: externalResourceKeyWire.optional(), + }) + + .describe( + "Snapshot of the customer's information at the time the invoice was issued.", + ) + +export const appStripeCreateCheckoutSessionConsentCollectionWire = z + .strictObject({ + payment_method_reuse_agreement: + appStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreementWire.optional(), + promotions: + appStripeCreateCheckoutSessionConsentCollectionPromotionsWire.optional(), + terms_of_service: + appStripeCreateCheckoutSessionConsentCollectionTermsOfServiceWire.optional(), + }) + .describe('Checkout Session consent collection configuration.') + +export const listCustomerEntitlementAccessResponseDataWire = z + .strictObject({ + data: z + .array(entitlementAccessResultWire) + .describe('The list of entitlement access results.'), + }) + .describe('List customer entitlement access response data.') + +export const rateCardEntitlementWire = z + .discriminatedUnion('type', [ + rateCardMeteredEntitlementWire, + rateCardStaticEntitlementWire, + rateCardBooleanEntitlementWire, + ]) + + .describe( + 'Entitlement template configured on a rate card. The feature is taken from the rate card itself, so it is omitted here.', + ) + +export const workflowCollectionAlignmentAnchoredWire = z + .strictObject({ + type: z.literal('anchored').describe('The type of alignment.'), + recurring_period: recurringPeriodWire, + }) + + .describe( + 'BillingWorkflowCollectionAlignmentAnchored specifies the alignment for collecting the pending line items into an invoice.', + ) + +export const chargeFlatFeeSystemIntentWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + invoice_at: dateTimeWire, + service_period: closedPeriodWire, + full_service_period: closedPeriodWire, + billing_period: closedPeriodWire, + payment_term: pricePaymentTermWire, + discounts: chargeFlatFeeDiscountsWire.optional(), + proration_configuration: rateCardProrationConfigurationWire, + amount_before_proration: currencyAmountWire, + deleted_at: dateTimeWire.optional(), + }) + + .describe( + 'Flat fee intent fields from the system lifecycle controller shadowed by a manual override.', + ) + +export const subscriptionPagePaginatedResponseWire = z + .strictObject({ + data: z.array(subscriptionWire), + meta: paginatedMetaWire, + }) + .describe('Page paginated response.') + +export const subscriptionChangeResponseWire = z + .strictObject({ + current: subscriptionWire, + next: subscriptionWire, + }) + .describe('Response for changing a subscription.') + +export const subscriptionCancelWire = z + .strictObject({ + timing: subscriptionEditTimingWire.optional(), + }) + .describe('Request for canceling a subscription.') + +export const subscriptionChangeWire = z + .strictObject({ + labels: labelsWire.optional(), + settlement_mode: settlementModeWire.optional(), + customer: z + .strictObject({ + id: ulidWire.optional(), + key: externalResourceKeyWire.optional(), + }) + .describe('The customer to create the subscription for.'), + plan: z + .strictObject({ + id: ulidWire.optional(), + key: resourceKeyWire.optional(), + version: z + .number() + .int() + .optional() + + .describe( + 'The plan version of the subscription, if any. If not provided, the latest version of the plan will be used.', + ), + }) + .describe('The plan reference of the subscription.'), + billing_anchor: dateTimeWire.optional(), + timing: subscriptionEditTimingWire, + }) + .describe('Request for changing a subscription.') + +export const createSubscriptionAddonRequestWire = z + .strictObject({ + labels: labelsWire.optional(), + addon: addonReferenceWire, + quantity: z + .number() + .int() + .gte(1) + + .describe( + 'The quantity of the add-on. Always 1 for single instance add-ons.', + ), + timing: subscriptionEditTimingWire, + }) + .describe('SubscriptionAddon create request.') + +export const invoiceUsageQuantityDetailWire = z + .strictObject({ + raw_quantity: numericWire, + converted_quantity: numericWire, + invoiced_quantity: numericWire, + display_unit: z + .string() + .optional() + + .describe('The display unit label (e.g., "GB", "hours", "M tokens").'), + applied_unit_config: unitConfigWire, + }) + + .describe( + 'Usage quantity details on an invoice line item when UnitConfig is in effect. Provides the full audit trail from raw meter output to the invoiced amount.', + ) + +export const createTaxCodeRequestWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + key: resourceKeyWire, + app_mappings: z + .array(taxCodeAppMappingWire) + .describe('Mapping of app types to tax codes.'), + }) + .describe('TaxCode create request.') + +export const taxCodeWire = z + .strictObject({ + id: ulidWire, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + key: resourceKeyWire, + app_mappings: z + .array(taxCodeAppMappingWire) + .describe('Mapping of app types to tax codes.'), + }) + .describe('Tax codes by provider.') + +export const upsertTaxCodeRequestWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + app_mappings: z + .array(taxCodeAppMappingWire) + .describe('Mapping of app types to tax codes.'), + }) + .describe('TaxCode upsert request.') + +export const appCatalogItemWire = z + .strictObject({ + type: appTypeWire, + name: z.string().describe('Name of the app.'), + description: z.string().describe('Description of the app.'), + capabilities: z + .array(appCapabilityWire) + .describe('Capabilities of the app.'), + install_methods: z + .array(appInstallMethodsWire) + .describe('Available install methods of the app.'), + }) + + .describe( + 'Available apps for billing integrations to connect with third-party services. Apps can have various capabilities like syncing data from or to external systems, integrating with third-party services for tax calculation, delivery of invoices, collection of payments, etc.', + ) + +export const invoiceWorkflowWire = z + .strictObject({ + invoicing: invoiceWorkflowInvoicingSettingsWire.optional(), + payment: workflowPaymentSettingsWire.optional(), + }) + + .describe( + 'Invoice-level snapshot of the workflow configuration. Contains only the settings that are meaningful for an already-created invoice: invoicing behaviour and payment settings. Collection alignment and tax policy are gather-time / profile-wide concerns and are not included.', + ) + +export const invoiceStatusDetailsWire = z + .strictObject({ + immutable: z + .boolean() + + .describe( + 'Whether the invoice is immutable (i.e. cannot be modified or deleted).', + ), + failed: z.boolean().describe('Whether the invoice is in a failed state.'), + extended_status: z + .string() + + .describe( + 'Fine-grained internal status string providing additional workflow detail beyond the top-level status enum.', + ), + available_actions: invoiceAvailableActionsWire, + }) + .describe('Detailed status information for a standard invoice.') + +export const invoiceLineDiscountsWire = z + .strictObject({ + amount: z + .array(invoiceLineAmountDiscountWire) + .optional() + + .describe( + 'Monetary amount discounts (e.g. from maximum spend commitments).', + ), + usage: z + .array(invoiceLineUsageDiscountWire) + .optional() + .describe('Usage quantity discounts (e.g. free tier usage allowances).'), + }) + .describe('Discounts applied to an invoice line item.') + +export const updateBillingInvoiceWorkflowWire = z + .strictObject({ + invoicing: updateBillingInvoiceWorkflowInvoicingSettingsWire.optional(), + payment: updateBillingWorkflowPaymentSettingsWire.optional(), + }) + + .describe( + 'Invoice-level snapshot of the workflow configuration. Contains only the settings that are meaningful for an already-created invoice: invoicing behaviour and payment settings. Collection alignment and tax policy are gather-time / profile-wide concerns and are not included.', + ) + +export const currencyWire = z + .discriminatedUnion('type', [currencyFiatWire, currencyCustomWire]) + .describe('Fiat or custom currency.') + +export const governanceFeatureAccessWire = z + .strictObject({ + has_access: z + .boolean() + + .describe( + 'Whether the customer currently has access to the feature. `true` for boolean and static entitlements that are available, and for metered entitlements with remaining balance. `false` when the feature is unavailable, the usage limit has been reached, or (when applicable) credits have been exhausted.', + ), + reason: governanceFeatureAccessReasonWire.optional(), + }) + .describe('Access status for a single feature.') + +export const customerDataWire = z + .strictObject({ + billing_profile: profileReferenceWire.optional(), + app_data: appCustomerDataWire.optional(), + }) + .describe('Billing customer data.') + +export const upsertCustomerBillingDataRequestWire = z + .strictObject({ + billing_profile: profileReferenceWire.optional(), + app_data: appCustomerDataWire.optional(), + }) + .describe('CustomerBillingData upsert request.') + +export const creditBalancesWire = z + .strictObject({ + retrieved_at: dateTimeWire, + balances: z + .array(creditBalanceWire) + .describe('The balances by currencies.'), + }) + .describe('The balances of the credits of a customer.') + +export const creditTransactionPaginatedResponseWire = z + .strictObject({ + data: z.array(creditTransactionWire), + meta: cursorMetaWire, + }) + .describe('Cursor paginated response.') + +export const priceGraduatedWire = z + .strictObject({ + type: z.literal('graduated').describe('The type of the price.'), + tiers: z + .array(priceTierWire) + .min(1) + + .describe( + 'The tiers of the graduated price. At least one tier is required.', + ), + }) + + .describe( + "Graduated tiered price. Each tier's rate applies only to the usage within that tier. Pricing can change as cumulative usage crosses tier boundaries. When UnitConfig is present on the rate card, tier boundaries (up_to_amount) are expressed in converted billing units.", + ) + +export const priceVolumeWire = z + .strictObject({ + type: z.literal('volume').describe('The type of the price.'), + tiers: z + .array(priceTierWire) + .min(1) + + .describe( + 'The tiers of the volume price. At least one tier is required.', + ), + }) + + .describe( + 'Volume tiered price. The maximum quantity within a period determines the per-unit price for all units in that period. When UnitConfig is present on the rate card, tier boundaries (up_to_amount) are expressed in converted billing units.', + ) + +export const updatePriceGraduatedWire = z + .strictObject({ + type: z.literal('graduated').describe('The type of the price.'), + tiers: z + .array(updatePriceTierWire) + .min(1) + + .describe( + 'The tiers of the graduated price. At least one tier is required.', + ), + }) + + .describe( + "Graduated tiered price. Each tier's rate applies only to the usage within that tier. Pricing can change as cumulative usage crosses tier boundaries. When UnitConfig is present on the rate card, tier boundaries (up_to_amount) are expressed in converted billing units.", + ) + +export const updatePriceVolumeWire = z + .strictObject({ + type: z.literal('volume').describe('The type of the price.'), + tiers: z + .array(updatePriceTierWire) + .min(1) + + .describe( + 'The tiers of the volume price. At least one tier is required.', + ), + }) + + .describe( + 'Volume tiered price. The maximum quantity within a period determines the per-unit price for all units in that period. When UnitConfig is present on the rate card, tier boundaries (up_to_amount) are expressed in converted billing units.', + ) + +export const featureUnitCostWire = z + .discriminatedUnion('type', [ + featureManualUnitCostWire, + featureLlmUnitCostWire, + ]) + + .describe( + 'Per-unit cost configuration for a feature. Either a fixed manual amount or a dynamic LLM cost lookup.', + ) + +export const pricePagePaginatedResponseWire = z + .strictObject({ + data: z.array(llmCostPriceWire), + meta: paginatedMetaWire, + }) + .describe('Page paginated response.') + +export const createCreditGrantRequestWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: createLabelsWire.optional(), + funding_method: creditFundingMethodWire, + currency: createCurrencyCodeWire, + amount: numericWire, + purchase: createCreditGrantPurchaseWire.optional(), + tax_config: createCreditGrantTaxConfigWire.optional(), + filters: createCreditGrantFiltersWire.optional(), + priority: z + .number() + .int() + .gte(1) + .lte(1000) + .optional() + + .describe( + 'Draw-down priority of the grant. Lower values have higher priority.', + ), + effective_at: dateTimeWire.optional(), + expires_after: iso8601DurationWire.optional(), + key: externalResourceKeyWire.optional(), + }) + .describe('CreditGrant create request.') + +export const creditGrantWire = z + .strictObject({ + id: ulidWire, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + funding_method: creditFundingMethodWire, + currency: billingCurrencyCodeWire, + amount: numericWire, + purchase: creditGrantPurchaseWire.optional(), + tax_config: creditGrantTaxConfigWire.optional(), + invoice: creditGrantInvoiceReferenceWire.optional(), + filters: creditGrantFiltersWire.optional(), + priority: z + .number() + .int() + .gte(1) + .lte(1000) + .optional() + + .describe( + 'Draw-down priority of the grant. Lower values have higher priority.', + ), + effective_at: dateTimeWire.optional(), + key: externalResourceKeyWire.optional(), + expires_at: dateTimeWire.optional(), + voided_at: dateTimeWire.optional(), + status: creditGrantStatusWire, + }) + + .describe( + 'A credit grant allocates credits to a customer. Credits are drawn down against charges according to the settlement mode configured on the rate card.', + ) + +export const createChargeFlatFeeRequestWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + type: z.literal('flat_fee').describe('The type of the charge.'), + currency: currencyCodeWire, + invoice_at: dateTimeWire, + service_period: closedPeriodWire, + unique_reference_id: z + .string() + .optional() + .describe('Unique reference ID of the charge.'), + settlement_mode: settlementModeWire, + tax_config: taxConfigWire.optional(), + payment_term: pricePaymentTermWire, + discounts: chargeFlatFeeDiscountsWire.optional(), + feature_key: z + .string() + .optional() + .describe('The feature associated with the charge, when applicable.'), + proration_configuration: rateCardProrationConfigurationWire, + amount_before_proration: currencyAmountWire, + full_service_period: closedPeriodWire.optional(), + billing_period: closedPeriodWire.optional(), + }) + .describe('Flat fee charge create request.') + +export const workflowTaxSettingsWire = z + .strictObject({ + enabled: z + .boolean() + .optional() + + .describe( + 'Enable automatic tax calculation when tax is supported by the app. For example, with Stripe Invoicing when enabled, tax is calculated via Stripe Tax.', + ), + enforced: z + .boolean() + .optional() + + .describe( + 'Enforce tax calculation when tax is supported by the app. When enabled, the billing system will not allow to create an invoice without tax calculation. Enforcement is different per apps, for example, Stripe app requires customer to have a tax location when starting a paid subscription.', + ), + default_tax_config: taxConfigWire.optional(), + }) + .describe('Tax settings for a billing workflow.') + +export const planAddonPagePaginatedResponseWire = z + .strictObject({ + data: z.array(planAddonWire), + meta: paginatedMetaWire, + }) + .describe('Page paginated response.') + +export const ingestedEventPaginatedResponseWire = z + .strictObject({ + data: z.array(ingestedEventWire), + meta: cursorMetaWire, + }) + .describe('Cursor paginated response.') + +export const invalidParametersWire = z + .array(invalidParameterWire) + .min(1) + .describe('The list of parameters that failed validation.') + +export const meterQueryRequestWire = z + .strictObject({ + from: dateTimeWire.optional(), + to: dateTimeWire.optional(), + granularity: meterQueryGranularityWire.optional(), + time_zone: z + .string() + .optional() + + .describe( + 'The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones). The time zone is used to determine the start and end of the time buckets. If not specified, the UTC timezone will be used.', + ), + group_by_dimensions: z + .array(z.string()) + .max(100) + .optional() + .describe('The dimensions to group the results by.'), + filters: meterQueryFiltersWire.optional(), + }) + .describe('A meter query request.') + +export const customerPagePaginatedResponseWire = z + .strictObject({ + data: z.array(customerWire), + meta: paginatedMetaWire, + }) + .describe('Page paginated response.') + +export const partyWire = z + .strictObject({ + id: z.string().optional().describe('Unique identifier for the party.'), + key: externalResourceKeyWire.optional(), + name: z + .string() + .optional() + .describe('Legal name or representation of the party.'), + tax_id: partyTaxIdentityWire.optional(), + addresses: partyAddressesWire.optional(), + }) + .describe('Party represents a person or business entity.') + +export const supplierWire = z + .strictObject({ + name: z + .string() + .optional() + .describe('Legal name or representation of the party.'), + tax_id: partyTaxIdentityWire.optional(), + addresses: partyAddressesWire.optional(), + id: z.string().optional().describe('Unique identifier for the party.'), + }) + + .describe( + "Snapshot of the supplier's information at the time the invoice was issued. Structurally a read-only subset of `BillingParty` (the type configured on the billing profile), so the snapshot stays aligned with the source. `key` is omitted because it is not part of the snapshotted supplier data.", + ) + +export const updateSupplierWire = z + .strictObject({ + name: z + .string() + .optional() + .describe('Legal name or representation of the party.'), + tax_id: updateBillingPartyTaxIdentityWire.optional(), + addresses: updateBillingPartyAddressesWire.optional(), + id: z.string().optional().describe('Unique identifier for the party.'), + }) + + .describe( + "Snapshot of the supplier's information at the time the invoice was issued. Structurally a read-only subset of `BillingParty` (the type configured on the billing profile), so the snapshot stays aligned with the source. `key` is omitted because it is not part of the snapshotted supplier data.", + ) + +export const appStripeCreateCheckoutSessionRequestOptionsWire = z + .strictObject({ + billing_address_collection: + appStripeCreateCheckoutSessionBillingAddressCollectionWire.optional(), + cancel_url: z + .string() + .optional() + + .describe( + 'URL to redirect customers who cancel the checkout session. Not allowed when ui_mode is "embedded".', + ), + client_reference_id: z + .string() + .optional() + + .describe( + 'Unique reference string for reconciling sessions with internal systems. Can be a customer ID, cart ID, or any other identifier.', + ), + customer_update: + appStripeCreateCheckoutSessionCustomerUpdateWire.optional(), + consent_collection: + appStripeCreateCheckoutSessionConsentCollectionWire.optional(), + currency: currencyCodeWire.optional(), + custom_text: appStripeCheckoutSessionCustomTextParamsWire.optional(), + expires_at: z.coerce + .bigint() + .gte(-9223372036854775808n) + .lte(9223372036854775807n) + .optional() + + .describe( + 'Unix timestamp when the checkout session expires. Can be 30 minutes to 24 hours from creation. Defaults to 24 hours.', + ), + locale: z + .string() + .optional() + + .describe( + 'IETF language tag for the checkout UI locale. If blank or "auto", uses the browser\'s locale. Example: "en", "fr", "de".', + ), + metadata: z + .record(z.string(), z.string()) + .optional() + + .describe( + 'Set of key-value pairs to attach to the checkout session. Useful for storing additional structured information.', + ), + return_url: z + .string() + .optional() + + .describe( + 'Return URL for embedded checkout sessions after payment authentication. Required if ui_mode is "embedded" and redirect-based payment methods are enabled.', + ), + success_url: z + .string() + .optional() + + .describe( + 'Success URL to redirect customers after completing payment or setup. Not allowed when ui_mode is "embedded". See: https://docs.stripe.com/payments/checkout/custom-success-page', + ), + ui_mode: appStripeCheckoutSessionUiModeWire.optional(), + payment_method_types: z + .array(z.string()) + .optional() + + .describe( + 'List of payment method types to enable (e.g., "card", "us_bank_account"). If not specified, Stripe enables all relevant payment methods.', + ), + redirect_on_completion: + appStripeCreateCheckoutSessionRedirectOnCompletionWire.optional(), + tax_id_collection: + appStripeCreateCheckoutSessionTaxIdCollectionWire.optional(), + }) + + .describe( + "Configuration options for creating a Stripe Checkout Session. Based on Stripe's [Checkout Session API parameters](https://docs.stripe.com/api/checkout/sessions/create).", + ) + +export const workflowCollectionAlignmentWire = z + .discriminatedUnion('type', [ + workflowCollectionAlignmentSubscriptionWire, + workflowCollectionAlignmentAnchoredWire, + ]) + + .describe( + 'The alignment for collecting the pending line items into an invoice. Defaults to subscription, which means that we are to create a new invoice every time the a subscription period starts (for in advance items) or ends (for in arrears items).', + ) + +export const taxCodePagePaginatedResponseWire = z + .strictObject({ + data: z.array(taxCodeWire), + meta: paginatedMetaWire, + }) + .describe('Page paginated response.') + +export const appStripeWire = z + .strictObject({ + id: ulidWire, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + type: z.literal('stripe').describe('The app type.'), + definition: appCatalogItemWire, + status: appStatusWire, + account_id: z + .string() + + .describe( + 'The Stripe account ID associated with the connected Stripe account.', + ), + livemode: z + .boolean() + + .describe( + 'Indicates whether the app is connected to a live Stripe account.', + ), + masked_api_key: z + .string() + + .describe( + 'The masked Stripe API key that only exposes the first and last few characters.', + ), + }) + .describe('Stripe app.') + +export const appSandboxWire = z + .strictObject({ + id: ulidWire, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + type: z.literal('sandbox').describe('The app type.'), + definition: appCatalogItemWire, + status: appStatusWire, + }) + .describe('Sandbox app can be used for testing billing features.') + +export const appExternalInvoicingWire = z + .strictObject({ + id: ulidWire, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + type: z.literal('external_invoicing').describe('The app type.'), + definition: appCatalogItemWire, + status: appStatusWire, + enable_draft_sync_hook: z + .boolean() + + .describe( + 'Enable draft synchronization hook. When enabled, invoices will pause at the draft state and wait for the integration to call the draft synchronized endpoint before progressing to the issuing state. This allows the external system to validate and prepare the invoice data. When disabled, invoices automatically progress through the draft state based on the configured workflow timing.', + ), + enable_issuing_sync_hook: z + .boolean() + + .describe( + 'Enable issuing synchronization hook. When enabled, invoices will pause at the issuing state and wait for the integration to call the issuing synchronized endpoint before progressing to the issued state. This ensures the external invoicing system has successfully created and finalized the invoice before it is marked as issued. When disabled, invoices automatically progress through the issuing state and are immediately marked as issued.', + ), + }) + + .describe( + 'External Invoicing app enables integration with third-party invoicing or payment system. The app supports a bi-directional synchronization pattern where OpenMeter Billing manages the invoice lifecycle while the external system handles invoice presentation and payment collection. Integration workflow: 1. The billing system creates invoices and transitions them through lifecycle states (draft → issuing → issued) 2. The integration receives webhook notifications about invoice state changes 3. The integration calls back to provide external system IDs and metadata 4. The integration reports payment events back via the payment status API State synchronization is controlled by hooks that pause invoice progression until the external system confirms synchronization via API callbacks.', + ) + +export const appCatalogItemPagePaginatedResponseWire = z + .strictObject({ + data: z.array(appCatalogItemWire), + meta: paginatedMetaWire, + }) + .describe('Page paginated response.') + +export const invoiceWorkflowSettingsWire = z + .strictObject({ + apps: invoiceWorkflowAppsReferencesWire.optional(), + source_billing_profile: profileReferenceWire, + workflow: invoiceWorkflowWire, + }) + + .describe( + 'Snapshot of the billing workflow configuration captured at invoice creation.', + ) + +export const invoiceDetailedLineWire = z + .strictObject({ + id: ulidWire, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + service_period: closedPeriodWire, + totals: totalsWire, + category: invoiceDetailedLineCostCategoryWire, + discounts: invoiceLineDiscountsWire.optional(), + credits_applied: z + .array(invoiceLineCreditsAppliedWire) + .optional() + .describe('Credit applied to this detailed line.'), + external_references: invoiceLineExternalReferencesWire.optional(), + quantity: numericWire, + unit_price: numericWire, + }) + + .describe( + 'A detailed (child) sub-line belonging to a parent invoice line. Detailed lines represent the individual flat-fee components that make up a usage-based parent line after quantity snapshotting.', + ) + +export const updateInvoiceWorkflowSettingsWire = z + .strictObject({ + workflow: updateBillingInvoiceWorkflowWire, + }) + + .describe( + 'Snapshot of the billing workflow configuration captured at invoice creation.', + ) + +export const currencyPagePaginatedResponseWire = z + .strictObject({ + data: z.array(currencyWire), + meta: paginatedMetaWire, + }) + .describe('Page paginated response.') + +export const governanceQueryResultWire = z + .strictObject({ + matched: z + .array(z.string()) + + .describe( + 'The list of identifiers from the request that resolved to this customer. Each entry is either the customer `key` or one of its usage-attribution subject `key`s. Duplicate or aliased identifiers that resolve to the same customer collapse to a single result entry, with every requested identifier listed here.', + ), + customer: customerWire, + features: z + .record(z.string(), governanceFeatureAccessWire) + + .describe( + 'Map of features with their access status. Map keys are the feature keys requested in `feature.keys`, or every feature `key` available in the organization when the feature filter was omitted.', + ), + updated_at: dateTimeWire, + }) + .describe('Access evaluation result for a single resolved customer.') + +export const priceWire = z + .discriminatedUnion('type', [ + priceFreeWire, + priceFlatWire, + priceUnitWire, + priceGraduatedWire, + priceVolumeWire, + ]) + .describe('Price.') + +export const priceUsageBasedWire = z + .discriminatedUnion('type', [ + priceUnitWire, + priceGraduatedWire, + priceVolumeWire, + ]) + + .describe( + 'Usage-based price types that can appear on a usage-based rate card. When UnitConfig is present on the rate card, these price types operate on billing units (i.e. post-conversion quantities), not raw metered units.', + ) + +export const updatePriceWire = z + .discriminatedUnion('type', [ + updatePriceFreeWire, + updatePriceFlatWire, + updatePriceUnitWire, + updatePriceGraduatedWire, + updatePriceVolumeWire, + ]) + .describe('Price.') + +export const featureWire = z + .strictObject({ + id: ulidWire, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + key: resourceKeyWire, + meter: featureMeterReferenceWire.optional(), + unit_cost: featureUnitCostWire.optional(), + }) + .describe('A capability or billable dimension offered by a provider.') + +export const createFeatureRequestWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + key: resourceKeyWire, + meter: featureMeterReferenceWire.optional(), + unit_cost: featureUnitCostWire.optional(), + }) + .describe('Feature create request.') + +export const updateFeatureRequestWire = z + .strictObject({ + unit_cost: featureUnitCostWire + .nullable() + .optional() + + .describe( + 'Optional per-unit cost configuration. Use "manual" for a fixed per-unit cost, or "llm" to look up cost from the LLM cost database based on meter group-by properties. Set to `null` to clear the existing unit cost; omit to leave it unchanged.', + ), + }) + + .describe( + 'Request body for updating a feature. Currently only the unit_cost field can be updated.', + ) + +export const creditGrantPagePaginatedResponseWire = z + .strictObject({ + data: z.array(creditGrantWire), + meta: paginatedMetaWire, + }) + .describe('Page paginated response.') + +export const badRequestWire = z + .intersection( + baseErrorWire, + z.strictObject({ + invalid_parameters: invalidParametersWire, + }), + ) + .describe('Bad Request.') + +export const invoiceBaseWire = z + .strictObject({ + id: ulidWire, + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + number: invoiceNumberWire, + currency: currencyCodeWire, + supplier: supplierWire, + customer: invoiceCustomerWire, + totals: totalsWire, + service_period: closedPeriodWire, + validation_issues: z + .array(invoiceValidationIssueWire) + .optional() + + .describe( + 'Validation issues found during invoice processing. Present only when there are one or more validation findings. An empty list is omitted.', + ), + external_references: invoiceExternalReferencesWire.optional(), + }) + + .describe( + 'Base fields shared by all invoice types. Spread this model into each concrete invoice variant.', + ) + +export const customerStripeCreateCheckoutSessionRequestWire = z + .strictObject({ + stripe_options: appStripeCreateCheckoutSessionRequestOptionsWire, + }) + + .describe( + 'Request to create a Stripe Checkout Session for the customer. Checkout Sessions are used to collect payment method information from customers in a secure, Stripe-hosted interface. This integration uses setup mode to collect payment methods that can be charged later for subscription billing.', + ) + +export const workflowCollectionSettingsWire = z + .strictObject({ + alignment: workflowCollectionAlignmentWire.optional(), + interval: z + .string() + .optional() + + .describe( + 'This grace period can be used to delay the collection of the pending line items specified in alignment. This is useful, in case of multiple subscriptions having slightly different billing periods.', + ), + }) + + .describe( + 'Workflow collection specifies how to collect the pending line items for an invoice.', + ) + +export const appWire = z + .discriminatedUnion('type', [ + appStripeWire, + appSandboxWire, + appExternalInvoicingWire, + ]) + .describe('Installed application.') + +export const governanceQueryResponseWire = z + .strictObject({ + data: z + .array(governanceQueryResultWire) + .describe('Access evaluation results, one entry per resolved customer.'), + errors: z + .array(governanceQueryErrorWire) + .describe('Partial errors encountered while processing the request.'), + meta: cursorMetaWire, + }) + .describe('Response of the governance query.') + +export const chargeFlatFeeWire = z + .strictObject({ + id: ulidWire, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + type: z.literal('flat_fee').describe('The type of the charge.'), + customer: billingCustomerReferenceWire, + lifecycle_controller: lifecycleControllerWire, + subscription: subscriptionReferenceWire.optional(), + currency: currencyCodeWire, + status: chargeStatusWire, + invoice_at: dateTimeWire, + service_period: closedPeriodWire, + full_service_period: closedPeriodWire, + billing_period: closedPeriodWire, + advance_after: dateTimeWire.optional(), + unique_reference_id: z + .string() + .optional() + .describe('Unique reference ID of the charge.'), + settlement_mode: settlementModeWire, + tax_config: taxConfigWire.optional(), + payment_term: pricePaymentTermWire, + discounts: chargeFlatFeeDiscountsWire.optional(), + feature_key: z + .string() + .optional() + .describe('The feature associated with the charge, when applicable.'), + proration_configuration: rateCardProrationConfigurationWire, + amount_after_proration: currencyAmountWire, + price: priceWire, + system_intent: chargeFlatFeeSystemIntentWire.optional(), + }) + .describe('A flat fee charge for a customer.') + +export const chargeUsageBasedSystemIntentWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + invoice_at: dateTimeWire, + service_period: closedPeriodWire, + full_service_period: closedPeriodWire, + billing_period: closedPeriodWire, + discounts: rateCardDiscountsWire.optional(), + price: priceWire, + deleted_at: dateTimeWire.optional(), + }) + + .describe( + 'Usage-based intent fields from the system lifecycle controller shadowed by a manual override.', + ) + +export const createChargeUsageBasedRequestWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + type: z.literal('usage_based').describe('The type of the charge.'), + currency: currencyCodeWire, + invoice_at: dateTimeWire, + service_period: closedPeriodWire, + unique_reference_id: z + .string() + .optional() + .describe('Unique reference ID of the charge.'), + settlement_mode: settlementModeWire, + tax_config: taxConfigWire.optional(), + discounts: rateCardDiscountsWire.optional(), + feature_key: z.string().describe('The feature associated with the charge.'), + price: priceWire, + full_service_period: closedPeriodWire.optional(), + billing_period: closedPeriodWire.optional(), + }) + .describe('Usage-based charge create request.') + +export const rateCardWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + key: resourceKeyWire, + feature: featureReferenceWire.optional(), + billing_cadence: iso8601DurationWire.optional(), + price: priceWire, + unit_config: unitConfigWire.optional(), + payment_term: pricePaymentTermWire.optional(), + commitments: spendCommitmentsWire.optional(), + discounts: rateCardDiscountsWire.optional(), + tax_config: rateCardTaxConfigWire.optional(), + entitlement: rateCardEntitlementWire.optional(), + }) + + .describe( + 'A rate card defines the pricing and entitlement of a feature or service.', + ) + +export const invoiceLineRateCardWire = z + .strictObject({ + price: priceWire, + tax_config: rateCardTaxConfigWire.optional(), + feature_key: resourceKeyWire.optional(), + discounts: rateCardDiscountsWire.optional(), + }) + .describe('Rate card configuration snapshot for a usage-based invoice line.') + +export const updateInvoiceLineRateCardWire = z + .strictObject({ + price: updatePriceWire, + tax_config: updateRateCardTaxConfigWire.optional(), + feature_key: resourceKeyWire.optional(), + discounts: updateDiscountsWire.optional(), + }) + .describe('Rate card configuration snapshot for a usage-based invoice line.') + +export const featurePagePaginatedResponseWire = z + .strictObject({ + data: z.array(featureWire), + meta: paginatedMetaWire, + }) + .describe('Page paginated response.') + +export const workflowWire = z + .strictObject({ + collection: workflowCollectionSettingsWire.optional(), + invoicing: workflowInvoicingSettingsWire.optional(), + payment: workflowPaymentSettingsWire.optional(), + tax: workflowTaxSettingsWire.optional(), + }) + .describe('Billing workflow settings.') + +export const appPagePaginatedResponseWire = z + .strictObject({ + data: z.array(appWire), + meta: paginatedMetaWire, + }) + .describe('Page paginated response.') + +export const billingInstallAppResponseWire = z + .strictObject({ + app: appWire, + default_for_capability_types: z.array(appCapabilityTypeWire), + }) + .describe('Response of the app install.') + +export const profileAppsWire = z + .strictObject({ + tax: appWire, + invoicing: appWire, + payment: appWire, + }) + .describe('Applications used by a billing profile.') + +export const chargeUsageBasedWire = z + .strictObject({ + id: ulidWire, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + type: z.literal('usage_based').describe('The type of the charge.'), + customer: billingCustomerReferenceWire, + lifecycle_controller: lifecycleControllerWire, + subscription: subscriptionReferenceWire.optional(), + currency: currencyCodeWire, + status: chargeStatusWire, + invoice_at: dateTimeWire, + service_period: closedPeriodWire, + full_service_period: closedPeriodWire, + billing_period: closedPeriodWire, + advance_after: dateTimeWire.optional(), + unique_reference_id: z + .string() + .optional() + .describe('Unique reference ID of the charge.'), + settlement_mode: settlementModeWire, + tax_config: taxConfigWire.optional(), + discounts: rateCardDiscountsWire.optional(), + feature_key: z.string().describe('The feature associated with the charge.'), + totals: chargeTotalsWire, + price: priceWire, + system_intent: chargeUsageBasedSystemIntentWire.optional(), + }) + .describe('A usage-based charge for a customer.') + +export const createChargeRequestWire = z + .discriminatedUnion('type', [ + createChargeFlatFeeRequestWire, + createChargeUsageBasedRequestWire, + ]) + .describe('Customer charge.') + +export const subscriptionAddonRateCardWire = z + .strictObject({ + rate_card: rateCardWire, + affected_subscription_item_ids: z + .array(ulidWire) + + .describe( + 'The IDs of the subscription items that this rate card belongs to.', + ), + }) + .describe('A rate card for a subscription add-on.') + +export const planPhaseWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + key: resourceKeyWire, + duration: iso8601DurationWire.optional(), + rate_cards: z.array(rateCardWire).describe('The rate cards of the plan.'), + }) + + .describe( + "The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses.", + ) + +export const addonWire = z + .strictObject({ + id: ulidWire, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + key: resourceKeyWire, + version: z + .number() + .int() + .gte(1) + + .describe( + 'Version of the add-on. Incremented when the add-on is updated.', + ), + instance_type: addonInstanceTypeWire, + currency: billingCurrencyCodeWire, + effective_from: dateTimeWire.optional(), + effective_to: dateTimeWire.optional(), + status: addonStatusWire, + rate_cards: z.array(rateCardWire).describe('The rate cards of the add-on.'), + validation_errors: z + .array(productCatalogValidationErrorWire) + .optional() + .describe('List of validation errors.'), + }) + + .describe( + 'Add-on allows extending subscriptions with compatible plans with additional ratecards.', + ) + +export const createAddonRequestWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + key: resourceKeyWire, + instance_type: addonInstanceTypeWire, + currency: billingCurrencyCodeWire, + rate_cards: z.array(rateCardWire).describe('The rate cards of the add-on.'), + }) + .describe('Addon create request.') + +export const upsertAddonRequestWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + instance_type: addonInstanceTypeWire, + rate_cards: z.array(rateCardWire).describe('The rate cards of the add-on.'), + }) + .describe('Addon upsert request.') + +export const invoiceStandardLineWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + id: ulidWire.optional(), + type: z + .literal('standard_line') + .describe('The type of charge this line item represents.'), + lifecycle_controller: lifecycleControllerWire, + service_period: closedPeriodWire, + totals: totalsWire, + discounts: invoiceLineDiscountsWire.optional(), + credits_applied: z + .array(invoiceLineCreditsAppliedWire) + .optional() + .describe('Credit applied to this line item.'), + external_references: invoiceLineExternalReferencesWire.optional(), + subscription: subscriptionReferenceWire.optional(), + rate_card: invoiceLineRateCardWire, + detailed_lines: z + .array(invoiceDetailedLineWire) + + .describe( + 'Detailed sub-lines that this line has been broken down into. Present when line has individual details.', + ), + charge: chargeReferenceWire.optional(), + }) + + .describe( + 'A top-level line item on an invoice. Each line represents a single charge, typically associated with a rate card from a subscription. Detailed (child) lines are nested under `detailed_lines` when present.', + ) + +export const updateInvoiceStandardLineWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: updateLabelsWire.optional(), + id: ulidWire.optional(), + type: z + .literal('standard_line') + .describe('The type of charge this line item represents.'), + service_period: updateClosedPeriodWire, + rate_card: updateInvoiceLineRateCardWire, + }) + + .describe( + 'A top-level line item on an invoice. Each line represents a single charge, typically associated with a rate card from a subscription. Detailed (child) lines are nested under `detailed_lines` when present.', + ) + +export const profileWire = z + .strictObject({ + id: ulidWire, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + supplier: partyWire, + workflow: workflowWire, + apps: profileAppReferencesWire, + default: z.boolean().describe('Whether this is the default profile.'), + }) + + .describe( + 'Billing profiles contain the settings for billing and controls invoice generation.', + ) + +export const createBillingProfileRequestWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + supplier: partyWire, + workflow: workflowWire, + apps: profileAppReferencesWire, + default: z.boolean().describe('Whether this is the default profile.'), + }) + .describe('BillingProfile create request.') + +export const upsertBillingProfileRequestWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + supplier: partyWire, + workflow: workflowWire, + default: z.boolean().describe('Whether this is the default profile.'), + }) + .describe('BillingProfile upsert request.') + +export const chargeWire = z + .discriminatedUnion('type', [chargeFlatFeeWire, chargeUsageBasedWire]) + .describe('Customer charge.') + +export const subscriptionAddonWire = z + .strictObject({ + id: ulidWire, + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + addon: addonReferenceWire, + quantity: z + .number() + .int() + .gte(1) + + .describe( + 'The quantity of the add-on. Always 1 for single instance add-ons.', + ), + quantity_at: dateTimeWire, + active_from: dateTimeWire, + active_to: dateTimeWire.optional(), + timeline: z + .array(subscriptionAddonTimelineSegmentWire) + + .describe( + 'The timeline of the add-on. The returned periods are sorted and continuous.', + ), + rate_cards: z + .array(subscriptionAddonRateCardWire) + .describe('The rate cards of the add-on.'), + }) + .describe('Addon purchased with a subscription.') + +export const planWire = z + .strictObject({ + id: ulidWire, + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + key: resourceKeyWire, + version: z + .number() + .int() + .gte(1) + + .describe( + 'Plans are versioned to allow you to make changes without affecting running subscriptions.', + ), + currency: currencyCodeWire, + billing_cadence: iso8601DurationWire, + pro_rating_enabled: z + .boolean() + .optional() + .describe('Whether pro-rating is enabled for this plan.'), + effective_from: dateTimeWire.optional(), + effective_to: dateTimeWire.optional(), + status: planStatusWire, + phases: z + .array(planPhaseWire) + .min(1) + + .describe( + 'The plan phases define the pricing ramp for a subscription. A phase switch occurs only at the end of a billing period. At least one phase is required.', + ), + settlement_mode: settlementModeWire.optional(), + validation_errors: z + .array(productCatalogValidationErrorWire) + .optional() + + .describe( + 'List of validation errors in `draft` state that prevent the plan from being published.', + ), + }) + .describe('Plans provide a template for subscriptions.') + +export const createPlanRequestWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + key: resourceKeyWire, + currency: currencyCodeWire, + billing_cadence: iso8601DurationWire, + pro_rating_enabled: z + .boolean() + .optional() + .describe('Whether pro-rating is enabled for this plan.'), + phases: z + .array(planPhaseWire) + .min(1) + + .describe( + 'The plan phases define the pricing ramp for a subscription. A phase switch occurs only at the end of a billing period. At least one phase is required.', + ), + }) + .describe('Plan create request.') + +export const upsertPlanRequestWire = z + .strictObject({ + name: z + .string() + .min(1) + .max(256) + .describe('Display name of the resource. Between 1 and 256 characters.'), + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + pro_rating_enabled: z + .boolean() + .optional() + .describe('Whether pro-rating is enabled for this plan.'), + phases: z + .array(planPhaseWire) + .min(1) + + .describe( + 'The plan phases define the pricing ramp for a subscription. A phase switch occurs only at the end of a billing period. At least one phase is required.', + ), + }) + .describe('Plan upsert request.') + +export const addonPagePaginatedResponseWire = z + .strictObject({ + data: z.array(addonWire), + meta: paginatedMetaWire, + }) + .describe('Page paginated response.') + +export const invoiceLineWire = z + .discriminatedUnion('type', [invoiceStandardLineWire]) + + .describe( + 'A top-level line item on an invoice. Each line represents a single charge, typically associated with a rate card from a subscription. Detailed (child) lines are nested under `detailed_lines` when present.', + ) + +export const updateInvoiceLineWire = z + .discriminatedUnion('type', [updateInvoiceStandardLineWire]) + + .describe( + 'A top-level line item on an invoice. Each line represents a single charge, typically associated with a rate card from a subscription. Detailed (child) lines are nested under `detailed_lines` when present.', + ) + +export const profilePagePaginatedResponseWire = z + .strictObject({ + data: z.array(profileWire), + meta: paginatedMetaWire, + }) + .describe('Page paginated response.') + +export const chargePagePaginatedResponseWire = z + .strictObject({ + data: z.array(chargeWire), + meta: paginatedMetaWire, + }) + .describe('Page paginated response.') + +export const subscriptionAddonPagePaginatedResponseWire = z + .strictObject({ + data: z.array(subscriptionAddonWire), + meta: paginatedMetaWire, + }) + .describe('Page paginated response.') + +export const planPagePaginatedResponseWire = z + .strictObject({ + data: z.array(planWire), + meta: paginatedMetaWire, + }) + .describe('Page paginated response.') + +export const invoiceStandardWire = z + .strictObject({ + id: ulidWire, + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: labelsWire.optional(), + created_at: dateTimeWire, + updated_at: dateTimeWire, + deleted_at: dateTimeWire.optional(), + number: invoiceNumberWire, + currency: currencyCodeWire, + supplier: supplierWire, + customer: invoiceCustomerWire, + totals: totalsWire, + service_period: closedPeriodWire, + validation_issues: z + .array(invoiceValidationIssueWire) + .optional() + + .describe( + 'Validation issues found during invoice processing. Present only when there are one or more validation findings. An empty list is omitted.', + ), + external_references: invoiceExternalReferencesWire.optional(), + type: z + .literal('standard') + .describe('Discriminator field identifying this as a standard invoice.'), + status: invoiceStandardStatusWire, + status_details: invoiceStatusDetailsWire, + issued_at: dateTimeWire.optional(), + draft_until: dateTimeWire.optional(), + quantity_snapshotted_at: dateTimeWire.optional(), + collection_at: dateTimeWire.optional(), + due_at: dateTimeWire.optional(), + sent_to_customer_at: dateTimeWire.optional(), + workflow: invoiceWorkflowSettingsWire, + lines: z + .array(invoiceLineWire) + .optional() + + .describe( + 'Line items on this invoice. Always returned on single-resource GET; omitted on list endpoints unless explicitly expanded. Editable via update: existing lines are matched by `id`, lines without an `id` are created, and lines present on the invoice but omitted from the update request are deleted. Detailed (child) lines are always computed and cannot be edited directly.', + ), + }) + .describe('A standard invoice for charges owed by the customer.') + +export const updateInvoiceStandardRequestWire = z + .strictObject({ + description: z + .string() + .max(1024) + .optional() + + .describe( + 'Optional description of the resource. Maximum 1024 characters.', + ), + labels: updateLabelsWire.optional(), + supplier: updateSupplierWire, + customer: updateInvoiceCustomerWire, + type: z + .literal('standard') + .describe('Discriminator field identifying this as a standard invoice.'), + workflow: updateInvoiceWorkflowSettingsWire, + lines: z + .array(updateInvoiceLineWire) + .optional() + + .describe( + 'Line items on this invoice. Always returned on single-resource GET; omitted on list endpoints unless explicitly expanded. Editable via update: existing lines are matched by `id`, lines without an `id` are created, and lines present on the invoice but omitted from the update request are deleted. Detailed (child) lines are always computed and cannot be edited directly.', + ), + }) + .describe('InvoiceStandard update request.') + +export const invoiceWire = z + .discriminatedUnion('type', [invoiceStandardWire]) + + .describe( + 'An invoice issued to a customer. The `type` field determines the concrete variant: - `standard`: a standard invoice for charges owed.', + ) + +export const updateInvoiceRequestWire = z + .discriminatedUnion('type', [updateInvoiceStandardRequestWire]) + .describe('UpdateInvoiceRequest update request.') + +export const invoicePagePaginatedResponseWire = z + .strictObject({ + data: z.array(invoiceWire), + meta: paginatedMetaWire, + }) + .describe('Page paginated response.') + +export const listMeteringEventsQueryParamsWire = z.object({ + page: cursorPaginationQueryPageWire.optional(), + filter: listEventsParamsFilterWire.optional(), + sort: z + .string() + .optional() + + .describe( + 'Sort events returned in the response. Supported sort attributes are: - `time` (default) - `ingested_at` - `stored_at` When omitted, events are sorted by `time desc` (most recent first). When a sort field is provided without a suffix, it sorts descending. Append the `asc` suffix to sort ascending, or the `desc` suffix to sort descending.', + ), +}) + +export const listMeteringEventsResponseWire = z.strictObject({ + data: z.array(ingestedEventWire), + meta: cursorMetaWire, +}) + +export const ingestMeteringEventsBodyWire = z.union([ + eventWire, + z.array(eventWire), +]) + +export const createMeterBodyWire = createMeterRequestWire + +export const createMeterResponseWire = meterWire + +export const getMeterPathParamsWire = z.object({ + meterId: ulidWire, +}) + +export const getMeterResponseWire = meterWire + +export const listMetersQueryParamsWire = z.object({ + page: z + .strictObject({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + sort: z + .string() + .optional() + + .describe( + 'Sort meters returned in the response. Supported sort attributes are: - `key` - `name` - `aggregation` - `created_at` (default) - `updated_at` The `asc` suffix is optional as the default sort order is ascending. The `desc` suffix is used to specify a descending order.', + ), + filter: listMetersParamsFilterWire.optional(), +}) + +export const listMetersResponseWire = z.strictObject({ + data: z.array(meterWire), + meta: paginatedMetaWire, +}) + +export const updateMeterPathParamsWire = z.object({ + meterId: ulidWire, +}) + +export const updateMeterBodyWire = updateMeterRequestWire + +export const updateMeterResponseWire = meterWire + +export const deleteMeterPathParamsWire = z.object({ + meterId: ulidWire, +}) + +export const queryMeterPathParamsWire = z.object({ + meterId: ulidWire, +}) + +export const queryMeterBodyWire = meterQueryRequestWire + +export const queryMeterResponseWire = meterQueryResultWire + +export const queryMeterCsvPathParamsWire = z.object({ + meterId: ulidWire, +}) + +export const queryMeterCsvBodyWire = meterQueryRequestWire + +export const queryMeterCsvResponseWire = z.string() + +export const createCustomerBodyWire = createCustomerRequestWire + +export const createCustomerResponseWire = customerWire + +export const getCustomerPathParamsWire = z.object({ + customerId: ulidWire, +}) + +export const getCustomerResponseWire = customerWire + +export const listCustomersQueryParamsWire = z.object({ + page: z + .strictObject({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + sort: z + .string() + .optional() + + .describe( + 'Sort customers returned in the response. Supported sort attributes are: - `id` - `name` (default) - `created_at` The `asc` suffix is optional as the default sort order is ascending. The `desc` suffix is used to specify a descending order.', + ), + filter: listCustomersParamsFilterWire.optional(), +}) + +export const listCustomersResponseWire = z.strictObject({ + data: z.array(customerWire), + meta: paginatedMetaWire, +}) + +export const upsertCustomerPathParamsWire = z.object({ + customerId: ulidWire, +}) + +export const upsertCustomerBodyWire = upsertCustomerRequestWire + +export const upsertCustomerResponseWire = customerWire + +export const deleteCustomerPathParamsWire = z.object({ + customerId: ulidWire, +}) + +export const getCustomerBillingPathParamsWire = z.object({ + customerId: ulidWire, +}) + +export const getCustomerBillingResponseWire = customerDataWire + +export const updateCustomerBillingPathParamsWire = z.object({ + customerId: ulidWire, +}) + +export const updateCustomerBillingBodyWire = + upsertCustomerBillingDataRequestWire + +export const updateCustomerBillingResponseWire = customerDataWire + +export const updateCustomerBillingAppDataPathParamsWire = z.object({ + customerId: ulidWire, +}) + +export const updateCustomerBillingAppDataBodyWire = + upsertAppCustomerDataRequestWire + +export const updateCustomerBillingAppDataResponseWire = appCustomerDataWire + +export const createCustomerStripeCheckoutSessionPathParamsWire = z.object({ + customerId: ulidWire, +}) + +export const createCustomerStripeCheckoutSessionBodyWire = + customerStripeCreateCheckoutSessionRequestWire + +export const createCustomerStripeCheckoutSessionResponseWire = + appStripeCreateCheckoutSessionResultWire + +export const createCustomerStripePortalSessionPathParamsWire = z.object({ + customerId: ulidWire, +}) + +export const createCustomerStripePortalSessionBodyWire = + customerStripeCreateCustomerPortalSessionRequestWire + +export const createCustomerStripePortalSessionResponseWire = + appStripeCreateCustomerPortalSessionResultWire + +export const listCustomerEntitlementAccessPathParamsWire = z.object({ + customerId: ulidWire, +}) + +export const listCustomerEntitlementAccessResponseWire = + listCustomerEntitlementAccessResponseDataWire + +export const createCreditGrantPathParamsWire = z.object({ + customerId: ulidWire, +}) + +export const createCreditGrantBodyWire = createCreditGrantRequestWire + +export const createCreditGrantResponseWire = creditGrantWire + +export const getCreditGrantPathParamsWire = z.object({ + customerId: ulidWire, + creditGrantId: ulidWire, +}) + +export const getCreditGrantResponseWire = creditGrantWire + +export const listCreditGrantsPathParamsWire = z.object({ + customerId: ulidWire, +}) + +export const listCreditGrantsQueryParamsWire = z.object({ + page: z + .strictObject({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + filter: listCreditGrantsParamsFilterWire.optional(), +}) + +export const listCreditGrantsResponseWire = z.strictObject({ + data: z.array(creditGrantWire), + meta: paginatedMetaWire, +}) + +export const getCustomerCreditBalancePathParamsWire = z.object({ + customerId: ulidWire, +}) + +export const getCustomerCreditBalanceQueryParamsWire = z.object({ + timestamp: dateTimeWire.optional(), + filter: getCreditBalanceParamsFilterWire.optional(), +}) + +export const getCustomerCreditBalanceResponseWire = creditBalancesWire + +export const createCreditAdjustmentPathParamsWire = z.object({ + customerId: ulidWire, +}) + +export const createCreditAdjustmentBodyWire = createCreditAdjustmentRequestWire + +export const createCreditAdjustmentResponseWire = creditAdjustmentWire + +export const voidCreditGrantPathParamsWire = z.object({ + customerId: ulidWire, + creditGrantId: ulidWire, +}) + +export const voidCreditGrantBodyWire = voidCreditGrantRequestWire + +export const voidCreditGrantResponseWire = creditGrantWire + +export const updateCreditGrantExternalSettlementPathParamsWire = z.object({ + customerId: ulidWire, + creditGrantId: ulidWire, +}) + +export const updateCreditGrantExternalSettlementBodyWire = + updateCreditGrantExternalSettlementRequestWire + +export const updateCreditGrantExternalSettlementResponseWire = creditGrantWire + +export const listCreditTransactionsPathParamsWire = z.object({ + customerId: ulidWire, +}) + +export const listCreditTransactionsQueryParamsWire = z.object({ + page: cursorPaginationQueryPageWire.optional(), + filter: listCreditTransactionsParamsFilterWire.optional(), +}) + +export const listCreditTransactionsResponseWire = z.strictObject({ + data: z.array(creditTransactionWire), + meta: cursorMetaWire, +}) + +export const listCustomerChargesPathParamsWire = z.object({ + customerId: ulidWire, +}) + +export const listCustomerChargesQueryParamsWire = z.object({ + page: z + .strictObject({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + sort: z + .string() + .optional() + + .describe( + 'Sort charges returned in the response. Supported sort attributes are: - `id` - `created_at` - `service_period.from` - `billing_period.from`', + ), + filter: listChargesParamsFilterWire.optional(), + expand: z + .array(chargesExpandWire) + .optional() + + .describe( + "Expand full objects for referenced entities. Supported values are: - `real_time_usage`: Expand the charge's real-time usage.", + ), +}) + +export const listCustomerChargesResponseWire = z.strictObject({ + data: z.array(chargeWire), + meta: paginatedMetaWire, +}) + +export const createCustomerChargesPathParamsWire = z.object({ + customerId: ulidWire, +}) + +export const createCustomerChargesBodyWire = createChargeRequestWire + +export const createCustomerChargesResponseWire = chargeWire + +export const createSubscriptionBodyWire = subscriptionCreateWire + +export const createSubscriptionResponseWire = subscriptionWire + +export const listSubscriptionsQueryParamsWire = z.object({ + page: z + .strictObject({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + sort: z + .string() + .optional() + + .describe( + 'Sort subscriptions returned in the response. Supported sort attributes are: - `id` - `active_from` (default) - `active_to` The `asc` suffix is optional as the default sort order is ascending. The `desc` suffix is used to specify a descending order.', + ), + filter: listSubscriptionsParamsFilterWire.optional(), +}) + +export const listSubscriptionsResponseWire = z.strictObject({ + data: z.array(subscriptionWire), + meta: paginatedMetaWire, +}) + +export const getSubscriptionPathParamsWire = z.object({ + subscriptionId: ulidWire, +}) + +export const getSubscriptionResponseWire = subscriptionWire + +export const cancelSubscriptionPathParamsWire = z.object({ + subscriptionId: ulidWire, +}) + +export const cancelSubscriptionBodyWire = subscriptionCancelWire + +export const cancelSubscriptionResponseWire = subscriptionWire + +export const unscheduleCancelationPathParamsWire = z.object({ + subscriptionId: ulidWire, +}) + +export const unscheduleCancelationResponseWire = subscriptionWire + +export const changeSubscriptionPathParamsWire = z.object({ + subscriptionId: ulidWire, +}) + +export const changeSubscriptionBodyWire = subscriptionChangeWire + +export const changeSubscriptionResponseWire = subscriptionChangeResponseWire + +export const createSubscriptionAddonPathParamsWire = z.object({ + subscriptionId: ulidWire, +}) + +export const createSubscriptionAddonBodyWire = + createSubscriptionAddonRequestWire + +export const createSubscriptionAddonResponseWire = subscriptionAddonWire + +export const listSubscriptionAddonsPathParamsWire = z.object({ + subscriptionId: ulidWire, +}) + +export const listSubscriptionAddonsQueryParamsWire = z.object({ + page: z + .strictObject({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + sort: z + .string() + .optional() + + .describe( + 'Sort subscription addons returned in the response. Supported sort attributes are: - `id` - `created_at` (default) - `updated_at` The `asc` suffix is optional as the default sort order is ascending. The `desc` suffix is used to specify a descending order.', + ), +}) + +export const listSubscriptionAddonsResponseWire = z.strictObject({ + data: z.array(subscriptionAddonWire), + meta: paginatedMetaWire, +}) + +export const getSubscriptionAddonPathParamsWire = z.object({ + subscriptionId: ulidWire, + subscriptionAddonId: ulidWire, +}) + +export const getSubscriptionAddonResponseWire = subscriptionAddonWire + +export const listAppsQueryParamsWire = z.object({ + page: z + .strictObject({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), +}) + +export const listAppsResponseWire = z.strictObject({ + data: z.array(appWire), + meta: paginatedMetaWire, +}) + +export const getAppPathParamsWire = z.object({ + appId: ulidWire, +}) + +export const getAppResponseWire = appWire + +export const listAppCatalogQueryParamsWire = z.object({ + page: z + .strictObject({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), +}) + +export const listAppCatalogResponseWire = z.strictObject({ + data: z.array(appCatalogItemWire), + meta: paginatedMetaWire, +}) + +export const getAppCatalogItemPathParamsWire = z.object({ + appType: appTypeWire, +}) + +export const getAppCatalogItemResponseWire = appCatalogItemWire + +export const installAppBodyWire = installAppRequestWire + +export const installAppResponseWire = billingInstallAppResponseWire + +export const listBillingProfilesQueryParamsWire = z.object({ + page: z + .strictObject({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), +}) + +export const listBillingProfilesResponseWire = z.strictObject({ + data: z.array(profileWire), + meta: paginatedMetaWire, +}) + +export const createBillingProfileBodyWire = createBillingProfileRequestWire + +export const createBillingProfileResponseWire = profileWire + +export const getBillingProfilePathParamsWire = z.object({ + id: ulidWire, +}) + +export const getBillingProfileResponseWire = profileWire + +export const updateBillingProfilePathParamsWire = z.object({ + id: ulidWire, +}) + +export const updateBillingProfileBodyWire = upsertBillingProfileRequestWire + +export const updateBillingProfileResponseWire = profileWire + +export const deleteBillingProfilePathParamsWire = z.object({ + id: ulidWire, +}) + +export const listInvoicesQueryParamsWire = z.object({ + page: z + .strictObject({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + sort: z + .string() + .optional() + + .describe( + 'Sort invoices returned in the response. Supported sort attributes: - `issued_at` - `created_at` (default) - `service_period_start` The `asc` suffix is optional as the default sort order is ascending. The `desc` suffix is used to specify a descending order.', + ), + filter: listInvoicesParamsFilterWire.optional(), +}) + +export const listInvoicesResponseWire = z.strictObject({ + data: z.array(invoiceWire), + meta: paginatedMetaWire, +}) + +export const getInvoicePathParamsWire = z.object({ + invoiceId: ulidWire, +}) + +export const getInvoiceResponseWire = invoiceWire + +export const updateInvoicePathParamsWire = z.object({ + invoiceId: ulidWire, +}) + +export const updateInvoiceBodyWire = updateInvoiceRequestWire + +export const updateInvoiceResponseWire = invoiceWire + +export const deleteInvoicePathParamsWire = z.object({ + invoiceId: ulidWire, +}) + +export const advanceInvoicePathParamsWire = z.object({ + invoiceId: ulidWire, +}) + +export const advanceInvoiceResponseWire = invoiceWire + +export const approveInvoicePathParamsWire = z.object({ + invoiceId: ulidWire, +}) + +export const approveInvoiceResponseWire = invoiceWire + +export const retryInvoicePathParamsWire = z.object({ + invoiceId: ulidWire, +}) + +export const retryInvoiceResponseWire = invoiceWire + +export const snapshotQuantitiesInvoicePathParamsWire = z.object({ + invoiceId: ulidWire, +}) + +export const snapshotQuantitiesInvoiceResponseWire = invoiceWire + +export const createTaxCodeBodyWire = createTaxCodeRequestWire + +export const createTaxCodeResponseWire = taxCodeWire + +export const getTaxCodePathParamsWire = z.object({ + taxCodeId: ulidWire, +}) + +export const getTaxCodeResponseWire = taxCodeWire + +export const listTaxCodesQueryParamsWire = z.object({ + page: z + .strictObject({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + include_deleted: z.coerce + .boolean() + .optional() + .describe('Include deleted tax codes in the response.'), +}) + +export const listTaxCodesResponseWire = z.strictObject({ + data: z.array(taxCodeWire), + meta: paginatedMetaWire, +}) + +export const upsertTaxCodePathParamsWire = z.object({ + taxCodeId: ulidWire, +}) + +export const upsertTaxCodeBodyWire = upsertTaxCodeRequestWire + +export const upsertTaxCodeResponseWire = taxCodeWire + +export const deleteTaxCodePathParamsWire = z.object({ + taxCodeId: ulidWire, +}) + +export const listCurrenciesQueryParamsWire = z.object({ + page: z + .strictObject({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + sort: z + .string() + .optional() + + .describe( + 'Sort currencies returned in the response. Supported sort attributes are: - `code` (default) - `name` The `asc` suffix is optional as the default sort order is ascending. The `desc` suffix is used to specify a descending order.', + ), + filter: listCurrenciesParamsFilterWire.optional(), +}) + +export const listCurrenciesResponseWire = z.strictObject({ + data: z.array(currencyWire), + meta: paginatedMetaWire, +}) + +export const createCustomCurrencyBodyWire = createCurrencyCustomRequestWire + +export const createCustomCurrencyResponseWire = currencyCustomWire + +export const listCostBasesPathParamsWire = z.object({ + currencyId: ulidWire, +}) + +export const listCostBasesQueryParamsWire = z.object({ + filter: listCostBasesParamsFilterWire.optional(), + page: z + .strictObject({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), +}) + +export const listCostBasesResponseWire = z.strictObject({ + data: z.array(costBasisWire), + meta: paginatedMetaWire, +}) + +export const createCostBasisPathParamsWire = z.object({ + currencyId: ulidWire, +}) + +export const createCostBasisBodyWire = createCostBasisRequestWire + +export const createCostBasisResponseWire = costBasisWire + +export const listFeaturesQueryParamsWire = z.object({ + page: z + .strictObject({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + sort: z + .string() + .optional() + + .describe( + 'Sort features returned in the response. Supported sort attributes are: - `key` - `name` - `created_at` (default) - `updated_at` The `asc` suffix is optional as the default sort order is ascending. The `desc` suffix is used to specify a descending order.', + ), + filter: listFeatureParamsFilterWire.optional(), +}) + +export const listFeaturesResponseWire = z.strictObject({ + data: z.array(featureWire), + meta: paginatedMetaWire, +}) + +export const createFeatureBodyWire = createFeatureRequestWire + +export const createFeatureResponseWire = featureWire + +export const getFeaturePathParamsWire = z.object({ + featureId: ulidWire, +}) + +export const getFeatureResponseWire = featureWire + +export const updateFeaturePathParamsWire = z.object({ + featureId: ulidWire, +}) + +export const updateFeatureBodyWire = updateFeatureRequestWire + +export const updateFeatureResponseWire = featureWire + +export const deleteFeaturePathParamsWire = z.object({ + featureId: ulidWire, +}) + +export const queryFeatureCostPathParamsWire = z.object({ + featureId: ulidWire, +}) + +export const queryFeatureCostBodyWire = meterQueryRequestWire + +export const queryFeatureCostResponseWire = featureCostQueryResultWire + +export const listLlmCostPricesQueryParamsWire = z.object({ + filter: listLlmCostPricesParamsFilterWire.optional(), + sort: z + .string() + .optional() + + .describe( + 'Sort prices returned in the response. Supported sort attributes are: - `id` - `provider.id` - `model.id` (default) - `effective_from` - `effective_to` The `asc` suffix is optional as the default sort order is ascending. The `desc` suffix is used to specify a descending order.', + ), + page: z + .strictObject({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), +}) + +export const listLlmCostPricesResponseWire = z.strictObject({ + data: z.array(llmCostPriceWire), + meta: paginatedMetaWire, +}) + +export const getLlmCostPricePathParamsWire = z.object({ + priceId: ulidWire, +}) + +export const getLlmCostPriceResponseWire = llmCostPriceWire + +export const listLlmCostOverridesQueryParamsWire = z.object({ + filter: listLlmCostPricesParamsFilterWire.optional(), + page: z + .strictObject({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), +}) + +export const listLlmCostOverridesResponseWire = z.strictObject({ + data: z.array(llmCostPriceWire), + meta: paginatedMetaWire, +}) + +export const createLlmCostOverrideBodyWire = llmCostOverrideCreateWire + +export const createLlmCostOverrideResponseWire = llmCostPriceWire + +export const deleteLlmCostOverridePathParamsWire = z.object({ + priceId: ulidWire, +}) + +export const listPlansQueryParamsWire = z.object({ + page: z + .strictObject({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + sort: z + .string() + .optional() + + .describe( + 'Sort plans returned in the response. Supported sort attributes are: - `id` - `key` - `version` - `created_at` (default) - `updated_at`', + ), + filter: listPlansParamsFilterWire.optional(), +}) + +export const listPlansResponseWire = z.strictObject({ + data: z.array(planWire), + meta: paginatedMetaWire, +}) + +export const createPlanBodyWire = createPlanRequestWire + +export const createPlanResponseWire = planWire + +export const updatePlanPathParamsWire = z.object({ + planId: ulidWire, +}) + +export const updatePlanBodyWire = upsertPlanRequestWire + +export const updatePlanResponseWire = planWire + +export const getPlanPathParamsWire = z.object({ + planId: ulidWire, +}) + +export const getPlanResponseWire = planWire + +export const deletePlanPathParamsWire = z.object({ + planId: ulidWire, +}) + +export const archivePlanPathParamsWire = z.object({ + planId: ulidWire, +}) + +export const archivePlanResponseWire = planWire + +export const publishPlanPathParamsWire = z.object({ + planId: ulidWire, +}) + +export const publishPlanResponseWire = planWire + +export const listAddonsQueryParamsWire = z.object({ + page: z + .strictObject({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), + sort: z + .string() + .optional() + + .describe( + 'Sort add-ons returned in the response. Supported sort attributes are: - `id` - `key` - `name` - `created_at` (default) - `updated_at` The `asc` suffix is optional as the default sort order is ascending. The `desc` suffix is used to specify a descending order.', + ), + filter: listAddonsParamsFilterWire.optional(), +}) + +export const listAddonsResponseWire = z.strictObject({ + data: z.array(addonWire), + meta: paginatedMetaWire, +}) + +export const createAddonBodyWire = createAddonRequestWire + +export const createAddonResponseWire = addonWire + +export const updateAddonPathParamsWire = z.object({ + addonId: ulidWire, +}) + +export const updateAddonBodyWire = upsertAddonRequestWire + +export const updateAddonResponseWire = addonWire + +export const getAddonPathParamsWire = z.object({ + addonId: ulidWire, +}) + +export const getAddonResponseWire = addonWire + +export const deleteAddonPathParamsWire = z.object({ + addonId: ulidWire, +}) + +export const archiveAddonPathParamsWire = z.object({ + addonId: ulidWire, +}) + +export const archiveAddonResponseWire = addonWire + +export const publishAddonPathParamsWire = z.object({ + addonId: ulidWire, +}) + +export const publishAddonResponseWire = addonWire + +export const listPlanAddonsPathParamsWire = z.object({ + planId: ulidWire, +}) + +export const listPlanAddonsQueryParamsWire = z.object({ + page: z + .strictObject({ + size: z.coerce + .number() + .int() + .optional() + .describe('The number of items to include per page.'), + number: z.coerce.number().int().optional().describe('The page number.'), + }) + .optional() + .describe('Determines which page of the collection to retrieve.'), +}) + +export const listPlanAddonsResponseWire = z.strictObject({ + data: z.array(planAddonWire), + meta: paginatedMetaWire, +}) + +export const createPlanAddonPathParamsWire = z.object({ + planId: ulidWire, +}) + +export const createPlanAddonBodyWire = createPlanAddonRequestWire + +export const createPlanAddonResponseWire = planAddonWire + +export const getPlanAddonPathParamsWire = z.object({ + planId: ulidWire, + planAddonId: ulidWire, +}) + +export const getPlanAddonResponseWire = planAddonWire + +export const updatePlanAddonPathParamsWire = z.object({ + planId: ulidWire, + planAddonId: ulidWire, +}) + +export const updatePlanAddonBodyWire = upsertPlanAddonRequestWire + +export const updatePlanAddonResponseWire = planAddonWire + +export const deletePlanAddonPathParamsWire = z.object({ + planId: ulidWire, + planAddonId: ulidWire, +}) + +export const getOrganizationDefaultTaxCodesResponseWire = + organizationDefaultTaxCodesWire + +export const updateOrganizationDefaultTaxCodesBodyWire = + updateOrganizationDefaultTaxCodesRequestWire + +export const updateOrganizationDefaultTaxCodesResponseWire = + organizationDefaultTaxCodesWire + +export const queryGovernanceAccessQueryParamsWire = z.object({ + page: cursorPaginationQueryPageWire.optional(), +}) + +export const queryGovernanceAccessBodyWire = governanceQueryRequestWire + +export const queryGovernanceAccessResponseWire = governanceQueryResponseWire diff --git a/api/spec/packages/aip-client-javascript/src/models/types.ts b/api/spec/packages/aip-client-javascript/src/models/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f2188e2483c2d00ceacdb5fef6595bda1b7fabc --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/models/types.ts @@ -0,0 +1,7047 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +/** + * Labels store metadata of an entity that can be used for filtering an entity list + * or for searching across entity types. + * + * Keys must be of length 1-63 characters, and cannot start with "kong", "konnect", + * "mesh", "kic", or "\_". + */ +export type Labels = Record + +/** Determines which page of the collection to retrieve. */ +export interface CursorPaginationQueryPage { + /** The number of items to include per page. */ + size?: number + /** Request the next page of data, starting with the item after this parameter. */ + after?: string + /** Request the previous page of data, starting with the item before this parameter. */ + before?: string +} + +/** + * Sort query. + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ +export interface SortQuery { + /** The attribute to sort by. */ + by: string + /** The sort order. `asc` for ascending, `desc` for descending. */ + order: 'asc' | 'desc' +} + +/** Event validation errors. */ +export interface IngestedEventValidationError { + /** The machine readable code of the error. */ + code: string + /** The human readable description of the error. */ + message: string + /** Additional attributes. */ + attributes?: Record +} + +/** Cursor pagination metadata. */ +export interface CursorMetaPage { + /** URI to the first page. */ + first?: string + /** URI to the last page. */ + last?: string + /** URI to the next page. */ + next: string | null + /** URI to the previous page. */ + previous: string | null + /** Requested page size. */ + size: number +} + +/** Standard error response. */ +export interface BaseError { + /** Type contains a URI that identifies the problem type. */ + type: string + /** + * The HTTP status code generated by the origin server for this occurrence of the + * problem. + */ + status: number + /** A a short, human-readable summary of the problem type. */ + title: string + /** A human-readable explanation specific to this occurrence of the problem. */ + detail: string + /** A URI reference that identifies the specific occurrence of the problem. */ + instance: string + [key: string]: unknown +} + +/** Pagination information. */ +export interface PageMeta { + /** Page number. */ + number: number + /** Page size. */ + size: number + /** Total number of items in the collection. */ + total: number +} + +/** + * A query filter for a string attribute. Operators are mutually exclusive, only + * one operator is allowed at a time. + */ +export interface QueryFilterString { + /** The attribute equals the provided value. */ + eq?: string + /** The attribute does not equal the provided value. */ + neq?: string + /** The attribute is one of the provided values. */ + in?: string[] + /** The attribute is not one of the provided values. */ + nin?: string[] + /** The attribute contains the provided value. */ + contains?: string + /** The attribute does not contain the provided value. */ + ncontains?: string + /** Combines the provided filters with a logical AND. */ + and?: QueryFilterString[] + /** Combines the provided filters with a logical OR. */ + or?: QueryFilterString[] +} + +/** Custom text displayed at various stages of the checkout flow. */ +export interface AppStripeCheckoutSessionCustomTextParams { + /** Text displayed after the payment confirmation button. */ + afterSubmit?: { message?: string } + /** Text displayed alongside shipping address collection. */ + shippingAddress?: { message?: string } + /** Text displayed alongside the payment confirmation button. */ + submit?: { message?: string } + /** Text replacing the default terms of service agreement text. */ + termsOfServiceAcceptance?: { message?: string } +} + +/** Request to create a Stripe Customer Portal Session. */ +export interface AppStripeCreateCustomerPortalSessionOptions { + /** + * The ID of an existing + * [Stripe configuration](https://docs.stripe.com/api/customer_portal/configurations) + * to use for this session, describing its functionality and features. If not + * specified, the session uses the default configuration. + */ + configurationId?: string + /** + * The IETF + * [language tag](https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-locale) + * of the locale customer portal is displayed in. If blank or `auto`, the + * customer's preferred_locales or browser's locale is used. + */ + locale?: string + /** + * The + * [URL to redirect](https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-return_url) + * the customer to after they have completed their requested actions. + */ + returnUrl?: string +} + +/** + * Labels store metadata of an entity that can be used for filtering an entity list + * or for searching across entity types. + * + * Keys must be of length 1-63 characters, and cannot start with "kong", "konnect", + * "mesh", "kic", or "\_". + */ +export type CreateLabels = Record + +/** The tax config for Stripe. */ +export interface TaxConfigStripe { + /** Product [tax code](https://docs.stripe.com/tax/tax-codes). */ + code: string +} + +/** External invoicing tax config. */ +export interface TaxConfigExternalInvoicing { + /** The tax code should be interpreted by the external invoicing provider. */ + code: string +} + +/** + * Discounts applicable to flat fee charges. + * + * This is the same as `ProductCatalog.Discounts` but without the `usage` field, + * which is not applicable to flat fee charges. + */ +export interface ChargeFlatFeeDiscounts { + /** Percentage discount applied to the price (0–100). */ + percentage?: number +} + +/** Free price. */ +export interface PriceFree { + /** The type of the price. */ + type: 'free' +} + +/** The entitlement template of a static entitlement. */ +export interface RateCardStaticEntitlement { + /** The type of the entitlement template. */ + type: 'static' + /** + * The entitlement config as a JSON object. Returned when checking entitlement + * access; useful for configuring fine-grained access settings implemented in your + * own system. + */ + config: unknown +} + +/** The entitlement template of a boolean entitlement. */ +export interface RateCardBooleanEntitlement { + /** The type of the entitlement template. */ + type: 'boolean' +} + +/** Model for installing an app from the catalog with an API key. */ +export interface InstallAppStripeWithApiKey { + /** Type of the app. */ + type: 'stripe' + /** Name of the app. */ + name: string + /** + * If true, a billing profile will be created for the app. The Stripe app will be + * also set as the default billing profile if the current default is a Sandbox app. + */ + createBillingProfile: boolean + /** API key for the app. */ + apiKey: string +} + +/** Base model for installing an app from the catalog. */ +export interface InstallAppSandbox { + /** Type of the app. */ + type: 'sandbox' + /** Name of the app. */ + name: string + /** + * If true, a billing profile will be created for the app. The Stripe app will be + * also set as the default billing profile if the current default is a Sandbox app. + */ + createBillingProfile: boolean +} + +/** Base model for installing an app from the catalog. */ +export interface InstallAppExternalInvoicing { + /** Type of the app. */ + type: 'external_invoicing' + /** Name of the app. */ + name: string + /** + * If true, a billing profile will be created for the app. The Stripe app will be + * also set as the default billing profile if the current default is a Sandbox app. + */ + createBillingProfile: boolean +} + +/** + * BillingWorkflowCollectionAlignmentSubscription specifies the alignment for + * collecting the pending line items into an invoice. + */ +export interface WorkflowCollectionAlignmentSubscription { + /** The type of alignment. */ + type: 'subscription' +} + +/** + * Payment settings for a billing workflow when the collection method is charge + * automatically. + */ +export interface WorkflowPaymentChargeAutomaticallySettings { + /** The collection method for the invoice. */ + collectionMethod: 'charge_automatically' +} + +/** + * Payment settings for a billing workflow when the collection method is send + * invoice. + */ +export interface WorkflowPaymentSendInvoiceSettings { + /** The collection method for the invoice. */ + collectionMethod: 'send_invoice' + /** + * The period after which the invoice is due. With some payment solutions it's only + * applicable for manual collection method. + */ + dueAfter: string +} + +/** External identifiers assigned to an invoice by third-party systems. */ +export interface InvoiceExternalReferences { + /** The ID assigned by the external invoicing app (e.g. Stripe invoice ID). */ + invoicingId?: string + /** The ID assigned by the external payment app (e.g. Stripe payment intent ID). */ + paymentId?: string +} + +/** Details about an available invoice action including the resulting state. */ +export interface InvoiceAvailableActionDetails { + /** The extended status the invoice will transition to after performing this action. */ + resultingState: string +} + +/** + * Invoice-level invoicing settings. + * + * A subset of BillingWorkflowInvoicingSettings limited to fields that are + * meaningful per-invoice. progressive_billing is omitted as it is a gather-time / + * profile-level decision. + */ +export interface InvoiceWorkflowInvoicingSettings { + /** Whether to automatically issue the invoice after the draft_period has passed. */ + autoAdvance: boolean + /** The period for the invoice to be kept in draft status for manual reviews. */ + draftPeriod: string + /** The period after which the invoice is considered overdue if not paid. */ + dueAfter?: string +} + +/** External identifiers for an invoice line item assigned by third-party systems. */ +export interface InvoiceLineExternalReferences { + /** The ID assigned by the external invoicing app. */ + invoicingId?: string +} + +/** + * Labels store metadata of an entity that can be used for filtering an entity list + * or for searching across entity types. + * + * Keys must be of length 1-63 characters, and cannot start with "kong", "konnect", + * "mesh", "kic", or "\_". + */ +export type UpdateLabels = Record + +/** + * Invoice-level invoicing settings. + * + * A subset of BillingWorkflowInvoicingSettings limited to fields that are + * meaningful per-invoice. progressive_billing is omitted as it is a gather-time / + * profile-level decision. + */ +export interface UpdateBillingInvoiceWorkflowInvoicingSettings { + /** Whether to automatically issue the invoice after the draft_period has passed. */ + autoAdvance: boolean + /** The period for the invoice to be kept in draft status for manual reviews. */ + draftPeriod: string +} + +/** + * Payment settings for a billing workflow when the collection method is charge + * automatically. + */ +export interface UpdateBillingWorkflowPaymentChargeAutomaticallySettings { + /** The collection method for the invoice. */ + collectionMethod: 'charge_automatically' +} + +/** + * Payment settings for a billing workflow when the collection method is send + * invoice. + */ +export interface UpdateBillingWorkflowPaymentSendInvoiceSettings { + /** The collection method for the invoice. */ + collectionMethod: 'send_invoice' + /** + * The period after which the invoice is due. With some payment solutions it's only + * applicable for manual collection method. + */ + dueAfter: string +} + +/** Free price. */ +export interface UpdatePriceFree { + /** The type of the price. */ + type: 'free' +} + +/** LLM Provider */ +export interface LlmCostProvider { + /** Identifier of the provider, e.g., "openai", "anthropic". */ + id: string + /** Name of the provider, e.g., "OpenAI", "Anthropic". */ + name: string +} + +/** LLM Model */ +export interface LlmCostModel { + /** Identifier of the model, e.g., "gpt-4", "claude-3-5-sonnet". */ + id: string + /** Name of the model, e.g., "GPT-4", "Claude 3.5 Sonnet". */ + name: string +} + +/** Validation errors providing detailed description of the issue. */ +export interface ProductCatalogValidationError { + /** Machine-readable error code. */ + code: string + /** Human-readable description of the error. */ + message: string + /** Additional structured context. */ + attributes?: Record + /** The path to the field. */ + field: string +} + +/** List of customer identifiers to evaluate access for. */ +export interface GovernanceQueryRequestCustomers { + /** + * Each entry can be a customer `key` or a usage-attribution subject `key`. + * Identifiers that cannot be resolved to a customer are reported in the response + * `errors` array. + */ + keys: string[] +} + +/** + * Optional list of feature keys to evaluate access for. If omitted, all features + * available in the organization are returned. Providing this list is recommended + * to reduce the response size and the load on the backend services. + */ +export interface GovernanceQueryRequestFeatures { + /** List of feature keys to evaluate access for. */ + keys: string[] +} + +/** + * A query filter for an integer attribute. Operators are mutually exclusive, only + * one operator is allowed at a time. + */ +export interface QueryFilterInteger { + /** The attribute equals the provided value. */ + eq?: number + /** The attribute does not equal the provided value. */ + neq?: number + /** The attribute is one of the provided values. */ + in?: number[] + /** The attribute is not one of the provided values. */ + nin?: number[] + /** The attribute is greater than the provided value. */ + gt?: number + /** The attribute is greater than or equal to the provided value. */ + gte?: number + /** The attribute is less than the provided value. */ + lt?: number + /** The attribute is less than or equal to the provided value. */ + lte?: number + /** Combines the provided filters with a logical AND. */ + and?: QueryFilterInteger[] + /** Combines the provided filters with a logical OR. */ + or?: QueryFilterInteger[] +} + +/** + * A query filter for a float attribute. Operators are mutually exclusive, only one + * operator is allowed at a time. + */ +export interface QueryFilterFloat { + /** The attribute is greater than the provided value. */ + gt?: number + /** The attribute is greater than or equal to the provided value. */ + gte?: number + /** The attribute is less than the provided value. */ + lt?: number + /** The attribute is less than or equal to the provided value. */ + lte?: number + /** Combines the provided filters with a logical AND. */ + and?: QueryFilterFloat[] + /** Combines the provided filters with a logical OR. */ + or?: QueryFilterFloat[] +} + +/** + * A query filter for a boolean attribute. Operators are mutually exclusive, only + * one operator is allowed at a time. + */ +export interface QueryFilterBoolean { + /** The attribute equals the provided value. */ + eq?: boolean +} + +/** Page pagination query. */ +export interface PagePaginationQuery { + /** Determines which page of the collection to retrieve. */ + page?: { size?: number; number?: number } +} + +/** + * Public labels store information about an entity that can be used for filtering a + * list of objects. + */ +export type PublicLabels = Record + +/** + * The system account access token is meant for automations and integrations that + * are not directly associated with a human identity. + */ +export interface SystemAccountAccessToken { + /** Http authentication */ + type: 'http' + /** bearer auth scheme */ + scheme: 'Bearer' +} + +/** + * The personal access token is meant to be used as an alternative to basic-auth + * when accessing Konnect via APIs. + */ +export interface PersonalAccessToken { + /** Http authentication */ + type: 'http' + /** bearer auth scheme */ + scheme: 'Bearer' +} + +/** + * The Konnect access token is meant to be used by the Konnect dashboard and the + * decK CLI authenticate with. + */ +export interface KonnectAccessToken { + /** Http authentication */ + type: 'http' + /** bearer auth scheme */ + scheme: 'Bearer' +} + +/** Meter update request. */ +export interface UpdateMeterRequest { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name?: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** + * Named JSONPath expressions to extract the group by values from the event data. + * + * Keys must be unique and consist only alphanumeric and underscore characters. + */ + dimensions?: Record +} + +/** Stripe customer data. */ +export interface AppCustomerDataStripe { + /** The Stripe customer ID used. */ + customerId?: string + /** The Stripe default payment method ID. */ + defaultPaymentMethodId?: string + /** Labels for this Stripe integration on the customer. */ + labels?: Labels +} + +/** External invoicing customer data. */ +export interface AppCustomerDataExternalInvoicing { + /** Labels for this external invoicing integration on the customer. */ + labels?: Labels +} + +/** Currency describes a currency supported by the billing system. */ +export interface CurrencyFiat { + /** The type of the currency. */ + type: 'fiat' + /** + * The name of the currency. It should be a human-readable string that represents + * the name of the currency, such as "US Dollar" or "Euro". + */ + name: string + /** + * The symbol of the currency. It should be a string that represents the symbol of + * the currency, such as "$" for US Dollar or "€" for Euro. + */ + symbol?: string + code: string +} + +/** Filter options for listing cost bases. */ +export interface ListCostBasesParamsFilter { + /** Filter cost bases by fiat currency code. */ + fiatCode?: string +} + +/** Monetary amount in a specific currency. */ +export interface CurrencyAmount { + amount: string + currency: string +} + +/** Flat price. */ +export interface PriceFlat { + /** The type of the price. */ + type: 'flat' + /** The amount of the flat price. */ + amount: string +} + +/** + * Unit price. + * + * Charges a fixed rate per billing unit. When UnitConfig is present on the rate + * card, billing units are the converted quantities (e.g. GB instead of bytes). + */ +export interface PriceUnit { + /** The type of the price. */ + type: 'unit' + /** The amount of the unit price. */ + amount: string +} + +/** Discount configuration for a rate card. */ +export interface RateCardDiscounts { + /** Percentage discount applied to the price (0–100). */ + percentage?: number + /** + * Number of usage units granted free before billing starts. Only applies to + * usage-based lines (not flat fees). Usage is treated as zero until this amount is + * exhausted. + */ + usage?: string +} + +/** Totals contains the summaries of all calculations for a billing resource. */ +export interface Totals { + /** The total value of the resource before taxes, discounts and commitments. */ + amount: string + /** The total tax amount applied to the resource. */ + taxesTotal: string + /** The total tax amount already included in the resource amount. */ + taxesInclusiveTotal: string + /** The total tax amount added on top of the resource amount. */ + taxesExclusiveTotal: string + /** The total amount contributed by additional charges. */ + chargesTotal: string + /** The total amount deducted through discounts. */ + discountsTotal: string + /** The total amount deducted through credits before taxes are applied. */ + creditsTotal: string + /** The final total value of the resource after taxes, discounts and commitments. */ + total: string +} + +/** + * Spend commitments for a rate card. The customer is committed to spend at least + * the minimum amount and at most the maximum amount. + */ +export interface SpendCommitments { + /** The customer is committed to spend at least the amount. */ + minimumAmount?: string + /** The customer is limited to spend at most the amount. */ + maximumAmount?: string +} + +/** A credit allocation applied to an invoice line item. */ +export interface InvoiceLineCreditsApplied { + /** The monetary amount credited. */ + amount: string + /** Optional human-readable description of the credit allocation. */ + description?: string +} + +/** Flat price. */ +export interface UpdatePriceFlat { + /** The type of the price. */ + type: 'flat' + /** The amount of the flat price. */ + amount: string +} + +/** + * Unit price. + * + * Charges a fixed rate per billing unit. When UnitConfig is present on the rate + * card, billing units are the converted quantities (e.g. GB instead of bytes). + */ +export interface UpdatePriceUnit { + /** The type of the price. */ + type: 'unit' + /** The amount of the unit price. */ + amount: string +} + +/** Discount configuration for a rate card. */ +export interface UpdateDiscounts { + /** Percentage discount applied to the price (0–100). */ + percentage?: number + /** + * Number of usage units granted free before billing starts. Only applies to + * usage-based lines (not flat fees). Usage is treated as zero until this amount is + * exhausted. + */ + usage?: string +} + +/** A fixed per-unit cost amount. */ +export interface FeatureManualUnitCost { + /** The type discriminator for manual unit cost. */ + type: 'manual' + /** Fixed per-unit cost amount in USD. */ + amount: string +} + +/** Resolved per-token pricing from the LLM cost database. */ +export interface FeatureLlmUnitCostPricing { + /** Cost per input token in USD. */ + inputPerToken: string + /** Cost per output token in USD. */ + outputPerToken: string + /** Cost per cache read token in USD. */ + cacheReadPerToken?: string + /** Cost per reasoning token in USD. */ + reasoningPerToken?: string + /** Cost per cache write token in USD. */ + cacheWritePerToken?: string +} + +/** Token pricing for an LLM model, denominated per token. */ +export interface LlmCostModelPricing { + /** Input price per token (USD). */ + inputPerToken: string + /** Output price per token (USD). */ + outputPerToken: string + /** Cache read price per token (USD). */ + cacheReadPerToken?: string + /** Cache write price per token (USD). */ + cacheWritePerToken?: string + /** Reasoning output price per token (USD). */ + reasoningPerToken?: string +} + +/** + * A query filter for a numeric attribute. Operators are mutually exclusive, only + * one operator is allowed at a time. + */ +export interface QueryFilterNumeric { + /** The attribute is greater than the provided value. */ + gt?: string + /** The attribute is greater than or equal to the provided value. */ + gte?: string + /** The attribute is less than the provided value. */ + lt?: string + /** The attribute is less than or equal to the provided value. */ + lte?: string + /** Combines the provided filters with a logical AND. */ + and?: QueryFilterNumeric[] + /** Combines the provided filters with a logical OR. */ + or?: QueryFilterNumeric[] +} + +/** Cursor page query. */ +export interface CursorPaginationQuery { + page?: CursorPaginationQueryPage +} + +/** Filter options for listing meters. */ +export interface ListMetersParamsFilter { + /** Filter meters by key. */ + key?: StringFieldFilter + /** Filter meters by name. */ + name?: StringFieldFilter +} + +/** Filter options for listing LLM cost prices. */ +export interface ListLlmCostPricesParamsFilter { + /** Filter by provider. e.g. ?filter[provider][eq]=openai */ + provider?: StringFieldFilter + /** Filter by model ID. e.g. ?filter[model_id][eq]=gpt-4 */ + modelId?: StringFieldFilter + /** Filter by model name. e.g. ?filter[model_name][contains]=gpt */ + modelName?: StringFieldFilter + /** Filter by currency code. e.g. ?filter[currency][eq]=USD */ + currency?: StringFieldFilter + /** Filter by source. e.g. ?filter[source][eq]=system */ + source?: StringFieldFilter +} + +/** + * Filters on the resource's `labels` field. + * + * The schema is a map keyed by the label name; each value is a + * `StringFieldFilter`. Both deepObject forms are accepted: + * `filter[labels][key]=value` (nested) and `filter[labels.key]=value` + * (dot-notation). + */ +export type LabelsFieldFilter = Record + +/** Customer reference. */ +export interface CustomerReference { + id: string +} + +/** Billing profile reference. */ +export interface ProfileReference { + /** The ID of the billing profile. */ + id: string +} + +/** TaxCode reference. */ +export interface CreateResourceReference { + id: string +} + +/** TaxCode reference. */ +export interface TaxCodeReference { + id: string +} + +/** Invoice references for the grant. */ +export interface CreditGrantInvoiceReference { + /** Identifier of the invoice associated with the grant. */ + id?: string + /** Identifier of the invoice line associated with the grant. */ + line?: { id: string } +} + +/** Customer reference. */ +export interface BillingCustomerReference { + /** The ID of the customer. */ + id: string +} + +/** + * Subscription reference represents a reference to the specific subscription item + * this entity represents. + */ +export interface SubscriptionReference { + /** The ID of the subscription. */ + id: string + /** The phase of the subscription. */ + phase: { id: string; item: { id: string } } +} + +/** Addon reference. */ +export interface AddonReference { + id: string +} + +/** Feature reference. */ +export interface FeatureReference { + id: string +} + +/** App reference. */ +export interface AppReference { + /** The ID of the app. */ + id: string +} + +/** Reference to a charge associated with an invoice line. */ +export interface ChargeReference { + /** Unique identifier for the charge. */ + id: string +} + +/** TaxCode reference. */ +export interface UpdateResourceReference { + id: string +} + +/** Metering event following the CloudEvents specification. */ +export interface Event { + /** Identifies the event. */ + id: string + /** Identifies the context in which an event happened. */ + source: string + /** The version of the CloudEvents specification which the event uses. */ + specversion: string + /** + * Contains a value describing the type of event related to the originating + * occurrence. + */ + type: string + /** + * Content type of the CloudEvents data value. Only the value "application/json" is + * allowed over HTTP. + */ + datacontenttype?: 'application/json' | null + /** Identifies the schema that data adheres to. */ + dataschema?: string | null + /** + * Describes the subject of the event in the context of the event producer + * (identified by source). + */ + subject: string + /** Timestamp of when the occurrence happened. Must adhere to RFC 3339. */ + time?: Date | null + /** The event payload. Optional, if present it must be a JSON object. */ + data?: Record | null +} + +/** A row in the result of a meter query. */ +export interface MeterQueryRow { + /** The aggregated value. */ + value: string + /** The start of the time bucket the value is aggregated over. */ + from: Date + /** The end of the time bucket the value is aggregated over. */ + to: Date + /** + * The dimensions the value is aggregated over. `subject` and `customer_id` are + * reserved dimensions. + */ + dimensions: Record +} + +/** + * Result of creating a + * [Stripe Customer Portal Session](https://docs.stripe.com/api/customer_portal/sessions/object). + * + * Contains all the information needed to redirect the customer to the Stripe + * Customer Portal. + */ +export interface AppStripeCreateCustomerPortalSessionResult { + /** + * The ID of the customer portal session. + * + * See: + * https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-id + */ + id: string + /** The ID of the stripe customer. */ + stripeCustomerId: string + /** + * Configuration used to customize the customer portal. + * + * See: + * https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-configuration + */ + configurationId: string + /** + * Livemode. + * + * See: + * https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-livemode + */ + livemode: boolean + /** + * Created at. + * + * See: + * https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-created + */ + createdAt: Date + /** + * Return URL. + * + * See: + * https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-return_url + */ + returnUrl: string + /** + * The IETF language tag of the locale customer portal is displayed in. + * + * See: + * https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-locale + */ + locale: string + /** + * The URL to redirect the customer to after they have completed their requested + * actions. + */ + url: string +} + +/** + * A period with defined start and end dates. + * + * The period is always inclusive at the start and exclusive at the end. + */ +export interface ClosedPeriod { + /** + * The start of the period. + * + * The period is inclusive at the start. + */ + from: Date + /** + * The end of the period. + * + * The period is exclusive at the end. + */ + to: Date +} + +/** A subscription add-on event. */ +export interface SubscriptionAddonTimelineSegment { + /** An ISO-8601 timestamp representation of the cadence start of the resource. */ + activeFrom: Date + /** An ISO-8601 timestamp representation of the cadence end of the resource. */ + activeTo?: Date + /** The quantity of the add-on for the given period. */ + quantity: number +} + +/** + * A period with defined start and end dates. + * + * The period is always inclusive at the start and exclusive at the end. + */ +export interface UpdateClosedPeriod { + /** + * The start of the period. + * + * The period is inclusive at the start. + */ + from: Date + /** + * The end of the period. + * + * The period is exclusive at the end. + */ + to: Date +} + +/** Describes currency basis supported by billing system. */ +export interface CostBasis { + id: string + /** The fiat currency code for the cost basis. */ + fiatCode: string + /** The cost rate for the currency. */ + rate: string + /** + * An ISO-8601 timestamp representation of the date from which the cost basis is + * effective. If not provided, it will be effective immediately and will be set to + * `now` by the system. + */ + effectiveFrom?: Date + /** + * An ISO-8601 timestamp representation of the date until which the cost basis is + * effective. If provided, it must be later than `effective_from`. If not provided, + * it remains effective until superseded. + */ + effectiveTo?: Date + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date +} + +/** CostBasis create request. */ +export interface CreateCostBasisRequest { + /** The fiat currency code for the cost basis. */ + fiatCode: string + /** The cost rate for the currency. */ + rate: string + /** + * An ISO-8601 timestamp representation of the date from which the cost basis is + * effective. If not provided, it will be effective immediately and will be set to + * `now` by the system. + */ + effectiveFrom?: Date + /** + * An ISO-8601 timestamp representation of the date until which the cost basis is + * effective. If provided, it must be later than `effective_from`. If not provided, + * it remains effective until superseded. + */ + effectiveTo?: Date +} + +/** A row in the result of a feature cost query. */ +export interface FeatureCostQueryRow { + /** The metered usage value for the period. */ + usage: string + /** + * The computed cost amount (usage × unit cost). Null when pricing is not available + * for the given combination of dimensions. + */ + cost: string | null + /** The currency code of the cost amount. */ + currency: string + /** + * Detail message when cost amount is null, explaining why the cost could not be + * resolved. + */ + detail?: string + /** The start of the time bucket the value is aggregated over. */ + from: Date + /** The end of the time bucket the value is aggregated over. */ + to: Date + /** + * The dimensions the value is aggregated over. `subject` and `customer_id` are + * reserved dimensions. + */ + dimensions: Record +} + +/** Represents common fields of resources. */ +export interface Resource { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date +} + +/** Represents common fields of immutable resources. */ +export interface ResourceImmutable { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date +} + +/** + * A query filter for a time attribute. Operators are mutually exclusive, only one + * operator is allowed at a time. + */ +export interface QueryFilterDateTime { + /** The attribute is greater than the provided value. */ + gt?: Date + /** The attribute is greater than or equal to the provided value. */ + gte?: Date + /** The attribute is less than the provided value. */ + lt?: Date + /** The attribute is less than or equal to the provided value. */ + lte?: Date + /** Combines the provided filters with a logical AND. */ + and?: QueryFilterDateTime[] + /** Combines the provided filters with a logical OR. */ + or?: QueryFilterDateTime[] +} + +/** Cursor pagination metadata. */ +export interface CursorMeta { + /** Page metadata. */ + page: CursorMetaPage +} + +/** A parameter that failed a standard validation rule. */ +export interface InvalidParameterStandard { + /** The name of the field that failed validation. */ + field: string + /** The validation rule that was violated. */ + rule?: + | 'required' + | 'is_array' + | 'is_base64' + | 'is_boolean' + | 'is_date_time' + | 'is_integer' + | 'is_null' + | 'is_number' + | 'is_object' + | 'is_string' + | 'is_uuid' + | 'is_fqdn' + | 'is_arn' + | 'unknown_property' + | 'missing_reference' + | 'is_label' + | 'matches_regex' + | 'invalid' + | 'is_supported_network_availability_zone_list' + | 'is_supported_network_cidr_block' + | 'is_supported_provider_region' + | 'type' + /** The part of the request the field came from (e.g. `body`, `query`). */ + source?: string + /** A human readable explanation of why the field failed validation. */ + reason: string +} + +/** A parameter that failed a minimum-length (or minimum-value) validation rule. */ +export interface InvalidParameterMinimumLength { + /** The name of the field that failed validation. */ + field: string + /** The minimum validation rule that was violated. */ + rule: + | 'min_length' + | 'min_digits' + | 'min_lowercase' + | 'min_uppercase' + | 'min_symbols' + | 'min_items' + | 'min' + /** The minimum allowed value or length. */ + minimum: number + /** The part of the request the field came from (e.g. `body`, `query`). */ + source?: string + /** A human readable explanation of why the field failed validation. */ + reason: string +} + +/** A parameter that failed a maximum-length (or maximum-value) validation rule. */ +export interface InvalidParameterMaximumLength { + /** The name of the field that failed validation. */ + field: string + /** The maximum validation rule that was violated. */ + rule: 'max_length' | 'max_items' | 'max' + /** The maximum allowed value or length. */ + maximum: number + /** The part of the request the field came from (e.g. `body`, `query`). */ + source?: string + /** A human readable explanation of why the field failed validation. */ + reason: string +} + +/** A parameter whose value was not one of the allowed choices. */ +export interface InvalidParameterChoiceItem { + /** The name of the field that failed validation. */ + field: string + /** The enum validation rule that was violated. */ + rule: 'enum' + /** A human readable explanation of why the field failed validation. */ + reason: string + /** The allowed choices for the field. */ + choices: unknown[] + /** The part of the request the field came from (e.g. `body`, `query`). */ + source?: string +} + +/** A parameter that failed a dependent-fields validation rule. */ +export interface InvalidParameterDependentItem { + /** The name of the field that failed validation. */ + field: string + /** The dependent-fields validation rule that was violated. */ + rule: 'dependent_fields' + /** A human readable explanation of why the field failed validation. */ + reason: string + /** The fields that this field depends on. */ + dependents: unknown[] + /** The part of the request the field came from (e.g. `body`, `query`). */ + source?: string +} + +/** Unauthorized. */ +export interface Unauthorized extends BaseError {} + +/** Forbidden. */ +export interface Forbidden extends BaseError {} + +/** Not Found. */ +export interface NotFound extends BaseError {} + +/** Gone. */ +export interface Gone extends BaseError {} + +/** Conflict. */ +export interface Conflict extends BaseError {} + +/** Payload Too Large. */ +export interface PayloadTooLarge extends BaseError {} + +/** Unsupported Media Type. */ +export interface UnsupportedMediaType extends BaseError {} + +/** Unprocessable Content. */ +export interface UnprocessableContent extends BaseError {} + +/** Too Many Requests. */ +export interface TooManyRequests extends BaseError {} + +/** Internal Server Error. */ +export interface Internal extends BaseError {} + +/** Not Implemented. */ +export interface NotImplemented extends BaseError {} + +/** Not Available. */ +export interface NotAvailable extends BaseError {} + +/** Filters for the credit grant. */ +export interface CreateCreditGrantFilters { + /** + * Limit the credit grant to specific features. If no features are specified, the + * credit grant can be used for any feature. + */ + features?: string[] +} + +/** Filters for the credit grant. */ +export interface CreditGrantFilters { + /** + * Limit the credit grant to specific features. If no features are specified, the + * credit grant can be used for any feature. + */ + features?: string[] +} + +/** PlanAddon upsert request. */ +export interface UpsertPlanAddonRequest { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** The key of the plan phase from which the add-on becomes available for purchase. */ + fromPlanPhase: string + /** + * The maximum number of times the add-on can be purchased for the plan. For + * single-instance add-ons this field must be omitted. For multi-instance add-ons + * when omitted, unlimited quantity can be purchased. + */ + maxQuantity?: number +} + +/** Represents common fields of resources with a key. */ +export interface ResourceWithKey { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + key: string +} + +/** Meter create request. */ +export interface CreateMeterRequest { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + key: string + /** The aggregation type to use for the meter. */ + aggregation: MeterAggregation + /** The event type to include in the aggregation. */ + eventType: string + /** + * The date since the meter should include events. Useful to skip old events. If + * not specified, all historical events are included. + */ + eventsFrom?: Date + /** + * JSONPath expression to extract the value from the ingested event's data + * property. + * + * The ingested value for sum, avg, min, and max aggregations is a number or a + * string that can be parsed to a number. + * + * For unique_count aggregation, the ingested value must be a string. For count + * aggregation the value_property is ignored. + */ + valueProperty?: string + /** + * Named JSONPath expressions to extract the group by values from the event data. + * + * Keys must be unique and consist only alphanumeric and underscore characters. + */ + dimensions?: Record +} + +/** A meter is a configuration that defines how to match and aggregate events. */ +export interface Meter { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + key: string + /** The aggregation type to use for the meter. */ + aggregation: MeterAggregation + /** The event type to include in the aggregation. */ + eventType: string + /** + * The date since the meter should include events. Useful to skip old events. If + * not specified, all historical events are included. + */ + eventsFrom?: Date + /** + * JSONPath expression to extract the value from the ingested event's data + * property. + * + * The ingested value for sum, avg, min, and max aggregations is a number or a + * string that can be parsed to a number. + * + * For unique_count aggregation, the ingested value must be a string. For count + * aggregation the value_property is ignored. + */ + valueProperty?: string + /** + * Named JSONPath expressions to extract the group by values from the event data. + * + * Keys must be unique and consist only alphanumeric and underscore characters. + */ + dimensions?: Record +} + +/** Pagination metadata. */ +export interface PaginatedMeta { + /** Page metadata. */ + page: PageMeta +} + +/** + * A query filter for an item in a string map attribute. Operators are mutually + * exclusive, only one operator is allowed at a time. + */ +export interface QueryFilterStringMapItem { + /** The attribute exists. */ + exists?: boolean + /** The attribute equals the provided value. */ + eq?: string + /** The attribute does not equal the provided value. */ + neq?: string + /** The attribute is one of the provided values. */ + in?: string[] + /** The attribute is not one of the provided values. */ + nin?: string[] + /** The attribute contains the provided value. */ + contains?: string + /** The attribute does not contain the provided value. */ + ncontains?: string + /** Combines the provided filters with a logical AND. */ + and?: QueryFilterString[] + /** Combines the provided filters with a logical OR. */ + or?: QueryFilterString[] +} + +/** Customer reference by external key. */ +export interface CustomerKeyReference { + /** The external key of the customer. */ + key: string +} + +/** + * Mapping to attribute metered usage to the customer. One customer can have zero + * or more subjects, but one subject can only belong to one customer. + */ +export interface CustomerUsageAttribution { + /** + * The subjects that are attributed to the customer. Can be empty when no usage + * event subjects are associated with the customer. + */ + subjectKeys: string[] +} + +/** + * Mapping to attribute metered usage to the customer. One customer can have zero + * or more subjects, but one subject can only belong to one customer. + */ +export interface UpdateCustomerUsageAttribution { + /** + * The subjects that are attributed to the customer. Can be empty when no usage + * event subjects are associated with the customer. + */ + subjectKeys: string[] +} + +/** Address */ +export interface Address { + /** + * Country code in [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) + * alpha-2 format. + */ + country?: string + /** Postal code. */ + postalCode?: string + /** State or province. */ + state?: string + /** City. */ + city?: string + /** First line of the address. */ + line1?: string + /** Second line of the address. */ + line2?: string + /** Phone number. */ + phoneNumber?: string +} + +/** Address */ +export interface UpdateAddress { + /** + * Country code in [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) + * alpha-2 format. + */ + country?: string + /** Postal code. */ + postalCode?: string + /** State or province. */ + state?: string + /** City. */ + city?: string + /** First line of the address. */ + line1?: string + /** Second line of the address. */ + line2?: string + /** Phone number. */ + phoneNumber?: string +} + +/** Controls which customer fields can be updated by the checkout session. */ +export interface AppStripeCreateCheckoutSessionCustomerUpdate { + /** + * Whether to save the billing address to customer.address. + * + * Defaults to "never". + */ + address: 'auto' | 'never' + /** + * Whether to save the customer name to customer.name. + * + * Defaults to "never". + */ + name: 'auto' | 'never' + /** + * Whether to save shipping information to customer.shipping. + * + * Defaults to "never". + */ + shipping: 'auto' | 'never' +} + +/** Payment method reuse agreement configuration. */ +export interface AppStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreement { + /** Position and visibility of the payment method reuse agreement. */ + position?: 'auto' | 'hidden' +} + +/** Tax ID collection configuration for checkout sessions. */ +export interface AppStripeCreateCheckoutSessionTaxIdCollection { + /** + * Enable tax ID collection during checkout. + * + * Defaults to false. + */ + enabled: boolean + /** + * Whether tax ID collection is required. + * + * Defaults to "never". + */ + required: 'if_supported' | 'never' +} + +/** + * Result of creating a Stripe Checkout Session. + * + * Contains all the information needed to redirect customers to the checkout or + * initialize an embedded checkout flow. + */ +export interface AppStripeCreateCheckoutSessionResult { + /** The customer ID in the billing system. */ + customerId: string + /** The Stripe customer ID. */ + stripeCustomerId: string + /** The Stripe checkout session ID. */ + sessionId: string + /** The setup intent ID created for collecting the payment method. */ + setupIntentId: string + /** + * Client secret for initializing Stripe.js on the client side. + * + * Required for embedded checkout sessions. See: + * https://docs.stripe.com/payments/checkout/custom-success-page + */ + clientSecret?: string + /** + * The client reference ID provided in the request. + * + * Useful for reconciling the session with your internal systems. + */ + clientReferenceId?: string + /** Customer's email address if provided to Stripe. */ + customerEmail?: string + /** Currency code for the checkout session. */ + currency?: string + /** Timestamp when the checkout session was created. */ + createdAt: Date + /** Timestamp when the checkout session will expire. */ + expiresAt?: Date + /** Metadata attached to the checkout session. */ + metadata?: Record + /** + * The status of the checkout session. + * + * See: + * https://docs.stripe.com/api/checkout/sessions/object#checkout_session_object-status + */ + status?: string + /** URL to redirect customers to the checkout page (for hosted mode). */ + url?: string + /** + * Mode of the checkout session. + * + * Currently only "setup" mode is supported for collecting payment methods. + */ + mode: 'setup' + /** The cancel URL where customers are redirected if they cancel. */ + cancelUrl?: string + /** The success URL where customers are redirected after completion. */ + successUrl?: string + /** The return URL for embedded sessions after authentication. */ + returnUrl?: string +} + +/** + * Request to create a Stripe Customer Portal Session for the customer. + * + * Useful to redirect the customer to the Stripe Customer Portal to manage their + * payment methods, change their billing address and access their invoice history. + * Only returns URL if the customer billing profile is linked to a stripe app and + * customer. + */ +export interface CustomerStripeCreateCustomerPortalSessionRequest { + /** Options for configuring the Stripe Customer Portal Session. */ + stripeOptions: AppStripeCreateCustomerPortalSessionOptions +} + +/** Entitlement access result. */ +export interface EntitlementAccessResult { + /** The type of the entitlement. */ + type: 'metered' | 'static' | 'boolean' + /** The feature key of the entitlement. */ + featureKey: string + /** + * Whether the customer has access to the feature. Always true for `boolean` and + * `static` entitlements. Depends on balance for `metered` entitlements. + */ + hasAccess: boolean + /** + * Only available for static entitlements. Config is the JSON parsable + * configuration of the entitlement. Useful to describe per customer configuration. + */ + config?: string +} + +/** Purchase and payment terms of the grant. */ +export interface CreateCreditGrantPurchase { + /** Currency of the purchase amount. */ + currency: string + /** + * Cost basis per credit unit used to calculate the purchase amount. + * + * If `per_unit_cost_basis` is 0.50 and credit amount is $100.00, the total charge + * is $50.00. The value must be greater than 0. If the cost basis is 0, use + * `funding_method=none` instead. + * + * Defaults to 1.0. + */ + perUnitCostBasis: string + /** + * Controls when credits become available for consumption. + * + * Defaults to `on_creation`. + */ + availabilityPolicy: 'on_creation' +} + +/** The entitlement template of a metered entitlement. */ +export interface RateCardMeteredEntitlement { + /** The type of the entitlement template. */ + type: 'metered' + /** + * If soft limit is true, the subject can use the feature even if the entitlement + * is exhausted; access remains granted. + */ + isSoftLimit: boolean + /** + * The amount of usage granted each usage period, in the feature's unit. Usage is + * counted against this allowance and the balance resets every usage period. When + * `is_soft_limit` is true the subject keeps access after the limit is reached; + * otherwise access is denied once the allowance is exhausted. + */ + limit?: number + /** + * The reset interval of the metered entitlement in ISO8601 format. Defaults to the + * billing cadence of the rate card. + */ + usagePeriod?: string +} + +/** Recurring period with an anchor and an interval. */ +export interface RecurringPeriod { + /** A date-time anchor to base the recurring period on. */ + anchor: Date + /** The interval duration in ISO 8601 format. */ + interval: string +} + +/** Purchase and payment terms of the grant. */ +export interface CreditGrantPurchase { + /** Currency of the purchase amount. */ + currency: string + /** + * Cost basis per credit unit used to calculate the purchase amount. + * + * If `per_unit_cost_basis` is 0.50 and credit amount is $100.00, the total charge + * is $50.00. The value must be greater than 0. If the cost basis is 0, use + * `funding_method=none` instead. + * + * Defaults to 1.0. + */ + perUnitCostBasis: string + /** The purchase amount. Calculated from `per_unit_cost_basis` and credit `amount`. */ + amount: string + /** + * Controls when credits become available for consumption. + * + * Defaults to `on_creation`. + */ + availabilityPolicy: 'on_creation' + /** Current payment settlement status. */ + settlementStatus?: 'pending' | 'authorized' | 'settled' +} + +/** + * Request body for updating the external payment settlement status of a credit + * grant. + */ +export interface UpdateCreditGrantExternalSettlementRequest { + /** The new payment settlement status. */ + status: 'pending' | 'authorized' | 'settled' +} + +/** Filter options for listing credit grants. */ +export interface ListCreditGrantsParamsFilter { + /** Filter credit grants by status. */ + status?: 'pending' | 'active' | 'expired' | 'voided' + /** Filter credit grants by currency. */ + currency?: string + /** Filter credit grants by key. */ + key?: StringFieldFilter +} + +/** Filter options for getting a credit balance. */ +export interface GetCreditBalanceParamsFilter { + /** Filter credit balance by currency. */ + currency?: StringFieldFilterExact + /** + * Filter credit balance by feature key. Omit to return the total portfolio value. + * Use `exists=false` to return only unrestricted balance. + */ + featureKey?: StringFieldFilter +} + +/** Filter options for listing charges. */ +export interface ListChargesParamsFilter { + /** + * Filter charges by status. + * + * Supported statuses are: + * + * - `created` + * - `active` + * - `final` + * - `deleted` + * + * If omitted, all statuses are returned except for `deleted`. + */ + status?: StringFieldFilterExact +} + +/** Filter options for listing plans. */ +export interface ListPlansParamsFilter { + key?: StringFieldFilter + name?: StringFieldFilter + status?: StringFieldFilterExact + currency?: StringFieldFilterExact +} + +/** Request body for voiding a credit grant. */ +export interface VoidCreditGrantRequest { + /** + * How voiding adjusts payment state related to the grant. + * + * Currently only `none` is supported: voiding does not adjust invoices, payment + * authorization, settlement, payment intents, or external collection state. If + * payment later completes, the original invoiced amount may still be collected. + */ + paymentAdjustment: 'none' +} + +/** Subscription create request. */ +export interface SubscriptionCreate { + labels?: Labels + /** + * Settlement mode for billing. + * + * Values: + * + * - `credit_then_invoice`: Credits are applied first, then any remainder is + * invoiced. + * - `credit_only`: Usage is settled exclusively against credits. + */ + settlementMode?: 'credit_then_invoice' | 'credit_only' + /** The customer to create the subscription for. */ + customer: { id?: string; key?: string } + /** The plan reference of the subscription. */ + plan: { id?: string; key?: string; version?: number } + /** + * A billing anchor is the fixed point in time that determines the subscription's + * recurring billing cycle. It affects when charges occur and how prorations are + * calculated. Common anchors: + * + * - Calendar month (1st of each month): `2025-01-01T00:00:00Z` + * - Subscription anniversary (day customer signed up) + * - Custom date (customer-specified day) + * + * If not provided, the subscription will be created with the subscription's + * creation time as the billing anchor. + */ + billingAnchor?: Date +} + +/** The proration configuration of the rate card. */ +export interface RateCardProrationConfiguration { + /** The proration mode of the rate card. */ + mode: 'no_proration' | 'prorate_prices' +} + +/** Subscription. */ +export interface Subscription { + id: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** The customer ID of the subscription. */ + customerId: string + /** The plan ID of the subscription. Set if subscription is created from a plan. */ + planId?: string + /** + * A billing anchor is the fixed point in time that determines the subscription's + * recurring billing cycle. It affects when charges occur and how prorations are + * calculated. Common anchors: + * + * - Calendar month (1st of each month): `2025-01-01T00:00:00Z` + * - Subscription anniversary (day customer signed up) + * - Custom date (customer-specified day) + */ + billingAnchor: Date + /** The status of the subscription. */ + status: 'active' | 'inactive' | 'canceled' | 'scheduled' + /** + * Settlement mode for billing. + * + * Values: + * + * - `credit_then_invoice`: Credits are applied first, then any remainder is + * invoiced. + * - `credit_only`: Usage is settled exclusively against credits. + */ + settlementMode?: 'credit_then_invoice' | 'credit_only' +} + +/** + * Unit conversion configuration. + * + * Transforms raw metered quantities into billing-ready units before pricing and + * entitlement evaluation. Applied at the rate card level so the same feature can + * be billed in different units across plans. + * + * Examples: + * + * - Meter bytes, bill GB: operation=divide, conversionFactor=1e9, + * rounding=ceiling, displayUnit="GB" + * - Meter seconds, bill hours: operation=divide, conversionFactor=3600, + * rounding=ceiling, displayUnit="hours" + * - Cost + 20% margin: operation=multiply, conversionFactor=1.2 + * - Bill per million tokens: operation=divide, conversionFactor=1e6, + * rounding=ceiling, displayUnit="M" + * + * v1 equivalents: + * + * - DynamicPrice(multiplier): operation=multiply, conversionFactor=multiplier + + * UnitPrice(amount=1) + * - PackagePrice(amount, quantityPerPkg): operation=divide, + * conversionFactor=quantityPerPkg, rounding=ceiling + UnitPrice(amount) + */ +export interface UnitConfig { + /** The arithmetic operation to apply to the raw metered quantity. */ + operation: 'divide' | 'multiply' + /** + * The factor used in the conversion operation. + * + * - For `divide`: `converted = raw / conversionFactor`. + * - For `multiply`: `converted = raw × conversionFactor`. + * + * Must be a positive non-zero value. + */ + conversionFactor: string + /** + * The rounding mode applied to the converted quantity for invoicing. + * + * Defaults to none (no rounding). Entitlement checks always use the precise + * (unrounded) value. + */ + rounding: 'ceiling' | 'floor' | 'half_up' | 'none' + /** + * The number of decimal places to retain after rounding. + * + * Only meaningful when rounding is not "none". Defaults to 0 (round to whole + * numbers). + */ + precision: number + /** + * A human-readable label for the converted unit shown on invoices and in the + * customer portal (e.g., "GB", "hours", "M tokens"). + * + * Optional. When omitted, no unit label is rendered. + */ + displayUnit?: string +} + +/** Mapping of app types to tax codes. */ +export interface TaxCodeAppMapping { + /** The app type that the tax code is associated with. */ + appType: 'sandbox' | 'stripe' | 'external_invoicing' + /** Tax code. */ + taxCode: string +} + +/** App capability describes a function that an App can perform. */ +export interface AppCapability { + /** Type of the capability. */ + type: + | 'report_usage' + | 'report_events' + | 'calculate_tax' + | 'invoice_customers' + | 'collect_payments' + /** Key of the capability. */ + key: string + /** Name of the capability. */ + name: string + /** Description of the capability. */ + description: string +} + +/** + * Identity stores the details required to identify an entity for tax purposes in a + * specific country. + */ +export interface PartyTaxIdentity { + /** Normalized tax identification code shown on the original identity document. */ + code?: string +} + +/** + * Identity stores the details required to identify an entity for tax purposes in a + * specific country. + */ +export interface UpdateBillingPartyTaxIdentity { + /** Normalized tax identification code shown on the original identity document. */ + code?: string +} + +/** Invoice settings for a billing workflow. */ +export interface WorkflowInvoicingSettings { + /** Whether to automatically issue the invoice after the draftPeriod has passed. */ + autoAdvance: boolean + /** The period for the invoice to be kept in draft status for manual reviews. */ + draftPeriod: string + /** Should progressive billing be allowed for this workflow? */ + progressiveBilling: boolean + /** Controls how subscription-ending shortened service periods are billed. */ + subscriptionEndProrationMode: 'bill_full_period' | 'bill_actual_period' +} + +/** + * A validation issue found during invoice processing. + * + * Converges on the same structure used by plan and subscription validation errors: + * a machine-readable `code`, a human-readable `message`, optional structured + * `attributes`, plus a `severity` and optional `field` path. + */ +export interface InvoiceValidationIssue { + /** Machine-readable error code. */ + code: string + /** Human-readable description of the error. */ + message: string + /** Additional structured context. */ + attributes?: Record + /** Severity of the validation issue. */ + severity: 'critical' | 'warning' + /** + * JSON path to the field that caused this validation issue, if applicable. + * + * For example: `lines/0/rate_card/price`. + */ + field?: string +} + +/** + * The set of state-transition actions available for an invoice in its current + * status. + * + * A field is present only when that action is permitted from the current state. + */ +export interface InvoiceAvailableActions { + /** Advance the invoice to the next workflow step. */ + advance?: InvoiceAvailableActionDetails + /** Approve the invoice for issuance. */ + approve?: InvoiceAvailableActionDetails + /** Delete the invoice. */ + delete?: InvoiceAvailableActionDetails + /** Retry a failed workflow step. */ + retry?: InvoiceAvailableActionDetails + /** Snapshot the current usage quantities. */ + snapshotQuantities?: InvoiceAvailableActionDetails +} + +/** A monetary amount discount applied to an invoice line item. */ +export interface InvoiceLineAmountDiscount { + /** Unique identifier for the discount. */ + id: string + /** The reason this discount was applied. */ + reason: 'maximum_spend' | 'ratecard_percentage' | 'ratecard_usage' + /** Optional human-readable description of the discount. */ + description?: string + /** External identifiers for this discount. */ + externalReferences?: InvoiceLineExternalReferences + /** The monetary amount deducted. */ + amount: string +} + +/** A usage quantity discount applied to an invoice line item. */ +export interface InvoiceLineUsageDiscount { + /** Unique identifier for the discount. */ + id: string + /** The reason this discount was applied. */ + reason: 'maximum_spend' | 'ratecard_percentage' | 'ratecard_usage' + /** Optional human-readable description of the discount. */ + description?: string + /** External identifiers for this discount. */ + externalReferences?: InvoiceLineExternalReferences + /** The usage quantity deducted (in billing units). */ + quantity: string +} + +/** Base fields shared by all invoice line item discounts. */ +export interface InvoiceLineBaseDiscount { + /** Unique identifier for the discount. */ + id: string + /** The reason this discount was applied. */ + reason: 'maximum_spend' | 'ratecard_percentage' | 'ratecard_usage' + /** Optional human-readable description of the discount. */ + description?: string + /** External identifiers for this discount. */ + externalReferences?: InvoiceLineExternalReferences +} + +/** Filter options for listing currencies. */ +export interface ListCurrenciesParamsFilter { + type?: 'fiat' | 'custom' + code?: StringFieldFilter +} + +/** Describes custom currency. */ +export interface CurrencyCustom { + /** The type of the currency. */ + type: 'custom' + /** + * The name of the currency. It should be a human-readable string that represents + * the name of the currency, such as "US Dollar" or "Euro". + */ + name: string + /** + * The symbol of the currency. It should be a string that represents the symbol of + * the currency, such as "$" for US Dollar or "€" for Euro. + */ + symbol?: string + id: string + code: string + /** An ISO-8601 timestamp representation of the custom currency creation date. */ + createdAt: Date +} + +/** CurrencyCustom create request. */ +export interface CreateCurrencyCustomRequest { + /** + * The name of the currency. It should be a human-readable string that represents + * the name of the currency, such as "US Dollar" or "Euro". + */ + name: string + /** + * The symbol of the currency. It should be a string that represents the symbol of + * the currency, such as "$" for US Dollar or "€" for Euro. + */ + symbol?: string + code: string +} + +/** Query to evaluate feature access for a list of customers. */ +export interface GovernanceQueryRequest { + /** + * Whether to include credit balance availability for each resolved customer. When + * true, each feature evaluation includes credit balance checks. + * + * Defaults to `false`. + */ + includeCredits: boolean + customer: GovernanceQueryRequestCustomers + feature?: GovernanceQueryRequestFeatures +} + +/** Reason a feature is not accessible to a customer. */ +export interface GovernanceFeatureAccessReason { + /** Machine-readable error code. */ + code: + | 'unknown' + | 'usage_limit_reached' + | 'feature_unavailable' + | 'feature_not_found' + | 'no_credit_available' + /** Human-readable description of the error. */ + message: string + /** Additional structured context. */ + attributes?: Record +} + +/** Query error within a partially successful governance query response. */ +export interface GovernanceQueryError { + /** Machine-readable error code. */ + code: 'unknown' | 'customer_not_found' + /** Human-readable description of the error. */ + message: string + /** Additional structured context. */ + attributes?: Record + /** The customer identifier from the request that produced this error. */ + customer?: string +} + +/** App customer data. */ +export interface AppCustomerData { + /** Used if the customer has a linked Stripe app. */ + stripe?: AppCustomerDataStripe + /** Used if the customer has a linked external invoicing app. */ + externalInvoicing?: AppCustomerDataExternalInvoicing +} + +/** AppCustomerData upsert request. */ +export interface UpsertAppCustomerDataRequest { + /** Used if the customer has a linked Stripe app. */ + stripe?: AppCustomerDataStripe + /** Used if the customer has a linked external invoicing app. */ + externalInvoicing?: AppCustomerDataExternalInvoicing +} + +/** + * A credit adjustment can be used to make manual adjustments to a customer's + * credit balance. + * + * Supported use-cases: + * + * - Usage correction + */ +export interface CreditAdjustment { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels +} + +/** The credit balance by currency. */ +export interface CreditBalance { + currency: BillingCurrencyCode + /** Credits available after applying currently live charge impacts. */ + live: string + /** Credits that have been booked on the ledger as of the balance timestamp. */ + settled: string + /** + * Credits that have been granted but are not yet written to the ledger, or are + * written to the ledger with a future booked time. + */ + pending: string +} + +/** CreditAdjustment create request. */ +export interface CreateCreditAdjustmentRequest { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** The currency of the granted credits. */ + currency: BillingCurrencyCode + /** Granted credit amount. */ + amount: string +} + +/** Filter options for listing credit transactions. */ +export interface ListCreditTransactionsParamsFilter { + /** Filter credit transactions by type. */ + type?: 'funded' | 'consumed' | 'expired' | 'voided' + /** Filter credit transactions by currency. */ + currency?: BillingCurrencyCode + /** + * Filter credit transactions by feature key. Omit to return all credit + * transactions. Use `exists=false` to return only unrestricted credit + * transactions. + */ + featureKey?: StringFieldFilter +} + +/** + * A credit transaction represents a single credit movement on the customer's + * balance. + * + * Credit transactions are immutable. + */ +export interface CreditTransaction { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** The date and time the transaction was booked. */ + bookedAt: Date + /** The type of credit transaction. */ + type: 'funded' | 'consumed' | 'expired' | 'voided' + /** Currency of the balance affected by the transaction. */ + currency: BillingCurrencyCode + /** + * Signed amount of the credit movement. Positive values add balance, negative + * values reduce balance. + */ + amount: string + /** The available balance before and after the transaction. */ + availableBalance: { before: string; after: string } +} + +/** + * A price tier used in graduated and volume pricing. + * + * At least one price component (flat_price or unit_price) must be set. When + * UnitConfig is present on the rate card, up_to_amount is expressed in converted + * billing units. + */ +export interface PriceTier { + /** + * Up to and including this quantity will be contained in the tier. If undefined, + * the tier is open-ended (the last tier). + */ + upToAmount?: string + /** The flat price component of the tier. Charged once when the tier is entered. */ + flatPrice?: PriceFlat + /** The unit price component of the tier. Charged per billing unit within the tier. */ + unitPrice?: PriceUnit +} + +/** + * The totals of a change. + * + * RealTime is only expanded when the `real_time_usage` expand is used. + */ +export interface ChargeTotals { + /** The amount of the charge already booked to the internal accounting system. */ + booked: Totals + /** + * The realtime amount of the charge. + * + * Requires the `realtime_usage` expand. + */ + realtime?: Totals +} + +/** + * A price tier used in graduated and volume pricing. + * + * At least one price component (flat_price or unit_price) must be set. When + * UnitConfig is present on the rate card, up_to_amount is expressed in converted + * billing units. + */ +export interface UpdatePriceTier { + /** + * Up to and including this quantity will be contained in the tier. If undefined, + * the tier is open-ended (the last tier). + */ + upToAmount?: string + /** The flat price component of the tier. Charged once when the tier is entered. */ + flatPrice?: UpdatePriceFlat + /** The unit price component of the tier. Charged per billing unit within the tier. */ + unitPrice?: UpdatePriceUnit +} + +/** + * LLM cost lookup configuration. Each dimension (provider, model, token type) can + * be specified as either a static value or a meter group-by property name + * (mutually exclusive). + */ +export interface FeatureLlmUnitCost { + /** The type discriminator for LLM unit cost. */ + type: 'llm' + /** + * Meter group-by property that holds the LLM provider. Use this when the meter has + * a group-by dimension for provider. Mutually exclusive with `provider`. + */ + providerProperty?: string + /** + * Static LLM provider value (e.g., "openai", "anthropic"). Use this when the + * feature tracks a single provider. Mutually exclusive with `provider_property`. + */ + provider?: string + /** + * Meter group-by property that holds the model ID. Use this when the meter has a + * group-by dimension for model. Mutually exclusive with `model`. + */ + modelProperty?: string + /** + * Static model ID value (e.g., "gpt-4", "claude-3-5-sonnet"). Use this when the + * feature tracks a single model. Mutually exclusive with `model_property`. + */ + model?: string + /** + * Meter group-by property that holds the token type. Use this when the meter has a + * group-by dimension for token type. Mutually exclusive with `token_type`. + */ + tokenTypeProperty?: string + /** + * Static token type value. Use this when the feature tracks a single token type + * (e.g., only input tokens). `request` is an alias for `input`, `response` is an + * alias for `output`. Mutually exclusive with `token_type_property`. + */ + tokenType?: + | 'input' + | 'output' + | 'cache_read' + | 'cache_write' + | 'reasoning' + | 'request' + | 'response' + /** + * Resolved per-token pricing from the LLM cost database. Populated in responses + * when the provider and model can be determined, either from static values or from + * meter group-by filters with exact matches. + */ + pricing?: FeatureLlmUnitCostPricing +} + +/** + * An LLM cost price record, representing the cost per token for a specific model + * from a specific provider. + */ +export interface LlmCostPrice { + /** Unique identifier. */ + id: string + /** Provider of the model. */ + provider: LlmCostProvider + /** The model. */ + model: LlmCostModel + /** Token pricing data. */ + pricing: LlmCostModelPricing + /** Currency code (currently always "USD"). */ + currency: string + /** Where this price came from. */ + source: 'manual' | 'system' + /** When this price becomes effective. */ + effectiveFrom: Date + /** When this price expires. Omitted when the price is currently effective. */ + effectiveTo?: Date + /** Creation timestamp. */ + createdAt: Date + /** Last update timestamp. */ + updatedAt: Date +} + +/** + * Input for creating a per-namespace price override. Unique per provider, model + * and currency. If an override already exists for the given provider, model and + * currency, it will be updated. If an override does not exist, it will be created. + */ +export interface LlmCostOverrideCreate { + /** Provider/vendor of the model. */ + provider: string + /** Canonical model identifier. */ + modelId: string + /** Human-readable model name. */ + modelName?: string + /** Token pricing data. */ + pricing: LlmCostModelPricing + /** Currency code. */ + currency: string + /** When this override becomes effective. */ + effectiveFrom: Date + /** When this override expires. */ + effectiveTo?: Date +} + +/** Filter options for listing customers. */ +export interface ListCustomersParamsFilter { + key?: StringFieldFilter + name?: StringFieldFilter + primaryEmail?: StringFieldFilter + usageAttributionSubjectKey?: StringFieldFilter + planKey?: StringFieldFilter + billingProfileId?: UlidFieldFilter +} + +/** Filter options for listing subscriptions. */ +export interface ListSubscriptionsParamsFilter { + id?: UlidFieldFilter + customerId?: UlidFieldFilter + status?: StringFieldFilterExact + planId?: UlidFieldFilter + planKey?: StringFieldFilterExact +} + +/** Filter options for listing features. */ +export interface ListFeatureParamsFilter { + meterId?: UlidFieldFilter + key?: StringFieldFilter + name?: StringFieldFilter +} + +/** Filter options for listing add-ons. */ +export interface ListAddonsParamsFilter { + id?: UlidFieldFilter + key?: StringFieldFilter + name?: StringFieldFilter + status?: StringFieldFilterExact + currency?: StringFieldFilterExact +} + +/** + * Tax configuration for a credit grant. + * + * Tax configuration should be provided to ensure correct revenue recognition, + * including for externally funded grants. + */ +export interface CreateCreditGrantTaxConfig { + /** Tax behavior applied to the invoice line item. */ + behavior?: 'inclusive' | 'exclusive' + /** Tax code applied to the invoice line item. */ + taxCode?: CreateResourceReference +} + +/** + * Tax configuration for a credit grant. + * + * Tax configuration should be provided to ensure correct revenue recognition, + * including for externally funded grants. + */ +export interface CreditGrantTaxConfig { + /** Tax behavior applied to the invoice line item. */ + behavior?: 'inclusive' | 'exclusive' + /** Tax code applied to the invoice line item. */ + taxCode?: TaxCodeReference +} + +/** Set of provider specific tax configs. */ +export interface TaxConfig { + /** + * Tax behavior. + * + * If not specified the billing profile is used to determine the tax behavior. If + * not specified in the billing profile, the provider's default behavior is used. + */ + behavior?: 'inclusive' | 'exclusive' + /** Stripe tax config. */ + stripe?: TaxConfigStripe + /** External invoicing tax config. */ + externalInvoicing?: TaxConfigExternalInvoicing + /** Tax code ID. */ + taxCodeId?: string + /** + * Tax code reference. + * + * When both `tax_code` and `tax_code_id` are provided, `tax_code` takes + * precedence. When `stripe.code` is also provided, `tax_code` still wins and + * `stripe.code` is ignored. + */ + taxCode?: TaxCodeReference +} + +/** The tax config of the rate card. */ +export interface RateCardTaxConfig { + behavior?: 'inclusive' | 'exclusive' + code: TaxCodeReference +} + +/** + * Organization-level default tax code references. + * + * Stores the default tax codes applied to specific billing contexts for this + * organization. Provisioned automatically when the organization is created. + */ +export interface OrganizationDefaultTaxCodes { + /** Default tax code for invoicing. */ + invoicingTaxCode: TaxCodeReference + /** Default tax code for credit grants. */ + creditGrantTaxCode: TaxCodeReference + /** Timestamp of creation. */ + createdAt: Date + /** Timestamp of last update. */ + updatedAt: Date +} + +/** OrganizationDefaultTaxCodes update request. */ +export interface UpdateOrganizationDefaultTaxCodesRequest { + /** Default tax code for invoicing. */ + invoicingTaxCode?: TaxCodeReference + /** Default tax code for credit grants. */ + creditGrantTaxCode?: TaxCodeReference +} + +/** + * PlanAddon represents an association between a plan and an add-on, controlling + * which add-ons are available for purchase within a plan. + */ +export interface PlanAddon { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** The add-on associated with the plan. */ + addon: AddonReference + /** The key of the plan phase from which the add-on becomes available for purchase. */ + fromPlanPhase: string + /** + * The maximum number of times the add-on can be purchased for the plan. For + * single-instance add-ons this field must be omitted. For multi-instance add-ons + * when omitted, unlimited quantity can be purchased. + */ + maxQuantity?: number + /** List of validation errors. */ + validationErrors?: ProductCatalogValidationError[] +} + +/** PlanAddon create request. */ +export interface CreatePlanAddonRequest { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** The add-on associated with the plan. */ + addon: AddonReference + /** The key of the plan phase from which the add-on becomes available for purchase. */ + fromPlanPhase: string + /** + * The maximum number of times the add-on can be purchased for the plan. For + * single-instance add-ons this field must be omitted. For multi-instance add-ons + * when omitted, unlimited quantity can be purchased. + */ + maxQuantity?: number +} + +/** References to the applications used by a billing profile. */ +export interface ProfileAppReferences { + /** The tax app used for this workflow. */ + tax: AppReference + /** The invoicing app used for this workflow. */ + invoicing: AppReference + /** The payment app used for this workflow. */ + payment: AppReference +} + +/** + * BillingInvoiceWorkflowAppsReferences represents the references (id) to the apps + * used by a billing profile + */ +export interface InvoiceWorkflowAppsReferences { + /** The tax app used for this workflow */ + tax: AppReference + /** The invoicing app used for this workflow */ + invoicing: AppReference + /** The payment app used for this workflow */ + payment: AppReference +} + +/** The tax config of the rate card. */ +export interface UpdateRateCardTaxConfig { + behavior?: 'inclusive' | 'exclusive' + code: UpdateResourceReference +} + +/** Filter options for listing ingested events. */ +export interface ListEventsParamsFilter { + /** Filter events by ID. */ + id?: StringFieldFilter + /** Filter events by source. */ + source?: StringFieldFilter + /** Filter events by subject. */ + subject?: StringFieldFilter + /** Filter events by type. */ + type?: StringFieldFilter + /** Filter events by the associated customer ID. */ + customerId?: UlidFieldFilter + /** Filter events by event time. */ + time?: DateTimeFieldFilter + /** Filter events by the time the event was ingested. */ + ingestedAt?: DateTimeFieldFilter + /** Filter events by the time the event was stored. */ + storedAt?: DateTimeFieldFilter +} + +/** Filter options for listing invoices. */ +export interface ListInvoicesParamsFilter { + /** Filter by invoice status. */ + status?: StringFieldFilterExact + /** Filter by customer ID. */ + customerId?: UlidFieldFilter + /** Filter by the time the invoice was issued. */ + issuedAt?: DateTimeFieldFilter + /** Filter by service period start. */ + servicePeriodStart?: DateTimeFieldFilter + /** Filter by invoice creation time. */ + createdAt?: DateTimeFieldFilter +} + +/** Resource filters. */ +export interface ResourceFilters { + name?: StringFieldFilter + labels?: LabelsFieldFilter + publicLabels?: LabelsFieldFilter + createdAt?: DateTimeFieldFilter + updatedAt?: DateTimeFieldFilter + deletedAt?: DateTimeFieldFilter +} + +/** Field filters with all supported types. */ +export interface FieldFilters { + boolean?: boolean | { eq: boolean } + numeric?: + | number + | { + eq?: number + neq?: number + oeq?: number[] + lt?: number + lte?: number + gt?: number + gte?: number + } + string?: StringFieldFilter + stringExact?: StringFieldFilterExact + ulid?: UlidFieldFilter + datetime?: DateTimeFieldFilter + labels?: LabelsFieldFilter +} + +/** An ingested metering event with ingestion metadata. */ +export interface IngestedEvent { + /** The original event ingested. */ + event: Event + /** The customer if the event is associated with a customer. */ + customer?: CustomerReference + /** The date and time the event was ingested and its processing started. */ + ingestedAt: Date + /** The date and time the event was stored in the database. */ + storedAt: Date + /** The validation errors of the ingested event. */ + validationErrors?: IngestedEventValidationError[] +} + +/** Meter query result. */ +export interface MeterQueryResult { + /** The start of the period the usage is queried from. */ + from?: Date + /** The end of the period the usage is queried to. */ + to?: Date + /** The usage data. If no data is available, an empty array is returned. */ + data: MeterQueryRow[] +} + +/** Result of a feature cost query. */ +export interface FeatureCostQueryResult { + /** Start of the queried period. */ + from?: Date + /** End of the queried period. */ + to?: Date + /** The cost data rows. */ + data: FeatureCostQueryRow[] +} + +/** Page paginated response. */ +export interface MeterPagePaginatedResponse { + data: Meter[] + meta: PaginatedMeta +} + +/** Page paginated response. */ +export interface CostBasisPagePaginatedResponse { + data: CostBasis[] + meta: PaginatedMeta +} + +/** Filters to apply to a meter query. */ +export interface MeterQueryFilters { + /** + * Filters to apply to the dimensions of the query. For `subject` and `customer_id` + * only equals ("eq", "in") comparisons are supported. + */ + dimensions?: Record +} + +/** Reference to a meter associated with a feature. */ +export interface FeatureMeterReference { + /** The ID of the meter to associate with this feature. */ + id: string + /** Filters to apply to the dimensions of the meter. */ + filters?: Record +} + +/** Customer create request. */ +export interface CreateCustomerRequest { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + key: string + /** Mapping to attribute metered usage to the customer by the event subject. */ + usageAttribution?: CustomerUsageAttribution + /** The primary email address of the customer. */ + primaryEmail?: string + /** Currency of the customer. Used for billing, tax and invoicing. */ + currency?: string + /** The billing address of the customer. Used for tax and invoicing. */ + billingAddress?: Address +} + +/** + * Customers can be individuals or organizations that can subscribe to plans and + * have access to features. + */ +export interface Customer { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + key: string + /** Mapping to attribute metered usage to the customer by the event subject. */ + usageAttribution?: CustomerUsageAttribution + /** The primary email address of the customer. */ + primaryEmail?: string + /** Currency of the customer. Used for billing, tax and invoicing. */ + currency?: string + /** The billing address of the customer. Used for tax and invoicing. */ + billingAddress?: Address +} + +/** Customer upsert request. */ +export interface UpsertCustomerRequest { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** Mapping to attribute metered usage to the customer by the event subject. */ + usageAttribution?: CustomerUsageAttribution + /** The primary email address of the customer. */ + primaryEmail?: string + /** Currency of the customer. Used for billing, tax and invoicing. */ + currency?: string + /** The billing address of the customer. Used for tax and invoicing. */ + billingAddress?: Address +} + +/** A collection of addresses for the party. */ +export interface PartyAddresses { + /** Billing address. */ + billingAddress: Address +} + +/** Snapshot of the customer's information at the time the invoice was issued. */ +export interface InvoiceCustomer { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** Mapping to attribute metered usage to the customer by the event subject. */ + usageAttribution?: CustomerUsageAttribution + /** The billing address of the customer. Used for tax and invoicing. */ + billingAddress?: Address + id: string + /** + * Optional external resource key for the customer. + * + * Omitted when the customer was created without a key. Unlike on the customer + * resource itself, the key is optional here because the invoice snapshot may + * predate or omit it. + */ + key?: string +} + +/** A collection of addresses for the party. */ +export interface UpdateBillingPartyAddresses { + /** Billing address. */ + billingAddress: UpdateAddress +} + +/** Snapshot of the customer's information at the time the invoice was issued. */ +export interface UpdateInvoiceCustomer { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** Mapping to attribute metered usage to the customer by the event subject. */ + usageAttribution?: UpdateCustomerUsageAttribution + /** The billing address of the customer. Used for tax and invoicing. */ + billingAddress?: UpdateAddress + id: string + /** + * Optional external resource key for the customer. + * + * Omitted when the customer was created without a key. Unlike on the customer + * resource itself, the key is optional here because the invoice snapshot may + * predate or omit it. + */ + key?: string +} + +/** Checkout Session consent collection configuration. */ +export interface AppStripeCreateCheckoutSessionConsentCollection { + /** Controls the visibility of payment method reuse agreement. */ + paymentMethodReuseAgreement?: AppStripeCreateCheckoutSessionConsentCollectionPaymentMethodReuseAgreement + /** + * Enables collection of promotional communication consent. + * + * Only available to US merchants. When set to "auto", Checkout determines whether + * to show the option based on the customer's locale. + */ + promotions?: 'auto' | 'none' + /** + * Requires customers to accept terms of service before payment. + * + * Requires a valid terms of service URL in your Stripe Dashboard settings. + */ + termsOfService?: 'none' | 'required' +} + +/** List customer entitlement access response data. */ +export interface ListCustomerEntitlementAccessResponseData { + /** The list of entitlement access results. */ + data: EntitlementAccessResult[] +} + +/** + * BillingWorkflowCollectionAlignmentAnchored specifies the alignment for + * collecting the pending line items into an invoice. + */ +export interface WorkflowCollectionAlignmentAnchored { + /** The type of alignment. */ + type: 'anchored' + /** The recurring period for the alignment. */ + recurringPeriod: RecurringPeriod +} + +/** + * Flat fee intent fields from the system lifecycle controller shadowed by a manual + * override. + */ +export interface ChargeFlatFeeSystemIntent { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** The timestamp when the charge is intended to be invoiced. */ + invoiceAt: Date + /** The effective service period covered by the charge. */ + servicePeriod: ClosedPeriod + /** The full, unprorated service period of the charge. */ + fullServicePeriod: ClosedPeriod + /** The billing period the charge belongs to. */ + billingPeriod: ClosedPeriod + /** Payment term of the flat fee charge. */ + paymentTerm: PricePaymentTerm + /** The discounts applied to the charge. */ + discounts?: ChargeFlatFeeDiscounts + /** The proration configuration of the charge. */ + prorationConfiguration: RateCardProrationConfiguration + /** The amount before proration of the system lifecycle controller flat fee intent. */ + amountBeforeProration: CurrencyAmount + /** + * The timestamp when the system lifecycle controller intent was deleted. The + * effective charge can remain visible while a manual override is active. + */ + deletedAt?: Date +} + +/** Page paginated response. */ +export interface SubscriptionPagePaginatedResponse { + data: Subscription[] + meta: PaginatedMeta +} + +/** Response for changing a subscription. */ +export interface SubscriptionChangeResponse { + /** The current subscription before the change. */ + current: Subscription + /** The new state of the subscription after the change. */ + next: Subscription +} + +/** Request for canceling a subscription. */ +export interface SubscriptionCancel { + /** If not provided the subscription is canceled immediately. */ + timing: SubscriptionEditTiming +} + +/** Request for changing a subscription. */ +export interface SubscriptionChange { + labels?: Labels + /** + * Settlement mode for billing. + * + * Values: + * + * - `credit_then_invoice`: Credits are applied first, then any remainder is + * invoiced. + * - `credit_only`: Usage is settled exclusively against credits. + */ + settlementMode?: 'credit_then_invoice' | 'credit_only' + /** The customer to create the subscription for. */ + customer: { id?: string; key?: string } + /** The plan reference of the subscription. */ + plan: { id?: string; key?: string; version?: number } + /** + * A billing anchor is the fixed point in time that determines the subscription's + * recurring billing cycle. It affects when charges occur and how prorations are + * calculated. Common anchors: + * + * - Calendar month (1st of each month): `2025-01-01T00:00:00Z` + * - Subscription anniversary (day customer signed up) + * - Custom date (customer-specified day) + * + * If not provided, the subscription will be created with the subscription's + * creation time as the billing anchor. + */ + billingAnchor?: Date + /** + * Timing configuration for the change, when the change should take effect. For + * changing a subscription, the accepted values depend on the subscription + * configuration. + */ + timing: SubscriptionEditTiming +} + +/** SubscriptionAddon create request. */ +export interface CreateSubscriptionAddonRequest { + labels?: Labels + /** The add-on associated with the subscription. */ + addon: AddonReference + /** The quantity of the add-on. Always 1 for single instance add-ons. */ + quantity: number + /** + * The timing of the operation. After the create or update, a new entry will be + * created in the timeline. + */ + timing: SubscriptionEditTiming +} + +/** + * Usage quantity details on an invoice line item when UnitConfig is in effect. + * + * Provides the full audit trail from raw meter output to the invoiced amount. + */ +export interface InvoiceUsageQuantityDetail { + /** The raw quantity as reported by the meter (native units). */ + rawQuantity: string + /** + * The precise decimal value after applying the conversion operation and factor, + * before rounding. + */ + convertedQuantity: string + /** The quantity after rounding, used for pricing. */ + invoicedQuantity: string + /** The display unit label (e.g., "GB", "hours", "M tokens"). */ + displayUnit?: string + /** + * Snapshot of the UnitConfig that was in effect at billing time. Ensures + * historical invoices reflect the config that was actually applied. + */ + appliedUnitConfig: UnitConfig +} + +/** TaxCode create request. */ +export interface CreateTaxCodeRequest { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + key: string + /** Mapping of app types to tax codes. */ + appMappings: TaxCodeAppMapping[] +} + +/** Tax codes by provider. */ +export interface TaxCode { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + key: string + /** Mapping of app types to tax codes. */ + appMappings: TaxCodeAppMapping[] +} + +/** TaxCode upsert request. */ +export interface UpsertTaxCodeRequest { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** Mapping of app types to tax codes. */ + appMappings: TaxCodeAppMapping[] +} + +/** + * Available apps for billing integrations to connect with third-party services. + * Apps can have various capabilities like syncing data from or to external + * systems, integrating with third-party services for tax calculation, delivery of + * invoices, collection of payments, etc. + */ +export interface AppCatalogItem { + /** Type of the app. */ + type: 'sandbox' | 'stripe' | 'external_invoicing' + /** Name of the app. */ + name: string + /** Description of the app. */ + description: string + /** Capabilities of the app. */ + capabilities: AppCapability[] + /** Available install methods of the app. */ + installMethods: ('with_oauth2' | 'with_api_key' | 'no_credentials_required')[] +} + +/** + * Invoice-level snapshot of the workflow configuration. + * + * Contains only the settings that are meaningful for an already-created invoice: + * invoicing behaviour and payment settings. Collection alignment and tax policy + * are gather-time / profile-wide concerns and are not included. + */ +export interface InvoiceWorkflow { + /** Invoicing settings for this invoice. */ + invoicing?: InvoiceWorkflowInvoicingSettings + /** Payment settings for this invoice. */ + payment?: WorkflowPaymentSettings +} + +/** Detailed status information for a standard invoice. */ +export interface InvoiceStatusDetails { + /** Whether the invoice is immutable (i.e. cannot be modified or deleted). */ + immutable: boolean + /** Whether the invoice is in a failed state. */ + failed: boolean + /** + * Fine-grained internal status string providing additional workflow detail beyond + * the top-level status enum. + */ + extendedStatus: string + /** The set of state-transition actions currently available for this invoice. */ + availableActions: InvoiceAvailableActions +} + +/** Discounts applied to an invoice line item. */ +export interface InvoiceLineDiscounts { + /** Monetary amount discounts (e.g. from maximum spend commitments). */ + amount?: InvoiceLineAmountDiscount[] + /** Usage quantity discounts (e.g. free tier usage allowances). */ + usage?: InvoiceLineUsageDiscount[] +} + +/** + * Invoice-level snapshot of the workflow configuration. + * + * Contains only the settings that are meaningful for an already-created invoice: + * invoicing behaviour and payment settings. Collection alignment and tax policy + * are gather-time / profile-wide concerns and are not included. + */ +export interface UpdateBillingInvoiceWorkflow { + /** Invoicing settings for this invoice. */ + invoicing?: UpdateBillingInvoiceWorkflowInvoicingSettings + /** Payment settings for this invoice. */ + payment?: UpdateBillingWorkflowPaymentSettings +} + +/** Access status for a single feature. */ +export interface GovernanceFeatureAccess { + /** + * Whether the customer currently has access to the feature. + * + * `true` for boolean and static entitlements that are available, and for metered + * entitlements with remaining balance. `false` when the feature is unavailable, + * the usage limit has been reached, or (when applicable) credits have been + * exhausted. + */ + hasAccess: boolean + /** + * Optional reason when the customer does not have access to the feature. Populated + * when `has_access` is `false`. + */ + reason?: GovernanceFeatureAccessReason +} + +/** Billing customer data. */ +export interface CustomerData { + /** + * The billing profile for the customer. + * + * If not provided, the default billing profile will be used. + */ + billingProfile?: ProfileReference + /** App customer data. */ + appData?: AppCustomerData +} + +/** CustomerBillingData upsert request. */ +export interface UpsertCustomerBillingDataRequest { + /** + * The billing profile for the customer. + * + * If not provided, the default billing profile will be used. + */ + billingProfile?: ProfileReference + /** App customer data. */ + appData?: AppCustomerData +} + +/** The balances of the credits of a customer. */ +export interface CreditBalances { + /** The timestamp of the balance retrieval. */ + retrievedAt: Date + /** The balances by currencies. */ + balances: CreditBalance[] +} + +/** Cursor paginated response. */ +export interface CreditTransactionPaginatedResponse { + data: CreditTransaction[] + meta: CursorMeta +} + +/** + * Graduated tiered price. + * + * Each tier's rate applies only to the usage within that tier. Pricing can change + * as cumulative usage crosses tier boundaries. + * + * When UnitConfig is present on the rate card, tier boundaries (up_to_amount) are + * expressed in converted billing units. + */ +export interface PriceGraduated { + /** The type of the price. */ + type: 'graduated' + /** The tiers of the graduated price. At least one tier is required. */ + tiers: PriceTier[] +} + +/** + * Volume tiered price. + * + * The maximum quantity within a period determines the per-unit price for all units + * in that period. + * + * When UnitConfig is present on the rate card, tier boundaries (up_to_amount) are + * expressed in converted billing units. + */ +export interface PriceVolume { + /** The type of the price. */ + type: 'volume' + /** The tiers of the volume price. At least one tier is required. */ + tiers: PriceTier[] +} + +/** + * Graduated tiered price. + * + * Each tier's rate applies only to the usage within that tier. Pricing can change + * as cumulative usage crosses tier boundaries. + * + * When UnitConfig is present on the rate card, tier boundaries (up_to_amount) are + * expressed in converted billing units. + */ +export interface UpdatePriceGraduated { + /** The type of the price. */ + type: 'graduated' + /** The tiers of the graduated price. At least one tier is required. */ + tiers: UpdatePriceTier[] +} + +/** + * Volume tiered price. + * + * The maximum quantity within a period determines the per-unit price for all units + * in that period. + * + * When UnitConfig is present on the rate card, tier boundaries (up_to_amount) are + * expressed in converted billing units. + */ +export interface UpdatePriceVolume { + /** The type of the price. */ + type: 'volume' + /** The tiers of the volume price. At least one tier is required. */ + tiers: UpdatePriceTier[] +} + +/** Page paginated response. */ +export interface PricePagePaginatedResponse { + data: LlmCostPrice[] + meta: PaginatedMeta +} + +/** CreditGrant create request. */ +export interface CreateCreditGrantRequest { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: CreateLabels + /** Funding method of the grant. */ + fundingMethod: 'none' | 'invoice' | 'external' + /** The currency of the granted credits. */ + currency: CreateCurrencyCode + /** Granted credit amount. */ + amount: string + /** Present when a funding workflow applies (funding_method is not `none`). */ + purchase?: CreateCreditGrantPurchase + /** + * Tax configuration for the grant. + * + * For `invoice` and `external` funding methods, tax configuration should be + * provided to ensure correct revenue recognition. When not provided, the default + * credit grant tax code is applied, if that's not set the global default taxcode + * is used. + */ + taxConfig?: CreateCreditGrantTaxConfig + filters?: CreateCreditGrantFilters + /** Draw-down priority of the grant. Lower values have higher priority. */ + priority: number + /** + * The timestamp when the credit grant becomes effective. + * + * Defaults to the current date and time. + */ + effectiveAt?: Date + /** + * The duration after which the credit grant expires. + * + * Defaults to never expiring. + */ + expiresAfter?: string + /** + * Idempotency key for the credit grant creation request. + * + * When provided, reusing the same key returns an HTTP 409 Conflict instead of + * creating a duplicate grant, which makes create requests safe to retry. + */ + key?: string +} + +/** + * A credit grant allocates credits to a customer. + * + * Credits are drawn down against charges according to the settlement mode + * configured on the rate card. + */ +export interface CreditGrant { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** Funding method of the grant. */ + fundingMethod: 'none' | 'invoice' | 'external' + /** The currency of the granted credits. */ + currency: BillingCurrencyCode + /** Granted credit amount. */ + amount: string + /** Present when a funding workflow applies (funding_method is not `none`). */ + purchase?: CreditGrantPurchase + /** + * Tax configuration for the grant. + * + * For `invoice` and `external` funding methods, tax configuration should be + * provided to ensure correct revenue recognition. When not provided, the default + * credit grant tax code is applied, if that's not set the global default taxcode + * is used. + */ + taxConfig?: CreditGrantTaxConfig + /** Available when `funding_method` is `invoice`. */ + invoice?: CreditGrantInvoiceReference + filters?: CreditGrantFilters + /** Draw-down priority of the grant. Lower values have higher priority. */ + priority: number + /** + * The timestamp when the credit grant becomes effective. + * + * Defaults to the current date and time. + */ + effectiveAt?: Date + /** + * Idempotency key for the credit grant creation request. + * + * When provided, reusing the same key returns an HTTP 409 Conflict instead of + * creating a duplicate grant, which makes create requests safe to retry. + */ + key?: string + /** + * The timestamp when the credit grant expires. + * + * Calculated from the grant effective time and `expires_after` if provided. + */ + expiresAt?: Date + /** Timestamp when the grant was voided. */ + voidedAt?: Date + /** Current lifecycle status of the grant. */ + status: 'pending' | 'active' | 'expired' | 'voided' +} + +/** Flat fee charge create request. */ +export interface CreateChargeFlatFeeRequest { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** The type of the charge. */ + type: 'flat_fee' + /** The currency of the charge. */ + currency: string + /** The timestamp when the charge is intended to be invoiced. */ + invoiceAt: Date + /** The effective service period covered by the charge. */ + servicePeriod: ClosedPeriod + /** Unique reference ID of the charge. */ + uniqueReferenceId?: string + /** Settlement mode of the charge. */ + settlementMode: 'credit_then_invoice' | 'credit_only' + /** Tax configuration of the charge. */ + taxConfig?: TaxConfig + /** Payment term of the flat fee charge. */ + paymentTerm: PricePaymentTerm + /** The discounts applied to the charge. */ + discounts?: ChargeFlatFeeDiscounts + /** The feature associated with the charge, when applicable. */ + featureKey?: string + /** The proration configuration of the charge. */ + prorationConfiguration: RateCardProrationConfiguration + /** The amount before proration of the charge. */ + amountBeforeProration: CurrencyAmount + /** The full, unprorated service period of the charge. */ + fullServicePeriod?: ClosedPeriod + /** The billing period the charge belongs to. */ + billingPeriod?: ClosedPeriod +} + +/** Tax settings for a billing workflow. */ +export interface WorkflowTaxSettings { + /** + * Enable automatic tax calculation when tax is supported by the app. For example, + * with Stripe Invoicing when enabled, tax is calculated via Stripe Tax. + */ + enabled: boolean + /** + * Enforce tax calculation when tax is supported by the app. When enabled, the + * billing system will not allow to create an invoice without tax calculation. + * Enforcement is different per apps, for example, Stripe app requires customer to + * have a tax location when starting a paid subscription. + */ + enforced: boolean + /** + * Default tax configuration to apply to the invoices for line items. + * + * Setting a tax code (`stripe.code` / `taxCodeId`) on a profile's default tax + * config is deprecated and can no longer be added or changed: the organization + * default tax code is used instead. Existing tax-code values may still be removed, + * and `behavior` remains fully supported. + */ + defaultTaxConfig?: TaxConfig +} + +/** Page paginated response. */ +export interface PlanAddonPagePaginatedResponse { + data: PlanAddon[] + meta: PaginatedMeta +} + +/** Cursor paginated response. */ +export interface IngestedEventPaginatedResponse { + data: IngestedEvent[] + meta: CursorMeta +} + +/** The list of parameters that failed validation. */ +export type InvalidParameters = InvalidParameter[] + +/** A meter query request. */ +export interface MeterQueryRequest { + /** The start of the period the usage is queried from. */ + from?: Date + /** The end of the period the usage is queried to. */ + to?: Date + /** + * The size of the time buckets to group the usage into. If not specified, the + * usage is aggregated over the entire period. + */ + granularity?: MeterQueryGranularity + /** + * The value is the name of the time zone as defined in the IANA Time Zone Database + * (http://www.iana.org/time-zones). The time zone is used to determine the start + * and end of the time buckets. If not specified, the UTC timezone will be used. + */ + timeZone: string + /** The dimensions to group the results by. */ + groupByDimensions?: string[] + /** Filters to apply to the query. */ + filters?: MeterQueryFilters +} + +/** Page paginated response. */ +export interface CustomerPagePaginatedResponse { + data: Customer[] + meta: PaginatedMeta +} + +/** Party represents a person or business entity. */ +export interface Party { + /** Unique identifier for the party. */ + id?: string + /** An optional unique key of the party. */ + key?: string + /** Legal name or representation of the party. */ + name?: string + /** + * The entity's legal identification used for tax purposes. They may have other + * numbers, but we're only interested in those valid for tax purposes. + */ + taxId?: PartyTaxIdentity + /** Address for where information should be sent if needed. */ + addresses?: PartyAddresses +} + +/** + * Snapshot of the supplier's information at the time the invoice was issued. + * + * Structurally a read-only subset of `BillingParty` (the type configured on the + * billing profile), so the snapshot stays aligned with the source. `key` is + * omitted because it is not part of the snapshotted supplier data. + */ +export interface Supplier { + /** Legal name or representation of the party. */ + name?: string + /** + * The entity's legal identification used for tax purposes. They may have other + * numbers, but we're only interested in those valid for tax purposes. + */ + taxId?: PartyTaxIdentity + /** Address for where information should be sent if needed. */ + addresses?: PartyAddresses + /** Unique identifier for the party. */ + id?: string +} + +/** + * Snapshot of the supplier's information at the time the invoice was issued. + * + * Structurally a read-only subset of `BillingParty` (the type configured on the + * billing profile), so the snapshot stays aligned with the source. `key` is + * omitted because it is not part of the snapshotted supplier data. + */ +export interface UpdateSupplier { + /** Legal name or representation of the party. */ + name?: string + /** + * The entity's legal identification used for tax purposes. They may have other + * numbers, but we're only interested in those valid for tax purposes. + */ + taxId?: UpdateBillingPartyTaxIdentity + /** Address for where information should be sent if needed. */ + addresses?: UpdateBillingPartyAddresses + /** Unique identifier for the party. */ + id?: string +} + +/** + * Configuration options for creating a Stripe Checkout Session. + * + * Based on Stripe's + * [Checkout Session API parameters](https://docs.stripe.com/api/checkout/sessions/create). + */ +export interface AppStripeCreateCheckoutSessionRequestOptions { + /** + * Whether to collect the customer's billing address. + * + * Defaults to auto, which only collects the address when necessary for tax + * calculation. + */ + billingAddressCollection: 'auto' | 'required' + /** + * URL to redirect customers who cancel the checkout session. + * + * Not allowed when ui_mode is "embedded". + */ + cancelUrl?: string + /** + * Unique reference string for reconciling sessions with internal systems. + * + * Can be a customer ID, cart ID, or any other identifier. + */ + clientReferenceId?: string + /** Controls which customer fields can be updated by the checkout session. */ + customerUpdate?: AppStripeCreateCheckoutSessionCustomerUpdate + /** Configuration for collecting customer consent during checkout. */ + consentCollection?: AppStripeCreateCheckoutSessionConsentCollection + /** + * Three-letter ISO 4217 currency code in uppercase. + * + * Required for payment mode sessions. Optional for setup mode sessions. + */ + currency?: string + /** Custom text to display during checkout at various stages. */ + customText?: AppStripeCheckoutSessionCustomTextParams + /** + * Unix timestamp when the checkout session expires. + * + * Can be 30 minutes to 24 hours from creation. Defaults to 24 hours. + */ + expiresAt?: bigint + /** + * IETF language tag for the checkout UI locale. + * + * If blank or "auto", uses the browser's locale. Example: "en", "fr", "de". + */ + locale?: string + /** + * Set of key-value pairs to attach to the checkout session. + * + * Useful for storing additional structured information. + */ + metadata?: Record + /** + * Return URL for embedded checkout sessions after payment authentication. + * + * Required if ui_mode is "embedded" and redirect-based payment methods are + * enabled. + */ + returnUrl?: string + /** + * Success URL to redirect customers after completing payment or setup. + * + * Not allowed when ui_mode is "embedded". See: + * https://docs.stripe.com/payments/checkout/custom-success-page + */ + successUrl?: string + /** + * The UI mode for the checkout session. + * + * "hosted" displays a Stripe-hosted page. "embedded" integrates directly into your + * app. Defaults to "hosted". + */ + uiMode: 'embedded' | 'hosted' + /** + * List of payment method types to enable (e.g., "card", "us_bank_account"). + * + * If not specified, Stripe enables all relevant payment methods. + */ + paymentMethodTypes?: string[] + /** + * Redirect behavior for embedded checkout sessions. + * + * Controls when to redirect users after completion. See: + * https://docs.stripe.com/payments/checkout/custom-success-page?payment-ui=embedded-form + */ + redirectOnCompletion?: 'always' | 'if_required' | 'never' + /** Configuration for collecting tax IDs during checkout. */ + taxIdCollection?: AppStripeCreateCheckoutSessionTaxIdCollection +} + +/** Page paginated response. */ +export interface TaxCodePagePaginatedResponse { + data: TaxCode[] + meta: PaginatedMeta +} + +/** Stripe app. */ +export interface AppStripe { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** The app type. */ + type: 'stripe' + /** The app catalog definition that this installed app is based on. */ + definition: AppCatalogItem + /** Status of the app connection. */ + status: 'ready' | 'unauthorized' + /** The Stripe account ID associated with the connected Stripe account. */ + accountId: string + /** Indicates whether the app is connected to a live Stripe account. */ + livemode: boolean + /** The masked Stripe API key that only exposes the first and last few characters. */ + maskedApiKey: string +} + +/** Sandbox app can be used for testing billing features. */ +export interface AppSandbox { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** The app type. */ + type: 'sandbox' + /** The app catalog definition that this installed app is based on. */ + definition: AppCatalogItem + /** Status of the app connection. */ + status: 'ready' | 'unauthorized' +} + +/** + * External Invoicing app enables integration with third-party invoicing or payment + * system. + * + * The app supports a bi-directional synchronization pattern where OpenMeter + * Billing manages the invoice lifecycle while the external system handles invoice + * presentation and payment collection. + * + * Integration workflow: + * + * 1. The billing system creates invoices and transitions them through lifecycle + * states (draft → issuing → issued) + * 2. The integration receives webhook notifications about invoice state changes + * 3. The integration calls back to provide external system IDs and metadata + * 4. The integration reports payment events back via the payment status API + * + * State synchronization is controlled by hooks that pause invoice progression + * until the external system confirms synchronization via API callbacks. + */ +export interface AppExternalInvoicing { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** The app type. */ + type: 'external_invoicing' + /** The app catalog definition that this installed app is based on. */ + definition: AppCatalogItem + /** Status of the app connection. */ + status: 'ready' | 'unauthorized' + /** + * Enable draft synchronization hook. + * + * When enabled, invoices will pause at the draft state and wait for the + * integration to call the draft synchronized endpoint before progressing to the + * issuing state. This allows the external system to validate and prepare the + * invoice data. + * + * When disabled, invoices automatically progress through the draft state based on + * the configured workflow timing. + */ + enableDraftSyncHook: boolean + /** + * Enable issuing synchronization hook. + * + * When enabled, invoices will pause at the issuing state and wait for the + * integration to call the issuing synchronized endpoint before progressing to the + * issued state. This ensures the external invoicing system has successfully + * created and finalized the invoice before it is marked as issued. + * + * When disabled, invoices automatically progress through the issuing state and are + * immediately marked as issued. + */ + enableIssuingSyncHook: boolean +} + +/** Page paginated response. */ +export interface AppCatalogItemPagePaginatedResponse { + data: AppCatalogItem[] + meta: PaginatedMeta +} + +/** Snapshot of the billing workflow configuration captured at invoice creation. */ +export interface InvoiceWorkflowSettings { + /** The apps that will be used to orchestrate the invoice's workflow. */ + apps?: InvoiceWorkflowAppsReferences + /** The billing profile that was the source of this workflow snapshot. */ + sourceBillingProfile: ProfileReference + /** + * The workflow configuration that was active when the invoice was created. + * + * Only the fields that are meaningful at the per-invoice level are included: + * invoicing behaviour (auto-advance, draft period) and payment settings + * (collection method, due date). Profile-wide settings such as collection + * alignment, progressive billing, and tax policy are omitted. + */ + workflow: InvoiceWorkflow +} + +/** + * A detailed (child) sub-line belonging to a parent invoice line. + * + * Detailed lines represent the individual flat-fee components that make up a + * usage-based parent line after quantity snapshotting. + */ +export interface InvoiceDetailedLine { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** The service period covered by this detailed line. */ + servicePeriod: ClosedPeriod + /** Aggregated financial totals for the detailed line. */ + totals: Totals + /** The cost category of this detailed line. */ + category: 'regular' | 'commitment' + /** Discounts applied to this detailed line. */ + discounts?: InvoiceLineDiscounts + /** Credit applied to this detailed line. */ + creditsApplied?: InvoiceLineCreditsApplied[] + /** External identifiers for this detailed line. */ + externalReferences?: InvoiceLineExternalReferences + /** The quantity of the detailed line. */ + quantity: string + /** The unit price of the detailed line. */ + unitPrice: string +} + +/** Snapshot of the billing workflow configuration captured at invoice creation. */ +export interface UpdateInvoiceWorkflowSettings { + /** + * The workflow configuration that was active when the invoice was created. + * + * Only the fields that are meaningful at the per-invoice level are included: + * invoicing behaviour (auto-advance, draft period) and payment settings + * (collection method, due date). Profile-wide settings such as collection + * alignment, progressive billing, and tax policy are omitted. + */ + workflow: UpdateBillingInvoiceWorkflow +} + +/** Page paginated response. */ +export interface CurrencyPagePaginatedResponse { + data: Currency[] + meta: PaginatedMeta +} + +/** Access evaluation result for a single resolved customer. */ +export interface GovernanceQueryResult { + /** + * The list of identifiers from the request that resolved to this customer. Each + * entry is either the customer `key` or one of its usage-attribution subject + * `key`s. + * + * Duplicate or aliased identifiers that resolve to the same customer collapse to a + * single result entry, with every requested identifier listed here. + */ + matched: string[] + /** The customer the matched identifiers resolved to. */ + customer: Customer + /** + * Map of features with their access status. + * + * Map keys are the feature keys requested in `feature.keys`, or every feature + * `key` available in the organization when the feature filter was omitted. + */ + features: Record + /** + * Timestamp of the most recent change to the customer's access state reflected in + * this result. + */ + updatedAt: Date +} + +/** A capability or billable dimension offered by a provider. */ +export interface Feature { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + key: string + /** + * The meter that the feature is associated with and based on which usage is + * calculated. If not specified, the feature is static. + */ + meter?: FeatureMeterReference + /** + * Optional per-unit cost configuration. Use "manual" for a fixed per-unit cost, or + * "llm" to look up cost from the LLM cost database based on meter group-by + * properties. + */ + unitCost?: FeatureUnitCost +} + +/** Feature create request. */ +export interface CreateFeatureRequest { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + key: string + /** + * The meter that the feature is associated with and based on which usage is + * calculated. If not specified, the feature is static. + */ + meter?: FeatureMeterReference + /** + * Optional per-unit cost configuration. Use "manual" for a fixed per-unit cost, or + * "llm" to look up cost from the LLM cost database based on meter group-by + * properties. + */ + unitCost?: FeatureUnitCost +} + +/** + * Request body for updating a feature. Currently only the unit_cost field can be + * updated. + */ +export interface UpdateFeatureRequest { + /** + * Optional per-unit cost configuration. Use "manual" for a fixed per-unit cost, or + * "llm" to look up cost from the LLM cost database based on meter group-by + * properties. Set to `null` to clear the existing unit cost; omit to leave it + * unchanged. + */ + unitCost?: FeatureUnitCost | null +} + +/** Page paginated response. */ +export interface CreditGrantPagePaginatedResponse { + data: CreditGrant[] + meta: PaginatedMeta +} + +/** Bad Request. */ +export interface BadRequest extends BaseError { + /** The list of parameters that failed validation. */ + invalidParameters: InvalidParameter[] +} + +/** + * Base fields shared by all invoice types. + * + * Spread this model into each concrete invoice variant. + */ +export interface InvoiceBase { + id: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** Human-readable invoice number generated by the invoicing app. */ + number: string + /** Three-letter ISO 4217 currency code for the invoice. */ + currency: string + /** + * Snapshot of the supplier's contact information at the time the invoice was + * issued. + */ + supplier: Supplier + /** Snapshot of the customer's information at the time the invoice was issued. */ + customer: InvoiceCustomer + /** Aggregated financial totals for the invoice. */ + totals: Totals + /** + * The service period covered by this invoice. + * + * For flat fee the service period can be empty which means `from` will be equals + * to `to`. In other cases those fields will be filled with the actual service + * period. + */ + servicePeriod: ClosedPeriod + /** + * Validation issues found during invoice processing. + * + * Present only when there are one or more validation findings. An empty list is + * omitted. + */ + validationIssues?: InvoiceValidationIssue[] + /** External identifiers assigned to this invoice by third-party systems. */ + externalReferences?: InvoiceExternalReferences +} + +/** + * Request to create a Stripe Checkout Session for the customer. + * + * Checkout Sessions are used to collect payment method information from customers + * in a secure, Stripe-hosted interface. This integration uses setup mode to + * collect payment methods that can be charged later for subscription billing. + */ +export interface CustomerStripeCreateCheckoutSessionRequest { + /** + * Options for configuring the Stripe Checkout Session. + * + * These options are passed directly to Stripe's + * [checkout session creation API](https://docs.stripe.com/api/checkout/sessions/create). + */ + stripeOptions: AppStripeCreateCheckoutSessionRequestOptions +} + +/** + * Workflow collection specifies how to collect the pending line items for an + * invoice. + */ +export interface WorkflowCollectionSettings { + /** The alignment for collecting the pending line items into an invoice. */ + alignment: WorkflowCollectionAlignment + /** + * This grace period can be used to delay the collection of the pending line items + * specified in alignment. + * + * This is useful, in case of multiple subscriptions having slightly different + * billing periods. + */ + interval: string +} + +/** Response of the governance query. */ +export interface GovernanceQueryResponse { + /** Access evaluation results, one entry per resolved customer. */ + data: GovernanceQueryResult[] + /** Partial errors encountered while processing the request. */ + errors: GovernanceQueryError[] + /** + * Pagination metadata. The endpoint may return a partial response if the full + * response would exceed server-side limits. + */ + meta: CursorMeta +} + +/** A flat fee charge for a customer. */ +export interface ChargeFlatFee { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** The type of the charge. */ + type: 'flat_fee' + /** The customer owning the charge. */ + customer: BillingCustomerReference + /** + * Indicates whether the charge lifecycle is controlled by OpenMeter or manually + * overridden by the API user. + */ + lifecycleController: 'system' | 'manual' + /** + * The subscription that originated the charge, when the charge was created from a + * subscription item. + */ + subscription?: SubscriptionReference + /** The currency of the charge. */ + currency: string + /** The lifecycle status of the charge. */ + status: 'created' | 'active' | 'final' | 'deleted' + /** The timestamp when the charge is intended to be invoiced. */ + invoiceAt: Date + /** The effective service period covered by the charge. */ + servicePeriod: ClosedPeriod + /** The full, unprorated service period of the charge. */ + fullServicePeriod: ClosedPeriod + /** The billing period the charge belongs to. */ + billingPeriod: ClosedPeriod + /** + * The earliest time when the charge should be advanced again by background + * processing. + */ + advanceAfter?: Date + /** Unique reference ID of the charge. */ + uniqueReferenceId?: string + /** Settlement mode of the charge. */ + settlementMode: 'credit_then_invoice' | 'credit_only' + /** Tax configuration of the charge. */ + taxConfig?: TaxConfig + /** Payment term of the flat fee charge. */ + paymentTerm: PricePaymentTerm + /** The discounts applied to the charge. */ + discounts?: ChargeFlatFeeDiscounts + /** The feature associated with the charge, when applicable. */ + featureKey?: string + /** The proration configuration of the charge. */ + prorationConfiguration: RateCardProrationConfiguration + /** The amount after proration of the charge. */ + amountAfterProration: CurrencyAmount + /** The price of the charge. */ + price: Price + /** + * Current intent from the system lifecycle controller for a charge that has an + * active manual override. The top-level charge fields remain the effective + * customer-facing intent. + */ + systemIntent?: ChargeFlatFeeSystemIntent +} + +/** + * Usage-based intent fields from the system lifecycle controller shadowed by a + * manual override. + */ +export interface ChargeUsageBasedSystemIntent { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** The timestamp when the charge is intended to be invoiced. */ + invoiceAt: Date + /** The effective service period covered by the charge. */ + servicePeriod: ClosedPeriod + /** The full, unprorated service period of the charge. */ + fullServicePeriod: ClosedPeriod + /** The billing period the charge belongs to. */ + billingPeriod: ClosedPeriod + /** Discounts applied to the usage-based charge. */ + discounts?: RateCardDiscounts + /** The price of the charge. */ + price: Price + /** + * The timestamp when the system lifecycle controller intent was deleted. The + * effective charge can remain visible while a manual override is active. + */ + deletedAt?: Date +} + +/** Usage-based charge create request. */ +export interface CreateChargeUsageBasedRequest { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** The type of the charge. */ + type: 'usage_based' + /** The currency of the charge. */ + currency: string + /** The timestamp when the charge is intended to be invoiced. */ + invoiceAt: Date + /** The effective service period covered by the charge. */ + servicePeriod: ClosedPeriod + /** Unique reference ID of the charge. */ + uniqueReferenceId?: string + /** Settlement mode of the charge. */ + settlementMode: 'credit_then_invoice' | 'credit_only' + /** Tax configuration of the charge. */ + taxConfig?: TaxConfig + /** Discounts applied to the usage-based charge. */ + discounts?: RateCardDiscounts + /** The feature associated with the charge. */ + featureKey: string + /** The price of the charge. */ + price: Price + /** The full, unprorated service period of the charge. */ + fullServicePeriod?: ClosedPeriod + /** The billing period the charge belongs to. */ + billingPeriod?: ClosedPeriod +} + +/** A rate card defines the pricing and entitlement of a feature or service. */ +export interface RateCard { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + key: string + /** The feature associated with the rate card. */ + feature?: FeatureReference + /** + * The billing cadence of the rate card. When null, the charge is one-time + * (non-recurring). Only valid for flat prices. + */ + billingCadence?: string + /** The price of the rate card. */ + price: Price + /** + * Unit conversion configuration for the rate card. + * + * Synthesized on read for plans authored with v1 dynamic or package prices: + * dynamic prices map to a unit price with a multiply unit config, and package + * prices map to a unit price with a divide unit config. + * + * Accepted on create and update only when the UnitConfig feature is enabled on the + * deployment; otherwise rejected. + */ + unitConfig?: UnitConfig + /** + * The payment term of the rate card. In advance payment term can only be used for + * flat prices. + */ + paymentTerm: PricePaymentTerm + /** + * Spend commitments for this rate card. Only applicable to usage-based prices + * (unit, graduated, volume). + */ + commitments?: SpendCommitments + /** The discounts of the rate card. */ + discounts?: RateCardDiscounts + /** The tax config of the rate card. */ + taxConfig?: RateCardTaxConfig + /** + * The entitlement template granted to subscribers of a plan or addon containing + * this rate card. Requires `feature` to be set. + */ + entitlement?: RateCardEntitlement +} + +/** Rate card configuration snapshot for a usage-based invoice line. */ +export interface InvoiceLineRateCard { + /** The price definition used to calculate charges for this line. */ + price: Price + /** Tax configuration snapshot for this line. */ + taxConfig?: RateCardTaxConfig + /** The feature key associated with this line's rate card. */ + featureKey?: string + /** Discount configuration from the rate card. */ + discounts?: RateCardDiscounts +} + +/** Rate card configuration snapshot for a usage-based invoice line. */ +export interface UpdateInvoiceLineRateCard { + /** The price definition used to calculate charges for this line. */ + price: UpdatePrice + /** Tax configuration snapshot for this line. */ + taxConfig?: UpdateRateCardTaxConfig + /** The feature key associated with this line's rate card. */ + featureKey?: string + /** Discount configuration from the rate card. */ + discounts?: UpdateDiscounts +} + +/** Page paginated response. */ +export interface FeaturePagePaginatedResponse { + data: Feature[] + meta: PaginatedMeta +} + +/** Billing workflow settings. */ +export interface Workflow { + /** The collection settings for this workflow */ + collection?: WorkflowCollectionSettings + /** The invoicing settings for this workflow */ + invoicing?: WorkflowInvoicingSettings + /** The payment settings for this workflow */ + payment?: WorkflowPaymentSettings + /** The tax settings for this workflow */ + tax?: WorkflowTaxSettings +} + +/** Page paginated response. */ +export interface AppPagePaginatedResponse { + data: App[] + meta: PaginatedMeta +} + +/** Response of the app install. */ +export interface BillingInstallAppResponse { + app: App + defaultForCapabilityTypes: ( + | 'report_usage' + | 'report_events' + | 'calculate_tax' + | 'invoice_customers' + | 'collect_payments' + )[] +} + +/** Applications used by a billing profile. */ +export interface ProfileApps { + /** The tax app used for this workflow. */ + tax: App + /** The invoicing app used for this workflow. */ + invoicing: App + /** The payment app used for this workflow. */ + payment: App +} + +/** A usage-based charge for a customer. */ +export interface ChargeUsageBased { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** The type of the charge. */ + type: 'usage_based' + /** The customer owning the charge. */ + customer: BillingCustomerReference + /** + * Indicates whether the charge lifecycle is controlled by OpenMeter or manually + * overridden by the API user. + */ + lifecycleController: 'system' | 'manual' + /** + * The subscription that originated the charge, when the charge was created from a + * subscription item. + */ + subscription?: SubscriptionReference + /** The currency of the charge. */ + currency: string + /** The lifecycle status of the charge. */ + status: 'created' | 'active' | 'final' | 'deleted' + /** The timestamp when the charge is intended to be invoiced. */ + invoiceAt: Date + /** The effective service period covered by the charge. */ + servicePeriod: ClosedPeriod + /** The full, unprorated service period of the charge. */ + fullServicePeriod: ClosedPeriod + /** The billing period the charge belongs to. */ + billingPeriod: ClosedPeriod + /** + * The earliest time when the charge should be advanced again by background + * processing. + */ + advanceAfter?: Date + /** Unique reference ID of the charge. */ + uniqueReferenceId?: string + /** Settlement mode of the charge. */ + settlementMode: 'credit_then_invoice' | 'credit_only' + /** Tax configuration of the charge. */ + taxConfig?: TaxConfig + /** Discounts applied to the usage-based charge. */ + discounts?: RateCardDiscounts + /** The feature associated with the charge. */ + featureKey: string + /** Aggregated booked and realtime totals for the charge. */ + totals: ChargeTotals + /** The price of the charge. */ + price: Price + /** + * Current intent from the system lifecycle controller for a charge that has an + * active manual override. The top-level charge fields remain the effective + * customer-facing intent. + */ + systemIntent?: ChargeUsageBasedSystemIntent +} + +/** A rate card for a subscription add-on. */ +export interface SubscriptionAddonRateCard { + /** The rate card. */ + rateCard: RateCard + /** The IDs of the subscription items that this rate card belongs to. */ + affectedSubscriptionItemIds: string[] +} + +/** + * The plan phase or pricing ramp allows changing a plan's rate cards over time as + * a subscription progresses. + */ +export interface PlanPhase { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + key: string + /** + * The duration of the phase. When not specified, the phase runs indefinitely. Only + * the last phase may omit the duration. + */ + duration?: string + /** The rate cards of the plan. */ + rateCards: RateCard[] +} + +/** + * Add-on allows extending subscriptions with compatible plans with additional + * ratecards. + */ +export interface Addon { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** + * A key is a semi-unique string that is used to identify the add-on. It is used to + * reference the latest `active` version of the add-on and is unique with the + * version number. + */ + key: string + /** Version of the add-on. Incremented when the add-on is updated. */ + version: number + /** The InstanceType of the add-ons. Can be "single" or "multiple". */ + instanceType: 'single' | 'multiple' + /** The currency code of the add-on. */ + currency: BillingCurrencyCode + /** + * The date and time when the add-on becomes effective. When not specified, the + * add-on is a draft. + */ + effectiveFrom?: Date + /** + * The date and time when the add-on is no longer effective. When not specified, + * the add-on is effective indefinitely. + */ + effectiveTo?: Date + /** + * The status of the add-on. Computed based on the effective start and end dates: + * + * - `draft`: `effective_from` is not set. + * - `active`: `effective_from <= now` and (`effective_to` is not set or + * `now < effective_to`). + * - `archived`: `effective_to <= now`. + */ + status: 'draft' | 'active' | 'archived' + /** The rate cards of the add-on. */ + rateCards: RateCard[] + /** List of validation errors. */ + validationErrors?: ProductCatalogValidationError[] +} + +/** Addon create request. */ +export interface CreateAddonRequest { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** + * A key is a semi-unique string that is used to identify the add-on. It is used to + * reference the latest `active` version of the add-on and is unique with the + * version number. + */ + key: string + /** The InstanceType of the add-ons. Can be "single" or "multiple". */ + instanceType: 'single' | 'multiple' + /** The currency code of the add-on. */ + currency: BillingCurrencyCode + /** The rate cards of the add-on. */ + rateCards: RateCard[] +} + +/** Addon upsert request. */ +export interface UpsertAddonRequest { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** The InstanceType of the add-ons. Can be "single" or "multiple". */ + instanceType: 'single' | 'multiple' + /** The rate cards of the add-on. */ + rateCards: RateCard[] +} + +/** + * A top-level line item on an invoice. + * + * Each line represents a single charge, typically associated with a rate card from + * a subscription. Detailed (child) lines are nested under `detailed_lines` when + * present. + */ +export interface InvoiceStandardLine { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** + * ID of the line. + * + * Optional on update: omit to create a new line, or supply the ID of an existing + * line to edit it. Existing lines omitted from an update's `lines` array are + * deleted. + */ + id?: string + /** The type of charge this line item represents. */ + type: 'standard_line' + /** + * Indicates whether this line item's lifecycle is controlled by OpenMeter or + * manually overridden by the API user. + */ + lifecycleController: 'system' | 'manual' + /** + * The service period covered by this invoice, spanning the earliest line start to + * the latest line end across all of its lines. + * + * For an invoice with no lines the period is empty, which means `from` will be + * equal to `to`. + */ + servicePeriod: ClosedPeriod + /** Aggregated financial totals for the line item. */ + totals: Totals + /** Discounts applied to this line item. */ + discounts?: InvoiceLineDiscounts + /** Credit applied to this line item. */ + creditsApplied?: InvoiceLineCreditsApplied[] + /** External identifiers for this line item assigned by third-party systems. */ + externalReferences?: InvoiceLineExternalReferences + /** Reference to the subscription item that generated this line. */ + subscription?: SubscriptionReference + /** The rate card configuration snapshot used to price this line item. */ + rateCard: InvoiceLineRateCard + /** + * Detailed sub-lines that this line has been broken down into. + * + * Present when line has individual details. + */ + detailedLines: InvoiceDetailedLine[] + /** Reference to the charge associated with this line item. */ + charge?: ChargeReference +} + +/** + * A top-level line item on an invoice. + * + * Each line represents a single charge, typically associated with a rate card from + * a subscription. Detailed (child) lines are nested under `detailed_lines` when + * present. + */ +export interface UpdateInvoiceStandardLine { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: UpdateLabels + /** + * ID of the line. + * + * Optional on update: omit to create a new line, or supply the ID of an existing + * line to edit it. Existing lines omitted from an update's `lines` array are + * deleted. + */ + id?: string + /** The type of charge this line item represents. */ + type: 'standard_line' + /** + * The service period covered by this invoice, spanning the earliest line start to + * the latest line end across all of its lines. + * + * For an invoice with no lines the period is empty, which means `from` will be + * equal to `to`. + */ + servicePeriod: UpdateClosedPeriod + /** The rate card configuration snapshot used to price this line item. */ + rateCard: UpdateInvoiceLineRateCard +} + +/** + * Billing profiles contain the settings for billing and controls invoice + * generation. + */ +export interface Profile { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** + * The name and contact information for the supplier this billing profile + * represents + */ + supplier: Party + /** The billing workflow settings for this profile */ + workflow: Workflow + /** The applications used by this billing profile. */ + apps: ProfileAppReferences + /** Whether this is the default profile. */ + default: boolean +} + +/** BillingProfile create request. */ +export interface CreateBillingProfileRequest { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** + * The name and contact information for the supplier this billing profile + * represents + */ + supplier: Party + /** The billing workflow settings for this profile */ + workflow: Workflow + /** The applications used by this billing profile. */ + apps: ProfileAppReferences + /** Whether this is the default profile. */ + default: boolean +} + +/** BillingProfile upsert request. */ +export interface UpsertBillingProfileRequest { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** + * The name and contact information for the supplier this billing profile + * represents + */ + supplier: Party + /** The billing workflow settings for this profile */ + workflow: Workflow + /** Whether this is the default profile. */ + default: boolean +} + +/** Addon purchased with a subscription. */ +export interface SubscriptionAddon { + id: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + /** The add-on associated with the subscription. */ + addon: AddonReference + /** The quantity of the add-on. Always 1 for single instance add-ons. */ + quantity: number + /** + * An ISO-8601 timestamp representation of which point in time the quantity was + * resolved to. + */ + quantityAt: Date + /** An ISO-8601 timestamp representation of the cadence start of the resource. */ + activeFrom: Date + /** An ISO-8601 timestamp representation of the cadence end of the resource. */ + activeTo?: Date + /** The timeline of the add-on. The returned periods are sorted and continuous. */ + timeline: SubscriptionAddonTimelineSegment[] + /** The rate cards of the add-on. */ + rateCards: SubscriptionAddonRateCard[] +} + +/** Plans provide a template for subscriptions. */ +export interface Plan { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** + * A key is a semi-unique string that is used to identify the plan. It is used to + * reference the latest `active` version of the plan and is unique with the version + * number. + */ + key: string + /** + * Plans are versioned to allow you to make changes without affecting running + * subscriptions. + */ + version: number + /** The currency code of the plan. */ + currency: string + /** The billing cadence for subscriptions using this plan. */ + billingCadence: string + /** Whether pro-rating is enabled for this plan. */ + proRatingEnabled: boolean + /** + * The date and time when the plan becomes `active`. When not specified, the plan + * is in `draft` status. + */ + effectiveFrom?: Date + /** + * A scheduled date and time when the plan becomes `archived`. When not specified, + * the plan is in `active` status indefinitely. + */ + effectiveTo?: Date + /** + * The status of the plan. Computed based on the effective start and end dates: + * + * - `draft`: `effective_from` is not set. + * - `scheduled`: `now < effective_from`. + * - `active`: `effective_from <= now` and (`effective_to` is not set or + * `now < effective_to`). + * - `archived`: `effective_to <= now`. + */ + status: 'draft' | 'active' | 'archived' | 'scheduled' + /** + * The plan phases define the pricing ramp for a subscription. A phase switch + * occurs only at the end of a billing period. At least one phase is required. + */ + phases: PlanPhase[] + /** + * Settlement mode for plan. + * + * Values: + * + * - `credit_then_invoice`: Credits are applied first, then any remainder is + * invoiced. + * - `credit_only`: Usage is settled exclusively against credits. + */ + settlementMode: 'credit_then_invoice' | 'credit_only' + /** + * List of validation errors in `draft` state that prevent the plan from being + * published. + */ + validationErrors?: ProductCatalogValidationError[] +} + +/** Plan create request. */ +export interface CreatePlanRequest { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** + * A key is a semi-unique string that is used to identify the plan. It is used to + * reference the latest `active` version of the plan and is unique with the version + * number. + */ + key: string + /** The currency code of the plan. */ + currency: string + /** The billing cadence for subscriptions using this plan. */ + billingCadence: string + /** Whether pro-rating is enabled for this plan. */ + proRatingEnabled: boolean + /** + * The plan phases define the pricing ramp for a subscription. A phase switch + * occurs only at the end of a billing period. At least one phase is required. + */ + phases: PlanPhase[] +} + +/** Plan upsert request. */ +export interface UpsertPlanRequest { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** Whether pro-rating is enabled for this plan. */ + proRatingEnabled: boolean + /** + * The plan phases define the pricing ramp for a subscription. A phase switch + * occurs only at the end of a billing period. At least one phase is required. + */ + phases: PlanPhase[] +} + +/** Page paginated response. */ +export interface AddonPagePaginatedResponse { + data: Addon[] + meta: PaginatedMeta +} + +/** Page paginated response. */ +export interface ProfilePagePaginatedResponse { + data: Profile[] + meta: PaginatedMeta +} + +/** Page paginated response. */ +export interface ChargePagePaginatedResponse { + data: Charge[] + meta: PaginatedMeta +} + +/** Page paginated response. */ +export interface SubscriptionAddonPagePaginatedResponse { + data: SubscriptionAddon[] + meta: PaginatedMeta +} + +/** Page paginated response. */ +export interface PlanPagePaginatedResponse { + data: Plan[] + meta: PaginatedMeta +} + +/** A standard invoice for charges owed by the customer. */ +export interface InvoiceStandard { + id: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** Human-readable invoice number generated by the invoicing app. */ + number: string + /** Three-letter ISO 4217 currency code for the invoice. */ + currency: string + /** + * Snapshot of the supplier's contact information at the time the invoice was + * issued. + */ + supplier: Supplier + /** Snapshot of the customer's information at the time the invoice was issued. */ + customer: InvoiceCustomer + /** Aggregated financial totals for the invoice. */ + totals: Totals + /** + * The service period covered by this invoice. + * + * For flat fee the service period can be empty which means `from` will be equals + * to `to`. In other cases those fields will be filled with the actual service + * period. + */ + servicePeriod: ClosedPeriod + /** + * Validation issues found during invoice processing. + * + * Present only when there are one or more validation findings. An empty list is + * omitted. + */ + validationIssues?: InvoiceValidationIssue[] + /** External identifiers assigned to this invoice by third-party systems. */ + externalReferences?: InvoiceExternalReferences + /** Discriminator field identifying this as a standard invoice. */ + type: 'standard' + /** Current lifecycle status of the invoice. */ + status: + | 'draft' + | 'issuing' + | 'issued' + | 'payment_processing' + | 'overdue' + | 'paid' + | 'uncollectible' + | 'voided' + /** Detailed status information including available actions and workflow state. */ + statusDetails: InvoiceStatusDetails + /** Timestamp when the invoice was issued to the customer. */ + issuedAt?: Date + /** + * Timestamp until which the invoice remains in draft state. + * + * The invoice advances automatically once this time is reached. + */ + draftUntil?: Date + /** Timestamp when usage quantities were last snapshotted for this invoice. */ + quantitySnapshottedAt?: Date + /** Timestamp when collection was initiated for this invoice. */ + collectionAt?: Date + /** Timestamp when payment is due. */ + dueAt?: Date + /** Timestamp when the invoice was sent to the customer. */ + sentToCustomerAt?: Date + /** Workflow configuration snapshot captured at invoice creation time. */ + workflow: InvoiceWorkflowSettings + /** + * Line items on this invoice. + * + * Always returned on single-resource GET; omitted on list endpoints unless + * explicitly expanded. Editable via update: existing lines are matched by `id`, + * lines without an `id` are created, and lines present on the invoice but omitted + * from the update request are deleted. Detailed (child) lines are always computed + * and cannot be edited directly. + */ + lines?: InvoiceLine[] +} + +/** InvoiceStandard update request. */ +export interface UpdateInvoiceStandardRequest { + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: UpdateLabels + /** + * Snapshot of the supplier's contact information at the time the invoice was + * issued. + */ + supplier: UpdateSupplier + /** Snapshot of the customer's information at the time the invoice was issued. */ + customer: UpdateInvoiceCustomer + /** Discriminator field identifying this as a standard invoice. */ + type: 'standard' + /** Workflow configuration snapshot captured at invoice creation time. */ + workflow: UpdateInvoiceWorkflowSettings + /** + * Line items on this invoice. + * + * Always returned on single-resource GET; omitted on list endpoints unless + * explicitly expanded. Editable via update: existing lines are matched by `id`, + * lines without an `id` are created, and lines present on the invoice but omitted + * from the update request are deleted. Detailed (child) lines are always computed + * and cannot be edited directly. + */ + lines?: UpdateInvoiceLine[] +} + +/** Page paginated response. */ +export interface InvoicePagePaginatedResponse { + data: Invoice[] + meta: PaginatedMeta +} + +/** + * Filters on the given string field value by either exact or fuzzy match. All + * properties are optional; provide exactly one to specify the comparison. + */ +export type StringFieldFilter = + | string + | { + eq?: string + neq?: string + contains?: string + ocontains?: string[] + oeq?: string[] + gt?: string + gte?: string + lt?: string + lte?: string + exists?: boolean + } + +/** The aggregation type to use for the meter. */ +export type MeterAggregation = + | 'sum' + | 'count' + | 'unique_count' + | 'avg' + | 'min' + | 'max' + | 'latest' + +/** + * The granularity of the time grouping. Time durations are specified in ISO 8601 + * format. + */ +export type MeterQueryGranularity = 'PT1M' | 'PT1H' | 'P1D' | 'P1M' + +/** + * Filters on the given string field value by exact match. All properties are + * optional; provide exactly one to specify the comparison. + */ +export type StringFieldFilterExact = + | string + | { eq?: string; oeq?: string[]; neq?: string } + +/** The payment term of a flat price. */ +export type PricePaymentTerm = 'in_advance' | 'in_arrears' + +/** Fiat or custom currency code. */ +export type BillingCurrencyCode = string + +/** Fiat or custom currency code. */ +export type CreateCurrencyCode = string + +/** + * Filters on the given ULID field value by exact match. All properties are + * optional; provide exactly one to specify the comparison. + */ +export type UlidFieldFilter = + | string + | { eq?: string; oeq?: string[]; neq?: string } + +/** + * Filters on the given datetime (RFC-3339) field value. All properties are + * optional; provide exactly one to specify the comparison. + */ +export type DateTimeFieldFilter = + | Date + | { eq?: Date; lt?: Date; lte?: Date; gt?: Date; gte?: Date } + +/** + * Subscription edit timing defined when the changes should take effect. If the + * provided configuration is not supported by the subscription, an error will be + * returned. + */ +export type SubscriptionEditTiming = 'immediate' | 'next_billing_cycle' | Date + +/** Request to install an app from the catalog. */ +export type InstallAppRequest = + | InstallAppStripeWithApiKey + | InstallAppSandbox + | InstallAppExternalInvoicing + +/** Payment settings for a billing workflow. */ +export type WorkflowPaymentSettings = + | WorkflowPaymentChargeAutomaticallySettings + | WorkflowPaymentSendInvoiceSettings + +/** Payment settings for a billing workflow. */ +export type UpdateBillingWorkflowPaymentSettings = + | UpdateBillingWorkflowPaymentChargeAutomaticallySettings + | UpdateBillingWorkflowPaymentSendInvoiceSettings + +/** A parameter that failed validation. */ +export type InvalidParameter = + | InvalidParameterStandard + | InvalidParameterMinimumLength + | InvalidParameterMaximumLength + | InvalidParameterChoiceItem + | InvalidParameterDependentItem + +/** + * Entitlement template configured on a rate card. The feature is taken from the + * rate card itself, so it is omitted here. + */ +export type RateCardEntitlement = + | RateCardMeteredEntitlement + | RateCardStaticEntitlement + | RateCardBooleanEntitlement + +/** Fiat or custom currency. */ +export type Currency = CurrencyFiat | CurrencyCustom + +/** + * Per-unit cost configuration for a feature. Either a fixed manual amount or a + * dynamic LLM cost lookup. + */ +export type FeatureUnitCost = FeatureManualUnitCost | FeatureLlmUnitCost + +/** + * The alignment for collecting the pending line items into an invoice. + * + * Defaults to subscription, which means that we are to create a new invoice every + * time the a subscription period starts (for in advance items) or ends (for in + * arrears items). + */ +export type WorkflowCollectionAlignment = + | WorkflowCollectionAlignmentSubscription + | WorkflowCollectionAlignmentAnchored + +/** Price. */ +export type Price = + | PriceFree + | PriceFlat + | PriceUnit + | PriceGraduated + | PriceVolume + +/** Price. */ +export type UpdatePrice = + | UpdatePriceFree + | UpdatePriceFlat + | UpdatePriceUnit + | UpdatePriceGraduated + | UpdatePriceVolume + +/** Installed application. */ +export type App = AppStripe | AppSandbox | AppExternalInvoicing + +/** Customer charge. */ +export type CreateChargeRequest = + | CreateChargeFlatFeeRequest + | CreateChargeUsageBasedRequest + +/** Customer charge. */ +export type Charge = ChargeFlatFee | ChargeUsageBased + +/** + * A top-level line item on an invoice. + * + * Each line represents a single charge, typically associated with a rate card from + * a subscription. Detailed (child) lines are nested under `detailed_lines` when + * present. + */ +export type InvoiceLine = InvoiceStandardLine + +/** + * A top-level line item on an invoice. + * + * Each line represents a single charge, typically associated with a rate card from + * a subscription. Detailed (child) lines are nested under `detailed_lines` when + * present. + */ +export type UpdateInvoiceLine = UpdateInvoiceStandardLine + +/** + * An invoice issued to a customer. + * + * The `type` field determines the concrete variant: + * + * - `standard`: a standard invoice for charges owed. + */ +export type Invoice = InvoiceStandard + +/** UpdateInvoiceRequest update request. */ +export type UpdateInvoiceRequest = UpdateInvoiceStandardRequest + +/** + * Sort query. + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ +export interface SortQueryInput { + /** The attribute to sort by. */ + by: string + /** The sort order. `asc` for ascending, `desc` for descending. */ + order?: 'asc' | 'desc' +} + +/** Standard error response. */ +export interface BaseErrorInput { + /** Type contains a URI that identifies the problem type. */ + type?: string + /** + * The HTTP status code generated by the origin server for this occurrence of the + * problem. + */ + status: number + /** A a short, human-readable summary of the problem type. */ + title: string + /** A human-readable explanation specific to this occurrence of the problem. */ + detail: string + /** A URI reference that identifies the specific occurrence of the problem. */ + instance: string + [key: string]: unknown +} + +/** + * Payment settings for a billing workflow when the collection method is send + * invoice. + */ +export interface WorkflowPaymentSendInvoiceSettingsInput { + /** The collection method for the invoice. */ + collectionMethod: 'send_invoice' + /** + * The period after which the invoice is due. With some payment solutions it's only + * applicable for manual collection method. + */ + dueAfter?: string +} + +/** + * Invoice-level invoicing settings. + * + * A subset of BillingWorkflowInvoicingSettings limited to fields that are + * meaningful per-invoice. progressive_billing is omitted as it is a gather-time / + * profile-level decision. + */ +export interface InvoiceWorkflowInvoicingSettingsInput { + /** Whether to automatically issue the invoice after the draft_period has passed. */ + autoAdvance?: boolean + /** The period for the invoice to be kept in draft status for manual reviews. */ + draftPeriod?: string + /** The period after which the invoice is considered overdue if not paid. */ + dueAfter?: string +} + +/** + * Invoice-level invoicing settings. + * + * A subset of BillingWorkflowInvoicingSettings limited to fields that are + * meaningful per-invoice. progressive_billing is omitted as it is a gather-time / + * profile-level decision. + */ +export interface UpdateBillingInvoiceWorkflowInvoicingSettingsInput { + /** Whether to automatically issue the invoice after the draft_period has passed. */ + autoAdvance?: boolean + /** The period for the invoice to be kept in draft status for manual reviews. */ + draftPeriod?: string +} + +/** + * Payment settings for a billing workflow when the collection method is send + * invoice. + */ +export interface UpdateBillingWorkflowPaymentSendInvoiceSettingsInput { + /** The collection method for the invoice. */ + collectionMethod: 'send_invoice' + /** + * The period after which the invoice is due. With some payment solutions it's only + * applicable for manual collection method. + */ + dueAfter?: string +} + +/** Metering event following the CloudEvents specification. */ +export interface EventInput { + /** Identifies the event. */ + id: string + /** Identifies the context in which an event happened. */ + source: string + /** The version of the CloudEvents specification which the event uses. */ + specversion?: string + /** + * Contains a value describing the type of event related to the originating + * occurrence. + */ + type: string + /** + * Content type of the CloudEvents data value. Only the value "application/json" is + * allowed over HTTP. + */ + datacontenttype?: 'application/json' | null + /** Identifies the schema that data adheres to. */ + dataschema?: string | null + /** + * Describes the subject of the event in the context of the event producer + * (identified by source). + */ + subject: string + /** Timestamp of when the occurrence happened. Must adhere to RFC 3339. */ + time?: Date | null + /** The event payload. Optional, if present it must be a JSON object. */ + data?: Record | null +} + +/** Unauthorized. */ +export interface UnauthorizedInput extends BaseErrorInput {} + +/** Forbidden. */ +export interface ForbiddenInput extends BaseErrorInput {} + +/** Not Found. */ +export interface NotFoundInput extends BaseErrorInput {} + +/** Gone. */ +export interface GoneInput extends BaseErrorInput {} + +/** Conflict. */ +export interface ConflictInput extends BaseErrorInput {} + +/** Payload Too Large. */ +export interface PayloadTooLargeInput extends BaseErrorInput {} + +/** Unsupported Media Type. */ +export interface UnsupportedMediaTypeInput extends BaseErrorInput {} + +/** Unprocessable Content. */ +export interface UnprocessableContentInput extends BaseErrorInput {} + +/** Too Many Requests. */ +export interface TooManyRequestsInput extends BaseErrorInput {} + +/** Internal Server Error. */ +export interface InternalInput extends BaseErrorInput {} + +/** Not Implemented. */ +export interface NotImplementedInput extends BaseErrorInput {} + +/** Not Available. */ +export interface NotAvailableInput extends BaseErrorInput {} + +/** Controls which customer fields can be updated by the checkout session. */ +export interface AppStripeCreateCheckoutSessionCustomerUpdateInput { + /** + * Whether to save the billing address to customer.address. + * + * Defaults to "never". + */ + address?: 'auto' | 'never' + /** + * Whether to save the customer name to customer.name. + * + * Defaults to "never". + */ + name?: 'auto' | 'never' + /** + * Whether to save shipping information to customer.shipping. + * + * Defaults to "never". + */ + shipping?: 'auto' | 'never' +} + +/** Tax ID collection configuration for checkout sessions. */ +export interface AppStripeCreateCheckoutSessionTaxIdCollectionInput { + /** + * Enable tax ID collection during checkout. + * + * Defaults to false. + */ + enabled?: boolean + /** + * Whether tax ID collection is required. + * + * Defaults to "never". + */ + required?: 'if_supported' | 'never' +} + +/** Purchase and payment terms of the grant. */ +export interface CreateCreditGrantPurchaseInput { + /** Currency of the purchase amount. */ + currency: string + /** + * Cost basis per credit unit used to calculate the purchase amount. + * + * If `per_unit_cost_basis` is 0.50 and credit amount is $100.00, the total charge + * is $50.00. The value must be greater than 0. If the cost basis is 0, use + * `funding_method=none` instead. + * + * Defaults to 1.0. + */ + perUnitCostBasis?: string + /** + * Controls when credits become available for consumption. + * + * Defaults to `on_creation`. + */ + availabilityPolicy?: 'on_creation' +} + +/** The entitlement template of a metered entitlement. */ +export interface RateCardMeteredEntitlementInput { + /** The type of the entitlement template. */ + type: 'metered' + /** + * If soft limit is true, the subject can use the feature even if the entitlement + * is exhausted; access remains granted. + */ + isSoftLimit?: boolean + /** + * The amount of usage granted each usage period, in the feature's unit. Usage is + * counted against this allowance and the balance resets every usage period. When + * `is_soft_limit` is true the subject keeps access after the limit is reached; + * otherwise access is denied once the allowance is exhausted. + */ + limit?: number + /** + * The reset interval of the metered entitlement in ISO8601 format. Defaults to the + * billing cadence of the rate card. + */ + usagePeriod?: string +} + +/** Purchase and payment terms of the grant. */ +export interface CreditGrantPurchaseInput { + /** Currency of the purchase amount. */ + currency: string + /** + * Cost basis per credit unit used to calculate the purchase amount. + * + * If `per_unit_cost_basis` is 0.50 and credit amount is $100.00, the total charge + * is $50.00. The value must be greater than 0. If the cost basis is 0, use + * `funding_method=none` instead. + * + * Defaults to 1.0. + */ + perUnitCostBasis?: string + /** The purchase amount. Calculated from `per_unit_cost_basis` and credit `amount`. */ + amount: string + /** + * Controls when credits become available for consumption. + * + * Defaults to `on_creation`. + */ + availabilityPolicy?: 'on_creation' + /** Current payment settlement status. */ + settlementStatus?: 'pending' | 'authorized' | 'settled' +} + +/** Request body for voiding a credit grant. */ +export interface VoidCreditGrantRequestInput { + /** + * How voiding adjusts payment state related to the grant. + * + * Currently only `none` is supported: voiding does not adjust invoices, payment + * authorization, settlement, payment intents, or external collection state. If + * payment later completes, the original invoiced amount may still be collected. + */ + paymentAdjustment?: 'none' +} + +/** + * Unit conversion configuration. + * + * Transforms raw metered quantities into billing-ready units before pricing and + * entitlement evaluation. Applied at the rate card level so the same feature can + * be billed in different units across plans. + * + * Examples: + * + * - Meter bytes, bill GB: operation=divide, conversionFactor=1e9, + * rounding=ceiling, displayUnit="GB" + * - Meter seconds, bill hours: operation=divide, conversionFactor=3600, + * rounding=ceiling, displayUnit="hours" + * - Cost + 20% margin: operation=multiply, conversionFactor=1.2 + * - Bill per million tokens: operation=divide, conversionFactor=1e6, + * rounding=ceiling, displayUnit="M" + * + * v1 equivalents: + * + * - DynamicPrice(multiplier): operation=multiply, conversionFactor=multiplier + + * UnitPrice(amount=1) + * - PackagePrice(amount, quantityPerPkg): operation=divide, + * conversionFactor=quantityPerPkg, rounding=ceiling + UnitPrice(amount) + */ +export interface UnitConfigInput { + /** The arithmetic operation to apply to the raw metered quantity. */ + operation: 'divide' | 'multiply' + /** + * The factor used in the conversion operation. + * + * - For `divide`: `converted = raw / conversionFactor`. + * - For `multiply`: `converted = raw × conversionFactor`. + * + * Must be a positive non-zero value. + */ + conversionFactor: string + /** + * The rounding mode applied to the converted quantity for invoicing. + * + * Defaults to none (no rounding). Entitlement checks always use the precise + * (unrounded) value. + */ + rounding?: 'ceiling' | 'floor' | 'half_up' | 'none' + /** + * The number of decimal places to retain after rounding. + * + * Only meaningful when rounding is not "none". Defaults to 0 (round to whole + * numbers). + */ + precision?: number + /** + * A human-readable label for the converted unit shown on invoices and in the + * customer portal (e.g., "GB", "hours", "M tokens"). + * + * Optional. When omitted, no unit label is rendered. + */ + displayUnit?: string +} + +/** Invoice settings for a billing workflow. */ +export interface WorkflowInvoicingSettingsInput { + /** Whether to automatically issue the invoice after the draftPeriod has passed. */ + autoAdvance?: boolean + /** The period for the invoice to be kept in draft status for manual reviews. */ + draftPeriod?: string + /** Should progressive billing be allowed for this workflow? */ + progressiveBilling?: boolean + /** Controls how subscription-ending shortened service periods are billed. */ + subscriptionEndProrationMode?: 'bill_full_period' | 'bill_actual_period' +} + +/** Query to evaluate feature access for a list of customers. */ +export interface GovernanceQueryRequestInput { + /** + * Whether to include credit balance availability for each resolved customer. When + * true, each feature evaluation includes credit balance checks. + * + * Defaults to `false`. + */ + includeCredits?: boolean + customer: GovernanceQueryRequestCustomers + feature?: GovernanceQueryRequestFeatures +} + +/** An ingested metering event with ingestion metadata. */ +export interface IngestedEventInput { + /** The original event ingested. */ + event: EventInput + /** The customer if the event is associated with a customer. */ + customer?: CustomerReference + /** The date and time the event was ingested and its processing started. */ + ingestedAt: Date + /** The date and time the event was stored in the database. */ + storedAt: Date + /** The validation errors of the ingested event. */ + validationErrors?: IngestedEventValidationError[] +} + +/** Request for canceling a subscription. */ +export interface SubscriptionCancelInput { + /** If not provided the subscription is canceled immediately. */ + timing?: SubscriptionEditTiming +} + +/** + * Usage quantity details on an invoice line item when UnitConfig is in effect. + * + * Provides the full audit trail from raw meter output to the invoiced amount. + */ +export interface InvoiceUsageQuantityDetailInput { + /** The raw quantity as reported by the meter (native units). */ + rawQuantity: string + /** + * The precise decimal value after applying the conversion operation and factor, + * before rounding. + */ + convertedQuantity: string + /** The quantity after rounding, used for pricing. */ + invoicedQuantity: string + /** The display unit label (e.g., "GB", "hours", "M tokens"). */ + displayUnit?: string + /** + * Snapshot of the UnitConfig that was in effect at billing time. Ensures + * historical invoices reflect the config that was actually applied. + */ + appliedUnitConfig: UnitConfigInput +} + +/** + * Invoice-level snapshot of the workflow configuration. + * + * Contains only the settings that are meaningful for an already-created invoice: + * invoicing behaviour and payment settings. Collection alignment and tax policy + * are gather-time / profile-wide concerns and are not included. + */ +export interface InvoiceWorkflowInput { + /** Invoicing settings for this invoice. */ + invoicing?: InvoiceWorkflowInvoicingSettingsInput + /** Payment settings for this invoice. */ + payment?: WorkflowPaymentSettingsInput +} + +/** + * Invoice-level snapshot of the workflow configuration. + * + * Contains only the settings that are meaningful for an already-created invoice: + * invoicing behaviour and payment settings. Collection alignment and tax policy + * are gather-time / profile-wide concerns and are not included. + */ +export interface UpdateBillingInvoiceWorkflowInput { + /** Invoicing settings for this invoice. */ + invoicing?: UpdateBillingInvoiceWorkflowInvoicingSettingsInput + /** Payment settings for this invoice. */ + payment?: UpdateBillingWorkflowPaymentSettingsInput +} + +/** CreditGrant create request. */ +export interface CreateCreditGrantRequestInput { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: CreateLabels + /** Funding method of the grant. */ + fundingMethod: 'none' | 'invoice' | 'external' + /** The currency of the granted credits. */ + currency: CreateCurrencyCode + /** Granted credit amount. */ + amount: string + /** Present when a funding workflow applies (funding_method is not `none`). */ + purchase?: CreateCreditGrantPurchaseInput + /** + * Tax configuration for the grant. + * + * For `invoice` and `external` funding methods, tax configuration should be + * provided to ensure correct revenue recognition. When not provided, the default + * credit grant tax code is applied, if that's not set the global default taxcode + * is used. + */ + taxConfig?: CreateCreditGrantTaxConfig + filters?: CreateCreditGrantFilters + /** Draw-down priority of the grant. Lower values have higher priority. */ + priority?: number + /** + * The timestamp when the credit grant becomes effective. + * + * Defaults to the current date and time. + */ + effectiveAt?: Date + /** + * The duration after which the credit grant expires. + * + * Defaults to never expiring. + */ + expiresAfter?: string + /** + * Idempotency key for the credit grant creation request. + * + * When provided, reusing the same key returns an HTTP 409 Conflict instead of + * creating a duplicate grant, which makes create requests safe to retry. + */ + key?: string +} + +/** + * A credit grant allocates credits to a customer. + * + * Credits are drawn down against charges according to the settlement mode + * configured on the rate card. + */ +export interface CreditGrantInput { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** Funding method of the grant. */ + fundingMethod: 'none' | 'invoice' | 'external' + /** The currency of the granted credits. */ + currency: BillingCurrencyCode + /** Granted credit amount. */ + amount: string + /** Present when a funding workflow applies (funding_method is not `none`). */ + purchase?: CreditGrantPurchaseInput + /** + * Tax configuration for the grant. + * + * For `invoice` and `external` funding methods, tax configuration should be + * provided to ensure correct revenue recognition. When not provided, the default + * credit grant tax code is applied, if that's not set the global default taxcode + * is used. + */ + taxConfig?: CreditGrantTaxConfig + /** Available when `funding_method` is `invoice`. */ + invoice?: CreditGrantInvoiceReference + filters?: CreditGrantFilters + /** Draw-down priority of the grant. Lower values have higher priority. */ + priority?: number + /** + * The timestamp when the credit grant becomes effective. + * + * Defaults to the current date and time. + */ + effectiveAt?: Date + /** + * Idempotency key for the credit grant creation request. + * + * When provided, reusing the same key returns an HTTP 409 Conflict instead of + * creating a duplicate grant, which makes create requests safe to retry. + */ + key?: string + /** + * The timestamp when the credit grant expires. + * + * Calculated from the grant effective time and `expires_after` if provided. + */ + expiresAt?: Date + /** Timestamp when the grant was voided. */ + voidedAt?: Date + /** Current lifecycle status of the grant. */ + status: 'pending' | 'active' | 'expired' | 'voided' +} + +/** Tax settings for a billing workflow. */ +export interface WorkflowTaxSettingsInput { + /** + * Enable automatic tax calculation when tax is supported by the app. For example, + * with Stripe Invoicing when enabled, tax is calculated via Stripe Tax. + */ + enabled?: boolean + /** + * Enforce tax calculation when tax is supported by the app. When enabled, the + * billing system will not allow to create an invoice without tax calculation. + * Enforcement is different per apps, for example, Stripe app requires customer to + * have a tax location when starting a paid subscription. + */ + enforced?: boolean + /** + * Default tax configuration to apply to the invoices for line items. + * + * Setting a tax code (`stripe.code` / `taxCodeId`) on a profile's default tax + * config is deprecated and can no longer be added or changed: the organization + * default tax code is used instead. Existing tax-code values may still be removed, + * and `behavior` remains fully supported. + */ + defaultTaxConfig?: TaxConfig +} + +/** Cursor paginated response. */ +export interface IngestedEventPaginatedResponseInput { + data: IngestedEventInput[] + meta: CursorMeta +} + +/** A meter query request. */ +export interface MeterQueryRequestInput { + /** The start of the period the usage is queried from. */ + from?: Date + /** The end of the period the usage is queried to. */ + to?: Date + /** + * The size of the time buckets to group the usage into. If not specified, the + * usage is aggregated over the entire period. + */ + granularity?: MeterQueryGranularity + /** + * The value is the name of the time zone as defined in the IANA Time Zone Database + * (http://www.iana.org/time-zones). The time zone is used to determine the start + * and end of the time buckets. If not specified, the UTC timezone will be used. + */ + timeZone?: string + /** The dimensions to group the results by. */ + groupByDimensions?: string[] + /** Filters to apply to the query. */ + filters?: MeterQueryFilters +} + +/** + * Configuration options for creating a Stripe Checkout Session. + * + * Based on Stripe's + * [Checkout Session API parameters](https://docs.stripe.com/api/checkout/sessions/create). + */ +export interface AppStripeCreateCheckoutSessionRequestOptionsInput { + /** + * Whether to collect the customer's billing address. + * + * Defaults to auto, which only collects the address when necessary for tax + * calculation. + */ + billingAddressCollection?: 'auto' | 'required' + /** + * URL to redirect customers who cancel the checkout session. + * + * Not allowed when ui_mode is "embedded". + */ + cancelUrl?: string + /** + * Unique reference string for reconciling sessions with internal systems. + * + * Can be a customer ID, cart ID, or any other identifier. + */ + clientReferenceId?: string + /** Controls which customer fields can be updated by the checkout session. */ + customerUpdate?: AppStripeCreateCheckoutSessionCustomerUpdateInput + /** Configuration for collecting customer consent during checkout. */ + consentCollection?: AppStripeCreateCheckoutSessionConsentCollection + /** + * Three-letter ISO 4217 currency code in uppercase. + * + * Required for payment mode sessions. Optional for setup mode sessions. + */ + currency?: string + /** Custom text to display during checkout at various stages. */ + customText?: AppStripeCheckoutSessionCustomTextParams + /** + * Unix timestamp when the checkout session expires. + * + * Can be 30 minutes to 24 hours from creation. Defaults to 24 hours. + */ + expiresAt?: bigint + /** + * IETF language tag for the checkout UI locale. + * + * If blank or "auto", uses the browser's locale. Example: "en", "fr", "de". + */ + locale?: string + /** + * Set of key-value pairs to attach to the checkout session. + * + * Useful for storing additional structured information. + */ + metadata?: Record + /** + * Return URL for embedded checkout sessions after payment authentication. + * + * Required if ui_mode is "embedded" and redirect-based payment methods are + * enabled. + */ + returnUrl?: string + /** + * Success URL to redirect customers after completing payment or setup. + * + * Not allowed when ui_mode is "embedded". See: + * https://docs.stripe.com/payments/checkout/custom-success-page + */ + successUrl?: string + /** + * The UI mode for the checkout session. + * + * "hosted" displays a Stripe-hosted page. "embedded" integrates directly into your + * app. Defaults to "hosted". + */ + uiMode?: 'embedded' | 'hosted' + /** + * List of payment method types to enable (e.g., "card", "us_bank_account"). + * + * If not specified, Stripe enables all relevant payment methods. + */ + paymentMethodTypes?: string[] + /** + * Redirect behavior for embedded checkout sessions. + * + * Controls when to redirect users after completion. See: + * https://docs.stripe.com/payments/checkout/custom-success-page?payment-ui=embedded-form + */ + redirectOnCompletion?: 'always' | 'if_required' | 'never' + /** Configuration for collecting tax IDs during checkout. */ + taxIdCollection?: AppStripeCreateCheckoutSessionTaxIdCollectionInput +} + +/** Snapshot of the billing workflow configuration captured at invoice creation. */ +export interface InvoiceWorkflowSettingsInput { + /** The apps that will be used to orchestrate the invoice's workflow. */ + apps?: InvoiceWorkflowAppsReferences + /** The billing profile that was the source of this workflow snapshot. */ + sourceBillingProfile: ProfileReference + /** + * The workflow configuration that was active when the invoice was created. + * + * Only the fields that are meaningful at the per-invoice level are included: + * invoicing behaviour (auto-advance, draft period) and payment settings + * (collection method, due date). Profile-wide settings such as collection + * alignment, progressive billing, and tax policy are omitted. + */ + workflow: InvoiceWorkflowInput +} + +/** + * A detailed (child) sub-line belonging to a parent invoice line. + * + * Detailed lines represent the individual flat-fee components that make up a + * usage-based parent line after quantity snapshotting. + */ +export interface InvoiceDetailedLineInput { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** The service period covered by this detailed line. */ + servicePeriod: ClosedPeriod + /** Aggregated financial totals for the detailed line. */ + totals: Totals + /** The cost category of this detailed line. */ + category?: 'regular' | 'commitment' + /** Discounts applied to this detailed line. */ + discounts?: InvoiceLineDiscounts + /** Credit applied to this detailed line. */ + creditsApplied?: InvoiceLineCreditsApplied[] + /** External identifiers for this detailed line. */ + externalReferences?: InvoiceLineExternalReferences + /** The quantity of the detailed line. */ + quantity: string + /** The unit price of the detailed line. */ + unitPrice: string +} + +/** Snapshot of the billing workflow configuration captured at invoice creation. */ +export interface UpdateInvoiceWorkflowSettingsInput { + /** + * The workflow configuration that was active when the invoice was created. + * + * Only the fields that are meaningful at the per-invoice level are included: + * invoicing behaviour (auto-advance, draft period) and payment settings + * (collection method, due date). Profile-wide settings such as collection + * alignment, progressive billing, and tax policy are omitted. + */ + workflow: UpdateBillingInvoiceWorkflowInput +} + +/** Page paginated response. */ +export interface CreditGrantPagePaginatedResponseInput { + data: CreditGrantInput[] + meta: PaginatedMeta +} + +/** Bad Request. */ +export interface BadRequestInput extends BaseErrorInput { + /** The list of parameters that failed validation. */ + invalidParameters: InvalidParameter[] +} + +/** + * Request to create a Stripe Checkout Session for the customer. + * + * Checkout Sessions are used to collect payment method information from customers + * in a secure, Stripe-hosted interface. This integration uses setup mode to + * collect payment methods that can be charged later for subscription billing. + */ +export interface CustomerStripeCreateCheckoutSessionRequestInput { + /** + * Options for configuring the Stripe Checkout Session. + * + * These options are passed directly to Stripe's + * [checkout session creation API](https://docs.stripe.com/api/checkout/sessions/create). + */ + stripeOptions: AppStripeCreateCheckoutSessionRequestOptionsInput +} + +/** + * Workflow collection specifies how to collect the pending line items for an + * invoice. + */ +export interface WorkflowCollectionSettingsInput { + /** The alignment for collecting the pending line items into an invoice. */ + alignment?: WorkflowCollectionAlignment + /** + * This grace period can be used to delay the collection of the pending line items + * specified in alignment. + * + * This is useful, in case of multiple subscriptions having slightly different + * billing periods. + */ + interval?: string +} + +/** A rate card defines the pricing and entitlement of a feature or service. */ +export interface RateCardInput { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + key: string + /** The feature associated with the rate card. */ + feature?: FeatureReference + /** + * The billing cadence of the rate card. When null, the charge is one-time + * (non-recurring). Only valid for flat prices. + */ + billingCadence?: string + /** The price of the rate card. */ + price: Price + /** + * Unit conversion configuration for the rate card. + * + * Synthesized on read for plans authored with v1 dynamic or package prices: + * dynamic prices map to a unit price with a multiply unit config, and package + * prices map to a unit price with a divide unit config. + * + * Accepted on create and update only when the UnitConfig feature is enabled on the + * deployment; otherwise rejected. + */ + unitConfig?: UnitConfigInput + /** + * The payment term of the rate card. In advance payment term can only be used for + * flat prices. + */ + paymentTerm?: PricePaymentTerm + /** + * Spend commitments for this rate card. Only applicable to usage-based prices + * (unit, graduated, volume). + */ + commitments?: SpendCommitments + /** The discounts of the rate card. */ + discounts?: RateCardDiscounts + /** The tax config of the rate card. */ + taxConfig?: RateCardTaxConfig + /** + * The entitlement template granted to subscribers of a plan or addon containing + * this rate card. Requires `feature` to be set. + */ + entitlement?: RateCardEntitlementInput +} + +/** Billing workflow settings. */ +export interface WorkflowInput { + /** The collection settings for this workflow */ + collection?: WorkflowCollectionSettingsInput + /** The invoicing settings for this workflow */ + invoicing?: WorkflowInvoicingSettingsInput + /** The payment settings for this workflow */ + payment?: WorkflowPaymentSettingsInput + /** The tax settings for this workflow */ + tax?: WorkflowTaxSettingsInput +} + +/** A rate card for a subscription add-on. */ +export interface SubscriptionAddonRateCardInput { + /** The rate card. */ + rateCard: RateCardInput + /** The IDs of the subscription items that this rate card belongs to. */ + affectedSubscriptionItemIds: string[] +} + +/** + * The plan phase or pricing ramp allows changing a plan's rate cards over time as + * a subscription progresses. + */ +export interface PlanPhaseInput { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + key: string + /** + * The duration of the phase. When not specified, the phase runs indefinitely. Only + * the last phase may omit the duration. + */ + duration?: string + /** The rate cards of the plan. */ + rateCards: RateCardInput[] +} + +/** + * Add-on allows extending subscriptions with compatible plans with additional + * ratecards. + */ +export interface AddonInput { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** + * A key is a semi-unique string that is used to identify the add-on. It is used to + * reference the latest `active` version of the add-on and is unique with the + * version number. + */ + key: string + /** Version of the add-on. Incremented when the add-on is updated. */ + version?: number + /** The InstanceType of the add-ons. Can be "single" or "multiple". */ + instanceType: 'single' | 'multiple' + /** The currency code of the add-on. */ + currency: BillingCurrencyCode + /** + * The date and time when the add-on becomes effective. When not specified, the + * add-on is a draft. + */ + effectiveFrom?: Date + /** + * The date and time when the add-on is no longer effective. When not specified, + * the add-on is effective indefinitely. + */ + effectiveTo?: Date + /** + * The status of the add-on. Computed based on the effective start and end dates: + * + * - `draft`: `effective_from` is not set. + * - `active`: `effective_from <= now` and (`effective_to` is not set or + * `now < effective_to`). + * - `archived`: `effective_to <= now`. + */ + status: 'draft' | 'active' | 'archived' + /** The rate cards of the add-on. */ + rateCards: RateCardInput[] + /** List of validation errors. */ + validationErrors?: ProductCatalogValidationError[] +} + +/** Addon create request. */ +export interface CreateAddonRequestInput { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** + * A key is a semi-unique string that is used to identify the add-on. It is used to + * reference the latest `active` version of the add-on and is unique with the + * version number. + */ + key: string + /** The InstanceType of the add-ons. Can be "single" or "multiple". */ + instanceType: 'single' | 'multiple' + /** The currency code of the add-on. */ + currency: BillingCurrencyCode + /** The rate cards of the add-on. */ + rateCards: RateCardInput[] +} + +/** Addon upsert request. */ +export interface UpsertAddonRequestInput { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** The InstanceType of the add-ons. Can be "single" or "multiple". */ + instanceType: 'single' | 'multiple' + /** The rate cards of the add-on. */ + rateCards: RateCardInput[] +} + +/** + * A top-level line item on an invoice. + * + * Each line represents a single charge, typically associated with a rate card from + * a subscription. Detailed (child) lines are nested under `detailed_lines` when + * present. + */ +export interface InvoiceStandardLineInput { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** + * ID of the line. + * + * Optional on update: omit to create a new line, or supply the ID of an existing + * line to edit it. Existing lines omitted from an update's `lines` array are + * deleted. + */ + id?: string + /** The type of charge this line item represents. */ + type: 'standard_line' + /** + * Indicates whether this line item's lifecycle is controlled by OpenMeter or + * manually overridden by the API user. + */ + lifecycleController: 'system' | 'manual' + /** + * The service period covered by this invoice, spanning the earliest line start to + * the latest line end across all of its lines. + * + * For an invoice with no lines the period is empty, which means `from` will be + * equal to `to`. + */ + servicePeriod: ClosedPeriod + /** Aggregated financial totals for the line item. */ + totals: Totals + /** Discounts applied to this line item. */ + discounts?: InvoiceLineDiscounts + /** Credit applied to this line item. */ + creditsApplied?: InvoiceLineCreditsApplied[] + /** External identifiers for this line item assigned by third-party systems. */ + externalReferences?: InvoiceLineExternalReferences + /** Reference to the subscription item that generated this line. */ + subscription?: SubscriptionReference + /** The rate card configuration snapshot used to price this line item. */ + rateCard: InvoiceLineRateCard + /** + * Detailed sub-lines that this line has been broken down into. + * + * Present when line has individual details. + */ + detailedLines: InvoiceDetailedLineInput[] + /** Reference to the charge associated with this line item. */ + charge?: ChargeReference +} + +/** + * Billing profiles contain the settings for billing and controls invoice + * generation. + */ +export interface ProfileInput { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** + * The name and contact information for the supplier this billing profile + * represents + */ + supplier: Party + /** The billing workflow settings for this profile */ + workflow: WorkflowInput + /** The applications used by this billing profile. */ + apps: ProfileAppReferences + /** Whether this is the default profile. */ + default: boolean +} + +/** BillingProfile create request. */ +export interface CreateBillingProfileRequestInput { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** + * The name and contact information for the supplier this billing profile + * represents + */ + supplier: Party + /** The billing workflow settings for this profile */ + workflow: WorkflowInput + /** The applications used by this billing profile. */ + apps: ProfileAppReferences + /** Whether this is the default profile. */ + default: boolean +} + +/** BillingProfile upsert request. */ +export interface UpsertBillingProfileRequestInput { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** + * The name and contact information for the supplier this billing profile + * represents + */ + supplier: Party + /** The billing workflow settings for this profile */ + workflow: WorkflowInput + /** Whether this is the default profile. */ + default: boolean +} + +/** Addon purchased with a subscription. */ +export interface SubscriptionAddonInput { + id: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + /** The add-on associated with the subscription. */ + addon: AddonReference + /** The quantity of the add-on. Always 1 for single instance add-ons. */ + quantity: number + /** + * An ISO-8601 timestamp representation of which point in time the quantity was + * resolved to. + */ + quantityAt: Date + /** An ISO-8601 timestamp representation of the cadence start of the resource. */ + activeFrom: Date + /** An ISO-8601 timestamp representation of the cadence end of the resource. */ + activeTo?: Date + /** The timeline of the add-on. The returned periods are sorted and continuous. */ + timeline: SubscriptionAddonTimelineSegment[] + /** The rate cards of the add-on. */ + rateCards: SubscriptionAddonRateCardInput[] +} + +/** Plans provide a template for subscriptions. */ +export interface PlanInput { + id: string + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** + * A key is a semi-unique string that is used to identify the plan. It is used to + * reference the latest `active` version of the plan and is unique with the version + * number. + */ + key: string + /** + * Plans are versioned to allow you to make changes without affecting running + * subscriptions. + */ + version?: number + /** The currency code of the plan. */ + currency: string + /** The billing cadence for subscriptions using this plan. */ + billingCadence: string + /** Whether pro-rating is enabled for this plan. */ + proRatingEnabled?: boolean + /** + * The date and time when the plan becomes `active`. When not specified, the plan + * is in `draft` status. + */ + effectiveFrom?: Date + /** + * A scheduled date and time when the plan becomes `archived`. When not specified, + * the plan is in `active` status indefinitely. + */ + effectiveTo?: Date + /** + * The status of the plan. Computed based on the effective start and end dates: + * + * - `draft`: `effective_from` is not set. + * - `scheduled`: `now < effective_from`. + * - `active`: `effective_from <= now` and (`effective_to` is not set or + * `now < effective_to`). + * - `archived`: `effective_to <= now`. + */ + status: 'draft' | 'active' | 'archived' | 'scheduled' + /** + * The plan phases define the pricing ramp for a subscription. A phase switch + * occurs only at the end of a billing period. At least one phase is required. + */ + phases: PlanPhaseInput[] + /** + * Settlement mode for plan. + * + * Values: + * + * - `credit_then_invoice`: Credits are applied first, then any remainder is + * invoiced. + * - `credit_only`: Usage is settled exclusively against credits. + */ + settlementMode?: 'credit_then_invoice' | 'credit_only' + /** + * List of validation errors in `draft` state that prevent the plan from being + * published. + */ + validationErrors?: ProductCatalogValidationError[] +} + +/** Plan create request. */ +export interface CreatePlanRequestInput { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** + * A key is a semi-unique string that is used to identify the plan. It is used to + * reference the latest `active` version of the plan and is unique with the version + * number. + */ + key: string + /** The currency code of the plan. */ + currency: string + /** The billing cadence for subscriptions using this plan. */ + billingCadence: string + /** Whether pro-rating is enabled for this plan. */ + proRatingEnabled?: boolean + /** + * The plan phases define the pricing ramp for a subscription. A phase switch + * occurs only at the end of a billing period. At least one phase is required. + */ + phases: PlanPhaseInput[] +} + +/** Plan upsert request. */ +export interface UpsertPlanRequestInput { + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + name: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** Whether pro-rating is enabled for this plan. */ + proRatingEnabled?: boolean + /** + * The plan phases define the pricing ramp for a subscription. A phase switch + * occurs only at the end of a billing period. At least one phase is required. + */ + phases: PlanPhaseInput[] +} + +/** Page paginated response. */ +export interface AddonPagePaginatedResponseInput { + data: AddonInput[] + meta: PaginatedMeta +} + +/** Page paginated response. */ +export interface ProfilePagePaginatedResponseInput { + data: ProfileInput[] + meta: PaginatedMeta +} + +/** Page paginated response. */ +export interface SubscriptionAddonPagePaginatedResponseInput { + data: SubscriptionAddonInput[] + meta: PaginatedMeta +} + +/** Page paginated response. */ +export interface PlanPagePaginatedResponseInput { + data: PlanInput[] + meta: PaginatedMeta +} + +/** A standard invoice for charges owed by the customer. */ +export interface InvoiceStandardInput { + id: string + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: Labels + /** An ISO-8601 timestamp representation of entity creation date. */ + createdAt: Date + /** An ISO-8601 timestamp representation of entity last update date. */ + updatedAt: Date + /** An ISO-8601 timestamp representation of entity deletion date. */ + deletedAt?: Date + /** Human-readable invoice number generated by the invoicing app. */ + number: string + /** Three-letter ISO 4217 currency code for the invoice. */ + currency: string + /** + * Snapshot of the supplier's contact information at the time the invoice was + * issued. + */ + supplier: Supplier + /** Snapshot of the customer's information at the time the invoice was issued. */ + customer: InvoiceCustomer + /** Aggregated financial totals for the invoice. */ + totals: Totals + /** + * The service period covered by this invoice. + * + * For flat fee the service period can be empty which means `from` will be equals + * to `to`. In other cases those fields will be filled with the actual service + * period. + */ + servicePeriod: ClosedPeriod + /** + * Validation issues found during invoice processing. + * + * Present only when there are one or more validation findings. An empty list is + * omitted. + */ + validationIssues?: InvoiceValidationIssue[] + /** External identifiers assigned to this invoice by third-party systems. */ + externalReferences?: InvoiceExternalReferences + /** Discriminator field identifying this as a standard invoice. */ + type: 'standard' + /** Current lifecycle status of the invoice. */ + status: + | 'draft' + | 'issuing' + | 'issued' + | 'payment_processing' + | 'overdue' + | 'paid' + | 'uncollectible' + | 'voided' + /** Detailed status information including available actions and workflow state. */ + statusDetails: InvoiceStatusDetails + /** Timestamp when the invoice was issued to the customer. */ + issuedAt?: Date + /** + * Timestamp until which the invoice remains in draft state. + * + * The invoice advances automatically once this time is reached. + */ + draftUntil?: Date + /** Timestamp when usage quantities were last snapshotted for this invoice. */ + quantitySnapshottedAt?: Date + /** Timestamp when collection was initiated for this invoice. */ + collectionAt?: Date + /** Timestamp when payment is due. */ + dueAt?: Date + /** Timestamp when the invoice was sent to the customer. */ + sentToCustomerAt?: Date + /** Workflow configuration snapshot captured at invoice creation time. */ + workflow: InvoiceWorkflowSettingsInput + /** + * Line items on this invoice. + * + * Always returned on single-resource GET; omitted on list endpoints unless + * explicitly expanded. Editable via update: existing lines are matched by `id`, + * lines without an `id` are created, and lines present on the invoice but omitted + * from the update request are deleted. Detailed (child) lines are always computed + * and cannot be edited directly. + */ + lines?: InvoiceLineInput[] +} + +/** InvoiceStandard update request. */ +export interface UpdateInvoiceStandardRequestInput { + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + description?: string + labels?: UpdateLabels + /** + * Snapshot of the supplier's contact information at the time the invoice was + * issued. + */ + supplier: UpdateSupplier + /** Snapshot of the customer's information at the time the invoice was issued. */ + customer: UpdateInvoiceCustomer + /** Discriminator field identifying this as a standard invoice. */ + type: 'standard' + /** Workflow configuration snapshot captured at invoice creation time. */ + workflow: UpdateInvoiceWorkflowSettingsInput + /** + * Line items on this invoice. + * + * Always returned on single-resource GET; omitted on list endpoints unless + * explicitly expanded. Editable via update: existing lines are matched by `id`, + * lines without an `id` are created, and lines present on the invoice but omitted + * from the update request are deleted. Detailed (child) lines are always computed + * and cannot be edited directly. + */ + lines?: UpdateInvoiceLine[] +} + +/** Page paginated response. */ +export interface InvoicePagePaginatedResponseInput { + data: InvoiceInput[] + meta: PaginatedMeta +} + +/** Payment settings for a billing workflow. */ +export type WorkflowPaymentSettingsInput = + | WorkflowPaymentChargeAutomaticallySettings + | WorkflowPaymentSendInvoiceSettingsInput + +/** Payment settings for a billing workflow. */ +export type UpdateBillingWorkflowPaymentSettingsInput = + | UpdateBillingWorkflowPaymentChargeAutomaticallySettings + | UpdateBillingWorkflowPaymentSendInvoiceSettingsInput + +/** + * Entitlement template configured on a rate card. The feature is taken from the + * rate card itself, so it is omitted here. + */ +export type RateCardEntitlementInput = + | RateCardMeteredEntitlementInput + | RateCardStaticEntitlement + | RateCardBooleanEntitlement + +/** + * A top-level line item on an invoice. + * + * Each line represents a single charge, typically associated with a rate card from + * a subscription. Detailed (child) lines are nested under `detailed_lines` when + * present. + */ +export type InvoiceLineInput = InvoiceStandardLineInput + +/** + * An invoice issued to a customer. + * + * The `type` field determines the concrete variant: + * + * - `standard`: a standard invoice for charges owed. + */ +export type InvoiceInput = InvoiceStandardInput + +/** UpdateInvoiceRequest update request. */ +export type UpdateInvoiceRequestInput = UpdateInvoiceStandardRequestInput diff --git a/api/spec/packages/aip-client-javascript/src/sdk/addons.ts b/api/spec/packages/aip-client-javascript/src/sdk/addons.ts new file mode 100644 index 0000000000000000000000000000000000000000..a8b8b9e80453bc4d3959d889eedb0971f3eddfe5 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/sdk/addons.ts @@ -0,0 +1,153 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client } from '../core.js' +import { unwrap, type RequestOptions } from '../lib/types.js' +import { paginatePages } from '../lib/paginate.js' +import { + listAddons, + createAddon, + updateAddon, + getAddon, + deleteAddon, + archiveAddon, + publishAddon, +} from '../funcs/addons.js' +import type { + ListAddonsRequest, + ListAddonsResponse, + CreateAddonRequest, + CreateAddonResponse, + UpdateAddonRequest, + UpdateAddonResponse, + GetAddonRequest, + GetAddonResponse, + DeleteAddonRequest, + DeleteAddonResponse, + ArchiveAddonRequest, + ArchiveAddonResponse, + PublishAddonRequest, + PublishAddonResponse, +} from '../models/operations/addons.js' +import type { Addon } from '../models/types.js' + +export class Addons { + constructor(private readonly _client: Client) {} + + /** + * List add-ons + * + * List all add-ons. + * + * GET /openmeter/addons + */ + async list( + request?: ListAddonsRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listAddons(this._client, request, options)) + } + + /** + * List add-ons + * + * List all add-ons. + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/addons + */ + listAll( + request?: ListAddonsRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginatePages( + (req, opts) => listAddons(this._client, req, opts), + request ?? {}, + options, + ) + } + + /** + * Create add-on + * + * Create a new add-on. + * + * POST /openmeter/addons + */ + async create( + request: CreateAddonRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await createAddon(this._client, request, options)) + } + + /** + * Update add-on + * + * Update an add-on by id. + * + * PUT /openmeter/addons/{addonId} + */ + async update( + request: UpdateAddonRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await updateAddon(this._client, request, options)) + } + + /** + * Get add-on + * + * Get add-on by id. + * + * GET /openmeter/addons/{addonId} + */ + async get( + request: GetAddonRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await getAddon(this._client, request, options)) + } + + /** + * Soft delete add-on + * + * Soft delete add-on by id. + * + * DELETE /openmeter/addons/{addonId} + */ + async delete( + request: DeleteAddonRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await deleteAddon(this._client, request, options)) + } + + /** + * Archive add-on version + * + * Archive an add-on version. + * + * POST /openmeter/addons/{addonId}/archive + */ + async archive( + request: ArchiveAddonRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await archiveAddon(this._client, request, options)) + } + + /** + * Publish add-on version + * + * Publish an add-on version. + * + * POST /openmeter/addons/{addonId}/publish + */ + async publish( + request: PublishAddonRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await publishAddon(this._client, request, options)) + } +} diff --git a/api/spec/packages/aip-client-javascript/src/sdk/apps.ts b/api/spec/packages/aip-client-javascript/src/sdk/apps.ts new file mode 100644 index 0000000000000000000000000000000000000000..78eb03311e42327223c227e9cef8a0bd6b496dd1 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/sdk/apps.ts @@ -0,0 +1,139 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client } from '../core.js' +import { unwrap, type RequestOptions } from '../lib/types.js' +import { paginatePages } from '../lib/paginate.js' +import { + listApps, + getApp, + listAppCatalog, + getAppCatalogItem, + installApp, +} from '../funcs/apps.js' +import type { + ListAppsRequest, + ListAppsResponse, + GetAppRequest, + GetAppResponse, + ListAppCatalogRequest, + ListAppCatalogResponse, + GetAppCatalogItemRequest, + GetAppCatalogItemResponse, + InstallAppRequest, + InstallAppResponse, +} from '../models/operations/apps.js' +import type { App, AppCatalogItem } from '../models/types.js' + +export class Apps { + constructor(private readonly _client: Client) {} + + /** + * List apps + * + * List installed apps. + * + * GET /openmeter/apps + */ + async list( + request?: ListAppsRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listApps(this._client, request, options)) + } + + /** + * List apps + * + * List installed apps. + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/apps + */ + listAll( + request?: ListAppsRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginatePages( + (req, opts) => listApps(this._client, req, opts), + request ?? {}, + options, + ) + } + + /** + * Get app + * + * Get an installed app. + * + * GET /openmeter/apps/{appId} + */ + async get( + request: GetAppRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await getApp(this._client, request, options)) + } + + /** + * List app catalog + * + * List available apps. + * + * GET /openmeter/app-catalog + */ + async listCatalog( + request?: ListAppCatalogRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listAppCatalog(this._client, request, options)) + } + + /** + * List app catalog + * + * List available apps. + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/app-catalog + */ + listCatalogAll( + request?: ListAppCatalogRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginatePages( + (req, opts) => listAppCatalog(this._client, req, opts), + request ?? {}, + options, + ) + } + + /** + * Get app catalog item by type + * + * Get an app catalog item by type. + * + * GET /openmeter/app-catalog/{appType} + */ + async getCatalogItem( + request: GetAppCatalogItemRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await getAppCatalogItem(this._client, request, options)) + } + + /** + * Install app from the catalog + * + * Install an app from the catalog. + * + * POST /openmeter/app-catalog/install + */ + async install( + request: InstallAppRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await installApp(this._client, request, options)) + } +} diff --git a/api/spec/packages/aip-client-javascript/src/sdk/billing.ts b/api/spec/packages/aip-client-javascript/src/sdk/billing.ts new file mode 100644 index 0000000000000000000000000000000000000000..111d1d2b8b6812fcba85576a1230d8acd8e9c812 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/sdk/billing.ts @@ -0,0 +1,130 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client } from '../core.js' +import { unwrap, type RequestOptions } from '../lib/types.js' +import { paginatePages } from '../lib/paginate.js' +import { + listBillingProfiles, + createBillingProfile, + getBillingProfile, + updateBillingProfile, + deleteBillingProfile, +} from '../funcs/billing.js' +import type { + ListBillingProfilesRequest, + ListBillingProfilesResponse, + CreateBillingProfileRequest, + CreateBillingProfileResponse, + GetBillingProfileRequest, + GetBillingProfileResponse, + UpdateBillingProfileRequest, + UpdateBillingProfileResponse, + DeleteBillingProfileRequest, + DeleteBillingProfileResponse, +} from '../models/operations/billing.js' +import type { Profile } from '../models/types.js' + +export class Billing { + constructor(private readonly _client: Client) {} + + /** + * List billing profiles + * + * List billing profiles. + * + * GET /openmeter/profiles + */ + async listProfiles( + request?: ListBillingProfilesRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listBillingProfiles(this._client, request, options)) + } + + /** + * List billing profiles + * + * List billing profiles. + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/profiles + */ + listProfilesAll( + request?: ListBillingProfilesRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginatePages( + (req, opts) => listBillingProfiles(this._client, req, opts), + request ?? {}, + options, + ) + } + + /** + * Create a new billing profile + * + * Create a new billing profile. + * + * Billing profiles contain the settings for billing and controls invoice + * generation. An organization can have multiple billing profiles defined. A + * billing profile is linked to a specific app. This association is established + * during the billing profile's creation and remains immutable. + * + * POST /openmeter/profiles + */ + async createProfile( + request: CreateBillingProfileRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await createBillingProfile(this._client, request, options)) + } + + /** + * Get a billing profile + * + * Get a billing profile. + * + * GET /openmeter/profiles/{id} + */ + async getProfile( + request: GetBillingProfileRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await getBillingProfile(this._client, request, options)) + } + + /** + * Update a billing profile + * + * Update a billing profile. + * + * PUT /openmeter/profiles/{id} + */ + async updateProfile( + request: UpdateBillingProfileRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await updateBillingProfile(this._client, request, options)) + } + + /** + * Delete a billing profile + * + * Delete a billing profile. + * + * Only such billing profiles can be deleted that are: + * + * - not the default profile + * - not pinned to any customer using customer overrides + * - only have finalized invoices + * + * DELETE /openmeter/profiles/{id} + */ + async deleteProfile( + request: DeleteBillingProfileRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await deleteBillingProfile(this._client, request, options)) + } +} diff --git a/api/spec/packages/aip-client-javascript/src/sdk/customers.ts b/api/spec/packages/aip-client-javascript/src/sdk/customers.ts new file mode 100644 index 0000000000000000000000000000000000000000..0d95f9b9f989591c2bdfbdfd881fcf38ff921c3d --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/sdk/customers.ts @@ -0,0 +1,542 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client } from '../core.js' +import { unwrap, type RequestOptions } from '../lib/types.js' +import { paginateCursor, paginatePages } from '../lib/paginate.js' +import { + createCustomer, + getCustomer, + listCustomers, + upsertCustomer, + deleteCustomer, + getCustomerBilling, + updateCustomerBilling, + updateCustomerBillingAppData, + createCustomerStripeCheckoutSession, + createCustomerStripePortalSession, + createCreditGrant, + getCreditGrant, + listCreditGrants, + getCustomerCreditBalance, + createCreditAdjustment, + voidCreditGrant, + updateCreditGrantExternalSettlement, + listCreditTransactions, + listCustomerCharges, + createCustomerCharges, +} from '../funcs/customers.js' +import type { + CreateCustomerRequest, + CreateCustomerResponse, + GetCustomerRequest, + GetCustomerResponse, + ListCustomersRequest, + ListCustomersResponse, + UpsertCustomerRequest, + UpsertCustomerResponse, + DeleteCustomerRequest, + DeleteCustomerResponse, + GetCustomerBillingRequest, + GetCustomerBillingResponse, + UpdateCustomerBillingRequest, + UpdateCustomerBillingResponse, + UpdateCustomerBillingAppDataRequest, + UpdateCustomerBillingAppDataResponse, + CreateCustomerStripeCheckoutSessionRequest, + CreateCustomerStripeCheckoutSessionResponse, + CreateCustomerStripePortalSessionRequest, + CreateCustomerStripePortalSessionResponse, + CreateCreditGrantRequest, + CreateCreditGrantResponse, + GetCreditGrantRequest, + GetCreditGrantResponse, + ListCreditGrantsRequest, + ListCreditGrantsResponse, + GetCustomerCreditBalanceRequest, + GetCustomerCreditBalanceResponse, + CreateCreditAdjustmentRequest, + CreateCreditAdjustmentResponse, + VoidCreditGrantRequest, + VoidCreditGrantResponse, + UpdateCreditGrantExternalSettlementRequest, + UpdateCreditGrantExternalSettlementResponse, + ListCreditTransactionsRequest, + ListCreditTransactionsResponse, + ListCustomerChargesRequest, + ListCustomerChargesResponse, + CreateCustomerChargesRequest, + CreateCustomerChargesResponse, +} from '../models/operations/customers.js' +import type { + Charge, + CreditGrant, + CreditTransaction, + Customer, +} from '../models/types.js' + +export class Customers { + constructor(private readonly _client: Client) {} + + /** + * Create customer + * + * POST /openmeter/customers + */ + async create( + request: CreateCustomerRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await createCustomer(this._client, request, options)) + } + + /** + * Get customer + * + * GET /openmeter/customers/{customerId} + */ + async get( + request: GetCustomerRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await getCustomer(this._client, request, options)) + } + + /** + * List customers + * + * GET /openmeter/customers + */ + async list( + request?: ListCustomersRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listCustomers(this._client, request, options)) + } + + /** + * List customers + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/customers + */ + listAll( + request?: ListCustomersRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginatePages( + (req, opts) => listCustomers(this._client, req, opts), + request ?? {}, + options, + ) + } + + /** + * Upsert customer + * + * PUT /openmeter/customers/{customerId} + */ + async upsert( + request: UpsertCustomerRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await upsertCustomer(this._client, request, options)) + } + + /** + * Delete customer + * + * DELETE /openmeter/customers/{customerId} + */ + async delete( + request: DeleteCustomerRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await deleteCustomer(this._client, request, options)) + } + + private _billing?: CustomersBilling + get billing(): CustomersBilling { + return (this._billing ??= new CustomersBilling(this._client)) + } + + private _credits?: CustomersCredits + get credits(): CustomersCredits { + return (this._credits ??= new CustomersCredits(this._client)) + } + + private _charges?: CustomersCharges + get charges(): CustomersCharges { + return (this._charges ??= new CustomersCharges(this._client)) + } +} + +export class CustomersBilling { + constructor(private readonly _client: Client) {} + + /** + * Get customer billing data + * + * GET /openmeter/customers/{customerId}/billing + */ + async get( + request: GetCustomerBillingRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await getCustomerBilling(this._client, request, options)) + } + + /** + * Update customer billing data + * + * PUT /openmeter/customers/{customerId}/billing + */ + async update( + request: UpdateCustomerBillingRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await updateCustomerBilling(this._client, request, options)) + } + + /** + * Update customer billing app data + * + * PUT /openmeter/customers/{customerId}/billing/app-data + */ + async updateAppData( + request: UpdateCustomerBillingAppDataRequest, + options?: RequestOptions, + ): Promise { + return unwrap( + await updateCustomerBillingAppData(this._client, request, options), + ) + } + + /** + * Create Stripe Checkout Session + * + * Create a [Stripe Checkout Session](https://docs.stripe.com/payments/checkout) + * for the customer. + * + * Creates a Checkout Session for collecting payment method information from + * customers. The session operates in "setup" mode, which collects payment details + * without charging the customer immediately. The collected payment method can be + * used for future subscription billing. + * + * For hosted checkout sessions, redirect customers to the returned URL. For + * embedded sessions, use the client_secret to initialize Stripe.js in your + * application. + * + * POST /openmeter/customers/{customerId}/billing/stripe/checkout-sessions + */ + async createStripeCheckoutSession( + request: CreateCustomerStripeCheckoutSessionRequest, + options?: RequestOptions, + ): Promise { + return unwrap( + await createCustomerStripeCheckoutSession(this._client, request, options), + ) + } + + /** + * Create Stripe customer portal session + * + * Create Stripe Customer Portal Session. + * + * Useful to redirect the customer to the Stripe Customer Portal to manage their + * payment methods, change their billing address and access their invoice history. + * Only returns URL if the customer billing profile is linked to a stripe app and + * customer. + * + * POST /openmeter/customers/{customerId}/billing/stripe/portal-sessions + */ + async createStripePortalSession( + request: CreateCustomerStripePortalSessionRequest, + options?: RequestOptions, + ): Promise { + return unwrap( + await createCustomerStripePortalSession(this._client, request, options), + ) + } +} + +export class CustomersCredits { + constructor(private readonly _client: Client) {} + + private _grants?: CustomersCreditsGrants + get grants(): CustomersCreditsGrants { + return (this._grants ??= new CustomersCreditsGrants(this._client)) + } + + private _balance?: CustomersCreditsBalance + get balance(): CustomersCreditsBalance { + return (this._balance ??= new CustomersCreditsBalance(this._client)) + } + + private _adjustments?: CustomersCreditsAdjustments + get adjustments(): CustomersCreditsAdjustments { + return (this._adjustments ??= new CustomersCreditsAdjustments(this._client)) + } + + private _transactions?: CustomersCreditsTransactions + get transactions(): CustomersCreditsTransactions { + return (this._transactions ??= new CustomersCreditsTransactions( + this._client, + )) + } +} + +export class CustomersCreditsGrants { + constructor(private readonly _client: Client) {} + + /** + * Create a new credit grant + * + * Create a new credit grant. A credit grant represents an allocation of prepaid + * credits to a customer. + * + * POST /openmeter/customers/{customerId}/credits/grants + */ + async create( + request: CreateCreditGrantRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await createCreditGrant(this._client, request, options)) + } + + /** + * Get a credit grant + * + * Get a credit grant. + * + * GET /openmeter/customers/{customerId}/credits/grants/{creditGrantId} + */ + async get( + request: GetCreditGrantRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await getCreditGrant(this._client, request, options)) + } + + /** + * List credit grants + * + * List credit grants. + * + * GET /openmeter/customers/{customerId}/credits/grants + */ + async list( + request: ListCreditGrantsRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listCreditGrants(this._client, request, options)) + } + + /** + * List credit grants + * + * List credit grants. + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/customers/{customerId}/credits/grants + */ + listAll( + request: ListCreditGrantsRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginatePages( + (req, opts) => listCreditGrants(this._client, req, opts), + request, + options, + ) + } + + /** + * Void credit grant + * + * Void a credit grant, forfeiting the remaining unused balance. + * + * Voiding is a forward-looking, irreversible operation. Credits already consumed + * by usage remain unaffected — only the remaining balance is forfeited. The grant + * reads as `voided` status afterwards. Payment state is not adjusted when + * `payment_adjustment` is `none`, so invoice-backed or externally collected + * payments may still collect the original amount. Only `active` grants can be + * voided; voiding a pending, expired, or fully consumed grant returns a conflict. + * Retrying a successful void is an idempotent success. + * + * POST /openmeter/customers/{customerId}/credits/grants/{creditGrantId}/void + */ + async void( + request: VoidCreditGrantRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await voidCreditGrant(this._client, request, options)) + } + + /** + * Update credit grant external settlement status + * + * Update the payment settlement status of an externally funded credit grant. + * + * Use this endpoint to synchronize the payment state of an external payment with + * the system so that revenue recognition and credit availability work as expected. + * + * POST /openmeter/customers/{customerId}/credits/grants/{creditGrantId}/settlement/external + */ + async updateExternalSettlement( + request: UpdateCreditGrantExternalSettlementRequest, + options?: RequestOptions, + ): Promise { + return unwrap( + await updateCreditGrantExternalSettlement(this._client, request, options), + ) + } +} + +export class CustomersCreditsBalance { + constructor(private readonly _client: Client) {} + + /** + * Get a customer's credit balance + * + * Get a credit balance. + * + * GET /openmeter/customers/{customerId}/credits/balance + */ + async get( + request: GetCustomerCreditBalanceRequest, + options?: RequestOptions, + ): Promise { + return unwrap( + await getCustomerCreditBalance(this._client, request, options), + ) + } +} + +export class CustomersCreditsAdjustments { + constructor(private readonly _client: Client) {} + + /** + * Create a credit adjustment + * + * A credit adjustment can be used to make manual adjustments to a customer's + * credit balance. + * + * Supported use-cases: + * + * - Usage correction + * + * POST /openmeter/customers/{customerId}/credits/adjustments + */ + async create( + request: CreateCreditAdjustmentRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await createCreditAdjustment(this._client, request, options)) + } +} + +export class CustomersCreditsTransactions { + constructor(private readonly _client: Client) {} + + /** + * List credit transactions + * + * List credit transactions for a customer. + * + * Returns an immutable, chronological record of credit movements: funded credits + * and consumed credits. Transactions are returned in reverse chronological order + * by default. + * + * GET /openmeter/customers/{customerId}/credits/transactions + */ + async list( + request: ListCreditTransactionsRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listCreditTransactions(this._client, request, options)) + } + + /** + * List credit transactions + * + * List credit transactions for a customer. + * + * Returns an immutable, chronological record of credit movements: funded credits + * and consumed credits. Transactions are returned in reverse chronological order + * by default. + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/customers/{customerId}/credits/transactions + */ + listAll( + request: ListCreditTransactionsRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginateCursor( + (req, opts) => listCreditTransactions(this._client, req, opts), + request, + options, + ) + } +} + +export class CustomersCharges { + constructor(private readonly _client: Client) {} + + /** + * List customer charges + * + * List customer charges. + * + * Returns the customer's charges that are represented as either flat fee or + * usage-based charges. + * + * GET /openmeter/customers/{customerId}/charges + */ + async list( + request: ListCustomerChargesRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listCustomerCharges(this._client, request, options)) + } + + /** + * List customer charges + * + * List customer charges. + * + * Returns the customer's charges that are represented as either flat fee or + * usage-based charges. + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/customers/{customerId}/charges + */ + listAll( + request: ListCustomerChargesRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginatePages( + (req, opts) => listCustomerCharges(this._client, req, opts), + request, + options, + ) + } + + /** + * Create customer charge + * + * Create customer charge. + * + * POST /openmeter/customers/{customerId}/charges + */ + async create( + request: CreateCustomerChargesRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await createCustomerCharges(this._client, request, options)) + } +} diff --git a/api/spec/packages/aip-client-javascript/src/sdk/defaults.ts b/api/spec/packages/aip-client-javascript/src/sdk/defaults.ts new file mode 100644 index 0000000000000000000000000000000000000000..dbdf48527f1addbef25d884de74121f5ee514d1f --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/sdk/defaults.ts @@ -0,0 +1,46 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client } from '../core.js' +import { unwrap, type RequestOptions } from '../lib/types.js' +import { + getOrganizationDefaultTaxCodes, + updateOrganizationDefaultTaxCodes, +} from '../funcs/defaults.js' +import type { + GetOrganizationDefaultTaxCodesRequest, + GetOrganizationDefaultTaxCodesResponse, + UpdateOrganizationDefaultTaxCodesRequest, + UpdateOrganizationDefaultTaxCodesResponse, +} from '../models/operations/defaults.js' + +export class Defaults { + constructor(private readonly _client: Client) {} + + /** + * Get organization default tax codes + * + * GET /openmeter/defaults/tax-codes + */ + async getOrganizationTaxCodes( + request: GetOrganizationDefaultTaxCodesRequest, + options?: RequestOptions, + ): Promise { + return unwrap( + await getOrganizationDefaultTaxCodes(this._client, request, options), + ) + } + + /** + * Update organization default tax codes + * + * PUT /openmeter/defaults/tax-codes + */ + async updateOrganizationTaxCodes( + request: UpdateOrganizationDefaultTaxCodesRequest, + options?: RequestOptions, + ): Promise { + return unwrap( + await updateOrganizationDefaultTaxCodes(this._client, request, options), + ) + } +} diff --git a/api/spec/packages/aip-client-javascript/src/sdk/entitlements.ts b/api/spec/packages/aip-client-javascript/src/sdk/entitlements.ts new file mode 100644 index 0000000000000000000000000000000000000000..4f88750f8516b24ca1286b2552c490e0a73bb089 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/sdk/entitlements.ts @@ -0,0 +1,27 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client } from '../core.js' +import { unwrap, type RequestOptions } from '../lib/types.js' +import { listCustomerEntitlementAccess } from '../funcs/entitlements.js' +import type { + ListCustomerEntitlementAccessRequest, + ListCustomerEntitlementAccessResponse, +} from '../models/operations/entitlements.js' + +export class Entitlements { + constructor(private readonly _client: Client) {} + + /** + * List customer entitlement access + * + * GET /openmeter/customers/{customerId}/entitlement-access + */ + async listCustomerAccess( + request: ListCustomerEntitlementAccessRequest, + options?: RequestOptions, + ): Promise { + return unwrap( + await listCustomerEntitlementAccess(this._client, request, options), + ) + } +} diff --git a/api/spec/packages/aip-client-javascript/src/sdk/events.ts b/api/spec/packages/aip-client-javascript/src/sdk/events.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9726475beff21f4afb0e5b73cc53db6574757a8 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/sdk/events.ts @@ -0,0 +1,65 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client } from '../core.js' +import { unwrap, type RequestOptions } from '../lib/types.js' +import { paginateCursor } from '../lib/paginate.js' +import { listMeteringEvents, ingestMeteringEvents } from '../funcs/events.js' +import type { + ListMeteringEventsRequest, + ListMeteringEventsResponse, + IngestMeteringEventsRequest, + IngestMeteringEventsResponse, +} from '../models/operations/events.js' +import type { IngestedEvent } from '../models/types.js' + +export class Events { + constructor(private readonly _client: Client) {} + + /** + * List metering events + * + * List ingested events. + * + * GET /openmeter/events + */ + async list( + request?: ListMeteringEventsRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listMeteringEvents(this._client, request, options)) + } + + /** + * List metering events + * + * List ingested events. + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/events + */ + listAll( + request?: ListMeteringEventsRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginateCursor( + (req, opts) => listMeteringEvents(this._client, req, opts), + request ?? {}, + options, + ) + } + + /** + * Ingest metering events + * + * Ingests an event or batch of events following the CloudEvents specification. + * + * POST /openmeter/events + */ + async ingest( + request: IngestMeteringEventsRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await ingestMeteringEvents(this._client, request, options)) + } +} diff --git a/api/spec/packages/aip-client-javascript/src/sdk/features.ts b/api/spec/packages/aip-client-javascript/src/sdk/features.ts new file mode 100644 index 0000000000000000000000000000000000000000..dfd0d70fbfe852e6a89d42498855886cd94c41a2 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/sdk/features.ts @@ -0,0 +1,136 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client } from '../core.js' +import { unwrap, type RequestOptions } from '../lib/types.js' +import { paginatePages } from '../lib/paginate.js' +import { + listFeatures, + createFeature, + getFeature, + updateFeature, + deleteFeature, + queryFeatureCost, +} from '../funcs/features.js' +import type { + ListFeaturesRequest, + ListFeaturesResponse, + CreateFeatureRequest, + CreateFeatureResponse, + GetFeatureRequest, + GetFeatureResponse, + UpdateFeatureRequest, + UpdateFeatureResponse, + DeleteFeatureRequest, + DeleteFeatureResponse, + QueryFeatureCostRequest, + QueryFeatureCostResponse, +} from '../models/operations/features.js' +import type { Feature } from '../models/types.js' + +export class Features { + constructor(private readonly _client: Client) {} + + /** + * List features + * + * List all features. + * + * GET /openmeter/features + */ + async list( + request?: ListFeaturesRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listFeatures(this._client, request, options)) + } + + /** + * List features + * + * List all features. + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/features + */ + listAll( + request?: ListFeaturesRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginatePages( + (req, opts) => listFeatures(this._client, req, opts), + request ?? {}, + options, + ) + } + + /** + * Create feature + * + * Create a feature. + * + * POST /openmeter/features + */ + async create( + request: CreateFeatureRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await createFeature(this._client, request, options)) + } + + /** + * Get feature + * + * Get a feature by id. + * + * GET /openmeter/features/{featureId} + */ + async get( + request: GetFeatureRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await getFeature(this._client, request, options)) + } + + /** + * Update feature + * + * Update a feature by id. Currently only the unit_cost field can be updated. + * + * PATCH /openmeter/features/{featureId} + */ + async update( + request: UpdateFeatureRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await updateFeature(this._client, request, options)) + } + + /** + * Delete feature + * + * Delete a feature by id. + * + * DELETE /openmeter/features/{featureId} + */ + async delete( + request: DeleteFeatureRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await deleteFeature(this._client, request, options)) + } + + /** + * Query feature cost + * + * Query the cost of a feature. + * + * POST /openmeter/features/{featureId}/cost/query + */ + async queryCost( + request: QueryFeatureCostRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await queryFeatureCost(this._client, request, options)) + } +} diff --git a/api/spec/packages/aip-client-javascript/src/sdk/internal.ts b/api/spec/packages/aip-client-javascript/src/sdk/internal.ts new file mode 100644 index 0000000000000000000000000000000000000000..50956af3b8ae2510778cb0dc058138962f5fefe3 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/sdk/internal.ts @@ -0,0 +1,418 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client } from '../core.js' +import { unwrap, type RequestOptions } from '../lib/types.js' +import { paginatePages } from '../lib/paginate.js' +import { createSubscriptionAddon } from '../funcs/subscriptions.js' +import { + listInvoices, + getInvoice, + updateInvoice, + deleteInvoice, + advanceInvoice, + approveInvoice, + retryInvoice, + snapshotQuantitiesInvoice, +} from '../funcs/invoices.js' +import { + listCurrencies, + createCustomCurrency, + listCostBases, + createCostBasis, +} from '../funcs/currencies.js' +import { queryGovernanceAccess } from '../funcs/governance.js' +import type { + CreateSubscriptionAddonRequest, + CreateSubscriptionAddonResponse, +} from '../models/operations/subscriptions.js' +import type { + ListInvoicesRequest, + ListInvoicesResponse, + GetInvoiceRequest, + GetInvoiceResponse, + UpdateInvoiceRequest, + UpdateInvoiceResponse, + DeleteInvoiceRequest, + DeleteInvoiceResponse, + AdvanceInvoiceRequest, + AdvanceInvoiceResponse, + ApproveInvoiceRequest, + ApproveInvoiceResponse, + RetryInvoiceRequest, + RetryInvoiceResponse, + SnapshotQuantitiesInvoiceRequest, + SnapshotQuantitiesInvoiceResponse, +} from '../models/operations/invoices.js' +import type { + ListCurrenciesRequest, + ListCurrenciesResponse, + CreateCustomCurrencyRequest, + CreateCustomCurrencyResponse, + ListCostBasesRequest, + ListCostBasesResponse, + CreateCostBasisRequest, + CreateCostBasisResponse, +} from '../models/operations/currencies.js' +import type { + QueryGovernanceAccessRequest, + QueryGovernanceAccessResponse, +} from '../models/operations/governance.js' +import type { CostBasis, Currency, Invoice } from '../models/types.js' + +/** + * Operations marked internal in the API definition. They are not part of + * the customer surface: they may require additional permissions, and they + * can change or be removed without notice or semver consideration. + */ +export class Internal { + constructor(private readonly _client: Client) {} + + private _subscriptions?: InternalSubscriptions + get subscriptions(): InternalSubscriptions { + return (this._subscriptions ??= new InternalSubscriptions(this._client)) + } + + private _invoices?: InternalInvoices + get invoices(): InternalInvoices { + return (this._invoices ??= new InternalInvoices(this._client)) + } + + private _currencies?: InternalCurrencies + get currencies(): InternalCurrencies { + return (this._currencies ??= new InternalCurrencies(this._client)) + } + + private _governance?: InternalGovernance + get governance(): InternalGovernance { + return (this._governance ??= new InternalGovernance(this._client)) + } +} + +export class InternalSubscriptions { + constructor(private readonly _client: Client) {} + + /** + * Create a new subscription add-on + * + * Add add-on to a subscription. + * + * POST /openmeter/subscriptions/{subscriptionId}/addons + */ + async createAddon( + request: CreateSubscriptionAddonRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await createSubscriptionAddon(this._client, request, options)) + } +} + +export class InternalInvoices { + constructor(private readonly _client: Client) {} + + /** + * List billing invoices + * + * List billing invoices. + * + * Returns a page of invoices. Gathering invoices are never included. Use `filter` + * to narrow by status, customer, dates, or service period start. Use `sort` to + * control ordering. + * + * GET /openmeter/billing/invoices + */ + async list( + request?: ListInvoicesRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listInvoices(this._client, request, options)) + } + + /** + * List billing invoices + * + * List billing invoices. + * + * Returns a page of invoices. Gathering invoices are never included. Use `filter` + * to narrow by status, customer, dates, or service period start. Use `sort` to + * control ordering. + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/billing/invoices + */ + listAll( + request?: ListInvoicesRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginatePages( + (req, opts) => listInvoices(this._client, req, opts), + request ?? {}, + options, + ) + } + + /** + * Get a billing invoice + * + * Get a billing invoice by ID. + * + * Returns the full invoice resource including line items, status details, totals, + * and workflow configuration snapshot. + * + * GET /openmeter/billing/invoices/{invoiceId} + */ + async get( + request: GetInvoiceRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await getInvoice(this._client, request, options)) + } + + /** + * Update a billing invoice + * + * Update a billing invoice. + * + * Only the mutable fields of the invoice can be edited: description, labels, + * supplier, customer, workflow settings, and top-level lines. Top-level lines are + * matched by `id`; lines without an `id` are created, and existing lines omitted + * from `lines` are deleted. Detailed (child) lines are always computed and cannot + * be edited directly. Only invoices in draft status can be updated. + * + * PUT /openmeter/billing/invoices/{invoiceId} + */ + async update( + request: UpdateInvoiceRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await updateInvoice(this._client, request, options)) + } + + /** + * Delete a billing invoice + * + * Delete a billing invoice. + * + * Only standard invoices in draft status can be deleted. Deleting an invoice will + * also delete all associated line items and workflow configuration. + * + * DELETE /openmeter/billing/invoices/{invoiceId} + */ + async delete( + request: DeleteInvoiceRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await deleteInvoice(this._client, request, options)) + } + + /** + * Advance billing invoice's next status + * + * Advance a billing invoice. + * + * Advances the invoice to the next workflow state. The next state is determined by + * the invoice's current status and workflow configuration. Only invoices in draft + * or issued status can be advanced. + * + * POST /openmeter/billing/invoices/{invoiceId}/advance + */ + async advance( + request: AdvanceInvoiceRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await advanceInvoice(this._client, request, options)) + } + + /** + * Send the invoice to the customer + * + * Approve a billing invoice. + * + * This call instantly sends the invoice to the customer using the configured + * billing profile app. + * + * This call is valid in two invoice statuses: + * + * - draft: the invoice will be sent to the customer, the invoice state becomes + * issued + * - manual_approval_needed: the invoice will be sent to the customer, the invoice + * state becomes issued + * + * POST /openmeter/billing/invoices/{invoiceId}/approve + */ + async approve( + request: ApproveInvoiceRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await approveInvoice(this._client, request, options)) + } + + /** + * Retry advancing the invoice after a failed attempt + * + * Retry sending a billing invoice. + * + * Retry advancing the invoice after a failed attempt. + * + * The action can be called when the invoice's statusDetails' actions field contain + * the "retry" action. + * + * POST /openmeter/billing/invoices/{invoiceId}/retry + */ + async retry( + request: RetryInvoiceRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await retryInvoice(this._client, request, options)) + } + + /** + * Snapshot quantities for usage based line items + * + * Snapshot quantities for usage-based line items. + * + * This call will snapshot the quantities for all usage based line items in the + * invoice. + * + * This call is only valid in draft.waiting_for_collection status, where the + * collection period can be skipped using this action. + * + * POST /openmeter/billing/invoices/{invoiceId}/snapshot-quantities + */ + async snapshotQuantities( + request: SnapshotQuantitiesInvoiceRequest, + options?: RequestOptions, + ): Promise { + return unwrap( + await snapshotQuantitiesInvoice(this._client, request, options), + ) + } +} + +export class InternalCurrencies { + constructor(private readonly _client: Client) {} + + /** + * List currencies + * + * List currencies supported by the billing system. + * + * GET /openmeter/currencies + */ + async list( + request?: ListCurrenciesRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listCurrencies(this._client, request, options)) + } + + /** + * List currencies + * + * List currencies supported by the billing system. + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/currencies + */ + listAll( + request?: ListCurrenciesRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginatePages( + (req, opts) => listCurrencies(this._client, req, opts), + request ?? {}, + options, + ) + } + + /** + * Create custom currency + * + * Create a custom currency. This operation allows defining your own custom + * currency for billing purposes. + * + * POST /openmeter/currencies/custom + */ + async createCustomCurrency( + request: CreateCustomCurrencyRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await createCustomCurrency(this._client, request, options)) + } + + /** + * List cost bases + * + * List cost bases for a currency. For custom currencies, there can be multiple + * cost bases with different `effective_from` dates. + * + * GET /openmeter/currencies/custom/{currencyId}/cost-bases + */ + async listCostBases( + request: ListCostBasesRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listCostBases(this._client, request, options)) + } + + /** + * List cost bases + * + * List cost bases for a currency. For custom currencies, there can be multiple + * cost bases with different `effective_from` dates. + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/currencies/custom/{currencyId}/cost-bases + */ + listCostBasesAll( + request: ListCostBasesRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginatePages( + (req, opts) => listCostBases(this._client, req, opts), + request, + options, + ) + } + + /** + * Create cost basis + * + * Create a cost basis for a currency. + * + * POST /openmeter/currencies/custom/{currencyId}/cost-bases + */ + async createCostBasis( + request: CreateCostBasisRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await createCostBasis(this._client, request, options)) + } +} + +export class InternalGovernance { + constructor(private readonly _client: Client) {} + + /** + * Query governance access + * + * Query feature access for a list of customers. + * + * The endpoint resolves each provided identifier to a customer and returns the + * access status for the requested features, plus optional credit balance + * availability. + * + * _Designed to be called on a fixed refresh interval and the query response is + * intended to be cached._ + * + * POST /openmeter/governance/query + */ + async queryAccess( + request: QueryGovernanceAccessRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await queryGovernanceAccess(this._client, request, options)) + } +} diff --git a/api/spec/packages/aip-client-javascript/src/sdk/invoices.ts b/api/spec/packages/aip-client-javascript/src/sdk/invoices.ts new file mode 100644 index 0000000000000000000000000000000000000000..598c815bad93f4b2836851c6cf9a9c60e89a0907 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/sdk/invoices.ts @@ -0,0 +1,92 @@ +import { type Client } from '../core.js' +import { unwrap, type RequestOptions } from '../lib/types.js' +import { + listInvoices, + getInvoice, + updateInvoice, + deleteInvoice, + advanceInvoice, + approveInvoice, + retryInvoice, + snapshotQuantitiesInvoice, +} from '../funcs/invoices.js' +import type { + ListInvoicesRequest, + ListInvoicesResponse, + GetInvoiceRequest, + GetInvoiceResponse, + UpdateInvoiceRequest, + UpdateInvoiceResponse, + DeleteInvoiceRequest, + DeleteInvoiceResponse, + AdvanceInvoiceRequest, + AdvanceInvoiceResponse, + ApproveInvoiceRequest, + ApproveInvoiceResponse, + RetryInvoiceRequest, + RetryInvoiceResponse, + SnapshotQuantitiesInvoiceRequest, + SnapshotQuantitiesInvoiceResponse, +} from '../models/operations/invoices.js' + +export class Invoices { + constructor(private readonly _client: Client) {} + + async list( + request?: ListInvoicesRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listInvoices(this._client, request, options)) + } + + async get( + request: GetInvoiceRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await getInvoice(this._client, request, options)) + } + + async update( + request: UpdateInvoiceRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await updateInvoice(this._client, request, options)) + } + + async delete( + request: DeleteInvoiceRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await deleteInvoice(this._client, request, options)) + } + + async advance( + request: AdvanceInvoiceRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await advanceInvoice(this._client, request, options)) + } + + async approve( + request: ApproveInvoiceRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await approveInvoice(this._client, request, options)) + } + + async retry( + request: RetryInvoiceRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await retryInvoice(this._client, request, options)) + } + + async snapshotQuantities( + request: SnapshotQuantitiesInvoiceRequest, + options?: RequestOptions, + ): Promise { + return unwrap( + await snapshotQuantitiesInvoice(this._client, request, options), + ) + } +} diff --git a/api/spec/packages/aip-client-javascript/src/sdk/llmCost.ts b/api/spec/packages/aip-client-javascript/src/sdk/llmCost.ts new file mode 100644 index 0000000000000000000000000000000000000000..e4cb641fecc1d8bf7eb987e1b52169f979f735c0 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/sdk/llmCost.ts @@ -0,0 +1,140 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client } from '../core.js' +import { unwrap, type RequestOptions } from '../lib/types.js' +import { paginatePages } from '../lib/paginate.js' +import { + listLlmCostPrices, + getLlmCostPrice, + listLlmCostOverrides, + createLlmCostOverride, + deleteLlmCostOverride, +} from '../funcs/llmCost.js' +import type { + ListLlmCostPricesRequest, + ListLlmCostPricesResponse, + GetLlmCostPriceRequest, + GetLlmCostPriceResponse, + ListLlmCostOverridesRequest, + ListLlmCostOverridesResponse, + CreateLlmCostOverrideRequest, + CreateLlmCostOverrideResponse, + DeleteLlmCostOverrideRequest, + DeleteLlmCostOverrideResponse, +} from '../models/operations/llmCost.js' +import type { LlmCostPrice } from '../models/types.js' + +export class LLMCost { + constructor(private readonly _client: Client) {} + + /** + * List LLM cost prices + * + * List global LLM cost prices. Returns prices with overrides applied if any. + * + * GET /openmeter/llm-cost/prices + */ + async listPrices( + request?: ListLlmCostPricesRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listLlmCostPrices(this._client, request, options)) + } + + /** + * List LLM cost prices + * + * List global LLM cost prices. Returns prices with overrides applied if any. + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/llm-cost/prices + */ + listPricesAll( + request?: ListLlmCostPricesRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginatePages( + (req, opts) => listLlmCostPrices(this._client, req, opts), + request ?? {}, + options, + ) + } + + /** + * Get LLM cost price + * + * Get a specific LLM cost price by ID. Returns the price with overrides applied if + * any. + * + * GET /openmeter/llm-cost/prices/{priceId} + */ + async getPrice( + request: GetLlmCostPriceRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await getLlmCostPrice(this._client, request, options)) + } + + /** + * List LLM cost overrides + * + * List per-namespace price overrides. + * + * GET /openmeter/llm-cost/overrides + */ + async listOverrides( + request?: ListLlmCostOverridesRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listLlmCostOverrides(this._client, request, options)) + } + + /** + * List LLM cost overrides + * + * List per-namespace price overrides. + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/llm-cost/overrides + */ + listOverridesAll( + request?: ListLlmCostOverridesRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginatePages( + (req, opts) => listLlmCostOverrides(this._client, req, opts), + request ?? {}, + options, + ) + } + + /** + * Create LLM cost override + * + * Create a per-namespace price override. + * + * POST /openmeter/llm-cost/overrides + */ + async createOverride( + request: CreateLlmCostOverrideRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await createLlmCostOverride(this._client, request, options)) + } + + /** + * Delete LLM cost override + * + * Delete a per-namespace price override. + * + * DELETE /openmeter/llm-cost/overrides/{priceId} + */ + async deleteOverride( + request: DeleteLlmCostOverrideRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await deleteLlmCostOverride(this._client, request, options)) + } +} diff --git a/api/spec/packages/aip-client-javascript/src/sdk/meters.ts b/api/spec/packages/aip-client-javascript/src/sdk/meters.ts new file mode 100644 index 0000000000000000000000000000000000000000..79829e12a780a2b7d060ec6fd4bf4abc9346ba1d --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/sdk/meters.ts @@ -0,0 +1,157 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client } from '../core.js' +import { unwrap, type RequestOptions } from '../lib/types.js' +import { paginatePages } from '../lib/paginate.js' +import { + createMeter, + getMeter, + listMeters, + updateMeter, + deleteMeter, + queryMeter, + queryMeterCsv, +} from '../funcs/meters.js' +import type { + CreateMeterRequest, + CreateMeterResponse, + GetMeterRequest, + GetMeterResponse, + ListMetersRequest, + ListMetersResponse, + UpdateMeterRequest, + UpdateMeterResponse, + DeleteMeterRequest, + DeleteMeterResponse, + QueryMeterRequest, + QueryMeterResponse, + QueryMeterCsvRequest, + QueryMeterCsvResponse, +} from '../models/operations/meters.js' +import type { Meter } from '../models/types.js' + +export class Meters { + constructor(private readonly _client: Client) {} + + /** + * Create meter + * + * Create a meter. + * + * POST /openmeter/meters + */ + async create( + request: CreateMeterRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await createMeter(this._client, request, options)) + } + + /** + * Get meter + * + * Get a meter by ID. + * + * GET /openmeter/meters/{meterId} + */ + async get( + request: GetMeterRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await getMeter(this._client, request, options)) + } + + /** + * List meters + * + * List meters. + * + * GET /openmeter/meters + */ + async list( + request?: ListMetersRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listMeters(this._client, request, options)) + } + + /** + * List meters + * + * List meters. + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/meters + */ + listAll( + request?: ListMetersRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginatePages( + (req, opts) => listMeters(this._client, req, opts), + request ?? {}, + options, + ) + } + + /** + * Update meter + * + * Update a meter. + * + * PUT /openmeter/meters/{meterId} + */ + async update( + request: UpdateMeterRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await updateMeter(this._client, request, options)) + } + + /** + * Delete meter + * + * Delete a meter. + * + * DELETE /openmeter/meters/{meterId} + */ + async delete( + request: DeleteMeterRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await deleteMeter(this._client, request, options)) + } + + /** + * Query meter + * + * Query a meter for usage. + * + * Set `Accept: application/json` (the default) to get a structured JSON response. + * Set `Accept: text/csv` to download the same data as a CSV file suitable for + * spreadsheets. The CSV columns, in order, are: + * + * `from, to, [subject,] [customer_id, customer_key, customer_name,] , value` + * + * The `subject` column is emitted only when `subject` is in the query's + * `group_by_dimensions`. The three `customer_*` columns are emitted together only + * when `customer_id` is in the query's `group_by_dimensions`. + * + * POST /openmeter/meters/{meterId}/query + */ + async query( + request: QueryMeterRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await queryMeter(this._client, request, options)) + } + + /** POST /openmeter/meters/{meterId}/query */ + async queryCsv( + request: QueryMeterCsvRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await queryMeterCsv(this._client, request, options)) + } +} diff --git a/api/spec/packages/aip-client-javascript/src/sdk/planAddons.ts b/api/spec/packages/aip-client-javascript/src/sdk/planAddons.ts new file mode 100644 index 0000000000000000000000000000000000000000..072e5b33779a246193ac6357b87dd547ac6122e2 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/sdk/planAddons.ts @@ -0,0 +1,119 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client } from '../core.js' +import { unwrap, type RequestOptions } from '../lib/types.js' +import { paginatePages } from '../lib/paginate.js' +import { + listPlanAddons, + createPlanAddon, + getPlanAddon, + updatePlanAddon, + deletePlanAddon, +} from '../funcs/planAddons.js' +import type { + ListPlanAddonsRequest, + ListPlanAddonsResponse, + CreatePlanAddonRequest, + CreatePlanAddonResponse, + GetPlanAddonRequest, + GetPlanAddonResponse, + UpdatePlanAddonRequest, + UpdatePlanAddonResponse, + DeletePlanAddonRequest, + DeletePlanAddonResponse, +} from '../models/operations/planAddons.js' +import type { PlanAddon } from '../models/types.js' + +export class PlanAddons { + constructor(private readonly _client: Client) {} + + /** + * List add-ons for plan + * + * List add-ons associated with a plan. + * + * GET /openmeter/plans/{planId}/addons + */ + async list( + request: ListPlanAddonsRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listPlanAddons(this._client, request, options)) + } + + /** + * List add-ons for plan + * + * List add-ons associated with a plan. + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/plans/{planId}/addons + */ + listAll( + request: ListPlanAddonsRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginatePages( + (req, opts) => listPlanAddons(this._client, req, opts), + request, + options, + ) + } + + /** + * Add add-on to plan + * + * Add an add-on to a plan. + * + * POST /openmeter/plans/{planId}/addons + */ + async create( + request: CreatePlanAddonRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await createPlanAddon(this._client, request, options)) + } + + /** + * Get add-on association for plan + * + * Get an add-on association for a plan. + * + * GET /openmeter/plans/{planId}/addons/{planAddonId} + */ + async get( + request: GetPlanAddonRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await getPlanAddon(this._client, request, options)) + } + + /** + * Update add-on association for plan + * + * Update an add-on association for a plan. + * + * PUT /openmeter/plans/{planId}/addons/{planAddonId} + */ + async update( + request: UpdatePlanAddonRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await updatePlanAddon(this._client, request, options)) + } + + /** + * Remove add-on from plan + * + * Remove an add-on from a plan. + * + * DELETE /openmeter/plans/{planId}/addons/{planAddonId} + */ + async delete( + request: DeletePlanAddonRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await deletePlanAddon(this._client, request, options)) + } +} diff --git a/api/spec/packages/aip-client-javascript/src/sdk/plans.ts b/api/spec/packages/aip-client-javascript/src/sdk/plans.ts new file mode 100644 index 0000000000000000000000000000000000000000..028dbe78f7d50ee070d90a1c70f991efed08b7ba --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/sdk/plans.ts @@ -0,0 +1,153 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client } from '../core.js' +import { unwrap, type RequestOptions } from '../lib/types.js' +import { paginatePages } from '../lib/paginate.js' +import { + listPlans, + createPlan, + updatePlan, + getPlan, + deletePlan, + archivePlan, + publishPlan, +} from '../funcs/plans.js' +import type { + ListPlansRequest, + ListPlansResponse, + CreatePlanRequest, + CreatePlanResponse, + UpdatePlanRequest, + UpdatePlanResponse, + GetPlanRequest, + GetPlanResponse, + DeletePlanRequest, + DeletePlanResponse, + ArchivePlanRequest, + ArchivePlanResponse, + PublishPlanRequest, + PublishPlanResponse, +} from '../models/operations/plans.js' +import type { Plan } from '../models/types.js' + +export class Plans { + constructor(private readonly _client: Client) {} + + /** + * List plans + * + * List all plans. + * + * GET /openmeter/plans + */ + async list( + request?: ListPlansRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listPlans(this._client, request, options)) + } + + /** + * List plans + * + * List all plans. + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/plans + */ + listAll( + request?: ListPlansRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginatePages( + (req, opts) => listPlans(this._client, req, opts), + request ?? {}, + options, + ) + } + + /** + * Create plan + * + * Create a new plan. + * + * POST /openmeter/plans + */ + async create( + request: CreatePlanRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await createPlan(this._client, request, options)) + } + + /** + * Update plan + * + * Update a plan by id. + * + * PUT /openmeter/plans/{planId} + */ + async update( + request: UpdatePlanRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await updatePlan(this._client, request, options)) + } + + /** + * Get plan + * + * Get a plan by id. + * + * GET /openmeter/plans/{planId} + */ + async get( + request: GetPlanRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await getPlan(this._client, request, options)) + } + + /** + * Delete plan + * + * Delete a plan by id. + * + * DELETE /openmeter/plans/{planId} + */ + async delete( + request: DeletePlanRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await deletePlan(this._client, request, options)) + } + + /** + * Archive plan version + * + * Archive a plan version. + * + * POST /openmeter/plans/{planId}/archive + */ + async archive( + request: ArchivePlanRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await archivePlan(this._client, request, options)) + } + + /** + * Publish plan version + * + * Publish a plan version. + * + * POST /openmeter/plans/{planId}/publish + */ + async publish( + request: PublishPlanRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await publishPlan(this._client, request, options)) + } +} diff --git a/api/spec/packages/aip-client-javascript/src/sdk/sdk.ts b/api/spec/packages/aip-client-javascript/src/sdk/sdk.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ac360935ed502e083182b0cc20039053b64ff0b --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/sdk/sdk.ts @@ -0,0 +1,101 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { Client } from '../core.js' +import { Events } from './events.js' +import { Meters } from './meters.js' +import { Customers } from './customers.js' +import { Entitlements } from './entitlements.js' +import { Subscriptions } from './subscriptions.js' +import { Apps } from './apps.js' +import { Billing } from './billing.js' +import { Tax } from './tax.js' +import { Features } from './features.js' +import { LLMCost } from './llmCost.js' +import { Plans } from './plans.js' +import { Addons } from './addons.js' +import { PlanAddons } from './planAddons.js' +import { Defaults } from './defaults.js' +import { Internal } from './internal.js' + +export class OpenMeter extends Client { + private _events?: Events + get events(): Events { + return (this._events ??= new Events(this)) + } + + private _meters?: Meters + get meters(): Meters { + return (this._meters ??= new Meters(this)) + } + + private _customers?: Customers + get customers(): Customers { + return (this._customers ??= new Customers(this)) + } + + private _entitlements?: Entitlements + get entitlements(): Entitlements { + return (this._entitlements ??= new Entitlements(this)) + } + + private _subscriptions?: Subscriptions + get subscriptions(): Subscriptions { + return (this._subscriptions ??= new Subscriptions(this)) + } + + private _apps?: Apps + get apps(): Apps { + return (this._apps ??= new Apps(this)) + } + + private _billing?: Billing + get billing(): Billing { + return (this._billing ??= new Billing(this)) + } + + private _tax?: Tax + get tax(): Tax { + return (this._tax ??= new Tax(this)) + } + + private _features?: Features + get features(): Features { + return (this._features ??= new Features(this)) + } + + private _llmCost?: LLMCost + get llmCost(): LLMCost { + return (this._llmCost ??= new LLMCost(this)) + } + + private _plans?: Plans + get plans(): Plans { + return (this._plans ??= new Plans(this)) + } + + private _addons?: Addons + get addons(): Addons { + return (this._addons ??= new Addons(this)) + } + + private _planAddons?: PlanAddons + get planAddons(): PlanAddons { + return (this._planAddons ??= new PlanAddons(this)) + } + + private _defaults?: Defaults + get defaults(): Defaults { + return (this._defaults ??= new Defaults(this)) + } + + private _internal?: Internal + /** + * Operations marked internal in the API definition. They are not part + * of the customer surface: they may require additional permissions, + * and they can change or be removed without notice or semver + * consideration. + */ + get internal(): Internal { + return (this._internal ??= new Internal(this)) + } +} diff --git a/api/spec/packages/aip-client-javascript/src/sdk/subscriptions.ts b/api/spec/packages/aip-client-javascript/src/sdk/subscriptions.ts new file mode 100644 index 0000000000000000000000000000000000000000..a5024e1e4ad85fd00c320f321405414776952a0f --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/sdk/subscriptions.ts @@ -0,0 +1,184 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client } from '../core.js' +import { unwrap, type RequestOptions } from '../lib/types.js' +import { paginatePages } from '../lib/paginate.js' +import { + createSubscription, + listSubscriptions, + getSubscription, + cancelSubscription, + unscheduleCancelation, + changeSubscription, + listSubscriptionAddons, + getSubscriptionAddon, +} from '../funcs/subscriptions.js' +import type { + CreateSubscriptionRequest, + CreateSubscriptionResponse, + ListSubscriptionsRequest, + ListSubscriptionsResponse, + GetSubscriptionRequest, + GetSubscriptionResponse, + CancelSubscriptionRequest, + CancelSubscriptionResponse, + UnscheduleCancelationRequest, + UnscheduleCancelationResponse, + ChangeSubscriptionRequest, + ChangeSubscriptionResponse, + ListSubscriptionAddonsRequest, + ListSubscriptionAddonsResponse, + GetSubscriptionAddonRequest, + GetSubscriptionAddonResponse, +} from '../models/operations/subscriptions.js' +import type { Subscription, SubscriptionAddon } from '../models/types.js' + +export class Subscriptions { + constructor(private readonly _client: Client) {} + + /** + * Create subscription + * + * POST /openmeter/subscriptions + */ + async create( + request: CreateSubscriptionRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await createSubscription(this._client, request, options)) + } + + /** + * List subscriptions + * + * GET /openmeter/subscriptions + */ + async list( + request?: ListSubscriptionsRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listSubscriptions(this._client, request, options)) + } + + /** + * List subscriptions + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/subscriptions + */ + listAll( + request?: ListSubscriptionsRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginatePages( + (req, opts) => listSubscriptions(this._client, req, opts), + request ?? {}, + options, + ) + } + + /** + * Get subscription + * + * GET /openmeter/subscriptions/{subscriptionId} + */ + async get( + request: GetSubscriptionRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await getSubscription(this._client, request, options)) + } + + /** + * Cancel subscription + * + * Cancels the subscription. Will result in a scheduling conflict if there are + * other subscriptions scheduled to start after the cancelation time. + * + * POST /openmeter/subscriptions/{subscriptionId}/cancel + */ + async cancel( + request: CancelSubscriptionRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await cancelSubscription(this._client, request, options)) + } + + /** + * Unschedule subscription cancelation + * + * Unschedules the subscription cancelation. + * + * POST /openmeter/subscriptions/{subscriptionId}/unschedule-cancelation + */ + async unscheduleCancelation( + request: UnscheduleCancelationRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await unscheduleCancelation(this._client, request, options)) + } + + /** + * Change subscription + * + * Closes a running subscription and starts a new one according to the + * specification. Can be used for upgrades, downgrades, and plan changes. + * + * POST /openmeter/subscriptions/{subscriptionId}/change + */ + async change( + request: ChangeSubscriptionRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await changeSubscription(this._client, request, options)) + } + + /** + * List subscription addons + * + * List the add-ons of a subscription. + * + * GET /openmeter/subscriptions/{subscriptionId}/addons + */ + async listAddons( + request: ListSubscriptionAddonsRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listSubscriptionAddons(this._client, request, options)) + } + + /** + * List subscription addons + * + * List the add-ons of a subscription. + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/subscriptions/{subscriptionId}/addons + */ + listAddonsAll( + request: ListSubscriptionAddonsRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginatePages( + (req, opts) => listSubscriptionAddons(this._client, req, opts), + request, + options, + ) + } + + /** + * Get add-on association for subscription + * + * Get an add-on association for a subscription. + * + * GET /openmeter/subscriptions/{subscriptionId}/addons/{subscriptionAddonId} + */ + async getAddon( + request: GetSubscriptionAddonRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await getSubscriptionAddon(this._client, request, options)) + } +} diff --git a/api/spec/packages/aip-client-javascript/src/sdk/tax.ts b/api/spec/packages/aip-client-javascript/src/sdk/tax.ts new file mode 100644 index 0000000000000000000000000000000000000000..235adf10167421a27c0f8e78e83ce2c80e0e5281 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/src/sdk/tax.ts @@ -0,0 +1,107 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import { type Client } from '../core.js' +import { unwrap, type RequestOptions } from '../lib/types.js' +import { paginatePages } from '../lib/paginate.js' +import { + createTaxCode, + getTaxCode, + listTaxCodes, + upsertTaxCode, + deleteTaxCode, +} from '../funcs/tax.js' +import type { + CreateTaxCodeRequest, + CreateTaxCodeResponse, + GetTaxCodeRequest, + GetTaxCodeResponse, + ListTaxCodesRequest, + ListTaxCodesResponse, + UpsertTaxCodeRequest, + UpsertTaxCodeResponse, + DeleteTaxCodeRequest, + DeleteTaxCodeResponse, +} from '../models/operations/tax.js' +import type { TaxCode } from '../models/types.js' + +export class Tax { + constructor(private readonly _client: Client) {} + + /** + * Create tax code + * + * POST /openmeter/tax-codes + */ + async createCode( + request: CreateTaxCodeRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await createTaxCode(this._client, request, options)) + } + + /** + * Get tax code + * + * GET /openmeter/tax-codes/{taxCodeId} + */ + async getCode( + request: GetTaxCodeRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await getTaxCode(this._client, request, options)) + } + + /** + * List tax codes + * + * GET /openmeter/tax-codes + */ + async listCodes( + request?: ListTaxCodesRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await listTaxCodes(this._client, request, options)) + } + + /** + * List tax codes + * + * Iterates every item across all pages, fetching more as the returned iterable is consumed. + * + * GET /openmeter/tax-codes + */ + listCodesAll( + request?: ListTaxCodesRequest, + options?: RequestOptions, + ): AsyncIterable { + return paginatePages( + (req, opts) => listTaxCodes(this._client, req, opts), + request ?? {}, + options, + ) + } + + /** + * Upsert tax code + * + * PUT /openmeter/tax-codes/{taxCodeId} + */ + async upsertCode( + request: UpsertTaxCodeRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await upsertTaxCode(this._client, request, options)) + } + + /** + * Delete tax code + * + * DELETE /openmeter/tax-codes/{taxCodeId} + */ + async deleteCode( + request: DeleteTaxCodeRequest, + options?: RequestOptions, + ): Promise { + return unwrap(await deleteTaxCode(this._client, request, options)) + } +} diff --git a/api/spec/packages/aip-client-javascript/tests/client.spec.ts b/api/spec/packages/aip-client-javascript/tests/client.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..260cbbc599b0572027f9ae5897d4b72c1e735142 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/tests/client.spec.ts @@ -0,0 +1,224 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import fetchMock from '@fetch-mock/vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { OpenMeter, ServerList } from '../src/index.js' +import { SDK_VERSION } from '../src/lib/version.js' + +const meter = { + id: '01ARZ3NDEKTSV4RRFFQ69G5FAV', + name: 'API calls', + key: 'api_calls', + aggregation: 'count', + event_type: 'api-request', + created_at: '2024-01-01T00:00:00Z', + updated_at: '2024-01-01T00:00:00Z', +} + +beforeEach(() => { + fetchMock.mockReset() +}) + +function mockMeter() { + fetchMock.route('*', { + body: meter, + headers: { 'Content-Type': 'application/json' }, + }) +} + +function lastUrl(): string { + return fetchMock.callHistory.lastCall()!.url +} + +function lastAuth(): string | null { + const headers = fetchMock.callHistory.lastCall()!.options.headers as Headers + return new Headers(headers).get('authorization') +} + +function lastUserAgent(): string | null { + const headers = fetchMock.callHistory.lastCall()!.options.headers as Headers + return new Headers(headers).get('user-agent') +} + +const fetch = fetchMock.fetchHandler + +describe('base URL construction', () => { + it('preserves the base path segment (/v3)', async () => { + mockMeter() + const sdk = new OpenMeter({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + fetch, + }) + await sdk.meters.get({ meterId: 'm' }) + expect(lastUrl()).toBe('https://eu.api.konghq.com/v3/openmeter/meters/m') + }) + + it('accepts a URL object as baseUrl', async () => { + mockMeter() + const sdk = new OpenMeter({ + baseUrl: new URL('https://us.api.konghq.com/v3'), + apiKey: 'k', + fetch, + }) + await sdk.meters.get({ meterId: 'm' }) + expect(lastUrl()).toBe('https://us.api.konghq.com/v3/openmeter/meters/m') + }) + + it('sets the bearer auth header', async () => { + mockMeter() + const sdk = new OpenMeter({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + fetch, + }) + await sdk.meters.get({ meterId: 'm' }) + expect(lastAuth()).toBe('Bearer k') + }) +}) + +describe('server-variable templating', () => { + it('substitutes a region variable', async () => { + mockMeter() + const sdk = new OpenMeter({ + baseUrl: ServerList[0], + serverVariables: { region: 'eu' }, + apiKey: 'k', + fetch, + }) + await sdk.meters.get({ meterId: 'm' }) + expect(lastUrl()).toBe('https://eu.api.konghq.com/v3/openmeter/meters/m') + }) + + it('throws when a required template variable is missing', () => { + expect( + () => new OpenMeter({ baseUrl: ServerList[0], apiKey: 'k', fetch }), + ).toThrow() + }) +}) + +describe('option clobbering is prevented', () => { + it('ignores a user-supplied prefix that would redirect requests', async () => { + mockMeter() + const sdk = new OpenMeter({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + prefix: 'http://evil.test/', + fetch, + }) + await sdk.meters.get({ meterId: 'm' }) + expect(lastUrl()).toBe('https://eu.api.konghq.com/v3/openmeter/meters/m') + }) + + it('applies SDK auth after user beforeRequest hooks', async () => { + mockMeter() + const sdk = new OpenMeter({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'real-key', + fetch, + hooks: { + beforeRequest: [ + ({ request }) => { + request.headers.set('Authorization', 'Bearer ATTACKER') + }, + ], + }, + }) + await sdk.meters.get({ meterId: 'm' }) + expect(lastAuth()).toBe('Bearer real-key') + }) +}) + +describe('SDK telemetry headers', () => { + afterEach(() => { + vi.unstubAllGlobals() + }) + + it('sets a default User-Agent header', async () => { + mockMeter() + const sdk = new OpenMeter({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + fetch, + }) + await sdk.meters.get({ meterId: 'm' }) + expect(lastUserAgent()).toBe(`openmeter-node/${SDK_VERSION}`) + }) + + it('does not overwrite a caller-provided User-Agent', async () => { + mockMeter() + const sdk = new OpenMeter({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + headers: { 'User-Agent': 'custom-agent/1.0' }, + fetch, + }) + await sdk.meters.get({ meterId: 'm' }) + expect(lastUserAgent()).toBe('custom-agent/1.0') + }) + + it('does not set a default User-Agent in browsers', async () => { + vi.stubGlobal('window', {}) + vi.stubGlobal('process', undefined) + mockMeter() + const sdk = new OpenMeter({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + fetch, + }) + await sdk.meters.get({ meterId: 'm' }) + expect(lastUserAgent()).toBeNull() + }) + + // Workers are CORS-bound but have no `window`, so a `window`-based gate would + // leak the header here and preflight the request. + it('does not set a default User-Agent in workers', async () => { + vi.stubGlobal('self', {}) + vi.stubGlobal('process', undefined) + mockMeter() + const sdk = new OpenMeter({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + fetch, + }) + await sdk.meters.get({ meterId: 'm' }) + expect(lastUserAgent()).toBeNull() + }) + + it('honors a caller-provided User-Agent in browsers', async () => { + vi.stubGlobal('window', {}) + vi.stubGlobal('process', undefined) + mockMeter() + const sdk = new OpenMeter({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + headers: { 'User-Agent': 'custom-agent/1.0' }, + fetch, + }) + await sdk.meters.get({ meterId: 'm' }) + expect(lastUserAgent()).toBe('custom-agent/1.0') + }) +}) + +describe('namespace composition', () => { + it('memoizes namespace accessors', () => { + const sdk = new OpenMeter({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + fetch, + }) + expect(sdk.meters).toBe(sdk.meters) + }) + + it('routes namespace calls through the root transport', async () => { + mockMeter() + const sdk = new OpenMeter({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + fetch, + }) + await sdk.meters.get({ meterId: 'm' }) + expect(lastUrl()).toBe('https://eu.api.konghq.com/v3/openmeter/meters/m') + expect(lastAuth()).toBe('Bearer k') + }) +}) diff --git a/api/spec/packages/aip-client-javascript/tests/errors.spec.ts b/api/spec/packages/aip-client-javascript/tests/errors.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..81fce2a6ec96e622b57c51622fc5732e6b845910 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/tests/errors.spec.ts @@ -0,0 +1,175 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import fetchMock from '@fetch-mock/vitest' +import { beforeEach, describe, expect, it } from 'vitest' +import { Client, HTTPError, funcs } from '../src/index.js' + +beforeEach(() => { + fetchMock.mockReset() +}) + +function client() { + return new Client({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + fetch: fetchMock.fetchHandler, + // Several of these tests mock retryable statuses (429, 500); disable ky's + // built-in retry so each test hits the mock exactly once and isn't slowed + // down (or, for a 30s Retry-After, timed out) by ky's own backoff. + retry: 0, + }) +} + +function mockProblem(status: number, body: Record) { + fetchMock.route('*', { + status, + body, + headers: { 'Content-Type': 'application/problem+json; charset=utf-8' }, + }) +} + +describe('error mapping', () => { + it('maps problem+json to a typed HTTPError with parsed fields', async () => { + mockProblem(404, { + type: 't', + title: 'Not Found', + status: 404, + detail: 'nope', + instance: '/x', + }) + const result = await funcs.getMeter(client(), { meterId: 'x' }) + expect(result.ok).toBe(false) + expect(result.error).toBeInstanceOf(HTTPError) + const httpError = result.error as HTTPError + expect(httpError.status).toBe(404) + expect(httpError.title).toBe('Not Found') + expect(httpError.message).toBe('nope') + }) + + it('sets the error name so it reads correctly in logs', async () => { + mockProblem(404, { + type: 't', + title: 'Not Found', + status: 404, + detail: 'nope', + instance: '/x', + }) + const result = await funcs.getMeter(client(), { meterId: 'x' }) + const httpError = result.error as HTTPError + expect(httpError.name).toBe('HTTPError') + }) + + it('exposes invalid_parameters via getField', async () => { + mockProblem(400, { + type: 't', + title: 'Bad Request', + status: 400, + detail: 'validation failed', + instance: '/x', + invalid_parameters: [{ field: 'name', reason: 'is required' }], + }) + const result = await funcs.getMeter(client(), { meterId: 'x' }) + const httpError = result.error as HTTPError + expect(httpError.getField('invalid_parameters')).toEqual([ + { field: 'name', reason: 'is required' }, + ]) + }) + + it('exposes invalid_parameters via the typed invalidParameters accessor', async () => { + mockProblem(400, { + type: 't', + title: 'Bad Request', + status: 400, + detail: 'validation failed', + instance: '/x', + invalid_parameters: [ + { field: 'name', reason: 'is required' }, + { + field: 'quantity', + rule: 'min', + minimum: 1, + reason: 'must be at least 1', + }, + ], + }) + const result = await funcs.getMeter(client(), { meterId: 'x' }) + const httpError = result.error as HTTPError + expect(httpError.invalidParameters).toEqual([ + { field: 'name', reason: 'is required' }, + { + field: 'quantity', + rule: 'min', + minimum: 1, + reason: 'must be at least 1', + }, + ]) + }) + + it('falls back to a status-only error for non-problem responses', async () => { + fetchMock.route('*', { + status: 500, + body: 'oops', + headers: { 'Content-Type': 'text/plain' }, + }) + const result = await funcs.getMeter(client(), { meterId: 'x' }) + expect(result.error).toBeInstanceOf(HTTPError) + const httpError = result.error as HTTPError + expect(httpError.status).toBe(500) + expect(httpError.invalidParameters).toBeUndefined() + }) +}) + +describe('retryAfter', () => { + it('parses a delta-seconds Retry-After header', async () => { + fetchMock.route('*', { + status: 429, + body: { + type: 't', + title: 'Too Many Requests', + status: 429, + detail: 'slow down', + instance: '/x', + }, + headers: { + 'Content-Type': 'application/problem+json; charset=utf-8', + 'Retry-After': '30', + }, + }) + const result = await funcs.getMeter(client(), { meterId: 'x' }) + const httpError = result.error as HTTPError + expect(httpError.retryAfter).toBe(30) + }) + + it('is undefined when the header is absent', async () => { + mockProblem(500, { + type: 't', + title: 'Internal Server Error', + status: 500, + detail: 'boom', + instance: '/x', + }) + const result = await funcs.getMeter(client(), { meterId: 'x' }) + const httpError = result.error as HTTPError + expect(httpError.retryAfter).toBeUndefined() + }) + + it('is undefined for an HTTP-date Retry-After header', async () => { + fetchMock.route('*', { + status: 429, + body: { + type: 't', + title: 'Too Many Requests', + status: 429, + detail: 'slow down', + instance: '/x', + }, + headers: { + 'Content-Type': 'application/problem+json; charset=utf-8', + 'Retry-After': 'Wed, 21 Oct 2015 07:28:00 GMT', + }, + }) + const result = await funcs.getMeter(client(), { meterId: 'x' }) + const httpError = result.error as HTTPError + expect(httpError.retryAfter).toBeUndefined() + }) +}) diff --git a/api/spec/packages/aip-client-javascript/tests/index-exports.spec.ts b/api/spec/packages/aip-client-javascript/tests/index-exports.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..5bf8c899b38cb0bb130b80e989991fa0d6ff3d3b --- /dev/null +++ b/api/spec/packages/aip-client-javascript/tests/index-exports.spec.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'vitest' +import type { Price, UpdateMeterRequest } from '../src/index.js' + +// The package root must resolve operation-alias names to the operation envelope, +// not to a raw domain model that shares the name. 18 names used to collide, and +// the explicit model re-export in index.ts silently shadowed the operation alias +// (ESM named exports win over `export type *`) with an incompatible shape — +// e.g. `UpdateMeterRequest` resolved to the bare update body, missing `meterId`. +// Checked at compile time by the tests typecheck; the runtime test only anchors +// the file in the suite. +type _UpdateMeterRequestIsEnvelope = UpdateMeterRequest extends { + meterId: string + body: unknown +} + ? true + : { __error: 'UpdateMeterRequest lost its operation envelope shape' } +const _updateMeterRequestIsEnvelope: _UpdateMeterRequestIsEnvelope = true + +// `Price` is a TypeSpec named union (`@discriminated union Price { free: ..., +// flat: ..., ... }`); before the emitter aliased named unions to a `types.ts` +// declaration, only its expansion (`PriceFree | PriceFlat | ...`) was +// reachable at each use site, so `Price` itself could not be imported, +// annotated, or narrowed by a standalone function. This narrows the imported +// alias by its discriminator and reads a variant-specific field, so a +// regression that inlines the union again (or drops the alias export) fails +// to compile. +function priceAmount(price: Price): string | number { + switch (price.type) { + case 'free': + return 0 + case 'flat': + case 'unit': + return price.amount + case 'graduated': + case 'volume': + return price.tiers.length + } +} + +describe('package-root type exports', () => { + it('resolves formerly colliding names to the operation envelope', () => { + expect(_updateMeterRequestIsEnvelope).toBe(true) + }) + + it('imports and narrows the named union alias Price', () => { + const free: Price = { type: 'free' } + const flat: Price = { type: 'flat', amount: '10' } + expect(priceAmount(free)).toBe(0) + expect(priceAmount(flat)).toBe('10') + }) +}) diff --git a/api/spec/packages/aip-client-javascript/tests/internal.spec.ts b/api/spec/packages/aip-client-javascript/tests/internal.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..319b5b90f6e4077597428604ee4fa64e3525dd45 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/tests/internal.spec.ts @@ -0,0 +1,71 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import fetchMock from '@fetch-mock/vitest' +import { beforeEach, describe, expect, it } from 'vitest' +import { OpenMeter } from '../src/index.js' + +beforeEach(() => { + fetchMock.mockReset() +}) + +const fetch = fetchMock.fetchHandler + +function client(): OpenMeter { + return new OpenMeter({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + fetch, + }) +} + +function lastUrl(): string { + return fetchMock.callHistory.lastCall()!.url +} + +describe('internal sub-client', () => { + it('is memoized and separate from the public surface', () => { + const sdk = client() + expect(sdk.internal).toBe(sdk.internal) + // x-internal operations must not leak onto the public sub-clients. + expect('createAddon' in sdk.subscriptions).toBe(false) + // Entirely-internal groups have no public getter at all. + expect('currencies' in sdk).toBe(false) + }) + + it('routes internal.subscriptions.createAddon() to the subscription addons resource', async () => { + fetchMock.route('*', { + body: { + id: '01ARZ3NDEKTSV4RRFFQ69G5FAV', + name: 'Addon', + addon: { id: '01ARZ3NDEKTSV4RRFFQ69G5FAW' }, + quantity: 1, + quantity_at: '2024-01-01T00:00:00Z', + active_from: '2024-01-01T00:00:00Z', + rate_cards: [], + created_at: '2024-01-01T00:00:00Z', + updated_at: '2024-01-01T00:00:00Z', + }, + headers: { 'Content-Type': 'application/json' }, + }) + await client().internal.subscriptions.createAddon({ + subscriptionId: '01ARZ3NDEKTSV4RRFFQ69G5FAV', + body: { + addon: { id: '01ARZ3NDEKTSV4RRFFQ69G5FAW' }, + quantity: 1, + timing: 'immediate', + }, + }) + expect(lastUrl()).toBe( + 'https://eu.api.konghq.com/v3/openmeter/subscriptions/01ARZ3NDEKTSV4RRFFQ69G5FAV/addons', + ) + }) + + it('routes internal.currencies.list() to the currencies resource', async () => { + fetchMock.route('*', { + body: { data: [], meta: { page: { number: 1, size: 10, total: 0 } } }, + headers: { 'Content-Type': 'application/json' }, + }) + await client().internal.currencies.list() + expect(lastUrl()).toBe('https://eu.api.konghq.com/v3/openmeter/currencies') + }) +}) diff --git a/api/spec/packages/aip-client-javascript/tests/meters.spec.ts b/api/spec/packages/aip-client-javascript/tests/meters.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..c1063be66518fbb4b7c51056d26e2d476ee7c5a9 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/tests/meters.spec.ts @@ -0,0 +1,104 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import fetchMock from '@fetch-mock/vitest' +import { beforeEach, describe, expect, it } from 'vitest' +import { Client, funcs } from '../src/index.js' + +const meter = { + id: '01ARZ3NDEKTSV4RRFFQ69G5FAV', + name: 'API calls', + key: 'api_calls', + aggregation: 'count', + event_type: 'api-request', + created_at: '2024-01-01T00:00:00Z', + updated_at: '2024-01-01T00:00:00Z', +} + +beforeEach(() => { + fetchMock.mockReset() +}) + +function client() { + return new Client({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + fetch: fetchMock.fetchHandler, + }) +} + +function mockList() { + fetchMock.route('*', { + body: { data: [meter], meta: { page: { number: 1, size: 10, total: 1 } } }, + headers: { 'Content-Type': 'application/json' }, + }) +} + +function lastQuery(): URLSearchParams { + return new URL(fetchMock.callHistory.lastCall()!.url).searchParams +} + +describe('listMeters query serialization', () => { + it('encodes page as a deep object', async () => { + mockList() + await funcs.listMeters(client(), { page: { size: 10, number: 2 } }) + const q = lastQuery() + expect(q.get('page[size]')).toBe('10') + expect(q.get('page[number]')).toBe('2') + }) + + it('encodes a scalar filter', async () => { + mockList() + await funcs.listMeters(client(), { filter: { key: 'm' } }) + expect(lastQuery().get('filter[key]')).toBe('m') + }) + + it('encodes a nested filter operand as a deep object', async () => { + mockList() + await funcs.listMeters(client(), { filter: { key: { eq: 'foo' } } }) + expect(lastQuery().get('filter[key][eq]')).toBe('foo') + }) + + it('comma-joins array operands into a single parameter', async () => { + mockList() + await funcs.listMeters(client(), { + filter: { key: { oeq: ['a', 'b', 'c'] } }, + }) + const q = lastQuery() + expect(q.getAll('filter[key][oeq]')).toHaveLength(1) + expect(q.get('filter[key][oeq]')).toBe('a,b,c') + }) + + it('serializes sort as a plain string, snake-ifying the field name', async () => { + mockList() + await funcs.listMeters(client(), { + sort: { by: 'createdAt', order: 'desc' }, + }) + const q = lastQuery() + expect(q.get('sort')).toBe('created_at desc') + expect(q.get('sort[by]')).toBeNull() + }) + + it('omits sort order when ascending is implied', async () => { + mockList() + await funcs.listMeters(client(), { sort: { by: 'name' } }) + expect(lastQuery().get('sort')).toBe('name') + }) +}) + +describe('responses are mapped to the camelCase shape', () => { + it('camelizes known fields and drops fields not in the schema', async () => { + fetchMock.route('*', { + body: { ...meter, brand_new_field: 'dropped' }, + headers: { 'Content-Type': 'application/json' }, + }) + const result = await funcs.getMeter(client(), { meterId: 'm' }) + expect(result.ok).toBe(true) + expect(result.value).toMatchObject({ + id: meter.id, + eventType: meter.event_type, + createdAt: new Date(meter.created_at), + }) + expect('event_type' in result.value!).toBe(false) + expect('brand_new_field' in result.value!).toBe(false) + }) +}) diff --git a/api/spec/packages/aip-client-javascript/tests/nesting.spec.ts b/api/spec/packages/aip-client-javascript/tests/nesting.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..79f63abd52ebf485c8cfcb4e1d71c68584aa7833 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/tests/nesting.spec.ts @@ -0,0 +1,35 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import fetchMock from '@fetch-mock/vitest' +import { beforeEach, describe, expect, it } from 'vitest' +import { OpenMeter } from '../src/index.js' + +beforeEach(() => { + fetchMock.mockReset() +}) + +const fetch = fetchMock.fetchHandler + +function lastUrl(): string { + return fetchMock.callHistory.lastCall()!.url +} + +describe('nested sub-clients', () => { + it('routes customers.charges.list() to the charges sub-resource', async () => { + fetchMock.route('*', { + body: { data: [], meta: { page: { number: 1, size: 10, total: 0 } } }, + headers: { 'Content-Type': 'application/json' }, + }) + const sdk = new OpenMeter({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + fetch, + }) + await sdk.customers.charges.list({ + customerId: '01ARZ3NDEKTSV4RRFFQ69G5FAV', + }) + expect(lastUrl()).toBe( + 'https://eu.api.konghq.com/v3/openmeter/customers/01ARZ3NDEKTSV4RRFFQ69G5FAV/charges', + ) + }) +}) diff --git a/api/spec/packages/aip-client-javascript/tests/paginate.spec.ts b/api/spec/packages/aip-client-javascript/tests/paginate.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..8aa338aec1cd69e33ea5e35fb9105112da9fca1a --- /dev/null +++ b/api/spec/packages/aip-client-javascript/tests/paginate.spec.ts @@ -0,0 +1,396 @@ +import fetchMock from '@fetch-mock/vitest' +import { beforeEach, describe, expect, it } from 'vitest' +import { OpenMeter, type IngestedEvent, type Meter } from '../src/index.js' +import { + PaginationLimitExceededError, + paginateCursor, + paginatePages, +} from '../src/lib/paginate.js' +import type { Result } from '../src/lib/types.js' + +beforeEach(() => { + fetchMock.mockReset() +}) + +function client() { + return new OpenMeter({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + fetch: fetchMock.fetchHandler, + }) +} + +function meterFixture(key: string) { + return { + id: `01ARZ3NDEKTSV4RRFFQ69G5${key.toUpperCase().padStart(4, '0')}`, + name: key, + key, + aggregation: 'count', + event_type: 'api-request', + created_at: '2024-01-01T00:00:00Z', + updated_at: '2024-01-01T00:00:00Z', + } +} + +function eventFixture(id: string) { + return { + event: { id, source: 'test', specversion: '1.0', type: 'test.event' }, + ingested_at: '2024-01-01T00:00:00Z', + stored_at: '2024-01-01T00:00:00Z', + } +} + +function jsonRoute(body: unknown) { + return { body, headers: { 'Content-Type': 'application/json' } } +} + +describe('paginatePages (page-number pagination)', () => { + it('iterates every item across 3 pages via client.meters.listAll', async () => { + // total 5 across pages of size 2, 2, 1 — the last page is short, which is + // what actually stops the iteration (see the exact-total test below for + // the other stop condition). + const pageKeys = [['a', 'b'], ['c', 'd'], ['e']] + fetchMock.route('*', (callLog) => { + const number = Number(callLog.queryParams?.get('page[number]') ?? '1') + const keys = pageKeys[number - 1] ?? [] + return jsonRoute({ + data: keys.map(meterFixture), + meta: { page: { number, size: 2, total: 5 } }, + }) + }) + + const keys: string[] = [] + for await (const meter of client().meters.listAll()) { + keys.push(meter.key) + } + + expect(keys).toEqual(['a', 'b', 'c', 'd', 'e']) + expect(fetchMock.callHistory.calls()).toHaveLength(3) + }) + + it('stops without an extra request when the final page exactly fills total', async () => { + fetchMock.route('*', (callLog) => { + const number = Number(callLog.queryParams?.get('page[number]') ?? '1') + const keys = number === 1 ? ['a', 'b'] : [] + return jsonRoute({ + data: keys.map(meterFixture), + meta: { page: { number, size: 2, total: 2 } }, + }) + }) + + const keys: string[] = [] + for await (const meter of client().meters.listAll()) { + keys.push(meter.key) + } + + expect(keys).toEqual(['a', 'b']) + expect(fetchMock.callHistory.calls()).toHaveLength(1) + }) + + it('yields nothing and fetches once for an empty first page', async () => { + fetchMock.route( + '*', + jsonRoute({ + data: [], + meta: { page: { number: 1, size: 10, total: 0 } }, + }), + ) + + const keys: string[] = [] + for await (const meter of client().meters.listAll()) { + keys.push(meter.key) + } + + expect(keys).toEqual([]) + expect(fetchMock.callHistory.calls()).toHaveLength(1) + }) + + it('fires no further requests once the consumer breaks early', async () => { + const pageKeys = [ + ['a', 'b'], + ['c', 'd'], + ] + fetchMock.route('*', (callLog) => { + const number = Number(callLog.queryParams?.get('page[number]') ?? '1') + return jsonRoute({ + data: (pageKeys[number - 1] ?? []).map(meterFixture), + meta: { page: { number, size: 2, total: 4 } }, + }) + }) + + for await (const meter of client().meters.listAll()) { + expect(meter.key).toBe('a') + break + } + + expect(fetchMock.callHistory.calls()).toHaveLength(1) + }) + + it('sends the caller-supplied filter and sort on every page, advancing only page.number', async () => { + fetchMock.route('*', (callLog) => { + const number = Number(callLog.queryParams?.get('page[number]') ?? '1') + const keys = number < 2 ? ['a', 'b'] : ['c'] + return jsonRoute({ + data: keys.map(meterFixture), + meta: { page: { number, size: 2, total: 3 } }, + }) + }) + + const items: Meter[] = [] + for await (const meter of client().meters.listAll({ + filter: { key: { eq: 'api' } }, + sort: { by: 'createdAt', order: 'desc' }, + })) { + items.push(meter) + } + + expect(items).toHaveLength(3) + const calls = fetchMock.callHistory.calls() + expect(calls).toHaveLength(2) + for (const [i, call] of calls.entries()) { + const q = new URL(call.url).searchParams + expect(q.get('filter[key][eq]')).toBe('api') + expect(q.get('sort')).toBe('created_at desc') + // The first request is whatever the caller supplied — no page.number at + // all, left to the server's own default — only later requests carry an + // explicit page.number, advanced from the previous response. + expect(q.get('page[number]')).toBe(i === 0 ? null : String(i + 1)) + } + }) + + it('propagates the AbortSignal to every page fetch, and aborting stops iteration', async () => { + const controller = new AbortController() + // ky composes the caller's signal into its own dependent AbortSignal + // before it reaches fetch (its `.aborted` state tracks the original, but + // it is not the same object), so propagation is verified behaviorally — + // a signal reaches every dispatched request, and aborting mid-iteration + // stops it — rather than by reference identity. + const signals: (AbortSignal | undefined)[] = [] + fetchMock.route('*', (callLog) => { + signals.push(callLog.signal) + const number = Number(callLog.queryParams?.get('page[number]') ?? '1') + return jsonRoute({ + data: [meterFixture(`m${number}`)], + meta: { page: { number, size: 1, total: 5 } }, + }) + }) + + const keys: string[] = [] + await expect(async () => { + for await (const meter of client().meters.listAll(undefined, { + signal: controller.signal, + })) { + keys.push(meter.key) + controller.abort() + } + }).rejects.toThrow() + + // The abort races with the second page's already-dispatched request: the + // mock still resolves a response for it (this route intercepts before + // ky/fetch's own abort check settles the promise), but the abort still + // wins — no page-2 item is yielded, and the iterable rejects instead of + // completing normally. + expect(keys).toEqual(['m1']) + expect(signals.length).toBeGreaterThanOrEqual(1) + expect(signals.every((signal) => signal !== undefined)).toBe(true) + }) + + it('throws PaginationLimitExceededError instead of looping forever on a server that never signals the end', async () => { + let calls = 0 + const fetchPage = async (): Promise< + Result<{ + data: unknown[] + meta: { page: { number: number; size: number; total: number } } + }> + > => { + calls++ + return { + ok: true, + value: { + data: [{}], + meta: { + page: { number: calls, size: 1, total: Number.MAX_SAFE_INTEGER }, + }, + }, + } + } + + await expect(async () => { + for await (const _ of paginatePages(fetchPage, {})) { + // drain + } + }).rejects.toThrow(PaginationLimitExceededError) + expect(calls).toBe(10_000) + }) +}) + +describe('paginateCursor (cursor pagination)', () => { + it('iterates every item across 3 pages via client.events.listAll', async () => { + const pages: Record = { + '': { ids: ['1', '2'], next: 'cursor-2' }, + 'cursor-2': { ids: ['3', '4'], next: 'cursor-3' }, + 'cursor-3': { ids: ['5'], next: undefined }, + } + fetchMock.route('*', (callLog) => { + const after = callLog.queryParams?.get('page[after]') ?? '' + const page = pages[after]! + return jsonRoute({ + data: page.ids.map(eventFixture), + meta: { page: { next: page.next ?? null } }, + }) + }) + + const ids: string[] = [] + for await (const event of client().events.listAll()) { + ids.push(event.event.id) + } + + expect(ids).toEqual(['1', '2', '3', '4', '5']) + expect(fetchMock.callHistory.calls()).toHaveLength(3) + }) + + it('stops after one fetch when the first page has no next cursor', async () => { + fetchMock.route( + '*', + jsonRoute({ + data: [eventFixture('1')], + meta: { page: { next: null } }, + }), + ) + + const ids: string[] = [] + for await (const event of client().events.listAll()) { + ids.push(event.event.id) + } + + expect(ids).toEqual(['1']) + expect(fetchMock.callHistory.calls()).toHaveLength(1) + }) + + it('fires no further requests once the consumer breaks early', async () => { + const pages: Record = { + '': { ids: ['1', '2'], next: 'cursor-2' }, + 'cursor-2': { ids: ['3'], next: undefined }, + } + fetchMock.route('*', (callLog) => { + const after = callLog.queryParams?.get('page[after]') ?? '' + const page = pages[after]! + return jsonRoute({ + data: page.ids.map(eventFixture), + meta: { page: { next: page.next ?? null } }, + }) + }) + + for await (const event of client().events.listAll()) { + expect(event.event.id).toBe('1') + break + } + + expect(fetchMock.callHistory.calls()).toHaveLength(1) + }) + + it('feeds meta.page.next back as page.after verbatim (an opaque token, not a URI to fetch)', async () => { + const pages: Record = { + '': { ids: ['1'], next: 'opaque-token-not-a-url' }, + 'opaque-token-not-a-url': { ids: ['2'], next: undefined }, + } + fetchMock.route('*', (callLog) => { + const after = callLog.queryParams?.get('page[after]') ?? '' + const page = pages[after]! + return jsonRoute({ + data: page.ids.map(eventFixture), + meta: { page: { next: page.next ?? null } }, + }) + }) + + const ids: string[] = [] + for await (const event of client().events.listAll()) { + ids.push(event.event.id) + } + + expect(ids).toEqual(['1', '2']) + }) + + it('sends the caller-supplied filter on every page, advancing only page.after', async () => { + const pages: Record = { + '': { ids: ['1'], next: 'cursor-2' }, + 'cursor-2': { ids: ['2'], next: undefined }, + } + fetchMock.route('*', (callLog) => { + const after = callLog.queryParams?.get('page[after]') ?? '' + const page = pages[after]! + return jsonRoute({ + data: page.ids.map(eventFixture), + meta: { page: { next: page.next ?? null } }, + }) + }) + + for await (const _ of client().events.listAll({ + filter: { subject: { eq: 'customer-1' } }, + })) { + // drain + } + + const calls = fetchMock.callHistory.calls() + expect(calls).toHaveLength(2) + for (const call of calls) { + expect(new URL(call.url).searchParams.get('filter[subject][eq]')).toBe( + 'customer-1', + ) + } + }) + + it('throws PaginationLimitExceededError instead of looping forever on a server that never stops returning a next cursor', async () => { + let calls = 0 + const fetchPage = async (): Promise< + Result<{ data: unknown[]; meta: { page: { next: string | null } } }> + > => { + calls++ + return { + ok: true, + value: { data: [{}], meta: { page: { next: 'again' } } }, + } + } + + await expect(async () => { + for await (const _ of paginateCursor(fetchPage, {})) { + // drain + } + }).rejects.toThrow(PaginationLimitExceededError) + expect(calls).toBe(10_000) + }) +}) + +describe('AsyncIterable type inference', () => { + // Compile-time proof that the facade companions infer the ITEM type, not + // the page envelope — `listAll`'s return type must be exactly + // `AsyncIterable`/`AsyncIterable`, with no cast at the + // call site required to get there. + type ListAllItem = T extends AsyncIterable ? Item : never + type _MetersListAllYieldsMeter = [ + ListAllItem>, + ] extends [Meter] + ? [Meter] extends [ListAllItem>] + ? true + : { __error: 'meters.listAll yields something narrower than Meter' } + : { __error: 'meters.listAll does not yield Meter' } + const _metersListAllYieldsMeter: _MetersListAllYieldsMeter = true + + type _EventsListAllYieldsIngestedEvent = [ + ListAllItem>, + ] extends [IngestedEvent] + ? [IngestedEvent] extends [ + ListAllItem>, + ] + ? true + : { + __error: 'events.listAll yields something narrower than IngestedEvent' + } + : { __error: 'events.listAll does not yield IngestedEvent' } + const _eventsListAllYieldsIngestedEvent: _EventsListAllYieldsIngestedEvent = true + + it('type-checks the item-level inference probes above', () => { + expect(_metersListAllYieldsMeter).toBe(true) + expect(_eventsListAllYieldsIngestedEvent).toBe(true) + }) +}) diff --git a/api/spec/packages/aip-client-javascript/tests/validation.spec.ts b/api/spec/packages/aip-client-javascript/tests/validation.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..6c1b437405d1d6c6f804db29f2ab1c4b4ecb864b --- /dev/null +++ b/api/spec/packages/aip-client-javascript/tests/validation.spec.ts @@ -0,0 +1,297 @@ +// Code generated by @openmeter/typespec-typescript. DO NOT EDIT. + +import fetchMock from '@fetch-mock/vitest' +import { beforeEach, describe, expect, it } from 'vitest' +import { Client, funcs, ValidationError } from '../src/index.js' +import { toWire } from '../src/lib/wire.js' +import * as schemas from '../src/models/schemas.js' + +const customerId = '01ARZ3NDEKTSV4RRFFQ69G5FAV' +const meterId = '01ARZ3NDEKTSV4RRFFQ69G5FAV' + +const ingestedEvent = { + event: { + id: 'event-1', + source: 'https://example.com/service', + specversion: '1.0', + type: 'api-request', + subject: 'customer-1', + time: '2024-01-01T00:00:00Z', + }, + ingested_at: '2024-01-01T00:00:01Z', + stored_at: '2024-01-01T00:00:02Z', +} + +beforeEach(() => { + fetchMock.mockReset() +}) + +function client(validate: boolean) { + return new Client({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + fetch: fetchMock.fetchHandler, + validate, + }) +} + +function json(body: unknown) { + return { + body, + headers: { 'Content-Type': 'application/json' }, + } +} + +describe('strict request validation uses the effective JSON payload', () => { + it('omits explicit undefined object properties and record entries in toWire', () => { + const wire = toWire( + { + timeZone: undefined, + filters: { + dimensions: { + subject: undefined, + customer_id: undefined, + }, + }, + }, + schemas.meterQueryRequest, + ) as Record + + expect(Object.hasOwn(wire, 'time_zone')).toBe(false) + expect(wire.filters).toEqual({ dimensions: {} }) + }) + + it('sends a meter query with undefined optional dimension entries', async () => { + let sentBody: unknown + fetchMock.route('*', async ({ options }) => { + sentBody = JSON.parse(options!.body as string) + return json({ data: [] }) + }) + + const result = await funcs.queryMeter(client(true), { + meterId, + body: { + filters: { + dimensions: { + subject: undefined as never, + customer_id: undefined as never, + model: { eq: 'gpt-4o' }, + }, + }, + }, + }) + + expect(result.ok).toBe(true) + expect(sentBody).toEqual({ + filters: { dimensions: { model: { eq: 'gpt-4o' } } }, + }) + }) + + it('rejects a genuinely invalid dimension filter before sending', async () => { + fetchMock.route('*', json({ data: [] })) + + const result = await funcs.queryMeter(client(true), { + meterId, + body: { + filters: { + dimensions: { subject: 'not-a-filter-object' as never }, + }, + }, + }) + + expect(result.ok).toBe(false) + expect(result.error).toBeInstanceOf(ValidationError) + expect(fetchMock.callHistory.calls()).toHaveLength(0) + }) + + it('keeps request validation disabled when validate is false', async () => { + fetchMock.route('*', json({ data: [] })) + + const result = await funcs.queryMeter(client(false), { + meterId, + body: { + filters: { + dimensions: { subject: 'not-a-filter-object' as never }, + }, + }, + }) + + expect(result.ok).toBe(true) + expect(fetchMock.callHistory.calls()).toHaveLength(1) + }) + + it('materializes required defaults before strict wire validation', async () => { + let sentBody: unknown + fetchMock.route('*', async ({ options }) => { + sentBody = JSON.parse(options!.body as string) + return 204 + }) + + const result = await funcs.ingestMeteringEvents(client(true), { + id: 'event-with-default', + source: 'https://example.com/service', + type: 'api-request', + subject: 'customer-1', + }) + + expect(result.ok).toBe(true) + expect(sentBody).toMatchObject({ specversion: '1.0' }) + }) +}) + +describe('strict sort validation follows the public and wire shapes', () => { + const eventsPage = { + data: [ingestedEvent], + meta: { page: { size: 1, next: null, previous: null } }, + } + + it('accepts a valid public sort object and validates its encoded string', async () => { + fetchMock.route('*', json(eventsPage)) + + const result = await funcs.listMeteringEvents(client(true), { + sort: { by: 'ingestedAt', order: 'desc' }, + }) + + expect(result.ok).toBe(true) + const query = new URL(fetchMock.callHistory.lastCall()!.url).searchParams + expect(query.get('sort')).toBe('ingested_at desc') + }) + + it('rejects an invalid public sort before encoding or sending', async () => { + fetchMock.route('*', json(eventsPage)) + + const result = await funcs.listMeteringEvents(client(true), { + sort: { by: 'ingestedAt', order: 'sideways' as never }, + }) + + expect(result.ok).toBe(false) + expect(result.error).toBeInstanceOf(ValidationError) + expect(fetchMock.callHistory.calls()).toHaveLength(0) + }) + + it('keeps the existing sort behavior when validate is false', async () => { + fetchMock.route('*', json(eventsPage)) + + const result = await funcs.listMeteringEvents(client(false), { + sort: { by: 'ingestedAt', order: 'sideways' as never }, + }) + + expect(result.ok).toBe(true) + const query = new URL(fetchMock.callHistory.lastCall()!.url).searchParams + expect(query.get('sort')).toBe('ingested_at') + }) +}) + +describe('strict path validation uses generated path schemas', () => { + it('rejects an invalid constrained path value before sending', async () => { + fetchMock.route('*', json({})) + + const result = await funcs.getMeter(client(true), { + meterId: 'not-a-ulid', + }) + + expect(result.ok).toBe(false) + expect(result.error).toBeInstanceOf(ValidationError) + expect(fetchMock.callHistory.calls()).toHaveLength(0) + }) + + it('keeps path validation disabled when validate is false', async () => { + fetchMock.route('*', json({})) + + const result = await funcs.getMeter(client(false), { + meterId: 'not-a-ulid', + }) + + expect(result.ok).toBe(true) + expect(fetchMock.callHistory.calls()).toHaveLength(1) + expect(fetchMock.callHistory.lastCall()!.url).toContain( + '/openmeter/meters/not-a-ulid', + ) + }) +}) + +describe('nullable cursor response validation', () => { + it('accepts an events page with a null previous cursor and returns its events', async () => { + fetchMock.route( + '*', + json({ + data: [ingestedEvent], + meta: { page: { size: 1, next: null, previous: null } }, + }), + ) + + const result = await funcs.listMeteringEvents(client(true), {}) + + expect(result.ok).toBe(true) + expect(result.value?.data).toHaveLength(1) + expect(result.value?.data[0]?.event.id).toBe('event-1') + expect(result.value?.meta.page.previous).toBeNull() + }) + + it('accepts an empty credit transaction page with null cursors', async () => { + fetchMock.route( + '*', + json({ + data: [], + meta: { page: { size: 100, next: null, previous: null } }, + }), + ) + + const result = await funcs.listCreditTransactions(client(true), { + customerId, + }) + + expect(result.ok).toBe(true) + expect(result.value?.data).toEqual([]) + expect(result.value?.meta.page.next).toBeNull() + expect(result.value?.meta.page.previous).toBeNull() + }) + + it('rejects a genuinely invalid cursor value', async () => { + fetchMock.route( + '*', + json({ + data: [ingestedEvent], + meta: { page: { size: 1, next: null, previous: 42 } }, + }), + ) + + const result = await funcs.listMeteringEvents(client(true), {}) + + expect(result.ok).toBe(false) + expect(result.error).toBeInstanceOf(ValidationError) + }) + + it('rejects a response missing a required field that has a request default', async () => { + const { specversion: _specversion, ...eventWithoutSpecversion } = + ingestedEvent.event + fetchMock.route( + '*', + json({ + data: [{ ...ingestedEvent, event: eventWithoutSpecversion }], + meta: { page: { size: 1, next: null, previous: null } }, + }), + ) + + const result = await funcs.listMeteringEvents(client(true), {}) + + expect(result.ok).toBe(false) + expect(result.error).toBeInstanceOf(ValidationError) + }) + + it('keeps response validation disabled when validate is false', async () => { + fetchMock.route( + '*', + json({ + data: [ingestedEvent], + meta: { page: { size: 1, next: null, previous: 42 } }, + }), + ) + + const result = await funcs.listMeteringEvents(client(false), {}) + + expect(result.ok).toBe(true) + expect(result.value?.data).toHaveLength(1) + expect(result.value?.meta.page.previous).toBe(42) + }) +}) diff --git a/api/spec/packages/aip-client-javascript/tests/void-responses.spec.ts b/api/spec/packages/aip-client-javascript/tests/void-responses.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ad6b85e4533df5296c6fb39d0f028ffdeace6d9 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/tests/void-responses.spec.ts @@ -0,0 +1,98 @@ +import fetchMock from '@fetch-mock/vitest' +import { beforeEach, describe, expect, it } from 'vitest' +import { Client, HTTPError, funcs } from '../src/index.js' + +beforeEach(() => { + fetchMock.mockReset() +}) + +function client() { + return new Client({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + fetch: fetchMock.fetchHandler, + }) +} + +describe('void operations do not parse the response body', () => { + it('resolves ingest of a single event on an empty 202 Accepted body', async () => { + fetchMock.route('*', { status: 202, body: '' }) + const result = await funcs.ingestMeteringEvents(client(), { + specversion: '1.0', + id: 'evt-1', + source: 'test', + type: 'request', + subject: 'customer-1', + }) + expect(result.ok).toBe(true) + expect(result.value).toBeUndefined() + }) + + it('resolves ingest of a batch of events (array body)', async () => { + fetchMock.route('*', { status: 202, body: '' }) + const result = await funcs.ingestMeteringEvents(client(), [ + { + specversion: '1.0', + id: 'evt-1', + source: 'test', + type: 'request', + subject: 'customer-1', + }, + { + specversion: '1.0', + id: 'evt-2', + source: 'test', + type: 'request', + subject: 'customer-2', + }, + ]) + expect(result.ok).toBe(true) + expect(result.value).toBeUndefined() + const sent = JSON.parse( + fetchMock.callHistory.lastCall()!.options.body as string, + ) + expect(Array.isArray(sent)).toBe(true) + expect(sent).toHaveLength(2) + }) + + it('resolves delete on a 204 No Content response', async () => { + fetchMock.route('*', { status: 204 }) + const result = await funcs.deleteMeter(client(), { meterId: 'm' }) + expect(result.ok).toBe(true) + expect(result.value).toBeUndefined() + }) + + it('still rejects a void operation on a non-2xx status', async () => { + fetchMock.route('*', { + status: 500, + body: 'oops', + headers: { 'Content-Type': 'text/plain' }, + }) + const result = await funcs.deleteMeter(client(), { meterId: 'm' }) + expect(result.ok).toBe(false) + expect(result.error).toBeInstanceOf(HTTPError) + expect((result.error as HTTPError).status).toBe(500) + }) + + it('preserves problem+json error detail on a void operation', async () => { + fetchMock.route('*', { + status: 404, + body: { + type: 't', + title: 'Not Found', + status: 404, + detail: 'nope', + instance: '/x', + }, + headers: { + 'Content-Type': 'application/problem+json; charset=utf-8', + }, + }) + const result = await funcs.deleteMeter(client(), { meterId: 'm' }) + expect(result.ok).toBe(false) + const error = result.error as HTTPError + expect(error.status).toBe(404) + expect(error.title).toBe('Not Found') + expect(error.message).toBe('nope') + }) +}) diff --git a/api/spec/packages/aip-client-javascript/tests/wire-helpers.ts b/api/spec/packages/aip-client-javascript/tests/wire-helpers.ts new file mode 100644 index 0000000000000000000000000000000000000000..e0d2d13688d4510262d79a3cba7f90509e87b0fa --- /dev/null +++ b/api/spec/packages/aip-client-javascript/tests/wire-helpers.ts @@ -0,0 +1,166 @@ +import type { ZodType } from 'zod' + +type ZodDef = { + type: string + innerType?: ZodType + valueType?: ZodType + element?: ZodType + options?: ZodType[] + entries?: Record +} + +function def(schema: ZodType | undefined): ZodDef | undefined { + return (schema as { def?: ZodDef } | undefined)?.def +} + +function shapeOf( + schema: ZodType | undefined, +): Record | undefined { + return (schema as { shape?: Record } | undefined)?.shape +} + +/** + * A value satisfying a schema's structure, with camelCase object keys (the emitted + * schemas are camelCase) and a deliberately underscore-containing record key so the + * casing assertion can tell a leaked field key from a preserved user key. + * + * Every field whose sample is defined is populated (so optional camelCase fields are + * exercised). A key whose sample comes back undefined is omitted rather than set to + * undefined, so a discriminated-union variant always carries its discriminator + * literal and the mapper can resolve every variant it descends into. The depth cap + * bounds the self-referential filter schemas. + */ +export function sampleCamel(schema: ZodType | undefined, depth = 0): unknown { + const d = def(schema) + if (!d || depth > 12) { + return undefined + } + switch (d.type) { + case 'object': { + const out: Record = {} + for (const [k, v] of Object.entries(shapeOf(schema) ?? {})) { + const value = sampleCamel(v, depth + 1) + if (value !== undefined) { + out[k] = value + } + } + return out + } + case 'optional': + case 'nullable': + case 'default': + return sampleCamel(d.innerType, depth) + case 'array': + return [sampleCamel(d.element, depth + 1)] + case 'record': + return { user_key_a: sampleCamel(d.valueType, depth + 1) } + case 'union': + return sampleCamel(d.options?.[0], depth) + case 'literal': + return (schema as { value?: unknown }).value + case 'enum': + // Without this, enum fields fall out of every sample entirely — and a + // required-with-default enum (e.g. an invoice line's `category`) then + // breaks response round-trip identity, because toWire materializes the + // default the sample never carried. + return Object.values(d.entries ?? {})[0] + case 'string': + return 's' + case 'int': + case 'number': + return 1 + case 'bigint': + return 1n + case 'boolean': + return true + case 'date': + return new Date(0) + default: + return undefined + } +} + +// Snake-cased counterpart for response samples: object keys are snake_cased so +// fromWire has wire-shaped input. Record user keys and literal values are kept. +export function sampleSnake(schema: ZodType | undefined, depth = 0): unknown { + const value = sampleCamel(schema, depth) + return toSnakeKeys(value) +} + +function toSnakeKeys(value: unknown): unknown { + if (value instanceof Date) { + // Wire samples carry the RFC 3339 string a JSON payload would. + return value.toISOString() + } + if (typeof value === 'bigint') { + // Wire samples carry the JSON number an int64 payload would. + return Number(value) + } + if (Array.isArray(value)) { + return value.map(toSnakeKeys) + } + if (value && typeof value === 'object') { + const out: Record = {} + for (const [k, v] of Object.entries(value)) { + const key = k.startsWith('user_key_') + ? k + : k.replace(/([A-Z])/g, (_m, c: string) => `_${c.toLowerCase()}`) + out[key] = toSnakeKeys(v) + } + return out + } + return value +} + +/** + * Every object key in the value, except keys of a `user_key_*` map (preserved + * record keys) and date values. Used to assert no casing leaks past the mapper. + */ +export function collectFieldKeys( + value: unknown, + keys: string[] = [], +): string[] { + if (Array.isArray(value)) { + for (const item of value) { + collectFieldKeys(item, keys) + } + return keys + } + if (value && typeof value === 'object' && !(value instanceof Date)) { + for (const [k, v] of Object.entries(value)) { + if (k.startsWith('user_key_')) { + // Preserved user record key — not itself a schema field, so it's excluded + // from the leak check. Its value can still be model-shaped (e.g. a + // governance feature-access record value), so keep walking into it — + // skipping the value too would blind the leak check to casing bugs in + // any schema field nested under a record. + collectFieldKeys(v, keys) + continue + } + keys.push(k) + collectFieldKeys(v, keys) + } + } + return keys +} + +/** Per-op schemas grouped by base name, from the generated schemas module. */ +export function operationSchemaPairs( + schemas: Record, +): Array<{ base: string; body?: ZodType; response?: ZodType }> { + const bases = new Map() + for (const [name, schema] of Object.entries(schemas)) { + const bodyMatch = name.match(/^(.*)Body$/) + const responseMatch = name.match(/^(.*)Response$/) + if (bodyMatch) { + const entry = bases.get(bodyMatch[1]) ?? {} + entry.body = schema as ZodType + bases.set(bodyMatch[1], entry) + } else if (responseMatch) { + const entry = bases.get(responseMatch[1]) ?? {} + entry.response = schema as ZodType + bases.set(responseMatch[1], entry) + } + } + return [...bases.entries()].map(([base, v]) => ({ base, ...v })) +} diff --git a/api/spec/packages/aip-client-javascript/tests/wire.generated.spec.ts b/api/spec/packages/aip-client-javascript/tests/wire.generated.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..e4f60d0753d49c47da427fa2829df3d68a37e2fa --- /dev/null +++ b/api/spec/packages/aip-client-javascript/tests/wire.generated.spec.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from 'vitest' +import * as schemas from '../src/models/schemas.js' +import { fromWire, toWire } from '../src/lib/wire.js' +import { + collectFieldKeys, + operationSchemaPairs, + sampleCamel, + sampleSnake, +} from './wire-helpers.js' + +const SNAKE_KEY = /_/ +const CAMEL_KEY = /[A-Z]/ + +const pairs = operationSchemaPairs(schemas as Record) + +// The casing-leak invariant, applied to every operation: toWire produces a +// snake_case body (no camelCase field key escapes), fromWire produces a camelCase +// shape (no snake_case field key escapes). Preserved record user keys +// (`user_key_*`) are excluded by collectFieldKeys, so a legitimately-preserved +// key never trips the assertion. Field names that are single-word in both cases +// pass trivially. +describe('per-operation wire casing (toWire → snake, fromWire → camel)', () => { + for (const { base, body, response } of pairs) { + if (body) { + it(`${base}: request body has no camelCase field key on the wire`, () => { + const wire = toWire(sampleCamel(body), body) + const leaked = collectFieldKeys(wire).filter((k) => CAMEL_KEY.test(k)) + expect(leaked).toEqual([]) + }) + + // Round-trips the public sample through the wire and back. Catches a silent + // drop or a mis-mapped name that the no-leak check alone cannot see: the + // sample contains only in-schema fields, so nothing should be dropped and + // identity must hold exactly. + it(`${base}: request body round-trips (camel → wire → camel)`, () => { + const sample = sampleCamel(body) + expect(fromWire(toWire(sample, body), body)).toEqual(sample) + }) + } + if (response) { + it(`${base}: response has no snake_case field key after mapping`, () => { + const camel = fromWire(sampleSnake(response), response) + const leaked = collectFieldKeys(camel).filter((k) => SNAKE_KEY.test(k)) + expect(leaked).toEqual([]) + }) + + it(`${base}: response round-trips (wire → camel → wire)`, () => { + const wire = sampleSnake(response) + expect(toWire(fromWire(wire, response), response)).toEqual(wire) + }) + } + } +}) + +// The strict `…Wire` schemas behind the validate option are emitted from the same +// TypeSpec walk as the camelCase schemas (one pass parameterized by casing + +// strictness), so they agree with the data mapper by construction — no per-op +// runtime sweep is needed. wire.spec.ts spot-checks the generated wire schemas +// (strict closed model, open record-spread, discriminator, record value, cyclic). diff --git a/api/spec/packages/aip-client-javascript/tests/wire.spec.ts b/api/spec/packages/aip-client-javascript/tests/wire.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..a72355134c0ffb68506089a7438bd8acca9a224f --- /dev/null +++ b/api/spec/packages/aip-client-javascript/tests/wire.spec.ts @@ -0,0 +1,754 @@ +import fetchMock from '@fetch-mock/vitest' +import { beforeEach, describe, expect, it } from 'vitest' +import { z } from 'zod' +import { Client, funcs, ValidationError } from '../src/index.js' +import * as schemas from '../src/models/schemas.js' +import { + DepthLimitExceededError, + UnsafeIntegerError, + fromWire, + toWire, +} from '../src/lib/wire.js' + +beforeEach(() => { + fetchMock.mockReset() +}) + +function client() { + return new Client({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + fetch: fetchMock.fetchHandler, + }) +} + +describe('wire mapper (toWire/fromWire over real schemas)', () => { + it('preserves record keys and renames value fields (governance)', () => { + const wire = { features: { my_user_feature: { has_access: true } } } + const camel = fromWire(wire, schemas.governanceQueryResult) as any + expect(Object.keys(camel.features)[0]).toBe('my_user_feature') + expect(camel.features.my_user_feature.hasAccess).toBe(true) + + const back = toWire( + { features: { my_user_feature: { hasAccess: true } } }, + schemas.governanceQueryResult, + ) as any + expect(Object.keys(back.features)[0]).toBe('my_user_feature') + expect(back.features.my_user_feature.has_access).toBe(true) + }) + + it('preserves a record entry keyed "__proto__" as a visible own property', () => { + // A literal object expression treats `__proto__` as a prototype setter, + // not a data key — build it the way a real HTTP response body arrives + // (JSON.parse always yields `__proto__` as an own enumerable property). + const wire = JSON.parse('{"features":{"__proto__":{"has_access":true}}}') + const camel = fromWire(wire, schemas.governanceQueryResult) as any + expect(Object.keys(camel.features)).toEqual(['__proto__']) + expect(camel.features.__proto__.hasAccess).toBe(true) + expect(Object.getPrototypeOf({})).toBe(Object.prototype) + }) + + it('restores a normal prototype on record and object outputs for consumers', () => { + // The null prototype used during construction (to block __proto__/constructor + // pollution) is restored before returning, so the result behaves like a normal + // object for consumers — instanceof checks, template literals, etc. — rather + // than staying a `[Object: null prototype]` forever. + const wire = { features: { my_user_feature: { has_access: true } } } + const camel = fromWire(wire, schemas.governanceQueryResult) as any + expect(Object.getPrototypeOf(camel)).toBe(Object.prototype) + expect(Object.getPrototypeOf(camel.features)).toBe(Object.prototype) + expect(Object.getPrototypeOf(camel.features.my_user_feature)).toBe( + Object.prototype, + ) + expect(camel instanceof Object).toBe(true) + expect(() => `${camel}`).not.toThrow() + }) + + it('treats a data key of "constructor" as an unknown field, not a shape hit', () => { + const wire = JSON.parse('{"id":"x","constructor":"evil"}') + const camel = fromWire(wire, schemas.taxCode) as any + // The wire value "evil" never becomes an own `constructor` property — since + // the prototype is restored, `camel.constructor` resolves to the ordinary + // inherited `Object` constructor, exactly as it would on any plain object. + expect(camel.constructor).toBe(Object) + expect(Object.keys(camel)).not.toContain('constructor') + }) + + it('throws a typed DepthLimitExceededError instead of a raw stack overflow on a deeply nested self-referential filter', () => { + let deep: unknown = { eq: 'leaf' } + for (let i = 0; i < 1000; i++) { + deep = { and: [deep] } + } + expect(() => fromWire(deep, schemas.queryFilterString)).toThrow( + DepthLimitExceededError, + ) + }) + + it('walks a moderately nested filter without hitting the depth limit', () => { + let nested: unknown = { eq: 'leaf' } + for (let i = 0; i < 20; i++) { + nested = { and: [nested] } + } + const wire = { and: [nested] } + expect(() => fromWire(wire, schemas.queryFilterString)).not.toThrow() + }) + + it('handles a multi-word discriminator (collection_method)', () => { + const wire = { collection_method: 'charge_automatically' } + const camel = fromWire(wire, schemas.workflowPaymentSettings) as any + expect(camel.collectionMethod).toBe('charge_automatically') + + const back = toWire( + { collectionMethod: 'charge_automatically' }, + schemas.workflowPaymentSettings, + ) as any + expect(back.collection_method).toBe('charge_automatically') + }) + + it('preserves meter dimension record keys', () => { + const wire = { dimensions: { my_dim_key: { eq: 'x' } } } + const camel = fromWire(wire, schemas.meterQueryFilters) as any + expect('my_dim_key' in camel.dimensions).toBe(true) + expect(camel.dimensions.my_dim_key.eq).toBe('x') + }) + + it('terminates on a cyclic filter (and/or self-reference)', () => { + const wire = { + dimensions: { + my_dim: { eq: 'a', and: [{ eq: 'b' }, { or: [{ eq: 'c' }] }] }, + }, + } + const camel = fromWire(wire, schemas.meterQueryFilters) as any + expect(camel.dimensions.my_dim.and[1].or[0].eq).toBe('c') + }) + + it('preserves arbitrary keys inside a record of unknown (event.data)', () => { + const wire = { type: 'x', source: 's', data: { user_set_key: { a_b: 1 } } } + const camel = fromWire(wire, schemas.event) as any + expect(camel.data.user_set_key).toEqual({ a_b: 1 }) + }) + + it('walks every element of a single-or-batch (T | T[]) body', () => { + // Mirrors the ingest body shape `EventInput | EventInput[]`. A batch must + // walk each element, not pass it through untransformed (the array branch + // must resolve the array variant's element schema from the union). + const single = z.object({ eventType: z.string() }) + const body = z.union([single, z.array(single)]) + + const batch = toWire( + [{ eventType: 'a' }, { eventType: 'b' }], + body, + ) as any[] + expect(batch).toHaveLength(2) + for (const e of batch) { + expect('event_type' in e).toBe(true) + expect('eventType' in e).toBe(false) + } + + const one = toWire({ eventType: 'a' }, body) as any + expect(one.event_type).toBe('a') + }) +}) + +describe('end-to-end wire mapping through a func', () => { + it('sends a snake body and returns a camelCase response (createMeter)', async () => { + let sentBody: any + fetchMock.route('*', async ({ options }) => { + sentBody = JSON.parse(options!.body as string) + return { + body: { + id: '01ARZ3NDEKTSV4RRFFQ69G5FAV', + name: 'API calls', + key: 'api_calls', + aggregation: 'count', + event_type: 'api-request', + created_at: '2024-01-01T00:00:00Z', + updated_at: '2024-01-01T00:00:00Z', + }, + headers: { 'Content-Type': 'application/json' }, + } + }) + + const result = await funcs.createMeter(client(), { + name: 'API calls', + key: 'api_calls', + aggregation: 'count', + eventType: 'api-request', + valueProperty: '$.value', + }) + + // request body is snake on the wire + expect(sentBody.event_type).toBe('api-request') + expect(sentBody.value_property).toBe('$.value') + expect('eventType' in sentBody).toBe(false) + + // response is camelCase, with datetimes revived into Dates + expect(result.ok).toBe(true) + expect(result.value).toMatchObject({ + eventType: 'api-request', + createdAt: new Date('2024-01-01T00:00:00Z'), + }) + }) +}) + +describe('date mapping at the wire boundary', () => { + const at = new Date('2024-05-01T10:20:30.000Z') + const iso = '2024-05-01T10:20:30.000Z' + + it('serializes meter query from/to Dates to RFC 3339 strings (toWire)', () => { + const wire = toWire({ from: at, to: at }, schemas.meterQueryRequest) as any + expect(wire.from).toBe(iso) + expect(wire.to).toBe(iso) + }) + + it('revives meter query row from/to into Dates (fromWire)', () => { + const row = fromWire( + { from: iso, to: iso, value: 1 }, + schemas.meterQueryRow, + ) + expect(row.from).toEqual(at) + expect(row.to).toEqual(at) + expect(row.value).toBe(1) + }) + + it('revives event.time behind its DateTime-or-null union, keeps null', () => { + const wire = { id: 'e1', time: iso } + const camel = fromWire(wire, schemas.event) + expect(camel.time).toEqual(at) + + const nullTime = fromWire({ id: 'e1', time: null }, schemas.event) + expect(nullTime.time).toBeNull() + }) + + it('keeps an enum literal a string, revives a date string (subscriptionEditTiming)', () => { + expect(fromWire('immediate', schemas.subscriptionEditTiming)).toBe( + 'immediate', + ) + expect(fromWire(iso, schemas.subscriptionEditTiming)).toEqual(at) + expect(toWire('immediate', schemas.subscriptionEditTiming)).toBe( + 'immediate', + ) + expect(toWire(at, schemas.subscriptionEditTiming) as unknown).toBe(iso) + }) + + it('maps the dateTimeFieldFilter shorthand and operand forms (toWire)', () => { + expect(toWire(at, schemas.dateTimeFieldFilter) as unknown).toBe(iso) + const wire = toWire({ gte: at, lt: at }, schemas.dateTimeFieldFilter) as any + expect(wire.gte).toBe(iso) + expect(wire.lt).toBe(iso) + }) + + it('walks record and array values that are date-typed (hand-built)', () => { + const rec = z.record(z.string(), z.date()) + const out = toWire({ user_key: at }, rec) as any + expect(out.user_key).toBe(iso) + const back = fromWire({ user_key: iso }, rec) as any + expect(back.user_key).toEqual(at) + + const arr = z.array(z.date()) + expect(toWire([at], arr)).toEqual([iso]) + expect(fromWire([iso], arr)).toEqual([at]) + }) + + it('fails open on strings a date variant cannot solely claim', () => { + // A competing plain-string variant keeps even a date-looking string a string. + const stringOrDate = z.union([z.string(), z.date()]) + expect(fromWire(iso, stringOrDate)).toBe(iso) + // A non-date string at a date-or-null union stays untouched. + expect(fromWire('not-a-date', z.union([z.date(), z.null()]))).toBe( + 'not-a-date', + ) + // A matching string literal sibling claims its value; anything else revives. + const literalOrDate = z.union([z.literal('now'), z.date()]) + expect(fromWire('now', literalOrDate)).toBe('now') + expect(fromWire(iso, literalOrDate)).toEqual(at) + }) + + it('lists metering events: filter Dates hit the query, event times revive (listMeteringEvents)', async () => { + fetchMock.route('*', { + body: { + data: [ + { + event: { + id: 'e-1', + source: 'svc', + specversion: '1.0', + type: 'api-request', + subject: 'cust-1', + time: iso, + }, + ingested_at: '2024-05-01T10:20:31.000Z', + stored_at: '2024-05-01T10:20:32.000Z', + }, + ], + meta: {}, + }, + headers: { 'Content-Type': 'application/json' }, + }) + + const result = await funcs.listMeteringEvents(client(), { + filter: { time: { gte: at, lt: '2024-06-01T00:00:00Z' } }, + }) + + // query leg: a Date operand serializes to RFC 3339, a string stays verbatim + const q = new URL(fetchMock.callHistory.lastCall()!.url).searchParams + expect(q.get('filter[time][gte]')).toBe(iso) + expect(q.get('filter[time][lt]')).toBe('2024-06-01T00:00:00Z') + + // response leg: event.time (behind its DateTime-or-null union) and the + // ingestion timestamps come back as real Dates + expect(result.ok).toBe(true) + const ev = result.value!.data[0] + expect(ev.event.time).toBeInstanceOf(Date) + expect(ev.event.time).toEqual(at) + expect(ev.ingestedAt).toEqual(new Date('2024-05-01T10:20:31.000Z')) + expect(ev.storedAt).toEqual(new Date('2024-05-01T10:20:32.000Z')) + }) + + it('accepts RFC 3339 strings for request dates and sends them verbatim', async () => { + // Request types are AcceptDateStrings-widened: `from` as a string compiles, + // and the mapper passes it through untouched (no re-parse, no added millis). + let sentBody: any + fetchMock.route('*', async ({ options }) => { + sentBody = JSON.parse(options!.body as string) + return { + body: { data: [] }, + headers: { 'Content-Type': 'application/json' }, + } + }) + const result = await funcs.queryMeter(client(), { + meterId: 'm', + body: { from: '2024-05-01T10:20:30Z', to: at }, + }) + expect(result.ok).toBe(true) + expect(sentBody.from).toBe('2024-05-01T10:20:30Z') + expect(sentBody.to).toBe(iso) + }) + + it('accepts a string event time under validate (wire schema checks the string)', async () => { + fetchMock.route('*', 204) + const validating = new Client({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + fetch: fetchMock.fetchHandler, + validate: true, + }) + const result = await funcs.ingestMeteringEvents(validating, { + id: 'e-2', + source: 'svc', + specversion: '1.0', + type: 'api-request', + subject: 'cust-1', + time: '2024-05-01T10:20:30Z', + }) + expect(result.ok).toBe(true) + }) + + it('ingests an event with a Date time: RFC 3339 on the wire, passes validate', async () => { + let sentBody: any + fetchMock.route('*', async ({ options }) => { + sentBody = JSON.parse(options!.body as string) + return 204 + }) + const validating = new Client({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + fetch: fetchMock.fetchHandler, + validate: true, + }) + const result = await funcs.ingestMeteringEvents(validating, { + id: 'e-1', + source: 'svc', + specversion: '1.0', + type: 'api-request', + subject: 'cust-1', + time: at, + }) + expect(result.ok).toBe(true) + expect(sentBody.time).toBe(iso) + }) +}) + +describe('wire walker edge cases', () => { + it('passes a scalar/null/array-of-scalars through unchanged', () => { + expect(toWire(5, z.number())).toBe(5) + expect(toWire(null, z.string().nullable())).toBe(null) + expect(toWire([1, 2], z.array(z.number()))).toEqual([1, 2]) + }) + + it('recurses a record whose value is an array or union of models', () => { + const arrModel = z.record( + z.string(), + z.array(z.object({ fooBar: z.string() })), + ) + expect(toWire({ user_k: [{ fooBar: 'x' }] }, arrModel)).toEqual({ + user_k: [{ foo_bar: 'x' }], + }) + + const unionModel = z.record( + z.string(), + z.union([ + z.object({ fooBar: z.string() }), + z.object({ bazQux: z.number() }), + ]), + ) + expect(toWire({ user_k: { fooBar: 'x' } }, unionModel)).toEqual({ + user_k: { foo_bar: 'x' }, + }) + }) + + it('leaves a record of scalars untouched (keys and values)', () => { + const scalarMap = z.record(z.string(), z.string()) + expect(toWire({ a_b: 'v', cD: 'w' }, scalarMap)).toEqual({ + a_b: 'v', + cD: 'w', + }) + }) + + it('renames the object variant of a scalar-or-object union', () => { + // The realistic non-discriminated shape (a filter field: string | { op }). + // The codegen gate guarantees at most one object variant, so it is picked + // unambiguously; scalar data flows through the scalar branch unchanged. + const union = z.union([z.string(), z.object({ fooBar: z.string() })]) + expect(toWire({ fooBar: 'x' }, union)).toEqual({ foo_bar: 'x' }) + expect(toWire('plain', union)).toBe('plain') + }) + + it('fails closed on a discriminated union with an unknown discriminator value', () => { + const union = z.discriminatedUnion('kind', [ + z.object({ kind: z.literal('a'), fooBar: z.string() }), + z.object({ kind: z.literal('b'), bazQux: z.number() }), + ]) + // no variant has kind === 'z' → returned unchanged + expect(toWire({ kind: 'z', fooBar: 'x' }, union)).toEqual({ + kind: 'z', + fooBar: 'x', + }) + }) + + it('reuses the memoized variant map across calls on the same union', () => { + const union = z.discriminatedUnion('kind', [ + z.object({ kind: z.literal('a'), fooBar: z.string() }), + z.object({ kind: z.literal('b'), bazQux: z.number() }), + ]) + // First call builds the map; second hits the cache. Both dispatch correctly. + expect(toWire({ kind: 'a', fooBar: 'x' }, union)).toEqual({ + kind: 'a', + foo_bar: 'x', + }) + expect(toWire({ kind: 'b', bazQux: 2 }, union)).toEqual({ + kind: 'b', + baz_qux: 2, + }) + }) + + it('walks array data against a union schema with an array variant', () => { + // exercises arrayElement resolving the array option of a union + const union = z.union([ + z.object({ fooBar: z.string() }), + z.array(z.object({ fooBar: z.string() })), + ]) + expect(toWire([{ fooBar: 'x' }], union)).toEqual([{ foo_bar: 'x' }]) + }) + + it('passes array data through when the union has no array variant', () => { + // arrayElement returns undefined → elements walked with no schema → unchanged + const union = z.union([ + z.object({ fooBar: z.string() }), + z.object({ bazQux: z.number() }), + ]) + expect(toWire([{ fooBar: 'x' }], union)).toEqual([{ fooBar: 'x' }]) + }) + + it('keeps a record whose value schema is an unknown/any (event.data-like)', () => { + const rec = z.record(z.string(), z.unknown()) + expect(toWire({ user_k: { aB: 1 } }, rec)).toEqual({ user_k: { aB: 1 } }) + }) +}) + +describe('optional schema validation (validate option)', () => { + const goodMeter = { + id: '01ARZ3NDEKTSV4RRFFQ69G5FAV', + name: 'API calls', + key: 'api_calls', + aggregation: 'count', + event_type: 'api-request', + created_at: '2024-01-01T00:00:00Z', + updated_at: '2024-01-01T00:00:00Z', + } + const goodCreate = { + name: 'API calls', + key: 'api_calls', + aggregation: 'count' as const, + eventType: 'api-request', + valueProperty: '$.value', + } + + function validatingClient() { + return new Client({ + baseUrl: 'https://eu.api.konghq.com/v3', + apiKey: 'k', + fetch: fetchMock.fetchHandler, + validate: true, + }) + } + + it('passes a valid request and response when validate is on', async () => { + fetchMock.route('*', { + body: goodMeter, + headers: { 'Content-Type': 'application/json' }, + }) + const result = await funcs.createMeter(validatingClient(), goodCreate) + expect(result.ok).toBe(true) + expect(result.value).toMatchObject({ eventType: 'api-request' }) + }) + + it('rejects a request body that fails its schema', async () => { + fetchMock.route('*', { + body: goodMeter, + headers: { 'Content-Type': 'application/json' }, + }) + // name is required; omit it + const result = await funcs.createMeter(validatingClient(), { + ...goodCreate, + name: undefined as unknown as string, + }) + expect(result.ok).toBe(false) + expect(result.error).toBeInstanceOf(ValidationError) + }) + + it('rejects an enum-drift response (the reason validation is off by default)', async () => { + fetchMock.route('*', { + // server sends an aggregation value this SDK version does not know + body: { ...goodMeter, aggregation: 'p99' }, + headers: { 'Content-Type': 'application/json' }, + }) + const result = await funcs.getMeter(validatingClient(), { meterId: 'm' }) + expect(result.ok).toBe(false) + expect(result.error).toBeInstanceOf(ValidationError) + }) + + it('does NOT reject the same enum-drift response when validate is off', async () => { + fetchMock.route('*', { + body: { ...goodMeter, aggregation: 'p99' }, + headers: { 'Content-Type': 'application/json' }, + }) + const result = await funcs.getMeter(client(), { meterId: 'm' }) + expect(result.ok).toBe(true) + }) + + it('rejects a bad body on a void/no-JSON-response op as Result.error, not a throw', async () => { + // ingestMeteringEvents has a request body but a void response; body validation + // must run inside request() so a failure becomes Result.error here too. + fetchMock.route('*', { status: 204 }) + const result = await funcs.ingestMeteringEvents( + validatingClient(), + {} as never, + ) + expect(result.ok).toBe(false) + expect(result.error).toBeInstanceOf(ValidationError) + }) + + it('rejects a bad query object before the request is sent, same as a bad body', async () => { + // listMeters has no request body, only query params; the wire query object + // (built by toWire) must still be checked against its …QueryParamsWire schema + // when validate is on, the same guarantee bodies already had. + fetchMock.route('*', { + body: { + data: [goodMeter], + meta: { page: { number: 1, size: 10, total: 1 } }, + }, + headers: { 'Content-Type': 'application/json' }, + }) + const result = await funcs.listMeters(validatingClient(), { + page: { size: Number.NaN }, + }) + expect(result.ok).toBe(false) + expect(result.error).toBeInstanceOf(ValidationError) + }) + + it('passes a valid query object when validate is on', async () => { + fetchMock.route('*', { + body: { + data: [goodMeter], + meta: { page: { number: 1, size: 10, total: 1 } }, + }, + headers: { 'Content-Type': 'application/json' }, + }) + const result = await funcs.listMeters(validatingClient(), { + page: { size: 10, number: 1 }, + }) + expect(result.ok).toBe(true) + }) +}) + +describe('generated wire schemas (snake_case, strict)', () => { + const ok = (s: { safeParse(v: unknown): { success: boolean } }, v: unknown) => + s.safeParse(v).success + + const meterWireData = { + id: '01ARZ3NDEKTSV4RRFFQ69G5FAV', + name: 'n', + key: 'k', + aggregation: 'count', + event_type: 'e', + created_at: '2024-01-01T00:00:00Z', + updated_at: '2024-01-01T00:00:00Z', + } + + it('a closed model wire schema is snake-keyed and strict', () => { + expect(ok(schemas.meterWire, meterWireData)).toBe(true) + // leaked camelCase key rejected + expect(ok(schemas.meterWire, { ...meterWireData, eventType: 'x' })).toBe( + false, + ) + // unknown/extra wire key rejected + expect(ok(schemas.meterWire, { ...meterWireData, new_field: 1 })).toBe( + false, + ) + }) + + it('a record value model wire schema preserves user keys, snakeifies fields', () => { + expect(ok(schemas.governanceFeatureAccessWire, { has_access: true })).toBe( + true, + ) + expect(ok(schemas.governanceFeatureAccessWire, { hasAccess: true })).toBe( + false, + ) + }) + + it('a discriminated union wire schema uses the snake discriminator', () => { + expect( + ok(schemas.workflowPaymentSettingsWire, { + collection_method: 'charge_automatically', + }), + ).toBe(true) + }) + + it('an open (record-spread) wire schema accepts extra keys (not strict)', () => { + // baseErrorWire is emitsAsIntersection — strict would defeat the record arm + // that exists to accept additional members. Must stay permissive. + expect( + ok(schemas.baseErrorWire, { + type: 't', + status: 400, + title: 'x', + detail: 'd', + instance: '/i', + anything_extra: 1, + }), + ).toBe(true) + }) + + it('a cyclic filter wire schema terminates and accepts nested data', () => { + expect( + ok(schemas.meterQueryFiltersWire, { + dimensions: { my_dim: { eq: 'a', and: [{ eq: 'b' }] } }, + }), + ).toBe(true) + }) +}) + +describe('required-with-default materialization (toWire)', () => { + const minimalEvent = { + id: 'e1', + source: 'my-app', + type: 'usage', + subject: 'customer-1', + } + + it('fills an omitted required-with-default field (event.specversion)', () => { + const wire = toWire(minimalEvent, schemas.event) as Record + expect(wire.specversion).toBe('1.0') + }) + + it('keeps a caller-provided value over the default', () => { + const wire = toWire( + { ...minimalEvent, specversion: '1.1' }, + schemas.event, + ) as Record + expect(wire.specversion).toBe('1.1') + }) + + it('replaces an explicit undefined with the default', () => { + const wire = toWire( + { ...minimalEvent, specversion: undefined }, + schemas.event, + ) as Record + expect(wire.specversion).toBe('1.0') + }) + + it('materializes into every element of a batch ingest body', () => { + const wire = toWire( + [minimalEvent, { ...minimalEvent, id: 'e2' }], + schemas.ingestMeteringEventsBody, + ) as Array> + expect(wire.map((e) => e.specversion)).toEqual(['1.0', '1.0']) + }) + + it('does not materialize spec-optional defaults (sortQuery.order)', () => { + // `.optional().default()` means the default is the server's to apply; + // writing it client-side would overwrite server state on updates. + const wire = toWire({ by: 'created_at' }, schemas.sortQuery) as Record< + string, + unknown + > + expect('order' in wire).toBe(false) + }) + + it('never fabricates fields on responses (fromWire)', () => { + const camel = fromWire(minimalEvent, schemas.event) as Record< + string, + unknown + > + expect('specversion' in camel).toBe(false) + }) + + it('sends specversion on the wire for the minimal documented ingest call', async () => { + fetchMock.route('*', 204) + const result = await funcs.ingestMeteringEvents(client(), minimalEvent) + expect(result.ok).toBe(true) + const body = JSON.parse( + fetchMock.callHistory.lastCall()!.options.body as string, + ) as Record + expect(body.specversion).toBe('1.0') + }) +}) + +describe('bigint (int64) mapping at the wire boundary', () => { + // Exercised against a hand-built schema (rather than a real int64 field like + // the checkout session's expiresAt) so this coverage survives future field + // changes in the spec. + const schema = z.object({ n: z.coerce.bigint() }) + + it('maps a bigint field to a JSON number (toWire)', () => { + const wire = toWire({ n: 1735689600n }, schema) as Record + expect(wire.n).toBe(1735689600) + // The whole point: the wire body must survive JSON serialization. + expect(() => JSON.stringify(wire)).not.toThrow() + }) + + it('throws a typed UnsafeIntegerError beyond JSON-safe integer range', () => { + for (const n of [ + BigInt(Number.MAX_SAFE_INTEGER) + 1n, + -BigInt(Number.MAX_SAFE_INTEGER) - 1n, + ]) { + expect(() => toWire({ n }, schema)).toThrow(UnsafeIntegerError) + } + }) + + it('revives a wire number into bigint at a bigint-typed node (fromWire)', () => { + const camel = fromWire({ n: 1735689600 }, schema) as Record + expect(camel.n).toBe(1735689600n) + }) + + it('passes non-integer wire values through unconverted at a bigint node', () => { + const camel = fromWire({ n: 1.5 }, schema) as Record + expect(camel.n).toBe(1.5) + }) + + it('passes a plain number through at a bigint node (untyped toWire caller)', () => { + const wire = toWire({ n: 1735689600 }, schema) as Record + expect(wire.n).toBe(1735689600) + }) +}) diff --git a/api/spec/packages/aip-client-javascript/tsconfig.json b/api/spec/packages/aip-client-javascript/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..adeb519165cd0b90ebe8c3e0d6c5252252ffea33 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "target": "esnext", + "module": "nodenext", + "strict": true, + "declaration": true, + "outDir": "dist" + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/api/spec/packages/aip-client-javascript/tsconfig.tests.json b/api/spec/packages/aip-client-javascript/tsconfig.tests.json new file mode 100644 index 0000000000000000000000000000000000000000..192fd9441278c642d1406423766daa27724dedc5 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/tsconfig.tests.json @@ -0,0 +1,17 @@ +// Type-checks tests/ (the build tsconfig only includes src/, so without this +// the spec files are never type-checked — vitest strips types without checking +// them). Used by the `typecheck` script; never emits. +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": true, + "declaration": false, + "declarationMap": false, + "sourceMap": false, + // @fetch-mock/vitest's own d.ts imports the undeclared jest 'expect' + // package; skip dependency declaration files (our .ts sources are still + // fully checked, and src/ is separately checked without this flag). + "skipLibCheck": true + }, + "include": ["src/**/*.ts", "tests/**/*.ts"] +} diff --git a/api/spec/packages/aip-client-javascript/vitest.config.ts b/api/spec/packages/aip-client-javascript/vitest.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..5fa61c13c08ec9eb6a346c9690c658b32f9bf772 --- /dev/null +++ b/api/spec/packages/aip-client-javascript/vitest.config.ts @@ -0,0 +1,27 @@ +import { defineConfig } from 'vitest/config' + +// The boundary mapper (src/lib/wire.ts) and the pagination iterators +// (src/lib/paginate.ts) are the hand-written runtime modules with no +// compile-time guard, so their behavior is covered entirely by tests. Hold +// them at full statement/line/function coverage. The branch threshold is +// below 100 because wire.ts's residual uncovered branches are defensive +// nullish-coalescing arms (`?? []`, `?? {}`) guarding zod internals that the +// preceding type-guard already makes non-null — unreachable with any real +// schema, so not worth contriving inputs for. paginate.ts itself has no such +// residual: tests/paginate.spec.ts exercises every stop condition (empty +// page, short page, exact-total page, absent next cursor) and both +// PaginationLimitExceededError throws. +export default defineConfig({ + test: { + coverage: { + provider: 'v8', + include: ['src/lib/wire.ts', 'src/lib/paginate.ts'], + thresholds: { + statements: 100, + functions: 100, + lines: 100, + branches: 85, + }, + }, + }, +}) diff --git a/api/spec/packages/aip/src/billing/totals.tsp b/api/spec/packages/aip/src/billing/totals.tsp new file mode 100644 index 0000000000000000000000000000000000000000..44e32d35519dba96535668edefe6b1e4c2afa4f9 --- /dev/null +++ b/api/spec/packages/aip/src/billing/totals.tsp @@ -0,0 +1,66 @@ +import "../shared/index.tsp"; + +namespace Billing; + +/** + * Totals contains the summaries of all calculations for a billing resource. + */ +#suppress "@openmeter/api-spec-aip/repeated-prefix-grouping" "taxes_* totals are intentionally kept flat for API compatibility" +@friendlyName("BillingTotals") +model BillingTotals { + /** + * The total value of the resource before taxes, discounts and commitments. + */ + @visibility(Lifecycle.Read) + @summary("Amount") + amount: Shared.Numeric; + + /** + * The total tax amount applied to the resource. + */ + @visibility(Lifecycle.Read) + @summary("Taxes total") + taxes_total: Shared.Numeric; + + /** + * The total tax amount already included in the resource amount. + */ + @visibility(Lifecycle.Read) + @summary("Inclusive taxes total") + taxes_inclusive_total: Shared.Numeric; + + /** + * The total tax amount added on top of the resource amount. + */ + @visibility(Lifecycle.Read) + @summary("Exclusive taxes total") + taxes_exclusive_total: Shared.Numeric; + + /** + * The total amount contributed by additional charges. + */ + @visibility(Lifecycle.Read) + @summary("Charges total") + charges_total: Shared.Numeric; + + /** + * The total amount deducted through discounts. + */ + @visibility(Lifecycle.Read) + @summary("Discounts total") + discounts_total: Shared.Numeric; + + /** + * The total amount deducted through credits before taxes are applied. + */ + @visibility(Lifecycle.Read) + @summary("Credits total") + credits_total: Shared.Numeric; + + /** + * The final total value of the resource after taxes, discounts and commitments. + */ + @visibility(Lifecycle.Read) + @summary("Total") + total: Shared.Numeric; +} diff --git a/api/spec/packages/aip/src/common/error.tsp b/api/spec/packages/aip/src/common/error.tsp new file mode 100644 index 0000000000000000000000000000000000000000..308dff7cce1934c4372c9253ec47d57a172b5d1c --- /dev/null +++ b/api/spec/packages/aip/src/common/error.tsp @@ -0,0 +1,456 @@ +import "@typespec/http"; +import "@typespec/openapi"; +import "@typespec/openapi3"; + +using TypeSpec.OpenAPI; +using TypeSpec.Http; + +namespace Common; + +/** + * Bad Request. + */ +#suppress "@openmeter/api-spec-aip/composition-over-inheritance" "inheritance" +@error +@useRef("../../../../common/definitions/errors.yaml#/components/responses/BadRequest") +@friendlyName("BadRequest") +model BadRequest extends BaseError { + @statusCode _: 400; + + /** + * The list of parameters that failed validation. + */ + invalid_parameters: InvalidParameters; +} + +/** + * Unauthorized. + */ +#suppress "@openmeter/api-spec-aip/composition-over-inheritance" "inheritance" +@error +@useRef("../../../../common/definitions/errors.yaml#/components/responses/Unauthorized") +@friendlyName("Unauthorized") +model Unauthorized extends BaseError { + @statusCode _: 401; +} + +/** + * Forbidden. + */ +#suppress "@openmeter/api-spec-aip/composition-over-inheritance" "inheritance" +@error +@useRef("../../../../common/definitions/errors.yaml#/components/responses/Forbidden") +@friendlyName("Forbidden") +model Forbidden extends BaseError { + @statusCode _: 403; +} + +/** + * Not Found. + */ +#suppress "@openmeter/api-spec-aip/composition-over-inheritance" "inheritance" +@error +@useRef("../../../../common/definitions/errors.yaml#/components/responses/NotFound") +@friendlyName("NotFound") +model NotFound extends BaseError { + @statusCode _: 404; +} + +/** + * Conflict. + */ +#suppress "@openmeter/api-spec-aip/composition-over-inheritance" "inheritance" +@error +@useRef("../../../../common/definitions/errors.yaml#/components/responses/Conflict") +@friendlyName("Conflict") +model Conflict extends BaseError { + @statusCode _: 409; +} + +/** + * Gone. + */ +#suppress "@openmeter/api-spec-aip/composition-over-inheritance" "inheritance" +@error +@useRef("../../../../common/definitions/errors.yaml#/components/responses/Gone") +@friendlyName("Gone") +model Gone extends BaseError { + @statusCode _: 410; +} + +/** + * Payload Too Large. + */ +#suppress "@openmeter/api-spec-aip/composition-over-inheritance" "inheritance" +@error +@friendlyName("PayloadTooLarge") +@useRef("../../../../common/definitions/errors.yaml#/components/responses/PayloadTooLarge") +@friendlyName("PayloadTooLarge") +model PayloadTooLarge extends BaseError { + @statusCode _: 413; +} + +/** + * Unsupported Media Type. + */ +#suppress "@openmeter/api-spec-aip/composition-over-inheritance" "inheritance" +@error +@friendlyName("UnsupportedMediaType") +@useRef("../../../../common/definitions/errors.yaml#/components/responses/UnsupportedMediaType") +@friendlyName("UnsupportedMediaType") +model UnsupportedMediaType extends BaseError { + @statusCode _: 415; +} + +/** + * Unprocessable Content. + */ +#suppress "@openmeter/api-spec-aip/composition-over-inheritance" "inheritance" +@error +@friendlyName("UnprocessableContent") +@useRef("../../../../common/definitions/errors.yaml#/components/responses/UnprocessableContent") +@friendlyName("UnprocessableContent") +model UnprocessableContent extends BaseError { + @statusCode _: 422; +} + +/** + * Too Many Requests. + */ +#suppress "@openmeter/api-spec-aip/composition-over-inheritance" "inheritance" +@error +@friendlyName("TooManyRequests") +@useRef("../../../../common/definitions/errors.yaml#/components/responses/TooManyRequests") +@friendlyName("TooManyRequests") +model TooManyRequests extends BaseError { + @statusCode _: 429; +} + +/** + * Internal Server Error. + */ +#suppress "@openmeter/api-spec-aip/composition-over-inheritance" "inheritance" +@error +@useRef("../../../../common/definitions/errors.yaml#/components/responses/Internal") +@friendlyName("Internal") +model Internal extends BaseError { + @statusCode _: 500; +} + +/** + * Not Implemented. + */ +#suppress "@openmeter/api-spec-aip/composition-over-inheritance" "inheritance" +@error +@friendlyName("NotImplemented") +@useRef("../../../../common/definitions/errors.yaml#/components/responses/NotImplemented") +@friendlyName("NotImplemented") +model NotImplemented extends BaseError { + @statusCode _: 501; +} + +/** + * Not Available. + */ +#suppress "@openmeter/api-spec-aip/composition-over-inheritance" "inheritance" +@error +@useRef("../../../../common/definitions/errors.yaml#/components/responses/NotAvailable") +@friendlyName("NotAvailable") +model NotAvailable extends BaseError { + @statusCode _: 503; +} + +alias ErrorResponses = BadRequest | Unauthorized | Forbidden; + +/** + * Standard error response. + */ +@error +@friendlyName("BaseError") +model BaseError { + @header contentType: "application/problem+json"; + + /** + * Type contains a URI that identifies the problem type. + */ + @example("about:blank") + @visibility(Lifecycle.Read) + type: string = "about:blank"; + + /** + * The HTTP status code generated by the origin server for this occurrence of the + * problem. + */ + @example(400) + @visibility(Lifecycle.Read) + status: integer; + + /** + * A a short, human-readable summary of the problem type. + */ + @example("Bad Request") + @visibility(Lifecycle.Read) + title: string; + + /** + * A human-readable explanation specific to this occurrence of the problem. + */ + @example("The request body must be a JSON object.") + detail: string; + + /** + * A URI reference that identifies the specific occurrence of the problem. + */ + @visibility(Lifecycle.Read) + instance: string; + + /** + * Additional properties specific to the problem type may be present. + */ + ...Record; +} + +/** + * The list of parameters that failed validation. + */ +@friendlyName("InvalidParameters") +@minItems(1) +model InvalidParameters is InvalidParameter[]; + +/** + * A parameter that failed validation. + */ +@friendlyName("InvalidParameter") +union InvalidParameter { + standard: InvalidParameterStandard, + minimumLength: InvalidParameterMinimumLength, + maximumLength: InvalidParameterMaximumLength, + choice: InvalidParameterChoiceItem, + dependent: InvalidParameterDependentItem, +} + +/** + * The validation rule that a parameter failed. + */ +@friendlyName("InvalidRules") +enum InvalidRules { + Required: "required", + IsArray: "is_array", + IsBase64: "is_base64", + IsBoolean: "is_boolean", + IsDateTime: "is_date_time", + IsInteger: "is_integer", + IsNull: "is_null", + IsNumber: "is_number", + IsObject: "is_object", + IsString: "is_string", + IsUuid: "is_uuid", + IsFqdn: "is_fqdn", + IsArn: "is_arn", + UnknownProperty: "unknown_property", + MissingReference: "missing_reference", + IsLabel: "is_label", + MatchesRegex: "matches_regex", + Invalid: "invalid", + IsSupportedNetworkAvailabilityZoneList: "is_supported_network_availability_zone_list", + IsSupportedNetworkCidrBlock: "is_supported_network_cidr_block", + IsSupportedProviderRegion: "is_supported_provider_region", + Type: "type", +} + +/** + * A parameter that failed a standard validation rule. + */ +@friendlyName("InvalidParameterStandard") +model InvalidParameterStandard { + /** + * The name of the field that failed validation. + */ + @visibility(Lifecycle.Read) + field: string; + + /** + * The validation rule that was violated. + */ + rule?: InvalidRules; + + /** + * The part of the request the field came from (e.g. `body`, `query`). + */ + source?: string; + + /** + * A human readable explanation of why the field failed validation. + */ + reason: string; +} + +/** + * A parameter that failed a minimum-length (or minimum-value) validation rule. + */ +@friendlyName("InvalidParameterMinimumLength") +model InvalidParameterMinimumLength { + /** + * The name of the field that failed validation. + */ + field: string; + + /** + * The minimum validation rule that was violated. + */ + rule: InvalidParameterMinimumRule; + + /** + * The minimum allowed value or length. + */ + minimum: integer; + + /** + * The part of the request the field came from (e.g. `body`, `query`). + */ + source?: string; + + /** + * A human readable explanation of why the field failed validation. + */ + reason: string; +} + +/** + * Minimum-length (or minimum-value) validation rules. + */ +@friendlyName("InvalidParameterMinimumRule") +enum InvalidParameterMinimumRule { + MinLength: "min_length", + MinDigits: "min_digits", + MinLowercase: "min_lowercase", + MinUppercase: "min_uppercase", + MinSymbols: "min_symbols", + MinItems: "min_items", + Min: "min", +} + +/** + * A parameter that failed a maximum-length (or maximum-value) validation rule. + */ +@friendlyName("InvalidParameterMaximumLength") +model InvalidParameterMaximumLength { + /** + * The name of the field that failed validation. + */ + @visibility(Lifecycle.Read) + field: string; + + /** + * The maximum validation rule that was violated. + */ + rule: InvalidParameterMaximumRule; + + /** + * The maximum allowed value or length. + */ + maximum: integer; + + /** + * The part of the request the field came from (e.g. `body`, `query`). + */ + source?: string; + + /** + * A human readable explanation of why the field failed validation. + */ + @visibility(Lifecycle.Read) + reason: string; +} + +/** + * Maximum-length (or maximum-value) validation rules. + */ +@friendlyName("InvalidParameterMaximumRule") +enum InvalidParameterMaximumRule { + MaxLength: "max_length", + MaxItems: "max_items", + Max: "max", +} + +/** + * A parameter whose value was not one of the allowed choices. + */ +@friendlyName("InvalidParameterChoiceItem") +model InvalidParameterChoiceItem { + /** + * The name of the field that failed validation. + */ + @visibility(Lifecycle.Read) + field: string; + + /** + * The enum validation rule that was violated. + */ + rule: InvalidParameterChoiceRule; + + /** + * A human readable explanation of why the field failed validation. + */ + @visibility(Lifecycle.Read) + reason: string; + + /** + * The allowed choices for the field. + */ + @visibility(Lifecycle.Read) + @minItems(1) + choices: unknown[]; + + /** + * The part of the request the field came from (e.g. `body`, `query`). + */ + source?: string; +} + +/** + * The enum validation rule. + */ +@friendlyName("InvalidParameterChoiceRule") +enum InvalidParameterChoiceRule { + Enum: "enum", +} + +/** + * A parameter that failed a dependent-fields validation rule. + */ +@friendlyName("InvalidParameterDependentItem") +model InvalidParameterDependentItem { + /** + * The name of the field that failed validation. + */ + field: string; + + /** + * The dependent-fields validation rule that was violated. + */ + rule: InvalidParameterDependentRule; + + /** + * A human readable explanation of why the field failed validation. + */ + reason: string; + + /** + * The fields that this field depends on. + */ + dependents: unknown[]; + + /** + * The part of the request the field came from (e.g. `body`, `query`). + */ + source?: string; +} + +/** + * The dependent-fields validation rule. + */ +@friendlyName("InvalidParameterDependentRule") +enum InvalidParameterDependentRule { + DependentFields: "dependent_fields", +} diff --git a/api/spec/packages/aip/src/common/pagination.tsp b/api/spec/packages/aip/src/common/pagination.tsp new file mode 100644 index 0000000000000000000000000000000000000000..2c1276664cb8f0762c34172e21b394cd52ad174f --- /dev/null +++ b/api/spec/packages/aip/src/common/pagination.tsp @@ -0,0 +1,145 @@ +import "@typespec/http"; +import "@typespec/openapi"; +import "@typespec/openapi3"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Common; + +/** + * Determines which page of the collection to retrieve. + */ +@friendlyName("CursorPaginationQueryPage") +model CursorPaginationQueryPage { + /** + * The number of items to include per page. + */ + size?: integer; + + /** + * Request the next page of data, starting with the item after this parameter. + */ + after?: string; + + /** + * Request the previous page of data, starting with the item before this parameter. + */ + before?: string; +} + +/** + * Cursor page query. + */ +@friendlyName("CursorPaginationQuery") +model CursorPaginationQuery { + #suppress "@openmeter/api-spec-aip/doc-decorator" "-" + @query(#{ explode: true, style: "deepObject" }) + page?: CursorPaginationQueryPage; +} + +/** + * Page pagination query. + */ +@friendlyName("PagePaginationQuery") +model PagePaginationQuery { + /** + * Determines which page of the collection to retrieve. + */ + @query(#{ explode: true, style: "deepObject" }) + page?: { + /** + * The number of items to include per page. + */ + size?: integer; + + /** + * The page number. + */ + number?: integer; + }; +} + +/** + * Cursor pagination metadata. + */ +@friendlyName("CursorMetaPage") +@useRef("../../../../common/definitions/metadatas.yaml#/components/schemas/CursorMetaPage") +model CursorMetaPage { + /** + * URI to the first page. + */ + @format("uri") + first?: string; + + /** + * URI to the last page. + */ + @format("uri") + last?: string; + + /** + * URI to the next page. + */ + #suppress "@openmeter/api-spec-aip/no-nullable" "the server returns null when there is no next page" + @format("uri") + next: string | null; + + /** + * URI to the previous page. + */ + #suppress "@openmeter/api-spec-aip/no-nullable" "the server returns null when there is no previous page" + @format("uri") + previous: string | null; + + /** + * Requested page size. + */ + size: integer; +} + +/** + * Cursor pagination metadata. + */ +@friendlyName("CursorMeta") +@useRef("../../../../common/definitions/metadatas.yaml#/components/schemas/CursorMeta") +model CursorMeta { + /** + * Page metadata. + */ + page: CursorMetaPage; +} + +/** + * Pagination metadata. + */ +@friendlyName("PaginatedMeta") +@useRef("../../../../common/definitions/metadatas.yaml#/components/schemas/PaginatedMeta") +model PageMeta { + /** + * Page metadata. + */ + page: PagePaginatedMeta; +} + +/** + * Pagination information. + */ +@friendlyName("PageMeta") +@useRef("../../../../common/definitions/metadatas.yaml#/components/schemas/PageMeta") +model PagePaginatedMeta { + /** + * Page number. + */ + number: integer; + + /** + * Page size. + */ + size: integer; + + /** + * Total number of items in the collection. + */ + total: integer; +} diff --git a/api/spec/packages/aip/src/common/parameters.tsp b/api/spec/packages/aip/src/common/parameters.tsp new file mode 100644 index 0000000000000000000000000000000000000000..151e2f85e1b07597f6351b05eec40e5c3d823b20 --- /dev/null +++ b/api/spec/packages/aip/src/common/parameters.tsp @@ -0,0 +1,294 @@ +import "@typespec/http"; +import "@typespec/openapi"; +import "@typespec/openapi3"; + +using TypeSpec.OpenAPI; + +namespace Common; + +/** + * Sort query. + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ +@useRef("../../../../common/definitions/aip_filters.yaml#/components/schemas/SortQuery") +@friendlyName("SortQuery") +model SortQuery { + /** + * The attribute to sort by. + */ + by: string; + + /** + * The sort order. `asc` for ascending, `desc` for descending. + */ + order?: "asc" | "desc" = "asc"; +} + +/** + * Filter by a boolean value (true/false). + */ +@friendlyName("BooleanFieldFilter") +@extension("x-go-type", "filters.FilterBoolean") +@extension( + "x-go-type-import", + #{ path: "github.com/openmeterio/openmeter/api/v3/filters" } +) +@summary("Boolean Field Filter") +union BooleanFieldFilter { + equals: boolean, + object: { + /** + * Value strictly equals the given boolean value. + */ + eq: boolean, + }, +} + +/** + * Filter by a numeric value. All properties are optional; provide exactly one to + * specify the comparison. + */ +@friendlyName("NumericFieldFilter") +@extension("x-go-type", "filters.FilterNumeric") +@extension( + "x-go-type-import", + #{ path: "github.com/openmeterio/openmeter/api/v3/filters" } +) +@summary("Numeric Field Filter") +union NumericFieldFilter { + equals: float64, + object: { + /** + * Value strictly equals the given numeric value. + */ + eq?: float64, + + /** + * Value does not equal the given numeric value. + */ + neq?: float64, + + /** + * Returns entities that match any of the comma-delimited numeric values. + */ + @encode(ArrayEncoding.commaDelimited) + oeq?: float64[], + + /** + * Value is less than the given numeric value. + */ + lt?: float64, + + /** + * Value is less than or equal to the given numeric value. + */ + lte?: float64, + + /** + * Value is greater than the given numeric value. + */ + gt?: float64, + + /** + * Value is greater than or equal to the given numeric value. + */ + gte?: float64, + }, +} + +/** + * Filters on the given string field value by either exact or fuzzy match. All + * properties are optional; provide exactly one to specify the comparison. + */ +@friendlyName("StringFieldFilter") +@extension("x-go-type", "filters.FilterString") +@extension( + "x-go-type-import", + #{ path: "github.com/openmeterio/openmeter/api/v3/filters" } +) +union StringFieldFilter { + equals: string, + object: { + /** + * Value strictly equals the given string value. + */ + eq?: string, + + /** + * Value does not equal the given string value. + */ + neq?: string, + + /** + * Value contains the given string value (fuzzy match). + */ + contains?: string, + + /** + * Returns entities that fuzzy-match any of the comma-delimited phrases in the + * filter string. + */ + @encode(ArrayEncoding.commaDelimited) + ocontains?: string[], + + /** + * Returns entities that exact match any of the comma-delimited phrases in the + * filter string. + */ + @encode(ArrayEncoding.commaDelimited) + oeq?: string[], + + /** + * Value is greater than the given string value (lexicographic compare). + */ + gt?: string, + + /** + * Value is greater than or equal to the given string value (lexicographic + * compare). + */ + gte?: string, + + /** + * Value is less than the given string value (lexicographic compare). + */ + lt?: string, + + /** + * Value is less than or equal to the given string value (lexicographic compare). + */ + lte?: string, + + /** + * When true, the field must be present (non-null); when false, the field must be + * absent (null). + */ + exists?: boolean, + }, +} + +/** + * Filters on the given string field value by exact match. All properties are + * optional; provide exactly one to specify the comparison. + */ +@friendlyName("StringFieldFilterExact") +@extension("x-go-type", "filters.FilterStringExact") +@extension( + "x-go-type-import", + #{ path: "github.com/openmeterio/openmeter/api/v3/filters" } +) +@summary("String Field Filter Exact") +union StringFieldFilterExact { + equals: string, + object: { + /** + * Value strictly equals the given string value. + */ + eq?: string, + + /** + * Returns entities that exact match any of the comma-delimited phrases in the + * filter string. + */ + @encode(ArrayEncoding.commaDelimited) + oeq?: string[], + + /** + * Value does not equal the given string value. + */ + neq?: string, + }, +} + +/** + * Filters on the given ULID field value by exact match. All properties are + * optional; provide exactly one to specify the comparison. + */ +@friendlyName("ULIDFieldFilter") +@extension("x-go-type", "filters.FilterULID") +@extension( + "x-go-type-import", + #{ path: "github.com/openmeterio/openmeter/api/v3/filters" } +) +@summary("ULID Field Filter") +union ULIDFieldFilter { + equals: Shared.ULID, + object: { + /** + * Value strictly equals the given ULID value. + */ + eq?: Shared.ULID, + + /** + * Returns entities that exact match any of the comma-delimited ULIDs in the filter + * string. + */ + @encode(ArrayEncoding.commaDelimited) + oeq?: Shared.ULID[], + + /** + * Value does not equal the given ULID value. + */ + neq?: Shared.ULID, + }, +} + +/** + * Filters on the given datetime (RFC-3339) field value. All properties are + * optional; provide exactly one to specify the comparison. + */ +@friendlyName("DateTimeFieldFilter") +@extension("x-go-type", "filters.FilterDateTime") +@extension( + "x-go-type-import", + #{ path: "github.com/openmeterio/openmeter/api/v3/filters" } +) +@summary("DateTime Field Filter") +union DateTimeFieldFilter { + equals: Shared.DateTime, + object: { + /** + * Value strictly equals given RFC-3339 formatted timestamp in UTC. + */ + eq?: Shared.DateTime, + + /** + * Value is less than the given RFC-3339 formatted timestamp in UTC. + */ + lt?: Shared.DateTime, + + /** + * Value is less than or equal to the given RFC-3339 formatted timestamp in UTC. + */ + lte?: Shared.DateTime, + + /** + * Value is greater than the given RFC-3339 formatted timestamp in UTC. + */ + gt?: Shared.DateTime, + + /** + * Value is greater than or equal to the given RFC-3339 formatted timestamp in UTC. + */ + gte?: Shared.DateTime, + }, +} + +/** + * Filters on the resource's `labels` field. + * + * The schema is a map keyed by the label name; each value is a + * `StringFieldFilter`. Both deepObject forms are accepted: + * `filter[labels][key]=value` (nested) and `filter[labels.key]=value` + * (dot-notation). + */ +@friendlyName("LabelsFieldFilter") +@extension("x-go-type", "filters.FilterLabels") +@extension( + "x-go-type-import", + #{ path: "github.com/openmeterio/openmeter/api/v3/filters" } +) +@summary("Labels Field Filter") +model LabelsFieldFilter is Record; diff --git a/api/spec/packages/aip/src/common/properties.tsp b/api/spec/packages/aip/src/common/properties.tsp new file mode 100644 index 0000000000000000000000000000000000000000..6456c5a387e7c72fc8221ea4108b06e833c66a31 --- /dev/null +++ b/api/spec/packages/aip/src/common/properties.tsp @@ -0,0 +1,37 @@ +import "@typespec/openapi"; +import "@typespec/openapi3"; + +using TypeSpec.OpenAPI; + +namespace Common; + +/** + * Alias to the top-level `Billing` namespace. + * + * Nesting operation interfaces under `Customers.Billing` (so the SDK generator + * emits `customers.billing.*`) shadows the global `Billing` namespace for + * unqualified `Billing.*` references inside `Customers`-scoped files. Use + * `Common.BillingRoot.*` from those files to reach the top-level `Billing` + * models unambiguously. An alias emits nothing, so the OpenAPI output is + * unchanged. + */ +alias BillingRoot = Billing; + +/** + * Labels store metadata of an entity that can be used for filtering an entity list + * or for searching across entity types. + * + * Keys must be of length 1-63 characters, and cannot start with "kong", "konnect", + * "mesh", "kic", or "\_". + */ +@useRef("../../../../common/definitions/konnect_properties.yaml#/components/schemas/Labels") +@friendlyName("Labels") +model Labels is Record; + +/** + * Public labels store information about an entity that can be used for filtering a + * list of objects. + */ +@useRef("../../../../common/definitions/konnect_properties.yaml#/components/schemas/PublicLabels") +@friendlyName("PublicLabels") +model PublicLabels is Record; diff --git a/api/spec/packages/aip/src/currencies/cost-bases/cost-basis.tsp b/api/spec/packages/aip/src/currencies/cost-bases/cost-basis.tsp new file mode 100644 index 0000000000000000000000000000000000000000..6fa54166830409b7164f7c4c9625708661080916 --- /dev/null +++ b/api/spec/packages/aip/src/currencies/cost-bases/cost-basis.tsp @@ -0,0 +1,47 @@ +import "../../shared/index.tsp"; + +namespace Currencies; + +/** + * Describes currency basis supported by billing system. + */ +@friendlyName("BillingCostBasis") +model CostBasis { + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + @visibility(Lifecycle.Read) + id: Shared.ULID; + + /** + * The fiat currency code for the cost basis. + */ + @visibility(Lifecycle.Create, Lifecycle.Read) + fiat_code: Shared.CurrencyCode; + + /** + * The cost rate for the currency. + */ + @visibility(Lifecycle.Create, Lifecycle.Read) + rate: Shared.Numeric; + + /** + * An ISO-8601 timestamp representation of the date from which the cost basis is + * effective. If not provided, it will be effective immediately and will be set to + * `now` by the system. + */ + @visibility(Lifecycle.Create, Lifecycle.Read) + effective_from?: Shared.DateTime; + + /** + * An ISO-8601 timestamp representation of the date until which the cost basis is + * effective. If provided, it must be later than `effective_from`. If not provided, + * it remains effective until superseded. + */ + @visibility(Lifecycle.Create, Lifecycle.Read) + effective_to?: Shared.DateTime; + + /** + * An ISO-8601 timestamp representation of entity creation date. + */ + @visibility(Lifecycle.Read) + created_at: Shared.DateTime; +} diff --git a/api/spec/packages/aip/src/currencies/cost-bases/operations.tsp b/api/spec/packages/aip/src/currencies/cost-bases/operations.tsp new file mode 100644 index 0000000000000000000000000000000000000000..dbe9caac3cf934b2046b34724c7d4be8bc861494 --- /dev/null +++ b/api/spec/packages/aip/src/currencies/cost-bases/operations.tsp @@ -0,0 +1,67 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "../../common/error.tsp"; +import "../../common/parameters.tsp"; +import "../../shared/index.tsp"; +import "../currency.tsp"; +import "./cost-basis.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Currencies; + +/** + * Filter options for listing cost bases. + */ +@friendlyName("ListCostBasesParamsFilter") +model ListCostBasesParamsFilter { + /** + * Filter cost bases by fiat currency code. + */ + fiat_code?: Shared.CurrencyCode; +} + +interface CurrenciesCustomCostBasesOperations { + /** + * List cost bases for a currency. For custom currencies, there can be multiple + * cost bases with different `effective_from` dates. + */ + @extension(Shared.UnstableExtension, true) + @extension(Shared.InternalExtension, true) + @get + @operationId("list-cost-bases") + @summary("List cost bases") + get_cost_bases( + @path currencyId: Shared.ULID, + + /** + * Filter cost bases returned in the response. + * + * To filter cost bases by fiat currency code add the following query param: + * filter[fiat_code]=USD + */ + @query(#{ style: "deepObject", explode: true }) + filter?: ListCostBasesParamsFilter, + + ...Common.PagePaginationQuery, + ): + | Shared.PagePaginatedResponse + | Common.NotFound + | Common.ErrorResponses; + + /** + * Create a cost basis for a currency. + */ + @extension(Shared.UnstableExtension, true) + @extension(Shared.InternalExtension, true) + @post + @operationId("create-cost-basis") + @summary("Create cost basis") + create_cost_basis( + @path currencyId: Shared.ULID, + @body body: Shared.CreateRequest, + ): Shared.CreateResponse | Common.ErrorResponses; +} diff --git a/api/spec/packages/aip/src/currencies/currency.tsp b/api/spec/packages/aip/src/currencies/currency.tsp new file mode 100644 index 0000000000000000000000000000000000000000..a1afac4b4442d75f3d900cdec977e5d8e5fbdf4a --- /dev/null +++ b/api/spec/packages/aip/src/currencies/currency.tsp @@ -0,0 +1,112 @@ +import "@typespec/openapi3"; +import "../shared/index.tsp"; + +namespace Currencies; + +using TypeSpec.OpenAPI; + +/** + * Currency type for custom currencies. It should be a unique code but not + * conflicting with any existing standard currency codes. + */ +@friendlyName("BillingCurrencyType") +enum CurrencyType { + Fiat: "fiat", + Custom: "custom", +} + +/** + * Fiat or custom currency. + */ +@friendlyName("BillingCurrency") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union Currency { + @summary("Fiat currency") + fiat: CurrencyFiat, + + @summary("Custom currency") + custom: CurrencyCustom, +} + +/** + * Fiat or custom currency code. + */ +@friendlyName("BillingCurrencyCode") +@extension("x-go-type", "string") +union CurrencyCode { + Shared.CurrencyCode, + // CurrencyCodeCustom, +} + +/** + * Describes the common properties of a currency. It is used as a base model for both standard currencies and custom currencies. + * It includes properties such as id, name, and symbol that are shared by both types of currencies. + */ +@friendlyName("BillingCustomCurrencyBase") +model CurrencyBase { + /** + * The type of the currency. + */ + @visibility(Lifecycle.Read) + type: T; + + /** + * The name of the currency. It should be a human-readable string that represents + * the name of the currency, such as "US Dollar" or "Euro". + */ + @visibility(Lifecycle.Create, Lifecycle.Read) + @minLength(1) + @maxLength(256) + name: string; + + /** + * The symbol of the currency. It should be a string that represents the symbol of + * the currency, such as "$" for US Dollar or "€" for Euro. + */ + @visibility(Lifecycle.Create, Lifecycle.Read) + @minLength(1) + symbol?: string; +} + +/** + * Currency describes a currency supported by the billing system. + */ +@friendlyName("BillingCurrencyFiat") +model CurrencyFiat { + ...CurrencyBase; + + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + @visibility(Lifecycle.Read) + code: Shared.CurrencyCode; +} + +/** + * Custom currency code. It should be a unique code but not conflicting with any + * existing fiat currency codes. + */ +@friendlyName("BillingCurrencyCodeCustom") +@minLength(3) +@maxLength(24) +scalar CurrencyCodeCustom extends string; + +/** + * Describes custom currency. + */ +@friendlyName("BillingCurrencyCustom") +model CurrencyCustom { + ...CurrencyBase; + + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + @visibility(Lifecycle.Read) + id: Shared.ULID; + + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + @visibility(Lifecycle.Create, Lifecycle.Read) + code: CurrencyCodeCustom; + + /** + * An ISO-8601 timestamp representation of the custom currency creation date. + */ + @visibility(Lifecycle.Read) + created_at: Shared.DateTime; +} diff --git a/api/spec/packages/aip/src/currencies/index.tsp b/api/spec/packages/aip/src/currencies/index.tsp new file mode 100644 index 0000000000000000000000000000000000000000..8443e67d9c4696fcbc8d10eaa175cbe534b4d5a9 --- /dev/null +++ b/api/spec/packages/aip/src/currencies/index.tsp @@ -0,0 +1,3 @@ +import "./currency.tsp"; +import "./operations.tsp"; +import "./cost-bases/operations.tsp"; diff --git a/api/spec/packages/aip/src/currencies/operations.tsp b/api/spec/packages/aip/src/currencies/operations.tsp new file mode 100644 index 0000000000000000000000000000000000000000..0c0a36c2836a9bdbc735c963f6788f975dd8913c --- /dev/null +++ b/api/spec/packages/aip/src/currencies/operations.tsp @@ -0,0 +1,73 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "../common/error.tsp"; +import "../common/parameters.tsp"; +import "../shared/index.tsp"; +import "./currency.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Currencies; + +/** + * Filter options for listing currencies. + */ +@friendlyName("ListCurrenciesParamsFilter") +model ListCurrenciesParamsFilter { + #suppress "@openmeter/api-spec-aip/doc-decorator" "filter field" + type?: CurrencyType; + #suppress "@openmeter/api-spec-aip/doc-decorator" "filter field" + code?: Common.StringFieldFilter; +} + +interface CurrenciesOperations { + /** + * List currencies supported by the billing system. + */ + @extension(Shared.UnstableExtension, true) + @extension(Shared.InternalExtension, true) + @get + @operationId("list-currencies") + @summary("List currencies") + list( + ...Common.PagePaginationQuery, + + /** + * Sort currencies returned in the response. Supported sort attributes are: + * + * - `code` (default) + * - `name` + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ + @query(#{ name: "sort" }) + sort?: Common.SortQuery, + + /** + * Filter currencies returned in the response. + * + * To filter currencies by type add the following query param: filter[type]=custom + */ + @query(#{ style: "deepObject", explode: true }) + filter?: ListCurrenciesParamsFilter, + ): Shared.PagePaginatedResponse | Common.ErrorResponses; +} + +interface CurrenciesCustomOperations { + /** + * Create a custom currency. This operation allows defining your own custom + * currency for billing purposes. + */ + @extension(Shared.UnstableExtension, true) + @extension(Shared.InternalExtension, true) + @post + @operationId("create-custom-currency") + @summary("Create custom currency") + create(@body body: Shared.CreateRequest): + | Shared.CreateResponse + | Common.ErrorResponses; +} diff --git a/api/spec/packages/aip/src/customers/billing.tsp b/api/spec/packages/aip/src/customers/billing.tsp new file mode 100644 index 0000000000000000000000000000000000000000..e8100abdd2817547ffbea222ca9ea9d251758478 --- /dev/null +++ b/api/spec/packages/aip/src/customers/billing.tsp @@ -0,0 +1,26 @@ +import "../apps/index.tsp"; +import "../billing/index.tsp"; + +namespace Customers; + +/** + * Billing customer data. + */ +@friendlyName("BillingCustomerData") +model CustomerBillingData { + /** + * The billing profile for the customer. + * + * If not provided, the default billing profile will be used. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Billing profile") + billing_profile?: Common.BillingRoot.BillingProfileReference; + + /** + * App customer data. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("App customer data") + app_data?: Apps.AppCustomerData; +} diff --git a/api/spec/packages/aip/src/customers/charges/charges.tsp b/api/spec/packages/aip/src/customers/charges/charges.tsp new file mode 100644 index 0000000000000000000000000000000000000000..58b3d5a703acc45815bf1bbc65ef65cb16f396e7 --- /dev/null +++ b/api/spec/packages/aip/src/customers/charges/charges.tsp @@ -0,0 +1,482 @@ +import "../../shared/index.tsp"; +import "../../productcatalog/index.tsp"; +import "../../subscriptions/index.tsp"; +import "../customer.tsp"; + +namespace Customers; + +/** + * Type of a charge. + * + * Values: + * + * - `flat_fee`: A fixed-amount charge. + * - `usage_based`: A usage-priced charge. + */ +@friendlyName("BillingChargeType") +@summary("Charge type") +enum ChargeType { + FlatFee: "flat_fee", + UsageBased: "usage_based", +} + +/** + * Lifecycle status of a charge. + * + * Values: + * + * - `created`: The charge has been created but is not active yet. + * - `active`: The charge is active. + * - `final`: The charge is fully finalized and no further changes are expected. + * - `deleted`: The charge has been deleted. + */ +@friendlyName("BillingChargeStatus") +@summary("Charge status") +enum ChargeStatus { + Created: "created", + Active: "active", + Final: "final", + Deleted: "deleted", +} + +/** + * Discounts applicable to flat fee charges. + * + * This is the same as `ProductCatalog.Discounts` but without the `usage` field, + * which is not applicable to flat fee charges. + */ +@friendlyName("BillingChargeFlatFeeDiscounts") +@summary("Flat fee charge discounts") +model ChargeFlatFeeDiscounts { + ...OmitProperties; +} + +/** + * Flat fee intent fields from the system lifecycle controller shadowed by a manual + * override. + */ +@friendlyName("BillingChargeFlatFeeSystemIntent") +@summary("Flat fee system lifecycle controller charge intent") +model ChargeFlatFeeSystemIntent { + ...PickProperties< + ChargeFlatFee, + + | "name" + | "description" + | "labels" + | "invoice_at" + | "service_period" + | "full_service_period" + | "billing_period" + | "payment_term" + | "discounts" + | "proration_configuration" + >; + + /** + * The amount before proration of the system lifecycle controller flat fee intent. + */ + @visibility(Lifecycle.Read) + @summary("Amount before proration") + amount_before_proration: Shared.CurrencyAmount; + + /** + * The timestamp when the system lifecycle controller intent was deleted. The + * effective charge can remain visible while a manual override is active. + */ + @visibility(Lifecycle.Read) + @summary("Deleted at") + deleted_at?: Shared.DateTime; +} + +/** + * Usage-based intent fields from the system lifecycle controller shadowed by a + * manual override. + */ +@friendlyName("BillingChargeUsageBasedSystemIntent") +@summary("Usage-based system lifecycle controller charge intent") +model ChargeUsageBasedSystemIntent { + ...PickProperties< + ChargeUsageBased, + + | "name" + | "description" + | "labels" + | "invoice_at" + | "service_period" + | "full_service_period" + | "billing_period" + | "discounts" + | "price" + >; + + /** + * The timestamp when the system lifecycle controller intent was deleted. The + * effective charge can remain visible while a manual override is active. + */ + @visibility(Lifecycle.Read) + @summary("Deleted at") + deleted_at?: Shared.DateTime; +} + +/** + * Shared fields present on all customer charge responses. + */ +#suppress "@openmeter/api-spec-aip/repeated-prefix-grouping" "charge temporal fields should remain flat" +@friendlyName("BillingChargeBase") +@summary("Charge") +model ChargeBase { + ...Shared.Resource; + + /** + * The type of the charge. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Type") + type: T; + + /** + * The customer owning the charge. + */ + @visibility(Lifecycle.Read) + @summary("Customer") + customer: CustomerReference; + + /** + * Indicates whether the charge lifecycle is controlled by OpenMeter or manually + * overridden by the API user. + */ + @visibility(Lifecycle.Read) + @summary("Lifecycle controller") + lifecycle_controller: Shared.LifecycleController; + + /** + * The subscription that originated the charge, when the charge was created from a + * subscription item. + */ + @visibility(Lifecycle.Read) + @summary("Subscription") + subscription?: Subscriptions.SubscriptionReference; + + /** + * The currency of the charge. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Currency") + currency: Shared.CurrencyCode; + + /** + * The lifecycle status of the charge. + */ + @visibility(Lifecycle.Read) + @summary("Status") + status: ChargeStatus; + + /** + * The timestamp when the charge is intended to be invoiced. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Invoice at") + invoice_at: Shared.DateTime; + + /** + * The effective service period covered by the charge. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Service period") + service_period: Shared.ClosedPeriod; + + /** + * The full, unprorated service period of the charge. + */ + @visibility(Lifecycle.Read) + @summary("Full service period") + full_service_period: Shared.ClosedPeriod; + + /** + * The billing period the charge belongs to. + */ + @visibility(Lifecycle.Read) + @summary("Billing period") + billing_period: Shared.ClosedPeriod; + + /** + * The earliest time when the charge should be advanced again by background + * processing. + */ + @visibility(Lifecycle.Read) + @summary("Advance after") + advance_after?: Shared.DateTime; + + /** + * Unique reference ID of the charge. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Unique reference ID") + unique_reference_id?: string; + + /** + * Settlement mode of the charge. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Settlement mode") + settlement_mode: ProductCatalog.SettlementMode; + + /** + * Tax configuration of the charge. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Tax configuration") + tax_config?: Common.BillingRoot.TaxConfig; +} + +/** + * A flat fee charge for a customer. + */ +#suppress "@openmeter/api-spec-aip/repeated-prefix-grouping" "" +@friendlyName("BillingChargeFlatFee") +@summary("Flat fee charge") +model ChargeFlatFee { + ...ChargeBase; + + /** + * Payment term of the flat fee charge. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Payment term") + payment_term: ProductCatalog.PricePaymentTerm; + + /** + * The discounts applied to the charge. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Discounts") + discounts?: ChargeFlatFeeDiscounts; + + /** + * The feature associated with the charge, when applicable. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Feature key") + feature_key?: string; + + /** + * The proration configuration of the charge. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Proration configuration") + proration_configuration: ProductCatalog.ProrationConfiguration; + + /** + * The amount before proration of the charge. + */ + @visibility(Lifecycle.Create) + @summary("Amount before proration") + amount_before_proration: Shared.CurrencyAmount; + + // Calculated fields + /** + * The amount after proration of the charge. + */ + @visibility(Lifecycle.Read) + @summary("Amount after proration") + amount_after_proration: Shared.CurrencyAmount; + + /** + * The price of the charge. + */ + @visibility(Lifecycle.Read) + @summary("Price") + price: ProductCatalog.Price; + + /** + * Current intent from the system lifecycle controller for a charge that has an + * active manual override. The top-level charge fields remain the effective + * customer-facing intent. + */ + @visibility(Lifecycle.Read) + @summary("System intent") + system_intent?: ChargeFlatFeeSystemIntent; +} + +/** + * The totals of a change. + * + * RealTime is only expanded when the `real_time_usage` expand is used. + */ +@friendlyName("BillingChargeTotals") +model ChargeTotals { + /** + * The amount of the charge already booked to the internal accounting system. + */ + @visibility(Lifecycle.Read) + @summary("Booked") + booked: Common.BillingRoot.BillingTotals; + + /** + * The realtime amount of the charge. + * + * Requires the `realtime_usage` expand. + */ + @visibility(Lifecycle.Read) + @summary("Realtime totals") + realtime?: Common.BillingRoot.BillingTotals; +} + +/** + * A usage-based charge for a customer. + */ +@friendlyName("BillingChargeUsageBased") +@summary("Usage-based charge") +model ChargeUsageBased { + ...ChargeBase; + + /** + * Discounts applied to the usage-based charge. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Discounts") + discounts?: ProductCatalog.Discounts; + + /** + * The feature associated with the charge. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Feature key") + feature_key: string; + + // Status fields + + /** + * Aggregated booked and realtime totals for the charge. + */ + @visibility(Lifecycle.Read) + @summary("Totals for the charge") + totals: ChargeTotals; + + /** + * The price of the charge. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Price") + price: ProductCatalog.Price; + + /** + * Current intent from the system lifecycle controller for a charge that has an + * active manual override. The top-level charge fields remain the effective + * customer-facing intent. + */ + @visibility(Lifecycle.Read) + @summary("System intent") + system_intent?: ChargeUsageBasedSystemIntent; +} + +/** + * Customer charge. + */ +@friendlyName("BillingCharge") +@summary("Customer charge") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union Charge { + /** + * A flat fee charge. + */ + flat_fee: ChargeFlatFee, + + /** + * A usage-based charge. + */ + usage_based: ChargeUsageBased, +} + +/** + * Expands for customer charges. + * + * Values: + * + * - `real_time_usage`: The charge's real-time usage. + */ +@friendlyName("BillingChargesExpand") +@summary("Customer charge expands") +enum ChargesExpand { + RealTimeUsage: "real_time_usage", +} + +/** + * Customer charge. + */ +@friendlyName("CreateChargeRequest") +@summary("Customer charge create request.") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union CreateCharge { + /** + * A flat fee charge. + */ + flat_fee: CreateChargeFlatFee, + + /** + * A usage-based charge. + */ + usage_based: CreateChargeUsageBased, +} + +/** + * Create a flat fee charge for a customer. + */ +@doc("Flat fee charge create request.") +@withVisibility(Lifecycle.Create) +@friendlyName("CreateChargeFlatFeeRequest") +model CreateChargeFlatFee { + ...OmitProperties; + + /** + * The full, unprorated service period of the charge. + */ + @visibility(Lifecycle.Create) + @summary("Full service period") + full_service_period?: Shared.ClosedPeriod; + + /** + * The billing period the charge belongs to. + */ + @visibility(Lifecycle.Create) + @summary("Billing period") + billing_period?: Shared.ClosedPeriod; +} + +/** + * Create a usage-based charge for a customer. + */ +@doc("Usage-based charge create request.") +@withVisibility(Lifecycle.Create) +@friendlyName("CreateChargeUsageBasedRequest") +model CreateChargeUsageBased { + ...OmitProperties; + + /** + * The full, unprorated service period of the charge. + */ + @visibility(Lifecycle.Create) + @summary("Full service period") + full_service_period?: Shared.ClosedPeriod; + + /** + * The billing period the charge belongs to. + */ + @visibility(Lifecycle.Create) + @summary("Billing period") + billing_period?: Shared.ClosedPeriod; +} + +/** + * Reference to a charge associated with an invoice line. + */ +@friendlyName("BillingChargeReference") +model ChargeReference { + /** + * Unique identifier for the charge. + */ + @visibility(Lifecycle.Read) + @summary("ID") + id: Shared.ULID; +} diff --git a/api/spec/packages/aip/src/customers/charges/index.tsp b/api/spec/packages/aip/src/customers/charges/index.tsp new file mode 100644 index 0000000000000000000000000000000000000000..42a8986c07a03fea11117375ae3f9b884bf97ca4 --- /dev/null +++ b/api/spec/packages/aip/src/customers/charges/index.tsp @@ -0,0 +1,2 @@ +import "./charges.tsp"; +import "./operations.tsp"; diff --git a/api/spec/packages/aip/src/customers/charges/operations.tsp b/api/spec/packages/aip/src/customers/charges/operations.tsp new file mode 100644 index 0000000000000000000000000000000000000000..ebea59cd6f9365e3ac9cf2262d4dc35056d83229 --- /dev/null +++ b/api/spec/packages/aip/src/customers/charges/operations.tsp @@ -0,0 +1,98 @@ +import "@typespec/http"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "../../common/error.tsp"; +import "../../common/pagination.tsp"; +import "../../shared/index.tsp"; +import "../../common/parameters.tsp"; +import "./charges.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Customers; + +/** + * Filter options for listing charges. + */ +@friendlyName("ListChargesParamsFilter") +model ListCustomerChargesParamsFilter { + /** + * Filter charges by status. + * + * Supported statuses are: + * + * - `created` + * - `active` + * - `final` + * - `deleted` + * + * If omitted, all statuses are returned except for `deleted`. + */ + status?: Common.StringFieldFilterExact; +} + +namespace Charges { + interface CustomerChargesOperations { + /** + * List customer charges. + * + * Returns the customer's charges that are represented as either flat fee or + * usage-based charges. + */ + @extension(Shared.UnstableExtension, true) + @get + @operationId("list-customer-charges") + @summary("List customer charges") + list( + ...Common.PagePaginationQuery, + @path customerId: Shared.ULID, + + /** + * Sort charges returned in the response. + * + * Supported sort attributes are: + * + * - `id` + * - `created_at` + * - `service_period.from` + * - `billing_period.from` + */ + @query(#{ name: "sort" }) + sort?: Common.SortQuery, + + /** + * Filter charges. + * + * To filter charges by status add the following query param: + * `filter[status][oeq]=created,active` + */ + @query(#{ style: "deepObject", explode: true }) + filter?: ListCustomerChargesParamsFilter, + + /** + * Expand full objects for referenced entities. + * + * Supported values are: + * + * - `real_time_usage`: Expand the charge's real-time usage. + */ + @query(#{ name: "expand", explode: true }) + expand?: ChargesExpand[], + ): + | Shared.PagePaginatedResponse + | Common.NotFound + | Common.ErrorResponses; + + /** + * Create customer charge. + */ + @extension(Shared.UnstableExtension, true) + @post + @operationId("create-customer-charges") + @summary("Create customer charge") + create(@path customerId: Shared.ULID, @body charge: CreateCharge): + | Shared.CreateResponse + | Common.ErrorResponses; + } +} diff --git a/api/spec/packages/aip/src/customers/credits/adjustment.tsp b/api/spec/packages/aip/src/customers/credits/adjustment.tsp new file mode 100644 index 0000000000000000000000000000000000000000..875a0433b216d5fb23d72e83d178b8def194f9f4 --- /dev/null +++ b/api/spec/packages/aip/src/customers/credits/adjustment.tsp @@ -0,0 +1,28 @@ +import "../../shared/index.tsp"; +import "../../currencies/index.tsp"; + +/** + * A credit adjustment can be used to make manual adjustments to a customer's + * credit balance. + * + * Supported use-cases: + * + * - Usage correction + */ +@friendlyName("BillingCreditAdjustment") +@summary("Credit adjustment") +model CreditAdjustment { + ...PickProperties; + + /** + * The currency of the granted credits. + */ + @visibility(Lifecycle.Create) + currency: Currencies.CurrencyCode; + + /** + * Granted credit amount. + */ + @visibility(Lifecycle.Create) + amount: Shared.Numeric; +} diff --git a/api/spec/packages/aip/src/customers/credits/balance.tsp b/api/spec/packages/aip/src/customers/credits/balance.tsp new file mode 100644 index 0000000000000000000000000000000000000000..40a8d0c38050dc8b30ef366b0ca214547c98a90b --- /dev/null +++ b/api/spec/packages/aip/src/customers/credits/balance.tsp @@ -0,0 +1,56 @@ +import "../../shared/index.tsp"; +import "../../currencies/index.tsp"; + +namespace Customers; + +/** + * The balances of the credits of a customer. + */ +@friendlyName("BillingCreditBalances") +@summary("Credit balances") +model CreditBalances { + /** + * The timestamp of the balance retrieval. + */ + @visibility(Lifecycle.Read) + retrieved_at: Shared.DateTime; + + /** + * The balances by currencies. + */ + @visibility(Lifecycle.Read) + balances: CreditBalance[]; +} + +/** + * The credit balance by currency. + */ +@friendlyName("CreditBalance") +@summary("Credit balance") +model CreditBalance { + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + @visibility(Lifecycle.Read) + currency: Currencies.CurrencyCode; + + /** + * Credits available after applying currently live charge impacts. + */ + @visibility(Lifecycle.Read) + @example("200.00") + live: Shared.Numeric; + + /** + * Credits that have been booked on the ledger as of the balance timestamp. + */ + @visibility(Lifecycle.Read) + @example("150.00") + settled: Shared.Numeric; + + /** + * Credits that have been granted but are not yet written to the ledger, or are + * written to the ledger with a future booked time. + */ + @visibility(Lifecycle.Read) + @example("50.00") + pending: Shared.Numeric; +} diff --git a/api/spec/packages/aip/src/customers/credits/grant.tsp b/api/spec/packages/aip/src/customers/credits/grant.tsp new file mode 100644 index 0000000000000000000000000000000000000000..01394230df33b83959b678ab7f38a8cddbd28711 --- /dev/null +++ b/api/spec/packages/aip/src/customers/credits/grant.tsp @@ -0,0 +1,328 @@ +import "../../shared/index.tsp"; +import "../../currencies/index.tsp"; + +namespace Customers; + +/** + * The funding method describes how the grant is funded. + * + * - `none`: No funding workflow applies, for example promotional grants + * - `invoice`: The grant is funded by an in-system invoice flow + * - `external`: The grant is funded outside the system (e.g., wire transfer, + * external invoice, or manual reconciliation) + */ +@friendlyName("BillingCreditFundingMethod") +@summary("Credit funding method") +enum CreditFundingMethod { + // No funding workflow applies + None: "none", + + // The grant is funded by an in-system invoice flow + Invoice: "invoice", + + // The grant is funded outside the system + External: "external", +} + +/** + * When credits become available for consumption. + * + * - `on_creation`: Credits are available as soon as the grant is created. + * - `on_authorization`: Credits are available once the payment is authorized. + * - `on_settlement`: Credits are available once the payment is settled. + */ +@friendlyName("BillingCreditAvailabilityPolicy") +@summary("Credit availability policy") +enum CreditAvailabilityPolicy { + // Credits become eligible when the grant is created + OnCreation: "on_creation", + + // // Credits become eligible when payment is authorized + // OnAuthorization: "on_authorization", + + // // Credits become eligible when payment is settled + // OnSettlement: "on_settlement", +} + +/** + * Credit purchase payment settlement status. + * + * - `pending`: Payment has been initiated and is not yet authorized. + * - `authorized`: Payment has been authorized. + * - `settled`: Payment has been settled. + */ +@friendlyName("BillingCreditPurchasePaymentSettlementStatus") +@summary("Credit purchase payment settlement status") +enum CreditPurchasePaymentSettlementStatus { + // Payment has been initiated and is not yet authorized. + Pending: "pending", + + // Payment has been authorized. + Authorized: "authorized", + + // Payment has been settled. + Settled: "settled", +} + +/** + * Credit grant lifecycle status. + * + * - `pending`: The credit block has been created but is not yet valid. + * (`effective_at` is in the future or availability_policy is not met) + * - `active`: The credit block is currently valid and eligible for consumption. + * (`effective_at` is in the past, `expires_at` is in the future and + * availability_policy is met) + * - `expired`: The credit block expired with remaining unused balance, + * `expires_at` time has passed. + * - `voided`: The credit block was voided. Remaining balance is forfeited. + */ +@friendlyName("BillingCreditGrantStatus") +@summary("Credit grant lifecycle status") +enum CreditGrantStatus { + // The credit block has been created but is not yet eligible for consumption. (`effective_at` is in the future or availability_policy is not met) + Pending: "pending", + + // The credit block is currently eligible for consumption. (`effective_at` is in the past, `expires_at` is in the future and availability_policy is met) + Active: "active", + + // The credit block expired with remaining unused balance, `expires_at` time has passed. + Expired: "expired", + + // The credit block was voided. + Voided: "voided", +} + +/** + * Describes how voiding a credit grant adjusts related payment state. + * + * - `none`: Voiding does not adjust invoices, payment authorization, settlement, + * payment intents, or external collection state. + */ +@friendlyName("BillingCreditGrantVoidPaymentAdjustment") +@summary("Credit grant void payment adjustment") +enum CreditGrantVoidPaymentAdjustment { + // No payment state is adjusted by the void operation. + None: "none", +} + +/** + * Tax configuration for a credit grant. + * + * Tax configuration should be provided to ensure correct revenue recognition, + * including for externally funded grants. + */ +@friendlyName("BillingCreditGrantTaxConfig") +@summary("Tax configuration for a credit grant") +model CreditGrantTaxConfig { + /** + * Tax behavior applied to the invoice line item. + */ + behavior?: Common.BillingRoot.TaxBehavior; + + /** + * Tax code applied to the invoice line item. + */ + tax_code?: Shared.ResourceReference; +} + +/** + * A credit grant allocates credits to a customer. + * + * Credits are drawn down against charges according to the settlement mode + * configured on the rate card. + */ +#suppress "@openmeter/api-spec-aip/repeated-prefix-grouping" "credit grant model" +@summary("Credit grant") +@friendlyName("BillingCreditGrant") +model CreditGrant { + ...Shared.Resource; + + /** + * Funding method of the grant. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + funding_method: CreditFundingMethod; + + /** + * The currency of the granted credits. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + currency: Currencies.CurrencyCode; + + /** + * Granted credit amount. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + amount: Shared.Numeric; + + /** + * Present when a funding workflow applies (funding_method is not `none`). + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + purchase?: CreditGrantPurchase; + + /** + * Tax configuration for the grant. + * + * For `invoice` and `external` funding methods, tax configuration should be + * provided to ensure correct revenue recognition. When not provided, the default + * credit grant tax code is applied, if that's not set the global default taxcode + * is used. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + tax_config?: CreditGrantTaxConfig; + + /** + * Available when `funding_method` is `invoice`. + */ + @visibility(Lifecycle.Read) + invoice?: CreditGrantInvoiceReference; + + #suppress "@openmeter/api-spec-aip/doc-decorator" "nested model" + @visibility(Lifecycle.Read, Lifecycle.Create) + filters?: CreditGrantFilters; + + /** + * Draw-down priority of the grant. Lower values have higher priority. + */ + @visibility(Lifecycle.Create, Lifecycle.Read) + @minValue(1) + @maxValue(1000) + priority?: int16 = 10; + + /** + * The timestamp when the credit grant becomes effective. + * + * Defaults to the current date and time. + */ + @visibility(Lifecycle.Create, Lifecycle.Read) + effective_at?: Shared.DateTime; + + /** + * The duration after which the credit grant expires. + * + * Defaults to never expiring. + */ + @visibility(Lifecycle.Create) + expires_after?: Shared.ISO8601Duration; + + /** + * Idempotency key for the credit grant creation request. + * + * When provided, reusing the same key returns an HTTP 409 Conflict instead of + * creating a duplicate grant, which makes create requests safe to retry. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + key?: Shared.ExternalResourceKey; + + /** + * The timestamp when the credit grant expires. + * + * Calculated from the grant effective time and `expires_after` if provided. + */ + @visibility(Lifecycle.Read) + expires_at?: Shared.DateTime; + + /** + * Timestamp when the grant was voided. + */ + @visibility(Lifecycle.Read) + voided_at?: Shared.DateTime; + + /** + * Current lifecycle status of the grant. + */ + @visibility(Lifecycle.Read) + status: CreditGrantStatus; +} + +/** + * Purchase and payment terms of the grant. + */ +@friendlyName("BillingCreditGrantPurchase") +model CreditGrantPurchase { + /** + * Currency of the purchase amount. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + currency: Shared.CurrencyCode; + + /** + * Cost basis per credit unit used to calculate the purchase amount. + * + * If `per_unit_cost_basis` is 0.50 and credit amount is $100.00, the total charge + * is $50.00. The value must be greater than 0. If the cost basis is 0, use + * `funding_method=none` instead. + * + * Defaults to 1.0. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + per_unit_cost_basis?: Shared.Numeric = "1.0"; + + /** + * The purchase amount. Calculated from `per_unit_cost_basis` and credit `amount`. + */ + @visibility(Lifecycle.Read) + amount: Shared.Numeric; + + /** + * Controls when credits become available for consumption. + * + * Defaults to `on_creation`. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + availability_policy?: CreditAvailabilityPolicy = CreditAvailabilityPolicy.OnCreation; + + // TODO: add this option later + // /** + // * The initial payment settlement status when creating a grant with + // * `external` funding method. + // * + // * Governs the payment state of the grant on creation. If the external + // * system tracks payment status, synchronize their state with this system + // * so that revenue recognition works as expected. + // * + // * Defaults to `settled` (the external payment is assumed to be already settled on creation). + // */ + // @visibility(Lifecycle.Create) + // external_payment_initial_settlement_status?: CreditPurchasePaymentSettlementStatus = CreditPurchasePaymentSettlementStatus.Settled; + + /** + * Current payment settlement status. + */ + @visibility(Lifecycle.Read) + settlement_status?: CreditPurchasePaymentSettlementStatus; +} + +/** + * Filters for the credit grant. + */ +@friendlyName("BillingCreditGrantFilters") +model CreditGrantFilters { + /** + * Limit the credit grant to specific features. If no features are specified, the + * credit grant can be used for any feature. + */ + @example(#["input_tokens", "output_tokens"]) + features?: Shared.ResourceKey[]; +} + +/** + * Invoice references for the grant. + */ +@friendlyName("BillingCreditGrantInvoiceReference") +model CreditGrantInvoiceReference { + /** + * Identifier of the invoice associated with the grant. + */ + @visibility(Lifecycle.Read) + id?: Shared.ULID; + + /** + * Identifier of the invoice line associated with the grant. + */ + @visibility(Lifecycle.Read) + line?: { + id: Shared.ULID; + }; +} diff --git a/api/spec/packages/aip/src/customers/credits/index.tsp b/api/spec/packages/aip/src/customers/credits/index.tsp new file mode 100644 index 0000000000000000000000000000000000000000..2d8783b29ce804f91816b2b59e3c63c930b557d7 --- /dev/null +++ b/api/spec/packages/aip/src/customers/credits/index.tsp @@ -0,0 +1,3 @@ +import "./grant.tsp"; +import "./ledger.tsp"; +import "./operations.tsp"; diff --git a/api/spec/packages/aip/src/customers/credits/ledger.tsp b/api/spec/packages/aip/src/customers/credits/ledger.tsp new file mode 100644 index 0000000000000000000000000000000000000000..309792944ac80739204d59539c9b437d3bfc25c0 --- /dev/null +++ b/api/spec/packages/aip/src/customers/credits/ledger.tsp @@ -0,0 +1,130 @@ +import "../../shared/index.tsp"; +import "../../currencies/index.tsp"; + +namespace Customers; + +/** + * The type of the credit transaction. + * + * - `funded`: Credit granted and available for consumption. + * - `consumed`: Credit consumed by usage or fees. + * - `expired`: Credit removed because it expired before being used. + * - `voided`: Credit removed because the grant was voided before being used. + */ +@friendlyName("BillingCreditTransactionType") +enum CreditTransactionType { + // Credit granted and available for consumption. + Funded: "funded", + + // Credit consumed by usage or fees. + Consumed: "consumed", + + // Credit removed because it expired before being used. + Expired: "expired", + + // Credit removed because the grant was voided before being used. + Voided: "voided", +} + +// /** +// * The type of actor that caused the credit transaction. +// * +// * - `system`: Automated system operations (consumption, expiry). +// * - `customer`: Initiated by the customer. +// * - `admin`: Initiated by the admin. +// * - `payment_provider`: Initiated by the payment provider. +// */ +// @friendlyName("BillingCreditTransactionActorType") +// @summary("Credit transaction actor type") +// enum CreditTransactionActorType { +// // Automated system operations (consumption, expiry). +// System: "system", + +// // Initiated by the customer. +// Customer: "customer", + +// // Initiated by the admin. +// Admin: "admin", + +// // Initiated by the payment provider. +// PaymentProvider: "payment_provider", + +// // TODO: figure out if this is called actor or source +// } + +// /** +// * The actor that caused the credit transaction. +// */ +// @friendlyName("BillingCreditTransactionActor") +// @summary("Credit transaction actor") +// model CreditTransactionActor { +// /** +// * The type of actor. +// */ +// @visibility(Lifecycle.Read) +// type: CreditTransactionActorType; + +// // TODO: add additional metadata for the actor +// } + +/** + * A credit transaction represents a single credit movement on the customer's + * balance. + * + * Credit transactions are immutable. + */ +@friendlyName("BillingCreditTransaction") +@summary("Credit transaction") +model CreditTransaction { + // Add references in labels: + // https://kong-aip.netlify.app/aip/129/ + // - charge_id + // - subscription_id + // - subscription_phase_id + // - subscription_item_id + // - feature_id + // and later add references: {} to the type + ...Shared.ResourceImmutable; + + /** + * The date and time the transaction was booked. + */ + @visibility(Lifecycle.Read) + booked_at: Shared.DateTime; + + /** + * The type of credit transaction. + */ + @visibility(Lifecycle.Read) + type: CreditTransactionType; + + /** + * Currency of the balance affected by the transaction. + */ + @visibility(Lifecycle.Read) + currency: Currencies.CurrencyCode; + + /** + * Signed amount of the credit movement. Positive values add balance, negative + * values reduce balance. + */ + @visibility(Lifecycle.Read) + amount: Shared.Numeric; + + /** + * The available balance before and after the transaction. + */ + @visibility(Lifecycle.Read) + available_balance: { + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + before: Shared.Numeric; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + after: Shared.Numeric; + }; + + // /** + // * The actor that caused this credit transaction. + // */ + // @visibility(Lifecycle.Read) + // actor: CreditTransactionActor; +} diff --git a/api/spec/packages/aip/src/customers/credits/operations.tsp b/api/spec/packages/aip/src/customers/credits/operations.tsp new file mode 100644 index 0000000000000000000000000000000000000000..6c1c79a58e4987115ecf05e4d5309f46f1004771 --- /dev/null +++ b/api/spec/packages/aip/src/customers/credits/operations.tsp @@ -0,0 +1,294 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "../../common/error.tsp"; +import "../../common/parameters.tsp"; +import "../../shared/index.tsp"; +import "./grant.tsp"; +import "./balance.tsp"; +import "./ledger.tsp"; +import "./adjustment.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Customers; + +/** + * Filter options for listing credit grants. + */ +@friendlyName("ListCreditGrantsParamsFilter") +model ListCreditGrantsParamsFilter { + /** + * Filter credit grants by status. + */ + status?: CreditGrantStatus; + + /** + * Filter credit grants by currency. + */ + currency?: Shared.CurrencyCode; + + /** + * Filter credit grants by key. + */ + key?: Common.StringFieldFilter; +} + +namespace Credits.Grants { + interface CustomerCreditGrantsOperations { + /** + * Create a new credit grant. A credit grant represents an allocation of prepaid + * credits to a customer. + */ + @extension(Shared.UnstableExtension, true) + @post + @operationId("create-credit-grant") + @summary("Create a new credit grant") + create( + @path customerId: Shared.ULID, + @body credit_grant: Shared.CreateRequestNested, + ): + | Shared.CreateResponse + | Common.NotFound + | Common.Conflict + | Common.ErrorResponses; + + /** + * Get a credit grant. + */ + @extension(Shared.UnstableExtension, true) + @get + @operationId("get-credit-grant") + @summary("Get a credit grant") + get(@path customerId: Shared.ULID, @path creditGrantId: Shared.ULID): + | Shared.GetResponse + | Common.NotFound + | Common.ErrorResponses; + + /** + * List credit grants. + */ + @extension(Shared.UnstableExtension, true) + @get + @operationId("list-credit-grants") + @summary("List credit grants") + list( + @path customerId: Shared.ULID, + ...Common.PagePaginationQuery, + + /** + * Filter credit grants returned in the response. + */ + @query(#{ style: "deepObject", explode: true }) + filter?: ListCreditGrantsParamsFilter, + ): + | Shared.PagePaginatedResponse + | Common.NotFound + | Common.ErrorResponses; + } +} + +namespace Credits.Grants { + /** + * Request body for voiding a credit grant. + */ + @friendlyName("VoidCreditGrantRequest") + model VoidCreditGrantRequest { + /** + * How voiding adjusts payment state related to the grant. + * + * Currently only `none` is supported: voiding does not adjust invoices, payment + * authorization, settlement, payment intents, or external collection state. If + * payment later completes, the original invoiced amount may still be collected. + */ + payment_adjustment?: CreditGrantVoidPaymentAdjustment = CreditGrantVoidPaymentAdjustment.None; + } + + interface CustomerCreditGrantVoidOperations { + /** + * Void a credit grant, forfeiting the remaining unused balance. + * + * Voiding is a forward-looking, irreversible operation. Credits already consumed + * by usage remain unaffected — only the remaining balance is forfeited. The grant + * reads as `voided` status afterwards. Payment state is not adjusted when + * `payment_adjustment` is `none`, so invoice-backed or externally collected + * payments may still collect the original amount. Only `active` grants can be + * voided; voiding a pending, expired, or fully consumed grant returns a conflict. + * Retrying a successful void is an idempotent success. + */ + @extension(Shared.UnstableExtension, true) + @post + @operationId("void-credit-grant") + @summary("Void credit grant") + voidGrant( + @path customerId: Shared.ULID, + @path creditGrantId: Shared.ULID, + @body request?: VoidCreditGrantRequest, + ): + | Shared.UpdateResponse + | Common.NotFound + | Common.Conflict + | Common.ErrorResponses; + } +} + +/** + * Request body for updating the external payment settlement status of a credit + * grant. + */ +@friendlyName("UpdateCreditGrantExternalSettlementRequest") +model UpdateCreditGrantExternalSettlementRequest { + /** + * The new payment settlement status. + */ + status: CreditPurchasePaymentSettlementStatus; +} + +namespace Credits.Grants { + interface CustomerCreditGrantExternalSettlementOperations { + /** + * Update the payment settlement status of an externally funded credit grant. + * + * Use this endpoint to synchronize the payment state of an external payment with + * the system so that revenue recognition and credit availability work as expected. + */ + @extension(Shared.UnstableExtension, true) + @post + @operationId("update-credit-grant-external-settlement") + @summary("Update credit grant external settlement status") + updateExternalSettlement( + @path customerId: Shared.ULID, + @path creditGrantId: Shared.ULID, + @body body: UpdateCreditGrantExternalSettlementRequest, + ): + | Shared.UpdateResponse + | Common.NotFound + | Common.ErrorResponses; + } +} + +/** + * Filter options for getting a credit balance. + */ +@friendlyName("GetCreditBalanceParamsFilter") +model GetCreditBalanceParamsFilter { + /** + * Filter credit balance by currency. + */ + currency?: Common.StringFieldFilterExact; + + /** + * Filter credit balance by feature key. Omit to return the total portfolio value. + * Use `exists=false` to return only unrestricted balance. + */ + feature_key?: Common.StringFieldFilter; +} + +namespace Credits.Balance { + interface CustomerCreditBalancesOperations { + /** + * Get a credit balance. + */ + @extension(Shared.UnstableExtension, true) + @get + @operationId("get-customer-credit-balance") + @summary("Get a customer's credit balance") + get( + @path customerId: Shared.ULID, + + /** + * Return the credit balance as of this timestamp. + * + * Defaults to the current time. + */ + @query + timestamp?: Shared.DateTime, + + @query(#{ style: "deepObject", explode: true }) + filter?: GetCreditBalanceParamsFilter, + ): + | Shared.GetResponse + | Common.NotFound + | Common.ErrorResponses; + } +} + +/** + * Filter options for listing credit transactions. + */ +@friendlyName("ListCreditTransactionsParamsFilter") +model ListCreditTransactionsParamsFilter { + /** + * Filter credit transactions by type. + */ + type?: CreditTransactionType; + + /** + * Filter credit transactions by currency. + */ + currency?: Currencies.CurrencyCode; + + /** + * Filter credit transactions by feature key. Omit to return all credit + * transactions. Use `exists=false` to return only unrestricted credit + * transactions. + */ + feature_key?: Common.StringFieldFilter; + + // TODO: add date filters for created_at and booked_at +} + +namespace Credits.Transactions { + interface CustomerCreditTransactionOperations { + /** + * List credit transactions for a customer. + * + * Returns an immutable, chronological record of credit movements: funded credits + * and consumed credits. Transactions are returned in reverse chronological order + * by default. + */ + @extension(Shared.UnstableExtension, true) + @get + @operationId("list-credit-transactions") + @summary("List credit transactions") + list( + @path customerId: Shared.ULID, + ...Common.CursorPaginationQuery, + + /** + * Filter credit transactions returned in the response. + */ + @query(#{ style: "deepObject", explode: true }) + filter?: ListCreditTransactionsParamsFilter, + ): + | Shared.CursorPaginatedResponse + | Common.NotFound + | Common.ErrorResponses; + } +} + +namespace Credits.Adjustments { + interface CustomerCreditAdjustmentsOperations { + /** + * A credit adjustment can be used to make manual adjustments to a customer's + * credit balance. + * + * Supported use-cases: + * + * - Usage correction + */ + @extension(Shared.UnstableExtension, true) + @post + @operationId("create-credit-adjustment") + @summary("Create a credit adjustment") + create( + @path customerId: Shared.ULID, + @body credit_adjustment: Shared.CreateRequest, + ): + | Shared.CreateResponse + | Common.NotFound + | Common.ErrorResponses; + } +} diff --git a/api/spec/packages/aip/src/customers/customer.tsp b/api/spec/packages/aip/src/customers/customer.tsp new file mode 100644 index 0000000000000000000000000000000000000000..1b98366f0f9be42e56b1d007bbbbb565688204bb --- /dev/null +++ b/api/spec/packages/aip/src/customers/customer.tsp @@ -0,0 +1,90 @@ +import "../shared/index.tsp"; +import "../common/properties.tsp"; + +namespace Customers; + +/** + * Customers can be individuals or organizations that can subscribe to plans and + * have access to features. + */ +@friendlyName("BillingCustomer") +model Customer { + ...Shared.Resource; + + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + @visibility(Lifecycle.Create, Lifecycle.Read) + key: Shared.ExternalResourceKey; + + /** + * Mapping to attribute metered usage to the customer by the event subject. + */ + @visibility(Lifecycle.Create, Lifecycle.Read, Lifecycle.Update) + @summary("Usage Attribution") + usage_attribution?: CustomerUsageAttribution; + + /** + * The primary email address of the customer. + */ + @visibility(Lifecycle.Create, Lifecycle.Read, Lifecycle.Update) + @summary("Primary Email") + primary_email?: string; + + /** + * Currency of the customer. Used for billing, tax and invoicing. + */ + @visibility(Lifecycle.Create, Lifecycle.Read, Lifecycle.Update) + @summary("Currency") + currency?: Shared.CurrencyCode; + + /** + * The billing address of the customer. Used for tax and invoicing. + */ + @visibility(Lifecycle.Create, Lifecycle.Read, Lifecycle.Update) + @summary("Billing Address") + billing_address?: Shared.Address; +} + +/** + * Mapping to attribute metered usage to the customer. One customer can have zero + * or more subjects, but one subject can only belong to one customer. + */ +@friendlyName("BillingCustomerUsageAttribution") +model CustomerUsageAttribution { + /** + * The subjects that are attributed to the customer. Can be empty when no usage + * event subjects are associated with the customer. + */ + @visibility(Lifecycle.Create, Lifecycle.Read, Lifecycle.Update) + @summary("Subject Keys") + @minItems(0) + subject_keys: UsageAttributionSubjectKey[]; +} + +/** + * Subject key. + */ +@minLength(1) +@friendlyName("UsageAttributionSubjectKey") +scalar UsageAttributionSubjectKey extends string; + +/** + * Customer reference. + */ +@friendlyName("BillingCustomerReference") +model CustomerReference { + /** + * The ID of the customer. + */ + id: Shared.ULID; +} + +/** + * Customer reference by external key. + */ +@friendlyName("BillingCustomerKeyReference") +model CustomerKeyReference { + /** + * The external key of the customer. + */ + key: Shared.ExternalResourceKey; +} diff --git a/api/spec/packages/aip/src/customers/index.tsp b/api/spec/packages/aip/src/customers/index.tsp new file mode 100644 index 0000000000000000000000000000000000000000..1a5557a193674433a71affe6d4b173589cbd13d9 --- /dev/null +++ b/api/spec/packages/aip/src/customers/index.tsp @@ -0,0 +1,4 @@ +import "./customer.tsp"; +import "./operations.tsp"; +import "./credits/index.tsp"; +import "./charges/index.tsp"; diff --git a/api/spec/packages/aip/src/customers/operations.tsp b/api/spec/packages/aip/src/customers/operations.tsp new file mode 100644 index 0000000000000000000000000000000000000000..63c6c4f5f8a4ab44ce15bd709c38e9783ed9f45b --- /dev/null +++ b/api/spec/packages/aip/src/customers/operations.tsp @@ -0,0 +1,220 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "../common/error.tsp"; +import "../common/pagination.tsp"; +import "../common/parameters.tsp"; +import "../shared/index.tsp"; +import "./customer.tsp"; +import "./billing.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Customers; + +/** + * Filter options for listing customers. + */ +@friendlyName("ListCustomersParamsFilter") +model ListCustomersParamsFilter { + #suppress "@openmeter/api-spec-aip/doc-decorator" "filter field" + key?: Common.StringFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "filter field" + name?: Common.StringFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "filter field" + primary_email?: Common.StringFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "filter field" + usage_attribution_subject_key?: Common.StringFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "filter field" + plan_key?: Common.StringFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "filter field" + billing_profile_id?: Common.ULIDFieldFilter; +} + +interface CustomersOperations { + @post + @operationId("create-customer") + @summary("Create customer") + create( + @body + customer: Shared.CreateRequest, + ): Shared.CreateResponse | Common.ErrorResponses; + + @get + @operationId("get-customer") + @summary("Get customer") + get(@path customerId: Shared.ULID): + | Shared.GetResponse + | Common.NotFound + | Common.ErrorResponses; + + @get + @operationId("list-customers") + @summary("List customers") + list( + ...Common.PagePaginationQuery, + + /** + * Sort customers returned in the response. Supported sort attributes are: + * + * - `id` + * - `name` (default) + * - `created_at` + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ + @query(#{ name: "sort" }) + sort?: Common.SortQuery, + + /** + * Filter customers returned in the response. + * + * To filter customers by key add the following query param: filter[key]=my-db-id + */ + @query(#{ style: "deepObject", explode: true }) + filter?: ListCustomersParamsFilter, + ): Shared.PagePaginatedResponse | Common.ErrorResponses; + + @put + @operationId("upsert-customer") + @summary("Upsert customer") + upsert( + @path customerId: Shared.ULID, + + @body + customer: Shared.UpsertRequest, + ): + | Shared.UpsertResponse + | Common.Gone + | Common.NotFound + | Common.ErrorResponses; + + @delete + @operationId("delete-customer") + @summary("Delete customer") + delete(@path customerId: Shared.ULID): + | Shared.DeleteResponse + | Common.NotFound + | Common.ErrorResponses; +} + +namespace Billing { + interface CustomerBillingOperations { + @get + @operationId("get-customer-billing") + @summary("Get customer billing data") + get(@path customerId: Shared.ULID): + | Shared.GetResponse + | Common.NotFound + | Common.ErrorResponses; + + @put + @operationId("update-customer-billing") + @summary("Update customer billing data") + upsert( + @path customerId: Shared.ULID, + @body body: Shared.UpsertRequest, + ): + | Shared.UpsertResponse + | Common.Gone + | Common.NotFound + | Common.ErrorResponses; + + @put + @route("/app-data") + @operationId("update-customer-billing-app-data") + @summary("Update customer billing app data") + upsertAppData( + @path customerId: Shared.ULID, + @body body: Shared.UpsertRequest, + ): + | Shared.UpsertResponse + | Common.Gone + | Common.NotFound + | Common.ErrorResponses; + + /** + * Create a [Stripe Checkout Session](https://docs.stripe.com/payments/checkout) + * for the customer. + * + * Creates a Checkout Session for collecting payment method information from + * customers. The session operates in "setup" mode, which collects payment details + * without charging the customer immediately. The collected payment method can be + * used for future subscription billing. + * + * For hosted checkout sessions, redirect customers to the returned URL. For + * embedded sessions, use the client_secret to initialize Stripe.js in your + * application. + */ + @post + @route("/stripe/checkout-sessions") + @operationId("create-customer-stripe-checkout-session") + @summary("Create Stripe Checkout Session") + createCheckoutSession( + @path customerId: Shared.ULID, + @body body: CustomerBillingStripeCreateCheckoutSessionRequest, + ): + | Shared.CreateResponse + | Common.Gone + | Common.NotFound + | Common.ErrorResponses; + + /** + * Create Stripe Customer Portal Session. + * + * Useful to redirect the customer to the Stripe Customer Portal to manage their + * payment methods, change their billing address and access their invoice history. + * Only returns URL if the customer billing profile is linked to a stripe app and + * customer. + */ + @post + @route("/stripe/portal-sessions") + @operationId("create-customer-stripe-portal-session") + @summary("Create Stripe customer portal session") + createPortalSession( + @path customerId: Shared.ULID, + @body body: CustomerBillingStripeCreateCustomerPortalSessionRequest, + ): + | Shared.CreateResponse + | Common.Gone + | Common.NotFound + | Common.ErrorResponses; + } +} + +/** + * Request to create a Stripe Checkout Session for the customer. + * + * Checkout Sessions are used to collect payment method information from customers + * in a secure, Stripe-hosted interface. This integration uses setup mode to + * collect payment methods that can be charged later for subscription billing. + */ +@friendlyName("BillingCustomerStripeCreateCheckoutSessionRequest") +model CustomerBillingStripeCreateCheckoutSessionRequest { + /** + * Options for configuring the Stripe Checkout Session. + * + * These options are passed directly to Stripe's + * [checkout session creation API](https://docs.stripe.com/api/checkout/sessions/create). + */ + stripe_options: Apps.CreateStripeCheckoutSessionRequestOptions; +} + +/** + * Request to create a Stripe Customer Portal Session for the customer. + * + * Useful to redirect the customer to the Stripe Customer Portal to manage their + * payment methods, change their billing address and access their invoice history. + * Only returns URL if the customer billing profile is linked to a stripe app and + * customer. + */ +@friendlyName("BillingCustomerStripeCreateCustomerPortalSessionRequest") +model CustomerBillingStripeCreateCustomerPortalSessionRequest { + /** + * Options for configuring the Stripe Customer Portal Session. + */ + stripe_options: Apps.CreateStripeCustomerPortalSessionOptions; +} diff --git a/api/spec/packages/aip/src/defaults/index.tsp b/api/spec/packages/aip/src/defaults/index.tsp new file mode 100644 index 0000000000000000000000000000000000000000..180c93c7919fb36b2f83923ab87bdc40edc4d21e --- /dev/null +++ b/api/spec/packages/aip/src/defaults/index.tsp @@ -0,0 +1,2 @@ +import "./taxcodes.tsp"; +import "./operations.tsp"; diff --git a/api/spec/packages/aip/src/defaults/operations.tsp b/api/spec/packages/aip/src/defaults/operations.tsp new file mode 100644 index 0000000000000000000000000000000000000000..758b93b27a7c6518633abe2d337c634beccc9732 --- /dev/null +++ b/api/spec/packages/aip/src/defaults/operations.tsp @@ -0,0 +1,32 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "../common/error.tsp"; +import "../shared/index.tsp"; +import "./taxcodes.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Defaults; + +interface OrganizationDefaultTaxCodesOperations { + @get + @operationId("get-organization-default-tax-codes") + @summary("Get organization default tax codes") + @extension(Shared.UnstableExtension, true) + get(): + | Shared.GetResponse + | Common.NotFound + | Common.ErrorResponses; + + @put + @operationId("update-organization-default-tax-codes") + @summary("Update organization default tax codes") + @extension(Shared.UnstableExtension, true) + update(@body body: Shared.UpdateRequest): + | Shared.UpsertResponse + | Common.NotFound + | Common.ErrorResponses; +} diff --git a/api/spec/packages/aip/src/defaults/taxcodes.tsp b/api/spec/packages/aip/src/defaults/taxcodes.tsp new file mode 100644 index 0000000000000000000000000000000000000000..56fc3c669060280831ff865421221ceeb1a34267 --- /dev/null +++ b/api/spec/packages/aip/src/defaults/taxcodes.tsp @@ -0,0 +1,37 @@ +import "../shared/index.tsp"; +import "../tax/codes.tsp"; + +namespace Defaults; + +/** + * Organization-level default tax code references. + * + * Stores the default tax codes applied to specific billing contexts for this + * organization. Provisioned automatically when the organization is created. + */ +@friendlyName("OrganizationDefaultTaxCodes") +model OrganizationDefaultTaxCodes { + /** + * Default tax code for invoicing. + */ + @summary("Invoicing tax code") + invoicing_tax_code: Shared.ResourceReference; + + /** + * Default tax code for credit grants. + */ + @summary("Credit grant tax code") + credit_grant_tax_code: Shared.ResourceReference; + + /** + * Timestamp of creation. + */ + @visibility(Lifecycle.Read) + created_at: Shared.DateTime; + + /** + * Timestamp of last update. + */ + @visibility(Lifecycle.Read) + updated_at: Shared.DateTime; +} diff --git a/api/spec/packages/aip/src/entitlements/access.tsp b/api/spec/packages/aip/src/entitlements/access.tsp new file mode 100644 index 0000000000000000000000000000000000000000..6270c42eeb6229e2dc6b6d30c6ce272eba7dcec4 --- /dev/null +++ b/api/spec/packages/aip/src/entitlements/access.tsp @@ -0,0 +1,40 @@ +import "./entitlements.tsp"; +import "../shared/index.tsp"; + +namespace Entitlements; + +/** + * Entitlement access result. + */ +@friendlyName("BillingEntitlementAccessResult") +model EntitlementAccessResult { + /** + * The type of the entitlement. + */ + @example(EntitlementType.Static) + @visibility(Lifecycle.Read) + type: EntitlementType; + + /** + * The feature key of the entitlement. + */ + @example("available_models") + @visibility(Lifecycle.Read) + feature_key: Shared.ResourceKey; + + /** + * Whether the customer has access to the feature. Always true for `boolean` and + * `static` entitlements. Depends on balance for `metered` entitlements. + */ + @example(true) + @visibility(Lifecycle.Read) + has_access: boolean; + + /** + * Only available for static entitlements. Config is the JSON parsable + * configuration of the entitlement. Useful to describe per customer configuration. + */ + @example("{ \"availableModels\": [\"gpt-5\", \"gpt-4o\"] }") + @visibility(Lifecycle.Read) + config?: string; +} diff --git a/api/spec/packages/aip/src/entitlements/entitlements.tsp b/api/spec/packages/aip/src/entitlements/entitlements.tsp new file mode 100644 index 0000000000000000000000000000000000000000..b9538671cbce5775cd8fddcc9d2d31b4c896f9e4 --- /dev/null +++ b/api/spec/packages/aip/src/entitlements/entitlements.tsp @@ -0,0 +1,105 @@ +import "../shared/index.tsp"; + +namespace Entitlements; + +/** + * The type of the entitlement. + */ +@friendlyName("BillingEntitlementType") +enum EntitlementType { + Metered: "metered", + Static: "static", + Boolean: "boolean", +} + +/** + * Entitlement template configured on a rate card. The feature is taken from the + * rate card itself, so it is omitted here. + */ +@friendlyName("BillingRateCardEntitlement") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union RateCardEntitlement { + @summary("Metered entitlement") + metered: RateCardMeteredEntitlement, + + @summary("Static entitlement") + static: RateCardStaticEntitlement, + + @summary("Boolean entitlement") + boolean: RateCardBooleanEntitlement, +} + +/** + * The entitlement template of a metered entitlement. + */ +@friendlyName("BillingRateCardMeteredEntitlement") +model RateCardMeteredEntitlement { + /** + * The type of the entitlement template. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Type") + type: Entitlements.EntitlementType.Metered; + + /** + * If soft limit is true, the subject can use the feature even if the entitlement + * is exhausted; access remains granted. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Soft limit") + is_soft_limit?: boolean = false; + + /** + * The amount of usage granted each usage period, in the feature's unit. Usage is + * counted against this allowance and the balance resets every usage period. When + * `is_soft_limit` is true the subject keeps access after the limit is reached; + * otherwise access is denied once the allowance is exhausted. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Usage limit") + @minValue(0) + limit?: float64; + + /** + * The reset interval of the metered entitlement in ISO8601 format. Defaults to the + * billing cadence of the rate card. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Usage period") + usage_period?: Shared.ISO8601Duration; +} + +/** + * The entitlement template of a static entitlement. + */ +@friendlyName("BillingRateCardStaticEntitlement") +model RateCardStaticEntitlement { + /** + * The type of the entitlement template. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Type") + type: Entitlements.EntitlementType.Static; + + /** + * The entitlement config as a JSON object. Returned when checking entitlement + * access; useful for configuring fine-grained access settings implemented in your + * own system. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Config") + config: unknown; +} + +/** + * The entitlement template of a boolean entitlement. + */ +@friendlyName("BillingRateCardBooleanEntitlement") +model RateCardBooleanEntitlement { + /** + * The type of the entitlement template. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Type") + type: Entitlements.EntitlementType.Boolean; +} diff --git a/api/spec/packages/aip/src/entitlements/index.tsp b/api/spec/packages/aip/src/entitlements/index.tsp new file mode 100644 index 0000000000000000000000000000000000000000..b1a9fd9257178f01789b4c045ce09ef847a9d792 --- /dev/null +++ b/api/spec/packages/aip/src/entitlements/index.tsp @@ -0,0 +1,3 @@ +import "./entitlements.tsp"; +import "./access.tsp"; +import "./operations.tsp"; diff --git a/api/spec/packages/aip/src/entitlements/operations.tsp b/api/spec/packages/aip/src/entitlements/operations.tsp new file mode 100644 index 0000000000000000000000000000000000000000..20ab756b39d2978f89925f5950357b87b5d2ab30 --- /dev/null +++ b/api/spec/packages/aip/src/entitlements/operations.tsp @@ -0,0 +1,43 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "../common/error.tsp"; +import "../shared/index.tsp"; +import "./access.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Entitlements; + +/** + * List the customer's active features and their access. + */ +@friendlyName("ListCustomerEntitlementAccessResponse") +model ListCustomerEntitlementAccessResponse { + @Http.statusCode _: 200; + @body body: ListCustomerEntitlementAccessResponseData; +} + +/** + * List customer entitlement access response data. + */ +@friendlyName("ListCustomerEntitlementAccessResponseData") +model ListCustomerEntitlementAccessResponseData { + /** + * The list of entitlement access results. + */ + @visibility(Lifecycle.Read) + data: EntitlementAccessResult[]; +} + +interface CustomerEntitlementsOperations { + @get + @operationId("list-customer-entitlement-access") + @summary("List customer entitlement access") + list(@path customerId: Shared.ULID): + | ListCustomerEntitlementAccessResponse + | Common.NotFound + | Common.ErrorResponses; +} diff --git a/api/spec/packages/aip/src/events/event.tsp b/api/spec/packages/aip/src/events/event.tsp new file mode 100644 index 0000000000000000000000000000000000000000..b4fd2218619c5fd3a23f7dda9ad6688d0e92fb29 --- /dev/null +++ b/api/spec/packages/aip/src/events/event.tsp @@ -0,0 +1,160 @@ +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "../shared/index.tsp"; + +namespace Events; + +/** + * Metering event following the CloudEvents specification. + */ +@friendlyName("MeteringEvent") +@summary("Metering Event") +@example(#{ + specversion: "1.0", + id: "5c10fade-1c9e-4d6c-8275-c52c36731d3c", + source: "service-name", + type: "prompt", + subject: "customer-id", + time: Shared.DateTime.fromISO("2023-01-01T01:01:01.001Z"), + data: #{ + prompt: "Hello, world!", + tokens: 100, + `model`: "gpt-4o", + type: "input", + }, +}) +model MeteringEvent { + /** + * Identifies the event. + */ + @minLength(1) + @example("5c10fade-1c9e-4d6c-8275-c52c36731d3c") + id: string; + + /** + * Identifies the context in which an event happened. + */ + @minLength(1) + @format("uri-reference") + @example("service-name") + source: string; + + /** + * The version of the CloudEvents specification which the event uses. + */ + @minLength(1) + @example("1.0") + specversion: string = "1.0"; + + /** + * Contains a value describing the type of event related to the originating + * occurrence. + */ + @minLength(1) + @example("com.example.someevent") + type: string; + + /** + * Content type of the CloudEvents data value. Only the value "application/json" is + * allowed over HTTP. + */ + @example("application/json") + datacontenttype?: "application/json" | null; + + /** + * Identifies the schema that data adheres to. + */ + @minLength(1) + dataschema?: url | null; + + /** + * Describes the subject of the event in the context of the event producer + * (identified by source). + */ + @minLength(1) + @example("customer-id") + subject: string; + + /** + * Timestamp of when the occurrence happened. Must adhere to RFC 3339. + */ + @example(Shared.DateTime.fromISO("2023-01-01T01:01:01.001Z")) + time?: Shared.DateTime | null; + + /** + * The event payload. Optional, if present it must be a JSON object. + */ + data?: Record | null; +} + +/** + * An ingested metering event with ingestion metadata. + */ +@friendlyName("MeteringIngestedEvent") +@summary("Ingested Event") +@example(#{ + event: #{ + id: "5c10fade-1c9e-4d6c-8275-c52c36731d3c", + source: "service-name", + specversion: "1.0", + type: "prompt", + subject: "customer_key", + time: Shared.DateTime.fromISO("2023-01-01T01:01:01.001Z"), + }, + customer: #{ id: "01G65Z755AFWAKHE12NY0CQ9FH" }, + ingested_at: Shared.DateTime.fromISO("2023-01-01T01:01:01.001Z"), + stored_at: Shared.DateTime.fromISO("2023-01-01T01:01:02.001Z"), +}) +model IngestedEvent { + /** + * The original event ingested. + */ + event: MeteringEvent; + + /** + * The customer if the event is associated with a customer. + */ + customer?: Shared.ResourceReference; + + /** + * The date and time the event was ingested and its processing started. + */ + ingested_at: Shared.DateTime; + + /** + * The date and time the event was stored in the database. + */ + stored_at: Shared.DateTime; + + /** + * The validation errors of the ingested event. + */ + validation_errors?: IngestedEventValidationError[]; +} + +/** + * Event validation errors. + */ +@friendlyName("MeteringIngestedEventValidationError") +model IngestedEventValidationError { + /** + * The machine readable code of the error. + */ + @visibility(Lifecycle.Read) + @summary("Code") + code: string; + + /** + * The human readable description of the error. + */ + @visibility(Lifecycle.Read) + @summary("Message") + message: string; + + /** + * Additional attributes. + */ + @visibility(Lifecycle.Read) + @summary("Attributes") + attributes?: Record; +} diff --git a/api/spec/packages/aip/src/events/index.tsp b/api/spec/packages/aip/src/events/index.tsp new file mode 100644 index 0000000000000000000000000000000000000000..bfbcb1c5545f16662806b2d9d90e4b9408a77c6a --- /dev/null +++ b/api/spec/packages/aip/src/events/index.tsp @@ -0,0 +1,2 @@ +import "./event.tsp"; +import "./operations.tsp"; diff --git a/api/spec/packages/aip/src/events/operations.tsp b/api/spec/packages/aip/src/events/operations.tsp new file mode 100644 index 0000000000000000000000000000000000000000..834372b8462ba11b1d34d170f081852906c20e16 --- /dev/null +++ b/api/spec/packages/aip/src/events/operations.tsp @@ -0,0 +1,134 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "../common/error.tsp"; +import "../common/pagination.tsp"; +import "../common/parameters.tsp"; +import "../shared/index.tsp"; +import "./event.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Events; + +/** + * The events have been ingested and are being processed asynchronously. + */ +@friendlyName("IngestEventsResponse") +model IngestEventsResponse { + @statusCode _: 202; +} + +/** + * Filter options for listing ingested events. + */ +@friendlyName("ListEventsParamsFilter") +model ListEventsParamsFilter { + /** + * Filter events by ID. + */ + id?: Common.StringFieldFilter; + + /** + * Filter events by source. + */ + source?: Common.StringFieldFilter; + + /** + * Filter events by subject. + */ + subject?: Common.StringFieldFilter; + + /** + * Filter events by type. + */ + type?: Common.StringFieldFilter; + + /** + * Filter events by the associated customer ID. + */ + customer_id?: Common.ULIDFieldFilter; + + /** + * Filter events by event time. + */ + time?: Common.DateTimeFieldFilter; + + /** + * Filter events by the time the event was ingested. + */ + ingested_at?: Common.DateTimeFieldFilter; + + /** + * Filter events by the time the event was stored. + */ + stored_at?: Common.DateTimeFieldFilter; +} + +interface EventsOperations { + /** + * List ingested events. + */ + @extension(Shared.UnstableExtension, true) + @get + @operationId("list-metering-events") + @summary("List metering events") + list( + ...Common.CursorPaginationQuery, + + /** + * Filter events returned in the response. + * + * To filter events by subject add the following query param: + * filter[subject][eq]=customer-1 + */ + @query(#{ style: "deepObject", explode: true }) + filter?: ListEventsParamsFilter, + + /** + * Sort events returned in the response. Supported sort attributes are: + * + * - `time` (default) + * - `ingested_at` + * - `stored_at` + * + * When omitted, events are sorted by `time desc` (most recent first). When a sort + * field is provided without a suffix, it sorts descending. Append the `asc` suffix + * to sort ascending, or the `desc` suffix to sort descending. + */ + @query + sort?: Common.SortQuery, + ): Shared.CursorPaginatedResponse | Common.ErrorResponses; + + /** + * Ingests an event or batch of events following the CloudEvents specification. + */ + @post + @operationId("ingest-metering-events") + @summary("Ingest metering events") + @sharedRoute + ingestEvent( + @header contentType: "application/cloudevents+json", + @body body: MeteringEvent, + ): IngestEventsResponse | Common.ErrorResponses; + + @post + @operationId("ingest-metering-events") + @summary("") + @sharedRoute + ingestEvents( + @header contentType: "application/cloudevents-batch+json", + @body body: MeteringEvent[], + ): IngestEventsResponse | Common.ErrorResponses; + + @post + @operationId("ingest-metering-events") + @summary("") + @sharedRoute + ingestEventsJson( + @header contentType: "application/json", + @body body: MeteringEvent | MeteringEvent[], + ): IngestEventsResponse | Common.ErrorResponses; +} diff --git a/api/spec/packages/aip/src/features/cost.tsp b/api/spec/packages/aip/src/features/cost.tsp new file mode 100644 index 0000000000000000000000000000000000000000..f861f2ab9da0e09ac85ab19ded6c12c7f95a9be0 --- /dev/null +++ b/api/spec/packages/aip/src/features/cost.tsp @@ -0,0 +1,71 @@ +import "@typespec/json-schema"; +import "../shared/index.tsp"; +import "../meters/query.tsp"; + +namespace Features; + +/** + * A row in the result of a feature cost query. + */ +@friendlyName("FeatureCostQueryRow") +model FeatureCostQueryRow { + /** + * The metered usage value for the period. + */ + usage: Shared.Numeric; + + /** + * The computed cost amount (usage × unit cost). Null when pricing is not available + * for the given combination of dimensions. + */ + #suppress "@openmeter/api-spec-aip/no-nullable" "cost is nullable" + cost: Shared.Numeric | null; + + /** + * The currency code of the cost amount. + */ + currency: Shared.CurrencyCode; + + /** + * Detail message when cost amount is null, explaining why the cost could not be + * resolved. + */ + detail?: string; + + /** + * The start of the time bucket the value is aggregated over. + */ + from: Shared.DateTime; + + /** + * The end of the time bucket the value is aggregated over. + */ + to: Shared.DateTime; + + /** + * The dimensions the value is aggregated over. `subject` and `customer_id` are + * reserved dimensions. + */ + dimensions: Record; +} + +/** + * Result of a feature cost query. + */ +@friendlyName("FeatureCostQueryResult") +model FeatureCostQueryResult { + /** + * Start of the queried period. + */ + from?: Shared.DateTime; + + /** + * End of the queried period. + */ + to?: Shared.DateTime; + + /** + * The cost data rows. + */ + data: FeatureCostQueryRow[]; +} diff --git a/api/spec/packages/aip/src/features/feature.tsp b/api/spec/packages/aip/src/features/feature.tsp new file mode 100644 index 0000000000000000000000000000000000000000..bae7beee64ce9603667fff99f511ba35343d9207 --- /dev/null +++ b/api/spec/packages/aip/src/features/feature.tsp @@ -0,0 +1,69 @@ +import "../shared/index.tsp"; +import "../meters/index.tsp"; +import "./unitcost.tsp"; +import "@typespec/json-schema"; + +using TypeSpec.JsonSchema; + +namespace Features; + +/** + * Reference to a meter associated with a feature. + */ +@friendlyName("FeatureMeterReference") +model FeatureMeterReference { + /** + * The ID of the meter to associate with this feature. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Meter ID") + id: Shared.ULID; + + /** + * Filters to apply to the dimensions of the meter. + */ + @maxProperties(10) + @summary("Meter dimensions filters") + filters?: Record; +} + +/** + * A capability or billable dimension offered by a provider. + */ +@friendlyName("Feature") +model Feature { + ...Shared.ResourceWithKey; + + /** + * The meter that the feature is associated with and based on which usage is + * calculated. If not specified, the feature is static. + */ + @summary("Meter reference") + @visibility(Lifecycle.Read, Lifecycle.Create) + meter?: FeatureMeterReference; + + /** + * Optional per-unit cost configuration. Use "manual" for a fixed per-unit cost, or + * "llm" to look up cost from the LLM cost database based on meter group-by + * properties. + */ + @summary("Unit cost") + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + unit_cost?: FeatureUnitCost; +} + +/** + * Request body for updating a feature. Currently only the unit_cost field can be + * updated. + */ +@friendlyName("UpdateFeatureRequest") +model FeatureUpdateRequest { + /** + * Optional per-unit cost configuration. Use "manual" for a fixed per-unit cost, or + * "llm" to look up cost from the LLM cost database based on meter group-by + * properties. Set to `null` to clear the existing unit cost; omit to leave it + * unchanged. + */ + @summary("Unit cost") + unit_cost?: FeatureUnitCost | null; +} diff --git a/api/spec/packages/aip/src/features/index.tsp b/api/spec/packages/aip/src/features/index.tsp new file mode 100644 index 0000000000000000000000000000000000000000..9b300551aff10f244c52072fac72f3db3bdaf5d5 --- /dev/null +++ b/api/spec/packages/aip/src/features/index.tsp @@ -0,0 +1,6 @@ +import "./cost.tsp"; +import "./unitcost.tsp"; +import "./operations.tsp"; +import "./feature.tsp"; + +namespace Features; diff --git a/api/spec/packages/aip/src/features/operations.tsp b/api/spec/packages/aip/src/features/operations.tsp new file mode 100644 index 0000000000000000000000000000000000000000..482473837bffd1166d7d529c2f51a5caff2b4e3b --- /dev/null +++ b/api/spec/packages/aip/src/features/operations.tsp @@ -0,0 +1,130 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "../common/error.tsp"; +import "../shared/index.tsp"; +import "../meters/query.tsp"; +import "./cost.tsp"; +import "./feature.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Features; + +/** + * Filter options for listing features. + */ +@friendlyName("ListFeatureParamsFilter") +model ListFeaturesParamsFilter { + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + meter_id?: Common.ULIDFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + key?: Common.StringFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + name?: Common.StringFieldFilter; +} + +interface FeatureOperations { + /** + * List all features. + */ + @get + @operationId("list-features") + @summary("List features") + @extension(Shared.UnstableExtension, true) + list( + ...Common.PagePaginationQuery, + + /** + * Sort features returned in the response. Supported sort attributes are: + * + * - `key` + * - `name` + * - `created_at` (default) + * - `updated_at` + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ + @query(#{ name: "sort" }) + sort?: Common.SortQuery, + + /** + * Filter features returned in the response. + * + * To filter features by meter_id add the following query param: + * filter[meter_id][oeq]= + */ + @query(#{ style: "deepObject", explode: true }) + filter?: ListFeaturesParamsFilter, + ): Shared.PagePaginatedResponse | Common.ErrorResponses; + + /** + * Create a feature. + */ + @post + @operationId("create-feature") + @summary("Create feature") + @extension(Shared.UnstableExtension, true) + create( + @body + feature: Shared.CreateRequest, + ): Shared.CreateResponse | Common.ErrorResponses; + + /** + * Get a feature by id. + */ + @get + @route("/{featureId}") + @operationId("get-feature") + @summary("Get feature") + @extension(Shared.UnstableExtension, true) + get(@path featureId: Shared.ULID): + | Shared.GetResponse + | Common.ErrorResponses + | Common.Gone + | Common.NotFound; + + /** + * Update a feature by id. Currently only the unit_cost field can be updated. + */ + @patch + @route("/{featureId}") + @operationId("update-feature") + @summary("Update feature") + @extension(Shared.UnstableExtension, true) + update(@path featureId: Shared.ULID, @body feature: FeatureUpdateRequest): + | Shared.UpdateResponse + | Common.ErrorResponses + | Common.NotFound; + + /** + * Delete a feature by id. + */ + @delete + @route("/{featureId}") + @operationId("delete-feature") + @summary("Delete feature") + @extension(Shared.UnstableExtension, true) + delete(@path featureId: Shared.ULID): + | Shared.DeleteResponse + | Common.ErrorResponses + | Common.NotFound; +} + +interface FeatureCostOperations { + /** + * Query the cost of a feature. + */ + @extension(Shared.UnstableExtension, true) + @post + @route("/query") + @operationId("query-feature-cost") + @summary("Query feature cost") + queryCost( + @path featureId: Shared.ULID, + @body request?: Meters.MeterQueryRequest, + ): FeatureCostQueryResult | Common.NotFound | Common.ErrorResponses; +} diff --git a/api/spec/packages/aip/src/features/unitcost.tsp b/api/spec/packages/aip/src/features/unitcost.tsp new file mode 100644 index 0000000000000000000000000000000000000000..f9def3fbe64d98fd9ad08702a363637f9843b428 --- /dev/null +++ b/api/spec/packages/aip/src/features/unitcost.tsp @@ -0,0 +1,163 @@ +import "../shared/index.tsp"; + +namespace Features; + +/** + * The type of unit cost. + */ +@friendlyName("BillingFeatureUnitCostType") +enum FeatureUnitCostType { + Llm: "llm", + Manual: "manual", +} + +/** + * A fixed per-unit cost amount. + */ +@friendlyName("BillingFeatureManualUnitCost") +model FeatureManualUnitCost { + /** + * The type discriminator for manual unit cost. + */ + type: FeatureUnitCostType.Manual; + + /** + * Fixed per-unit cost amount in USD. + */ + amount: Shared.Numeric; +} + +/** + * Token type for LLM cost lookup. + */ +@friendlyName("BillingFeatureLLMTokenType") +enum FeatureLlmTokenType { + Input: "input", + Output: "output", + CacheRead: "cache_read", + CacheWrite: "cache_write", + Reasoning: "reasoning", + + /** Alias for `input`. */ + Request: "request", + + /** Alias for `output`. */ + Response: "response", +} + +/** + * LLM cost lookup configuration. Each dimension (provider, model, token type) can + * be specified as either a static value or a meter group-by property name + * (mutually exclusive). + */ +#suppress "@openmeter/api-spec-aip/repeated-prefix-grouping" "token_type and token_type_property are distinct API fields, not a groupable prefix" +@friendlyName("BillingFeatureLLMUnitCost") +model FeatureLlmUnitCost { + /** + * The type discriminator for LLM unit cost. + */ + type: FeatureUnitCostType.Llm; + + /** + * Meter group-by property that holds the LLM provider. Use this when the meter has + * a group-by dimension for provider. Mutually exclusive with `provider`. + */ + @summary("Provider property") + provider_property?: string; + + /** + * Static LLM provider value (e.g., "openai", "anthropic"). Use this when the + * feature tracks a single provider. Mutually exclusive with `provider_property`. + */ + @summary("Provider") + provider?: string; + + /** + * Meter group-by property that holds the model ID. Use this when the meter has a + * group-by dimension for model. Mutually exclusive with `model`. + */ + @summary("Model property") + model_property?: string; + + /** + * Static model ID value (e.g., "gpt-4", "claude-3-5-sonnet"). Use this when the + * feature tracks a single model. Mutually exclusive with `model_property`. + */ + @summary("Model") + `model`?: string; + + /** + * Meter group-by property that holds the token type. Use this when the meter has a + * group-by dimension for token type. Mutually exclusive with `token_type`. + */ + @summary("Token type property") + token_type_property?: string; + + /** + * Static token type value. Use this when the feature tracks a single token type + * (e.g., only input tokens). `request` is an alias for `input`, `response` is an + * alias for `output`. Mutually exclusive with `token_type_property`. + */ + @summary("Token type") + token_type?: FeatureLlmTokenType; + + /** + * Resolved per-token pricing from the LLM cost database. Populated in responses + * when the provider and model can be determined, either from static values or from + * meter group-by filters with exact matches. + */ + @summary("Resolved pricing") + @visibility(Lifecycle.Read) + pricing?: FeatureLlmUnitCostPricing; +} + +/** + * Resolved per-token pricing from the LLM cost database. + */ +#suppress "@openmeter/api-spec-aip/repeated-prefix-grouping" "cache_read and cache_write are distinct pricing dimensions" +@friendlyName("BillingFeatureLLMUnitCostPricing") +model FeatureLlmUnitCostPricing { + /** + * Cost per input token in USD. + */ + @summary("Input per token") + input_per_token: Shared.Numeric; + + /** + * Cost per output token in USD. + */ + @summary("Output per token") + output_per_token: Shared.Numeric; + + /** + * Cost per cache read token in USD. + */ + @summary("Cache read per token") + cache_read_per_token?: Shared.Numeric; + + /** + * Cost per reasoning token in USD. + */ + @summary("Reasoning per token") + reasoning_per_token?: Shared.Numeric; + + /** + * Cost per cache write token in USD. + */ + @summary("Cache write per token") + cache_write_per_token?: Shared.Numeric; +} + +/** + * Per-unit cost configuration for a feature. Either a fixed manual amount or a + * dynamic LLM cost lookup. + */ +@friendlyName("BillingFeatureUnitCost") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union FeatureUnitCost { + @summary("Manual unit cost") + manual: FeatureManualUnitCost, + + @summary("LLM unit cost") + llm: FeatureLlmUnitCost, +} diff --git a/api/spec/packages/aip/src/governance/governance.tsp b/api/spec/packages/aip/src/governance/governance.tsp new file mode 100644 index 0000000000000000000000000000000000000000..e53e66b8e94e6f7e1c67b2152c990a15640535fa --- /dev/null +++ b/api/spec/packages/aip/src/governance/governance.tsp @@ -0,0 +1,227 @@ +import "../shared/index.tsp"; +import "../common/pagination.tsp"; +import "../customers/customer.tsp"; + +namespace Governance; + +/** + * List of customer identifiers to evaluate access for. + */ +@friendlyName("GovernanceQueryRequestCustomers") +model GovernanceQueryRequestCustomers { + /** + * Each entry can be a customer `key` or a usage-attribution subject `key`. + * Identifiers that cannot be resolved to a customer are reported in the response + * `errors` array. + */ + @summary("Customer keys and usage-attribution subjects") + @minItems(1) + @maxItems(100) + keys: string[]; +} + +/** + * Optional list of feature keys to evaluate access for. If omitted, all features + * available in the organization are returned. Providing this list is recommended + * to reduce the response size and the load on the backend services. + */ +@friendlyName("GovernanceQueryRequestFeatures") +model GovernanceQueryRequestFeatures { + /** + * List of feature keys to evaluate access for. + */ + @summary("Feature Keys") + @minItems(1) + @maxItems(100) + keys: string[]; +} + +/** + * Query to evaluate feature access for a list of customers. + */ +@friendlyName("GovernanceQueryRequest") +model GovernanceQueryRequest { + /** + * Whether to include credit balance availability for each resolved customer. When + * true, each feature evaluation includes credit balance checks. + * + * Defaults to `false`. + */ + @summary("Include credits") + include_credits?: boolean = false; + + #suppress "@openmeter/api-spec-aip/doc-decorator" "-" + @summary("Customer") + customer: GovernanceQueryRequestCustomers; + + #suppress "@openmeter/api-spec-aip/doc-decorator" "-" + @summary("Feature") + feature?: GovernanceQueryRequestFeatures; +} + +/** + * Response of the governance query. + */ +@friendlyName("GovernanceQueryResponse") +model GovernanceQueryResponse { + /** + * Access evaluation results, one entry per resolved customer. + */ + @visibility(Lifecycle.Read) + @summary("Data") + data: GovernanceQueryResult[]; + + /** + * Partial errors encountered while processing the request. + */ + @visibility(Lifecycle.Read) + @summary("Errors") + errors: GovernanceQueryError[]; + + /** + * Pagination metadata. The endpoint may return a partial response if the full + * response would exceed server-side limits. + */ + @visibility(Lifecycle.Read) + @summary("Meta") + meta: Common.CursorMeta; +} + +/** + * Access evaluation result for a single resolved customer. + */ +@friendlyName("GovernanceQueryResult") +model GovernanceQueryResult { + /** + * The list of identifiers from the request that resolved to this customer. Each + * entry is either the customer `key` or one of its usage-attribution subject + * `key`s. + * + * Duplicate or aliased identifiers that resolve to the same customer collapse to a + * single result entry, with every requested identifier listed here. + */ + @visibility(Lifecycle.Read) + @summary("Matched identifiers") + matched: string[]; + + /** + * The customer the matched identifiers resolved to. + */ + @visibility(Lifecycle.Read) + @summary("Customer") + customer: Customers.Customer; + + /** + * Map of features with their access status. + * + * Map keys are the feature keys requested in `feature.keys`, or every feature + * `key` available in the organization when the feature filter was omitted. + */ + @visibility(Lifecycle.Read) + @summary("Features") + features: Record; + + /** + * Timestamp of the most recent change to the customer's access state reflected in + * this result. + */ + @visibility(Lifecycle.Read) + @summary("Updated at") + updated_at: Shared.DateTime; +} + +/** + * Access status for a single feature. + */ +@friendlyName("GovernanceFeatureAccess") +model GovernanceFeatureAccess { + /** + * Whether the customer currently has access to the feature. + * + * `true` for boolean and static entitlements that are available, and for metered + * entitlements with remaining balance. `false` when the feature is unavailable, + * the usage limit has been reached, or (when applicable) credits have been + * exhausted. + */ + @visibility(Lifecycle.Read) + @summary("Has access") + has_access: boolean; + + /** + * Optional reason when the customer does not have access to the feature. Populated + * when `has_access` is `false`. + */ + @visibility(Lifecycle.Read) + @summary("Reason") + reason?: GovernanceFeatureAccessReason; +} + +/** + * Reason a feature is not accessible to a customer. + */ +@friendlyName("GovernanceFeatureAccessReason") +model GovernanceFeatureAccessReason + is Shared.BaseError; + +/** + * Machine-readable reason code for denied feature access. + */ +@friendlyName("GovernanceFeatureAccessReasonCode") +enum GovernanceFeatureAccessReasonCode { + /** + * Default zero value. Reserved for forward compatibility. + */ + Unknown: "unknown", + + /** + * The customer has reached the metered usage limit for the feature + * within the current usage period. + */ + UsageLimitReached: "usage_limit_reached", + + /** + * The feature is not available to the customer. + */ + FeatureUnavailable: "feature_unavailable", + + /** + * The feature `key` referenced by the request is not configured in the + * organization. + */ + FeatureNotFound: "feature_not_found", + + /** + * The customer has no available prepaid credit balance. + */ + NoCreditAvailable: "no_credit_available", +} + +/** + * Query error within a partially successful governance query response. + */ +@friendlyName("GovernanceQueryError") +model GovernanceQueryError is Shared.BaseError { + /** + * The customer identifier from the request that produced this error. + */ + @visibility(Lifecycle.Read) + @summary("Customer identifier") + customer?: string; +} + +/** + * Error code for a governance query failure. + */ +@friendlyName("GovernanceQueryErrorCode") +enum GovernanceQueryErrorCode { + /** + * Default zero value. Reserved for forward compatibility. + */ + Unknown: "unknown", + + /** + * The provided identifier could not be resolved to any customer + * (neither by customer `key` nor by a usage-attribution subject `key`). + */ + CustomerNotFound: "customer_not_found", +} diff --git a/api/spec/packages/aip/src/governance/index.tsp b/api/spec/packages/aip/src/governance/index.tsp new file mode 100644 index 0000000000000000000000000000000000000000..a1d975c49349207b66cbe378c48f4d0a5fe5afaf --- /dev/null +++ b/api/spec/packages/aip/src/governance/index.tsp @@ -0,0 +1,4 @@ +import "./governance.tsp"; +import "./operations.tsp"; + +namespace Governance; diff --git a/api/spec/packages/aip/src/governance/operations.tsp b/api/spec/packages/aip/src/governance/operations.tsp new file mode 100644 index 0000000000000000000000000000000000000000..684ab18629ec5df314a3676c018cd05d52725d49 --- /dev/null +++ b/api/spec/packages/aip/src/governance/operations.tsp @@ -0,0 +1,35 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "../common/error.tsp"; +import "../shared/index.tsp"; +import "./governance.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Governance; + +interface GovernanceOperations { + /** + * Query feature access for a list of customers. + * + * The endpoint resolves each provided identifier to a customer and returns the + * access status for the requested features, plus optional credit balance + * availability. + * + * _Designed to be called on a fixed refresh interval and the query response is + * intended to be cached._ + */ + @extension(Shared.UnstableExtension, true) + @extension(Shared.InternalExtension, true) + @extension(Shared.PrivateExtension, true) + @post + @route("/query") + @operationId("query-governance-access") + @summary("Query governance access") + query(...Common.CursorPaginationQuery, @body _: GovernanceQueryRequest): + | GovernanceQueryResponse + | Common.ErrorResponses; +} diff --git a/api/spec/packages/aip/src/invoices/index.tsp b/api/spec/packages/aip/src/invoices/index.tsp new file mode 100644 index 0000000000000000000000000000000000000000..0804a8fbaac59c2c44930cc25f13e1a4dc5cd56a --- /dev/null +++ b/api/spec/packages/aip/src/invoices/index.tsp @@ -0,0 +1,3 @@ +import "./invoice.tsp"; +import "./party.tsp"; +import "./operations.tsp"; diff --git a/api/spec/packages/aip/src/invoices/invoice.tsp b/api/spec/packages/aip/src/invoices/invoice.tsp new file mode 100644 index 0000000000000000000000000000000000000000..8b3d9760d1e47293e7436e623997857cfd29eb5b --- /dev/null +++ b/api/spec/packages/aip/src/invoices/invoice.tsp @@ -0,0 +1,1027 @@ +import "../shared/index.tsp"; +import "../customers/index.tsp"; +import "../productcatalog/price.tsp"; +import "../productcatalog/ratecard.tsp"; +import "../billing/profile.tsp"; +import "../billing/totals.tsp"; +import "../billing/tax.tsp"; +import "../subscriptions/index.tsp"; + +namespace Invoices; + +/** + * InvoiceNumber is a unique identifier for the invoice, generated by the invoicing + * app. + * + * The uniqueness depends on a lot of factors: + * + * - app setting (unique per app or unique per customer) + * - multiple app scenarios (multiple apps generating invoices with the same + * prefix) + */ +@example("INV-2024-01-01-01") +@minLength(1) +@maxLength(256) +@friendlyName("BillingInvoiceNumber") +scalar InvoiceNumber extends string; + +/** + * An invoice issued to a customer. + * + * The `type` field determines the concrete variant: + * + * - `standard`: a standard invoice for charges owed. + */ +@friendlyName("BillingInvoice") +@discriminated(#{ discriminatorPropertyName: "type", envelope: "none" }) +union Invoice { + @summary("Standard invoice") + standard: InvoiceStandard, + + // @summary("Credit note invoice") + // credit_note: BillingCreditNoteInvoice, +} + +@doc("UpdateInvoiceRequest update request.") +@friendlyName("UpdateInvoiceRequest") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union UpdateInvoiceRequest { + @summary("Standard invoice") + standard: Shared.UpdateRequestNested, +} + +/** + * The type of a billing invoice. + */ +@friendlyName("BillingInvoiceType") +enum InvoiceType { + /** + * A standard invoice for charges owed by the customer. + */ + Standard: "standard", + + // /** + // * A credit note reducing the amount owed on a previous invoice. + // */ + // CreditNote: "credit_note", +} + +/** + * Base fields shared by all invoice types. + * + * Spread this model into each concrete invoice variant. + */ +@friendlyName("BillingInvoiceBase") +model InvoiceBase { + ...OmitProperties; + + /** + * Human-readable invoice number generated by the invoicing app. + */ + @visibility(Lifecycle.Read) + @summary("Number") + number: InvoiceNumber; + + /** + * Three-letter ISO 4217 currency code for the invoice. + */ + @visibility(Lifecycle.Read) + @summary("Currency") + currency: Shared.CurrencyCode; + + /** + * Snapshot of the supplier's contact information at the time the invoice was + * issued. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + @summary("Supplier") + supplier: Supplier; + + /** + * Snapshot of the customer's information at the time the invoice was issued. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + @summary("Customer") + customer: InvoiceCustomer; + + /** + * Aggregated financial totals for the invoice. + */ + @visibility(Lifecycle.Read) + @summary("Totals") + totals: Billing.BillingTotals; + + /** + * The service period covered by this invoice. + * + * For flat fee the service period can be empty which means `from` will be equals + * to `to`. In other cases those fields will be filled with the actual service + * period. + */ + @visibility(Lifecycle.Read) + @summary("Service period") + service_period: Shared.ClosedPeriod; + + /** + * Validation issues found during invoice processing. + * + * Present only when there are one or more validation findings. An empty list is + * omitted. + */ + @visibility(Lifecycle.Read) + @summary("Validation issues") + validation_issues?: InvoiceValidationIssue[]; + + /** + * External identifiers assigned to this invoice by third-party systems. + */ + @visibility(Lifecycle.Read) + @summary("External references") + external_references?: InvoiceExternalReferences; +} + +/** + * A top-level line item on an invoice. + * + * Each line represents a single charge, typically associated with a rate card from + * a subscription. Detailed (child) lines are nested under `detailed_lines` when + * present. + */ +@friendlyName("BillingInvoiceLine") +@discriminated(#{ discriminatorPropertyName: "type", envelope: "none" }) +union InvoiceLine { + @summary("Standard invoice line") + standard_line: InvoiceStandardLine, + + // @summary("Credit note invoice") + // credit_note: BillingCreditNoteInvoice, +} + +/** + * A standard invoice for charges owed by the customer. + */ +@friendlyName("BillingInvoiceStandard") +model InvoiceStandard { + ...InvoiceBase; + + /** + * Discriminator field identifying this as a standard invoice. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + @summary("Type") + type: InvoiceType.Standard; + + /** + * Current lifecycle status of the invoice. + */ + @visibility(Lifecycle.Read) + @summary("Status") + status: InvoiceStandardStatus; + + /** + * Detailed status information including available actions and workflow state. + */ + @visibility(Lifecycle.Read) + @summary("Status details") + status_details: InvoiceStatusDetails; + + /** + * Timestamp when the invoice was issued to the customer. + */ + @visibility(Lifecycle.Read) + @summary("Issued at") + issued_at?: Shared.DateTime; + + /** + * Timestamp until which the invoice remains in draft state. + * + * The invoice advances automatically once this time is reached. + */ + @visibility(Lifecycle.Read) + @summary("Draft until") + draft_until?: Shared.DateTime; + + /** + * Timestamp when usage quantities were last snapshotted for this invoice. + */ + @visibility(Lifecycle.Read) + @summary("Quantity snapshotted at") + quantity_snapshotted_at?: Shared.DateTime; + + /** + * Timestamp when collection was initiated for this invoice. + */ + @visibility(Lifecycle.Read) + @summary("Collection at") + collection_at?: Shared.DateTime; + + /** + * Timestamp when payment is due. + */ + @visibility(Lifecycle.Read) + @summary("Due at") + due_at?: Shared.DateTime; + + /** + * Timestamp when the invoice was sent to the customer. + */ + @visibility(Lifecycle.Read) + @summary("Sent to customer at") + sent_to_customer_at?: Shared.DateTime; + + /** + * Workflow configuration snapshot captured at invoice creation time. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + @summary("Workflow") + workflow: InvoiceWorkflowSettings; + + /** + * Line items on this invoice. + * + * Always returned on single-resource GET; omitted on list endpoints unless + * explicitly expanded. Editable via update: existing lines are matched by `id`, + * lines without an `id` are created, and lines present on the invoice but omitted + * from the update request are deleted. Detailed (child) lines are always computed + * and cannot be edited directly. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + @summary("Lines") + lines?: InvoiceLine[]; +} + +/** + * Lifecycle status of a standard invoice. + */ +@friendlyName("BillingInvoiceStandardStatus") +enum InvoiceStandardStatus { + /** + * The invoice is in draft and can still be modified. + */ + Draft: "draft", + + /** + * The invoice is being issued (e.g. submitted to an invoicing app). + */ + Issuing: "issuing", + + /** + * The invoice has been issued and is awaiting payment. + */ + Issued: "issued", + + /** + * Payment processing is in progress. + */ + PaymentProcessing: "payment_processing", + + /** + * Payment is past due. + */ + Overdue: "overdue", + + /** + * The invoice has been paid in full. + */ + Paid: "paid", + + /** + * The invoice has been marked uncollectible. + */ + Uncollectible: "uncollectible", + + /** + * The invoice has been voided. + */ + Voided: "voided", +} + +// /** +// * A credit note invoice. +// * +// * @placeholder Credit note domain support is not yet implemented. This model is a +// * forward-compatibility placeholder and will be expanded in a future release. +// */ +// @friendlyName("BillingInvoiceCreditNote") +// model InvoiceCreditNote { +// ...InvoiceBase; + +// /** +// * Discriminator field identifying this as a credit note invoice. +// */ +// @visibility(Lifecycle.Read) +// @summary("Type") +// type: InvoiceType.CreditNote; + +// /** +// * Current lifecycle status of the credit note. +// */ +// @visibility(Lifecycle.Read) +// @summary("Status") +// status: InvoiceStatusCreditNote; +// } + +// /** +// * Lifecycle status of a credit note invoice. +// */ +// @friendlyName("BillingInvoiceStatusCreditNote") +// enum InvoiceStatusCreditNote { +// /** +// * The credit note is in draft state. +// */ +// Draft: "draft", + +// /** +// * The credit note has been issued. +// */ +// Issued: "issued", +// } + +/** + * Snapshot of the customer's information at the time the invoice was issued. + */ +@friendlyName("BillingInvoiceCustomer") +@withVisibility(Lifecycle.Read, Lifecycle.Update) +model InvoiceCustomer { + ...PickProperties< + Customers.Customer, + "name" | "usage_attribution" | "billing_address" + >; + + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + @visibility(Lifecycle.Read, Lifecycle.Update) + id: Shared.ULID; + + /** + * Optional external resource key for the customer. + * + * Omitted when the customer was created without a key. Unlike on the customer + * resource itself, the key is optional here because the invoice snapshot may + * predate or omit it. + */ + key?: Shared.ExternalResourceKey; +} + +/** + * Snapshot of the supplier's information at the time the invoice was issued. + * + * Structurally a read-only subset of `BillingParty` (the type configured on the + * billing profile), so the snapshot stays aligned with the source. `key` is + * omitted because it is not part of the snapshotted supplier data. + */ +@friendlyName("BillingSupplier") +@withVisibility(Lifecycle.Read, Lifecycle.Update) +model Supplier { + ...OmitProperties; + + /** + * Unique identifier for the party. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + id?: string; +} + +/** + * Snapshot of the billing workflow configuration captured at invoice creation. + */ +@friendlyName("BillingInvoiceWorkflowSettings") +model InvoiceWorkflowSettings { + /** + * The apps that will be used to orchestrate the invoice's workflow. + */ + @visibility(Lifecycle.Read) + @summary("Application that generated the invoice") + apps?: InvoiceWorkflowAppsReferences; + + /** + * The billing profile that was the source of this workflow snapshot. + */ + @visibility(Lifecycle.Read) + @summary("Source billing profile") + source_billing_profile: Billing.BillingProfileReference; + + /** + * The workflow configuration that was active when the invoice was created. + * + * Only the fields that are meaningful at the per-invoice level are included: + * invoicing behaviour (auto-advance, draft period) and payment settings + * (collection method, due date). Profile-wide settings such as collection + * alignment, progressive billing, and tax policy are omitted. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + @summary("Workflow config") + workflow: BillingInvoiceWorkflow; +} + +/** + * BillingInvoiceWorkflowAppsReferences represents the references (id) to the apps + * used by a billing profile + */ +@friendlyName("BillingInvoiceWorkflowAppsReferences") +model InvoiceWorkflowAppsReferences { + /** + * The tax app used for this workflow + */ + @visibility(Lifecycle.Read) + tax: Apps.AppReference; + + /** + * The invoicing app used for this workflow + */ + @visibility(Lifecycle.Read) + invoicing: Apps.AppReference; + + /** + * The payment app used for this workflow + */ + @visibility(Lifecycle.Read) + payment: Apps.AppReference; +} + +/** + * Invoice-level snapshot of the workflow configuration. + * + * Contains only the settings that are meaningful for an already-created invoice: + * invoicing behaviour and payment settings. Collection alignment and tax policy + * are gather-time / profile-wide concerns and are not included. + */ +@friendlyName("BillingInvoiceWorkflow") +model BillingInvoiceWorkflow { + /** + * Invoicing settings for this invoice. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + @summary("Invoicing settings") + invoicing?: BillingInvoiceWorkflowInvoicingSettings; + + /** + * Payment settings for this invoice. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + @summary("Payment settings") + payment?: Billing.BillingWorkflowPaymentSettings; +} + +/** + * Invoice-level invoicing settings. + * + * A subset of BillingWorkflowInvoicingSettings limited to fields that are + * meaningful per-invoice. progressive_billing is omitted as it is a gather-time / + * profile-level decision. + */ +@friendlyName("BillingInvoiceWorkflowInvoicingSettings") +model BillingInvoiceWorkflowInvoicingSettings { + /** + * Whether to automatically issue the invoice after the draft_period has passed. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + auto_advance?: boolean = true; + + /** + * The period for the invoice to be kept in draft status for manual reviews. + */ + @encode(DurationKnownEncoding.ISO8601) + @example("P1D") + @visibility(Lifecycle.Read, Lifecycle.Update) + draft_period?: string = "P0D"; + + /** + * The period after which the invoice is considered overdue if not paid. + */ + @encode(DurationKnownEncoding.ISO8601) + @example("P30D") + @visibility(Lifecycle.Read) + due_after?: string; +} + +/** + * Detailed status information for a standard invoice. + */ +@friendlyName("BillingInvoiceStatusDetails") +model InvoiceStatusDetails { + /** + * Whether the invoice is immutable (i.e. cannot be modified or deleted). + */ + @visibility(Lifecycle.Read) + @summary("Immutable") + immutable: boolean; + + /** + * Whether the invoice is in a failed state. + */ + @visibility(Lifecycle.Read) + @summary("Failed") + failed: boolean; + + /** + * Fine-grained internal status string providing additional workflow detail beyond + * the top-level status enum. + */ + @visibility(Lifecycle.Read) + @summary("Extended status") + extended_status: string; + + /** + * The set of state-transition actions currently available for this invoice. + */ + @visibility(Lifecycle.Read) + @summary("Available actions") + available_actions: InvoiceAvailableActions; +} + +/** + * The set of state-transition actions available for an invoice in its current + * status. + * + * A field is present only when that action is permitted from the current state. + */ +@friendlyName("BillingInvoiceAvailableActions") +model InvoiceAvailableActions { + /** + * Advance the invoice to the next workflow step. + */ + @visibility(Lifecycle.Read) + @summary("Advance") + advance?: InvoiceAvailableActionDetails; + + /** + * Approve the invoice for issuance. + */ + @visibility(Lifecycle.Read) + @summary("Approve") + approve?: InvoiceAvailableActionDetails; + + /** + * Delete the invoice. + */ + @visibility(Lifecycle.Read) + @summary("Delete") + delete?: InvoiceAvailableActionDetails; + + /** + * Retry a failed workflow step. + */ + @visibility(Lifecycle.Read) + @summary("Retry") + retry?: InvoiceAvailableActionDetails; + + /** + * Snapshot the current usage quantities. + */ + @visibility(Lifecycle.Read) + @summary("Snapshot quantities") + snapshot_quantities?: InvoiceAvailableActionDetails; +} + +/** + * Details about an available invoice action including the resulting state. + */ +@friendlyName("BillingInvoiceAvailableActionDetails") +model InvoiceAvailableActionDetails { + /** + * The extended status the invoice will transition to after performing this action. + */ + @visibility(Lifecycle.Read) + @summary("Resulting state") + resulting_state: string; +} + +/** + * External identifiers assigned to an invoice by third-party systems. + */ +@friendlyName("BillingInvoiceExternalReferences") +model InvoiceExternalReferences { + /** + * The ID assigned by the external invoicing app (e.g. Stripe invoice ID). + */ + @visibility(Lifecycle.Read) + @summary("Invoicing ID") + invoicing_id?: string; + + /** + * The ID assigned by the external payment app (e.g. Stripe payment intent ID). + */ + @visibility(Lifecycle.Read) + @summary("Payment ID") + payment_id?: string; +} + +/** + * Severity level of an invoice validation issue. + */ +@friendlyName("BillingInvoiceValidationIssueSeverity") +enum InvoiceValidationIssueSeverity { + /** + * A critical issue that prevents the invoice from being finalized. + */ + Critical: "critical", + + /** + * A warning that does not block finalization but should be reviewed. + */ + Warning: "warning", +} + +/** + * A validation issue found during invoice processing. + * + * Converges on the same structure used by plan and subscription validation errors: + * a machine-readable `code`, a human-readable `message`, optional structured + * `attributes`, plus a `severity` and optional `field` path. + */ +@friendlyName("BillingInvoiceValidationIssue") +model InvoiceValidationIssue is Shared.BaseError { + /** + * Severity of the validation issue. + */ + @visibility(Lifecycle.Read) + @summary("Severity") + severity: InvoiceValidationIssueSeverity; + + /** + * JSON path to the field that caused this validation issue, if applicable. + * + * For example: `lines/0/rate_card/price`. + */ + @visibility(Lifecycle.Read) + @summary("Field path") + field?: string; +} + +/** + * Line item type discriminator. + */ +@friendlyName("BillingInvoiceLineType") +enum InvoiceLineType { + /** + * A standard line item representing a single charge. + */ + StandardLine: "standard_line", + + /** + * A line item representing a credit purchase. + */ + // CreditPurchase: "credit_purchase"; +} + +/** + * A top-level line item on an invoice. + * + * Each line represents a single charge, typically associated with a rate card from + * a subscription. Detailed (child) lines are nested under `detailed_lines` when + * present. + */ +@friendlyName("BillingInvoiceStandardLine") +model InvoiceStandardLine { + ...OmitProperties; + + /** + * ID of the line. + * + * Optional on update: omit to create a new line, or supply the ID of an existing + * line to edit it. Existing lines omitted from an update's `lines` array are + * deleted. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + @summary("ID") + id?: Shared.ULID; + + /** + * The type of charge this line item represents. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + @summary("Type") + type: InvoiceLineType.StandardLine; + + /** + * Indicates whether this line item's lifecycle is controlled by OpenMeter or + * manually overridden by the API user. + */ + @visibility(Lifecycle.Read) + @summary("Lifecycle controller") + lifecycle_controller: Shared.LifecycleController; + + /** + * The service period covered by this invoice, spanning the earliest line start to + * the latest line end across all of its lines. + * + * For an invoice with no lines the period is empty, which means `from` will be + * equal to `to`. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + @summary("Service period") + service_period: Shared.ClosedPeriod; + + /** + * Aggregated financial totals for the line item. + */ + @visibility(Lifecycle.Read) + @summary("Totals") + totals: Billing.BillingTotals; + + /** + * Discounts applied to this line item. + */ + @visibility(Lifecycle.Read) + @summary("Discounts") + discounts?: InvoiceLineDiscounts; + + /** + * Credit applied to this line item. + */ + @visibility(Lifecycle.Read) + @summary("Credit applied") + credits_applied?: InvoiceLineCreditsApplied[]; + + /** + * External identifiers for this line item assigned by third-party systems. + */ + @visibility(Lifecycle.Read) + @summary("External references") + external_references?: InvoiceLineExternalReferences; + + /** + * Reference to the subscription item that generated this line. + */ + @visibility(Lifecycle.Read) + @summary("Subscription reference") + subscription?: Subscriptions.SubscriptionReference; + + /** + * The rate card configuration snapshot used to price this line item. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + @summary("Rate card") + rate_card: InvoiceLineRateCard; + + /** + * Detailed sub-lines that this line has been broken down into. + * + * Present when line has individual details. + */ + @visibility(Lifecycle.Read) + @summary("Detailed lines") + detailed_lines: InvoiceDetailedLine[]; + + /** + * Reference to the charge associated with this line item. + */ + @visibility(Lifecycle.Read) + @summary("Charge") + charge?: Customers.ChargeReference; +} + +/** + * Rate card configuration snapshot for a usage-based invoice line. + */ +@friendlyName("BillingInvoiceLineRateCard") +model InvoiceLineRateCard { + /** + * The price definition used to calculate charges for this line. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + @summary("Price") + price: ProductCatalog.Price; + + /** + * Tax configuration snapshot for this line. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + @summary("Tax config") + tax_config?: ProductCatalog.RateCardTaxConfig; + + /** + * The feature key associated with this line's rate card. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + @summary("Feature key") + feature_key?: Shared.ResourceKey; + + /** + * Discount configuration from the rate card. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + @summary("Discounts") + discounts?: ProductCatalog.Discounts; +} + +/** + * Discounts applied to an invoice line item. + */ +@friendlyName("BillingInvoiceLineDiscounts") +model InvoiceLineDiscounts { + /** + * Monetary amount discounts (e.g. from maximum spend commitments). + */ + @visibility(Lifecycle.Read) + @summary("Amount discounts") + amount?: InvoiceLineAmountDiscount[]; + + /** + * Usage quantity discounts (e.g. free tier usage allowances). + */ + @visibility(Lifecycle.Read) + @summary("Usage discounts") + usage?: InvoiceLineUsageDiscount[]; +} + +/** + * The reason a discount was applied to an invoice line. + */ +@friendlyName("BillingInvoiceDiscountReason") +enum InvoiceDiscountReason { + /** + * Discount applied because a maximum spend commitment was reached. + */ + MaximumSpend: "maximum_spend", + + /** + * Discount applied from a rate card percentage discount rule. + */ + RatecardPercentage: "ratecard_percentage", + + /** + * Discount applied from a rate card usage discount rule. + */ + RatecardUsage: "ratecard_usage", +} + +/** + * Base fields shared by all invoice line item discounts. + */ +@friendlyName("BillingInvoiceLineBaseDiscount") +model InvoiceLineBaseDiscount { + /** + * Unique identifier for the discount. + */ + @visibility(Lifecycle.Read) + @summary("ID") + id: Shared.ULID; + + /** + * The reason this discount was applied. + */ + @visibility(Lifecycle.Read) + @summary("Reason") + reason: InvoiceDiscountReason; + + /** + * Optional human-readable description of the discount. + */ + @visibility(Lifecycle.Read) + @summary("Description") + description?: string; + + /** + * External identifiers for this discount. + */ + @visibility(Lifecycle.Read) + @summary("External references") + external_references?: InvoiceLineExternalReferences; +} + +/** + * A monetary amount discount applied to an invoice line item. + */ +@friendlyName("BillingInvoiceLineAmountDiscount") +model InvoiceLineAmountDiscount { + ...InvoiceLineBaseDiscount; + + /** + * The monetary amount deducted. + */ + @visibility(Lifecycle.Read) + @summary("Amount") + amount: Shared.Numeric; +} + +/** + * A usage quantity discount applied to an invoice line item. + */ +@friendlyName("BillingInvoiceLineUsageDiscount") +model InvoiceLineUsageDiscount { + ...InvoiceLineBaseDiscount; + + /** + * The usage quantity deducted (in billing units). + */ + @visibility(Lifecycle.Read) + @summary("Quantity") + quantity: Shared.Numeric; +} + +/** + * A credit allocation applied to an invoice line item. + */ +@friendlyName("BillingInvoiceLineCreditsApplied") +model InvoiceLineCreditsApplied { + /** + * The monetary amount credited. + */ + @visibility(Lifecycle.Read) + @summary("Amount") + amount: Shared.Numeric; + + /** + * Optional human-readable description of the credit allocation. + */ + @visibility(Lifecycle.Read) + @summary("Description") + description?: string; +} + +/** + * External identifiers for an invoice line item assigned by third-party systems. + */ +@friendlyName("BillingInvoiceLineExternalReferences") +model InvoiceLineExternalReferences { + /** + * The ID assigned by the external invoicing app. + */ + @visibility(Lifecycle.Read) + @summary("Invoicing ID") + invoicing_id?: string; +} + +/** + * Cost category of a detailed invoice line item. + */ +@friendlyName("BillingInvoiceDetailedLineCostCategory") +enum InvoiceDetailedLineCostCategory { + /** + * A regular charge. + */ + Regular: "regular", + + /** + * A commitment charge (e.g. minimum spend). + */ + Commitment: "commitment", +} + +/** + * A detailed (child) sub-line belonging to a parent invoice line. + * + * Detailed lines represent the individual flat-fee components that make up a + * usage-based parent line after quantity snapshotting. + */ +@friendlyName("BillingInvoiceDetailedLine") +model InvoiceDetailedLine { + ...Shared.Resource; + + /** + * The service period covered by this detailed line. + */ + @visibility(Lifecycle.Read) + @summary("Service period") + service_period: Shared.ClosedPeriod; + + /** + * Aggregated financial totals for the detailed line. + */ + @visibility(Lifecycle.Read) + @summary("Totals") + totals: Billing.BillingTotals; + + /** + * The cost category of this detailed line. + */ + @visibility(Lifecycle.Read) + @summary("Category") + category: InvoiceDetailedLineCostCategory = InvoiceDetailedLineCostCategory.Regular; + + /** + * Discounts applied to this detailed line. + */ + @visibility(Lifecycle.Read) + @summary("Discounts") + discounts?: InvoiceLineDiscounts; + + /** + * Credit applied to this detailed line. + */ + @visibility(Lifecycle.Read) + @summary("Credit applied") + credits_applied?: InvoiceLineCreditsApplied[]; + + /** + * External identifiers for this detailed line. + */ + @visibility(Lifecycle.Read) + @summary("External references") + external_references?: InvoiceLineExternalReferences; + + /** + * The quantity of the detailed line. + */ + @visibility(Lifecycle.Read) + @summary("Quantity") + quantity: Shared.Numeric; + + /** + * The unit price of the detailed line. + */ + @visibility(Lifecycle.Read) + @summary("Unit Price") + unit_price: Shared.Numeric; +} diff --git a/api/spec/packages/aip/src/invoices/operations.tsp b/api/spec/packages/aip/src/invoices/operations.tsp new file mode 100644 index 0000000000000000000000000000000000000000..8600a8a282f7de5e1bd0916ee6dbe1f8893b526b --- /dev/null +++ b/api/spec/packages/aip/src/invoices/operations.tsp @@ -0,0 +1,248 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "../common/error.tsp"; +import "../common/pagination.tsp"; +import "../common/parameters.tsp"; +import "../shared/index.tsp"; +import "../billing/profile.tsp"; +import "./invoice.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Invoices; + +/** + * Filter options for listing invoices. + */ +@friendlyName("ListInvoicesParamsFilter") +model ListInvoicesParamsFilter { + /** + * Filter by invoice status. + */ + #suppress "@openmeter/api-spec-aip/doc-decorator" "filter field" + status?: Common.StringFieldFilterExact; + + /** + * Filter by customer ID. + */ + #suppress "@openmeter/api-spec-aip/doc-decorator" "filter field" + customer_id?: Common.ULIDFieldFilter; + + /** + * Filter by the time the invoice was issued. + */ + #suppress "@openmeter/api-spec-aip/doc-decorator" "filter field" + issued_at?: Common.DateTimeFieldFilter; + + /** + * Filter by service period start. + */ + #suppress "@openmeter/api-spec-aip/doc-decorator" "filter field" + service_period_start?: Common.DateTimeFieldFilter; + + /** + * Filter by invoice creation time. + */ + #suppress "@openmeter/api-spec-aip/doc-decorator" "filter field" + created_at?: Common.DateTimeFieldFilter; +} + +/** + * Operations for managing billing invoices. + */ +interface InvoicesOperations { + /** + * List billing invoices. + * + * Returns a page of invoices. Gathering invoices are never included. Use `filter` + * to narrow by status, customer, dates, or service period start. Use `sort` to + * control ordering. + */ + @extension(Shared.UnstableExtension, true) + @extension(Shared.InternalExtension, true) + @extension(Shared.PrivateExtension, true) + @get + @operationId("list-invoices") + @summary("List billing invoices") + list( + ...Common.PagePaginationQuery, + + /** + * Sort invoices returned in the response. Supported sort attributes: + * + * - `issued_at` + * - `created_at` (default) + * - `service_period_start` + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ + @query(#{ name: "sort" }) + sort?: Common.SortQuery, + + /** + * Filter invoices returned in the response. + * + * Examples: + * + * - `filter[status][oeq]=draft,issued` + * - `filter[customer_id]=01KPDB8K...` + * - `filter[issued_at][gte]=2024-01-01T00:00:00Z` + */ + @query(#{ style: "deepObject", explode: true }) + filter?: ListInvoicesParamsFilter, + ): Shared.PagePaginatedResponse | Common.ErrorResponses; + + /** + * Get a billing invoice by ID. + * + * Returns the full invoice resource including line items, status details, totals, + * and workflow configuration snapshot. + */ + @get + @operationId("get-invoice") + @summary("Get a billing invoice") + @extension(Shared.UnstableExtension, true) + @extension(Shared.InternalExtension, true) + @extension(Shared.PrivateExtension, true) + get(@path invoiceId: Shared.ULID): + | Shared.GetResponse + | Common.NotFound + | Common.ErrorResponses; + + /** + * Update a billing invoice. + * + * Only the mutable fields of the invoice can be edited: description, labels, + * supplier, customer, workflow settings, and top-level lines. Top-level lines are + * matched by `id`; lines without an `id` are created, and existing lines omitted + * from `lines` are deleted. Detailed (child) lines are always computed and cannot + * be edited directly. Only invoices in draft status can be updated. + */ + @put + @operationId("update-invoice") + @summary("Update a billing invoice") + @extension(Shared.UnstableExtension, true) + @extension(Shared.InternalExtension, true) + @extension(Shared.PrivateExtension, true) + update( + @path invoiceId: Shared.ULID, + + @body + invoice: UpdateInvoiceRequest, + ): Shared.UpdateResponse | Common.NotFound | Common.ErrorResponses; + + /** + * Delete a billing invoice. + * + * Only standard invoices in draft status can be deleted. Deleting an invoice will + * also delete all associated line items and workflow configuration. + */ + @delete + @operationId("delete-invoice") + @summary("Delete a billing invoice") + @extension(Shared.UnstableExtension, true) + @extension(Shared.InternalExtension, true) + @extension(Shared.PrivateExtension, true) + delete(@path invoiceId: Shared.ULID): + | Shared.DeleteResponse + | Common.NotFound + | Common.ErrorResponses; + + /** + * Advance a billing invoice. + * + * Advances the invoice to the next workflow state. The next state is determined by + * the invoice's current status and workflow configuration. Only invoices in draft + * or issued status can be advanced. + * + * @returns The updated invoice after advancing to the next state. + */ + @post + @route("/{invoiceId}/advance") + @operationId("advance-invoice") + @summary("Advance billing invoice's next status") + @extension(Shared.UnstableExtension, true) + @extension(Shared.InternalExtension, true) + @extension(Shared.PrivateExtension, true) + advance(@path invoiceId: Shared.ULID): + | Invoice + | Common.NotFound + | Common.ErrorResponses; + + /** + * Approve a billing invoice. + * + * This call instantly sends the invoice to the customer using the configured + * billing profile app. + * + * This call is valid in two invoice statuses: + * + * - draft: the invoice will be sent to the customer, the invoice state becomes + * issued + * - manual_approval_needed: the invoice will be sent to the customer, the invoice + * state becomes issued + * + * @returns The updated invoice after sending to the customer. + */ + @post + @route("/{invoiceId}/approve") + @operationId("approve-invoice") + @summary("Send the invoice to the customer") + @extension(Shared.UnstableExtension, true) + @extension(Shared.InternalExtension, true) + @extension(Shared.PrivateExtension, true) + approve(@path invoiceId: Shared.ULID): + | Invoice + | Common.NotFound + | Common.ErrorResponses; + + /** + * Retry sending a billing invoice. + * + * Retry advancing the invoice after a failed attempt. + * + * The action can be called when the invoice's statusDetails' actions field contain + * the "retry" action. + * + * @returns The updated invoice after retrying the action. + */ + @post + @route("/{invoiceId}/retry") + @operationId("retry-invoice") + @summary("Retry advancing the invoice after a failed attempt") + @extension(Shared.UnstableExtension, true) + @extension(Shared.InternalExtension, true) + @extension(Shared.PrivateExtension, true) + retry(@path invoiceId: Shared.ULID): + | Invoice + | Common.NotFound + | Common.ErrorResponses; + + /** + * Snapshot quantities for usage-based line items. + * + * This call will snapshot the quantities for all usage based line items in the + * invoice. + * + * This call is only valid in draft.waiting_for_collection status, where the + * collection period can be skipped using this action. + * + * @returns The updated invoice with the snapshot quantities for usage based line + * items. + */ + @post + @route("/{invoiceId}/snapshot-quantities") + @operationId("snapshot-quantities-invoice") + @summary("Snapshot quantities for usage based line items") + @extension(Shared.UnstableExtension, true) + @extension(Shared.InternalExtension, true) + @extension(Shared.PrivateExtension, true) + snapshotQuantities(@path invoiceId: Shared.ULID): + | Invoice + | Common.NotFound + | Common.ErrorResponses; +} diff --git a/api/spec/packages/aip/src/invoices/party.tsp b/api/spec/packages/aip/src/invoices/party.tsp new file mode 100644 index 0000000000000000000000000000000000000000..99e205ea47e31904981bc090cc58eaef1e691be2 --- /dev/null +++ b/api/spec/packages/aip/src/invoices/party.tsp @@ -0,0 +1,82 @@ +import "../shared/index.tsp"; + +namespace Invoices; + +/* + * Omitted fields + * + * identities: Set of codes used to identify the party in other systems. + * -> This is maintained by apps, and for now we don't see any reason to have this included. + * people: Details of physical people who represent the party. + * -> We don't need this level of detail for now, the name is enough if we deal with a person. + * inboxes: Digital inboxes used for forwarding electronic versions of documents + * -> We don't support this. + * emails: + * -> We don't need this on the invoice. + * websites: Public websites that provide further information about the party. + * telephones: Telephone numbers for contacting the party. + * registration: Additional registration details about the company that may need to be included in a document. + * logos: Images that can be used to identify the party visually. + * ext: (tax) Extension code map for any additional regime specific codes that may be required. + */ + +/** + * Party represents a person or business entity. + */ +@friendlyName("BillingParty") +model BillingParty { + /** + * Unique identifier for the party. + */ + @visibility(Lifecycle.Read) + id?: string; + + /** + * An optional unique key of the party. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + key?: Shared.ExternalResourceKey; + + /** + * Legal name or representation of the party. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + name?: string; + + /** + * The entity's legal identification used for tax purposes. They may have other + * numbers, but we're only interested in those valid for tax purposes. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + tax_id?: BillingPartyTaxIdentity; + + /** + * Address for where information should be sent if needed. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + addresses?: BillingPartyAddresses; +} + +/** + * A collection of addresses for the party. + */ +@friendlyName("BillingPartyAddresses") +model BillingPartyAddresses { + /** + * Billing address. + */ + billing_address: Shared.Address; +} + +/** + * Identity stores the details required to identify an entity for tax purposes in a + * specific country. + */ +@friendlyName("BillingPartyTaxIdentity") +model BillingPartyTaxIdentity { + /** + * Normalized tax identification code shown on the original identity document. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + code?: Shared.TaxIdentificationCode; +} diff --git a/api/spec/packages/aip/src/konnect.tsp b/api/spec/packages/aip/src/konnect.tsp new file mode 100644 index 0000000000000000000000000000000000000000..2b472788ed69d87c1588c033a86df3343737f0e1 --- /dev/null +++ b/api/spec/packages/aip/src/konnect.tsp @@ -0,0 +1,244 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "./shared/index.tsp"; +import "./events/index.tsp"; +import "./meters/index.tsp"; +import "./customers/index.tsp"; +import "./customers/credits/index.tsp"; +import "./entitlements/index.tsp"; +import "./subscriptions/index.tsp"; +import "./apps/index.tsp"; +import "./billing/index.tsp"; +import "./tax/index.tsp"; +import "./defaults/index.tsp"; +import "./governance/index.tsp"; +import "./invoices/index.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +/** + * Konnect Metering & Billing API. + */ +@service(#{ title: "Konnect ${Shared.MeteringAndBillingTitle}" }) +@info(#{ + version: "1.0.0", + contact: #{ name: "Kong", url: "https://cloud.konghq.com" }, +}) +@server("https://us.api.konghq.com/v3", "United-States Production region") +@server("https://eu.api.konghq.com/v3", "Europe Production region") +@server("https://au.api.konghq.com/v3", "Australia Production region") +@server("https://me.api.konghq.com/v3", "Middle-East Production region") +@server("https://in.api.konghq.com/v3", "India Production region") +// TODO: Uncomment this when the Singapore production region is available +// @server("https://sg.api.konghq.com/v3", "Singapore Production region") +@server("https://global.api.konghq.com/v3", "Global Production region") +@tagMetadata(Shared.MetersTag, #{ description: Shared.MetersDescription }) +@tagMetadata(Shared.EventsTag, #{ description: Shared.EventsDescription }) +@tagMetadata(Shared.CustomersTag, #{ description: Shared.CustomersDescription }) +@tagMetadata( + Shared.SubscriptionsTag, + #{ description: Shared.SubscriptionsDescription } +) +@tagMetadata( + Shared.EntitlementsTag, + #{ description: Shared.EntitlementsDescription } +) +@tagMetadata(Shared.AppsTag, #{ description: Shared.AppsDescription }) +@tagMetadata(Shared.BillingTag, #{ description: Shared.BillingDescription }) +@tagMetadata( + Shared.CurrenciesTag, + #{ description: Shared.CurrenciesDescription } +) +@tagMetadata(Shared.TaxTag, #{ description: Shared.TaxDescription }) +@tagMetadata(Shared.FeaturesTag, #{ description: Shared.FeaturesDescription }) +@tagMetadata(Shared.LLMCostTag, #{ description: Shared.LLMCostDescription }) +@tagMetadata( + Shared.ProductCatalogTag, + #{ description: Shared.ProductCatalogDescription } +) +@tagMetadata(Shared.DefaultsTag, #{ description: Shared.DefaultsDescription }) +@tagMetadata( + Shared.GovernanceTag, + #{ description: Shared.GovernanceDescription } +) +@useAuth(systemAccountAccessToken | personalAccessToken | konnectAccessToken) +namespace MeteringAndBilling; + +@route("/openmeter/events") +@tag(Shared.EventsTag) +interface EventsEndpoints extends Events.EventsOperations {} + +@route("/openmeter/meters") +@tag(Shared.MetersTag) +interface MetersEndpoints extends Meters.MetersOperations {} + +@route("/openmeter/meters/{meterId}/query") +@tag(Shared.MetersTag) +interface MetersQueryEndpoints extends Meters.MetersQueryOperations {} + +@route("/openmeter/customers") +@tag(Shared.CustomersTag) +interface CustomersEndpoints extends Customers.CustomersOperations {} + +@route("/openmeter/customers/{customerId}/billing") +@tag(Shared.CustomersTag) +interface CustomerBillingEndpoints + extends Customers.Billing.CustomerBillingOperations {} + +@route("/openmeter/customers/{customerId}/entitlement-access") +@tag(Shared.EntitlementsTag) +interface CustomerEntitlementsEndpoints + extends Entitlements.CustomerEntitlementsOperations {} + +@route("/openmeter/customers/{customerId}/credits/grants") +@tag(Shared.CustomersTag) +interface CustomerCreditGrantsEndpoints + extends Customers.Credits.Grants.CustomerCreditGrantsOperations {} + +@route("/openmeter/customers/{customerId}/credits/balance") +@tag(Shared.CustomersTag) +interface CustomerCreditBalanceEndpoints + extends Customers.Credits.Balance.CustomerCreditBalancesOperations {} + +@route("/openmeter/customers/{customerId}/credits/adjustments") +@tag(Shared.CustomersTag) +interface CustomerCreditAdjustmentsEndpoints + extends Customers.Credits.Adjustments.CustomerCreditAdjustmentsOperations {} + +@route("/openmeter/customers/{customerId}/credits/grants/{creditGrantId}") +@tag(Shared.CustomersTag) +interface CustomerCreditGrantEndpoints { + @route("/void") + voidGrant is Customers.Credits.Grants.CustomerCreditGrantVoidOperations.voidGrant; + + @route("/settlement/external") + updateExternalSettlement is Customers.Credits.Grants.CustomerCreditGrantExternalSettlementOperations.updateExternalSettlement; +} + +@route("/openmeter/customers/{customerId}/credits/transactions") +@tag(Shared.CustomersTag) +interface CustomerCreditTransactionEndpoints + extends Customers.Credits.Transactions.CustomerCreditTransactionOperations {} + +@route("/openmeter/customers/{customerId}/charges") +@tag(Shared.CustomersTag) +interface CustomerChargesEndpoints + extends Customers.Charges.CustomerChargesOperations {} + +@route("/openmeter/subscriptions") +@tag(Shared.SubscriptionsTag) +interface SubscriptionsEndpoints + extends Subscriptions.SubscriptionsOperations {} + +@route("/openmeter/subscriptions/{subscriptionId}/addons") +@tag(Shared.SubscriptionsTag) +interface SubscriptionAddonEndpoints + extends Subscriptions.SubscriptionAddonOperations {} + +@route("/openmeter/apps") +@tag(Shared.AppsTag) +interface AppsEndpoints extends Apps.AppsOperations {} + +@route("/openmeter/app-catalog") +@tag(Shared.AppsTag) +interface AppCatalogEndpoints extends Apps.AppCatalogOperations {} + +@route("/openmeter/profiles") +@tag(Shared.BillingTag) +interface BillingProfilesEndpoints extends Billing.BillingProfilesOperations {} + +@route("/openmeter/billing/invoices") +@tag(Shared.BillingTag) +interface BillingInvoicesEndpoints extends Invoices.InvoicesOperations {} + +@route("/openmeter/tax-codes") +@tag(Shared.TaxTag) +interface TaxCodesEndpoints extends Tax.TaxCodesOperations {} + +@route("/openmeter/currencies") +@tag(Shared.CurrenciesTag) +interface CurrenciesEndpoints extends Currencies.CurrenciesOperations {} + +@route("/openmeter/currencies/custom") +@tag(Shared.CurrenciesTag) +interface CurrenciesCustomEndpoints + extends Currencies.CurrenciesCustomOperations {} + +@route("/openmeter/currencies/custom/{currencyId}/cost-bases") +@tag(Shared.CurrenciesTag) +interface CurrenciesCustomCostBasesEndpoints + extends Currencies.CurrenciesCustomCostBasesOperations {} + +@route("/openmeter/features") +@tag(Shared.FeaturesTag) +interface FeaturesEndpoints extends Features.FeatureOperations {} + +@route("/openmeter/features/{featureId}/cost") +@tag(Shared.FeaturesTag) +interface FeatureCostEndpoints extends Features.FeatureCostOperations {} + +@route("/openmeter/llm-cost/prices") +@tag(Shared.LLMCostTag) +interface LLMCostPricesEndpoints extends LLMCost.LLMCostPricesOperations {} + +@route("/openmeter/llm-cost/overrides") +@tag(Shared.LLMCostTag) +interface LLMCostOverridesEndpoints + extends LLMCost.LLMCostOverridesOperations {} + +@route("/openmeter/plans") +@tag(Shared.ProductCatalogTag) +interface PlansEndpoints extends ProductCatalog.PlanOperations {} + +@route("/openmeter/addons") +@tag(Shared.ProductCatalogTag) +interface AddonsEndpoints extends ProductCatalog.AddonOperations {} + +@route("/openmeter/plans/{planId}/addons") +@tag(Shared.ProductCatalogTag) +interface PlanAddonEndpoints extends ProductCatalog.PlanAddonOperations {} + +@route("/openmeter/defaults/tax-codes") +@tag(Shared.DefaultsTag) +interface OrganizationDefaultTaxCodesEndpoints + extends Defaults.OrganizationDefaultTaxCodesOperations {} + +@route("/openmeter/governance") +@tag(Shared.GovernanceTag) +interface GovernanceEndpoints extends Governance.GovernanceOperations {} + +/** + * The system account access token is meant for automations and integrations that + * are not directly associated with a human identity. + */ +#suppress "@openmeter/api-spec-aip/casing" "Use existing values" +@friendlyName("systemAccountAccessToken") +@useRef("../../../../common/definitions/security.yaml#/components/securitySchemes/systemAccountAccessToken") +model systemAccountAccessToken { + ...Http.BearerAuth; +} + +/** + * The personal access token is meant to be used as an alternative to basic-auth + * when accessing Konnect via APIs. + */ +#suppress "@openmeter/api-spec-aip/casing" "Use existing values" +@friendlyName("personalAccessToken") +@useRef("../../../../common/definitions/security.yaml#/components/securitySchemes/personalAccessToken") +model personalAccessToken { + ...Http.BearerAuth; +} + +/** + * The Konnect access token is meant to be used by the Konnect dashboard and the + * decK CLI authenticate with. + */ +#suppress "@openmeter/api-spec-aip/casing" "Use existing values" +@friendlyName("konnectAccessToken") +@useRef("../../../../common/definitions/security.yaml#/components/securitySchemes/konnectAccessToken") +model konnectAccessToken { + ...Http.BearerAuth; +} diff --git a/api/spec/packages/aip/src/llmcost/index.tsp b/api/spec/packages/aip/src/llmcost/index.tsp new file mode 100644 index 0000000000000000000000000000000000000000..2c136bced0c5e08076fc344f28a2e4eed028fc93 --- /dev/null +++ b/api/spec/packages/aip/src/llmcost/index.tsp @@ -0,0 +1,2 @@ +import "./prices.tsp"; +import "./operations.tsp"; diff --git a/api/spec/packages/aip/src/llmcost/operations.tsp b/api/spec/packages/aip/src/llmcost/operations.tsp new file mode 100644 index 0000000000000000000000000000000000000000..3359bd71f3973a3e420c5255ec31e2e6b9e5f212 --- /dev/null +++ b/api/spec/packages/aip/src/llmcost/operations.tsp @@ -0,0 +1,137 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "../common/error.tsp"; +import "../common/parameters.tsp"; +import "../shared/index.tsp"; +import "./prices.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace LLMCost; + +/** + * Filter options for listing LLM cost prices. + */ +#suppress "@openmeter/api-spec-aip/repeated-prefix-grouping" "model_id and model_name should not be grouped" +@friendlyName("ListLLMCostPricesParamsFilter") +model ListPricesParamsFilter { + /** + * Filter by provider. e.g. ?filter[provider][eq]=openai + */ + provider?: Common.StringFieldFilter; + + /** + * Filter by model ID. e.g. ?filter[model_id][eq]=gpt-4 + */ + model_id?: Common.StringFieldFilter; + + /** + * Filter by model name. e.g. ?filter[model_name][contains]=gpt + */ + model_name?: Common.StringFieldFilter; + + /** + * Filter by currency code. e.g. ?filter[currency][eq]=USD + */ + currency?: Common.StringFieldFilter; + + /** + * Filter by source. e.g. ?filter[source][eq]=system + */ + source?: Common.StringFieldFilter; +} + +/** + * Operations for managing global LLM cost prices. + */ +interface LLMCostPricesOperations { + /** + * List global LLM cost prices. Returns prices with overrides applied if any. + */ + @extension(Shared.UnstableExtension, true) + @get + @operationId("list-llm-cost-prices") + @summary("List LLM cost prices") + list_prices( + /** + * Filter prices. + */ + @query(#{ style: "deepObject", explode: true }) + filter?: ListPricesParamsFilter, + + /** + * Sort prices returned in the response. Supported sort attributes are: + * + * - `id` + * - `provider.id` + * - `model.id` (default) + * - `effective_from` + * - `effective_to` + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ + @query(#{ name: "sort" }) + sort?: Common.SortQuery, + + ...Common.PagePaginationQuery, + ): Shared.PagePaginatedResponse | Common.ErrorResponses; + + /** + * Get a specific LLM cost price by ID. Returns the price with overrides applied if + * any. + */ + @extension(Shared.UnstableExtension, true) + @get + @operationId("get-llm-cost-price") + @summary("Get LLM cost price") + get_price(@path priceId: Shared.ULID): + | Price + | Common.NotFound + | Common.ErrorResponses; +} + +/** + * Operations for managing per-namespace price overrides. + */ +interface LLMCostOverridesOperations { + /** + * List per-namespace price overrides. + */ + @extension(Shared.UnstableExtension, true) + @get + @operationId("list-llm-cost-overrides") + @summary("List LLM cost overrides") + list_overrides( + @query(#{ style: "deepObject", explode: true }) + filter?: ListPricesParamsFilter, + + ...Common.PagePaginationQuery, + ): Shared.PagePaginatedResponse | Common.ErrorResponses; + + /** + * Create a per-namespace price override. + */ + @extension(Shared.UnstableExtension, true) + @post + @operationId("create-llm-cost-override") + @summary("Create LLM cost override") + create_override(@body body: OverrideCreate): + | Shared.CreateResponse + | Common.ErrorResponses; + + /** + * Delete a per-namespace price override. + */ + @extension(Shared.UnstableExtension, true) + @delete + @operationId("delete-llm-cost-override") + @summary("Delete LLM cost override") + delete_override(@path priceId: Shared.ULID): + | Shared.DeleteResponse + | Common.NotFound + | Common.ErrorResponses; +} diff --git a/api/spec/packages/aip/src/llmcost/prices.tsp b/api/spec/packages/aip/src/llmcost/prices.tsp new file mode 100644 index 0000000000000000000000000000000000000000..a227cc7c93cdc149b8f6b7552239cfbc433428d7 --- /dev/null +++ b/api/spec/packages/aip/src/llmcost/prices.tsp @@ -0,0 +1,191 @@ +import "../shared/index.tsp"; + +namespace LLMCost; + +/** + * Identifies where an LLM cost price came from. + */ +@friendlyName("LLMCostPriceSource") +enum PriceSource { + /** Price was manually configured by a user. */ + Manual: "manual", + + /** Price was automatically synced from external pricing sources. */ + System: "system", +} + +/** + * Token pricing for an LLM model, denominated per token. + */ +#suppress "@openmeter/api-spec-aip/repeated-prefix-grouping" "per token prices should be grouped together" +@friendlyName("LLMCostModelPricing") +model ModelPricing { + /** + * Input price per token (USD). + */ + input_per_token: Shared.Numeric; + + /** + * Output price per token (USD). + */ + output_per_token: Shared.Numeric; + + /** + * Cache read price per token (USD). + */ + cache_read_per_token?: Shared.Numeric; + + /** + * Cache write price per token (USD). + */ + cache_write_per_token?: Shared.Numeric; + + /** + * Reasoning output price per token (USD). + */ + reasoning_per_token?: Shared.Numeric; +} + +/** + * An LLM cost price record, representing the cost per token for a specific model + * from a specific provider. + */ +#suppress "@openmeter/api-spec-aip/repeated-prefix-grouping" "source and effective_from/to should be grouped together" +@friendlyName("LLMCostPrice") +model Price { + /** + * Unique identifier. + */ + @visibility(Lifecycle.Read) + id: Shared.ULID; + + /** + * Provider of the model. + */ + @visibility(Lifecycle.Read) + provider: Provider; + + /** + * The model. + */ + @visibility(Lifecycle.Read) + `model`: Model; + + /** + * Token pricing data. + */ + @visibility(Lifecycle.Read) + pricing: ModelPricing; + + /** + * Currency code (currently always "USD"). + */ + @visibility(Lifecycle.Read) + currency: Shared.CurrencyCode; + + /** + * Where this price came from. + */ + @visibility(Lifecycle.Read) + source: PriceSource; + + /** + * When this price becomes effective. + */ + @visibility(Lifecycle.Read) + effective_from: Shared.DateTime; + + /** + * When this price expires. Omitted when the price is currently effective. + */ + @visibility(Lifecycle.Read) + effective_to?: Shared.DateTime; + + /** + * Creation timestamp. + */ + @visibility(Lifecycle.Read) + created_at: Shared.DateTime; + + /** + * Last update timestamp. + */ + @visibility(Lifecycle.Read) + updated_at: Shared.DateTime; +} + +/** + * LLM Provider + */ +@friendlyName("LLMCostProvider") +model Provider { + /** + * Identifier of the provider, e.g., "openai", "anthropic". + */ + id: string; + + /** + * Name of the provider, e.g., "OpenAI", "Anthropic". + */ + name: string; +} + +/** + * LLM Model + */ +@friendlyName("LLMCostModel") +model Model { + /** + * Identifier of the model, e.g., "gpt-4", "claude-3-5-sonnet". + */ + id: string; + + /** + * Name of the model, e.g., "GPT-4", "Claude 3.5 Sonnet". + */ + name: string; +} + +/** + * Input for creating a per-namespace price override. Unique per provider, model + * and currency. If an override already exists for the given provider, model and + * currency, it will be updated. If an override does not exist, it will be created. + */ +#suppress "@openmeter/api-spec-aip/repeated-prefix-grouping" "model_id, model_name, and effective_from/to should be grouped together" +@friendlyName("LLMCostOverrideCreate") +model OverrideCreate { + /** + * Provider/vendor of the model. + */ + provider: string; + + /** + * Canonical model identifier. + */ + model_id: string; + + /** + * Human-readable model name. + */ + model_name?: string; + + /** + * Token pricing data. + */ + pricing: ModelPricing; + + /** + * Currency code. + */ + currency: Shared.CurrencyCode; + + /** + * When this override becomes effective. + */ + effective_from: Shared.DateTime; + + /** + * When this override expires. + */ + effective_to?: Shared.DateTime; +} diff --git a/api/spec/packages/aip/src/main.tsp b/api/spec/packages/aip/src/main.tsp new file mode 100644 index 0000000000000000000000000000000000000000..58b00636204dfaf25ee3daebcf654301a80f6d07 --- /dev/null +++ b/api/spec/packages/aip/src/main.tsp @@ -0,0 +1,3 @@ +import "./openmeter.tsp"; +import "./konnect.tsp"; +import "./test.tsp"; diff --git a/api/spec/packages/aip/src/meters/index.tsp b/api/spec/packages/aip/src/meters/index.tsp new file mode 100644 index 0000000000000000000000000000000000000000..fcf19b9218c984b9fcd1e0f4832081f137b6ee42 --- /dev/null +++ b/api/spec/packages/aip/src/meters/index.tsp @@ -0,0 +1,2 @@ +import "./meter.tsp"; +import "./operations.tsp"; diff --git a/api/spec/packages/aip/src/meters/meter.tsp b/api/spec/packages/aip/src/meters/meter.tsp new file mode 100644 index 0000000000000000000000000000000000000000..dffa38c741bd88e130761523eebb8cda4f5b44ae --- /dev/null +++ b/api/spec/packages/aip/src/meters/meter.tsp @@ -0,0 +1,83 @@ +import "../shared/index.tsp"; + +namespace Meters; + +/** + * A meter is a configuration that defines how to match and aggregate events. + */ +@friendlyName("Meter") +@example(#{ + id: "01G65Z755AFWAKHE12NY0CQ9FH", + key: "tokens_total", + name: "Tokens Total", + description: "AI Token Usage", + aggregation: "sum", + event_type: "prompt", + value_property: "$.tokens", + dimensions: #{ `model`: "$.model", type: "$.type" }, + created_at: Shared.DateTime.fromISO("2024-01-01T01:01:01.001Z"), + updated_at: Shared.DateTime.fromISO("2024-01-01T01:01:01.001Z"), +}) +model Meter { + ...Shared.ResourceWithKey; + + /** + * The aggregation type to use for the meter. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + aggregation: MeterAggregation; + + /** + * The event type to include in the aggregation. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @minLength(1) + @example("prompt") + event_type: string; + + /** + * The date since the meter should include events. Useful to skip old events. If + * not specified, all historical events are included. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + events_from?: Shared.DateTime; + + /** + * JSONPath expression to extract the value from the ingested event's data + * property. + * + * The ingested value for sum, avg, min, and max aggregations is a number or a + * string that can be parsed to a number. + * + * For unique_count aggregation, the ingested value must be a string. For count + * aggregation the value_property is ignored. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @minLength(1) + @example("$.tokens") + value_property?: string; + + /** + * Named JSONPath expressions to extract the group by values from the event data. + * + * Keys must be unique and consist only alphanumeric and underscore characters. + */ + // TODO: add key format enforcement + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @example(#{ type: "$.type" }) + dimensions?: Record; +} + +/** + * The aggregation type to use for the meter. + */ +@friendlyName("MeterAggregation") +union MeterAggregation { + sum: "sum", + count: "count", + unique_count: "unique_count", + avg: "avg", + min: "min", + max: "max", + latest: "latest", +} diff --git a/api/spec/packages/aip/src/meters/operations.tsp b/api/spec/packages/aip/src/meters/operations.tsp new file mode 100644 index 0000000000000000000000000000000000000000..1835f630501b7bfdc3144e27060b1c85b39f92a7 --- /dev/null +++ b/api/spec/packages/aip/src/meters/operations.tsp @@ -0,0 +1,186 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "../common/error.tsp"; +import "../common/pagination.tsp"; +import "../common/parameters.tsp"; +import "../shared/index.tsp"; +import "./meter.tsp"; +import "./query.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Meters; + +/** + * Filter options for listing meters. + */ +@friendlyName("ListMetersParamsFilter") +model ListMetersParamsFilter { + /** + * Filter meters by key. + */ + key?: Common.StringFieldFilter; + + /** + * Filter meters by name. + */ + name?: Common.StringFieldFilter; +} + +interface MetersOperations { + /** + * Create a meter. + */ + @post + @operationId("create-meter") + @summary("Create meter") + create(@body meter: Shared.CreateRequest): + | Shared.CreateResponse + | Common.ErrorResponses; + + /** + * Get a meter by ID. + */ + @get + @operationId("get-meter") + @summary("Get meter") + get(@path meterId: Shared.ULID): + | Shared.GetResponse + | Common.NotFound + | Common.ErrorResponses; + + /** + * List meters. + */ + @get + @operationId("list-meters") + @summary("List meters") + list( + ...Common.PagePaginationQuery, + + /** + * Sort meters returned in the response. Supported sort attributes are: + * + * - `key` + * - `name` + * - `aggregation` + * - `created_at` (default) + * - `updated_at` + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ + @query(#{ name: "sort" }) + sort?: Common.SortQuery, + + /** + * Filter meters returned in the response. + * + * To filter meters by key add the following query param: filter[key]=my-meter-key + */ + @query(#{ style: "deepObject", explode: true }) + filter?: ListMetersParamsFilter, + ): Shared.PagePaginatedResponse | Common.ErrorResponses; + + /** + * Update a meter. + */ + @extension(Shared.UnstableExtension, true) + @put + @operationId("update-meter") + @summary("Update meter") + update(@path meterId: Shared.ULID, @body meter: Shared.UpdateRequest): + | Shared.UpdateResponse + | Common.NotFound + | Common.ErrorResponses; + + /** + * Delete a meter. + */ + @delete + @operationId("delete-meter") + @summary("Delete meter") + delete(@path meterId: Shared.ULID): + | Shared.DeleteResponse + | Common.NotFound + | Common.ErrorResponses; +} + +interface MetersQueryOperations { + /** + * Query a meter for usage. + * + * Set `Accept: application/json` (the default) to get a structured JSON response. + * Set `Accept: text/csv` to download the same data as a CSV file suitable for + * spreadsheets. The CSV columns, in order, are: + * + * `from, to, [subject,] [customer_id, customer_key, customer_name,] , value` + * + * The `subject` column is emitted only when `subject` is in the query's + * `group_by_dimensions`. The three `customer_*` columns are emitted together only + * when `customer_id` is in the query's `group_by_dimensions`. + */ + @extension(Shared.UnstableExtension, true) + @post + @operationId("query-meter") + @summary("Query meter") + @sharedRoute + query(@path meterId: Shared.ULID, @body request: MeterQueryRequest): + | { + @header contentType: "application/json"; + @body _: MeterQueryResult; + } + | Common.NotFound + | Common.ErrorResponses; + + #suppress "@openmeter/api-spec-aip/operation-summary" "Avoid duplicating the summary in OpenAPI yaml" + @extension(Shared.UnstableExtension, true) + @opExample( + #{ + returnType: #{ + contentType: "text/csv", + _: """ + from,to,value + 2023-01-01T00:00:00Z,2023-01-01T00:01:00Z,12 + 2023-01-01T00:01:00Z,2023-01-01T00:02:00Z,20 + 2023-01-01T00:02:00Z,2023-01-01T00:03:00Z,4 + """, + }, + }, + #{ title: "No group-by dimensions" } + ) + @opExample( + #{ + returnType: #{ + contentType: "text/csv", + _: """ + from,to,customer_id,customer_key,customer_name,model,type,value + 2023-01-01T00:00:00Z,2023-01-01T00:01:00Z,01G65Z755AFWAKHE12NY0CQ9FH,acme-inc,Acme Inc.,gpt-4-turbo,input,12 + 2023-01-01T00:01:00Z,2023-01-01T00:02:00Z,01G65Z755AFWAKHE12NY0CQ9FH,acme-inc,Acme Inc.,gpt-4-turbo,input,20 + 2023-01-01T00:02:00Z,2023-01-01T00:03:00Z,01G65Z755B3YZ1KRA9W8V7PS2D,globex,Globex Corp,gpt-4-turbo,output,4 + """, + }, + }, + #{ title: "Grouped by customer and dimensions" } + ) + @friendlyName("queryMeterCsv") + @post + @operationId("query-meter") + @sharedRoute + queryCsv( + @path meterId: Shared.ULID, + // Note: to avoid generating anyOf in the OpenAPI yaml, we omit the request body + // @body request: MeterQueryRequest + ): + | { + @header contentType: "text/csv"; + + @body + _: string; + } + | Common.NotFound + | Common.ErrorResponses; +} diff --git a/api/spec/packages/aip/src/meters/query.tsp b/api/spec/packages/aip/src/meters/query.tsp new file mode 100644 index 0000000000000000000000000000000000000000..ca53b3b80b8f4a7a4c7bf74a7d04d063ab5f67eb --- /dev/null +++ b/api/spec/packages/aip/src/meters/query.tsp @@ -0,0 +1,173 @@ +import "@typespec/json-schema"; +import "../shared/index.tsp"; + +using TypeSpec.JsonSchema; + +namespace Meters; + +/** + * The granularity of the time grouping. Time durations are specified in ISO 8601 + * format. + */ +@friendlyName("MeterQueryGranularity") +union MeterQueryGranularity { + /** + * 1 minute time buckets. + */ + @summary("1 minute") + Minute: "PT1M", + + /** + * 1 hour time buckets. + */ + @summary("1 hour") + Hour: "PT1H", + + /** + * 1 day time buckets. + */ + @summary("1 day") + Day: "P1D", + + /** + * 1 month time buckets. + */ + @summary("1 month") + Month: "P1M", +} + +/** + * Filters to apply to a meter query. + */ +@friendlyName("MeterQueryFilters") +model MeterQueryFilters { + /** + * Filters to apply to the dimensions of the query. For `subject` and `customer_id` + * only equals ("eq", "in") comparisons are supported. + */ + @maxProperties(10) + dimensions?: Record; +} + +/** + * A meter query request. + */ +#suppress "@openmeter/api-spec-aip/repeated-prefix-grouping" "keep the request flat" +@friendlyName("MeterQueryRequest") +@example(#{ + from: Shared.DateTime.fromISO("2023-01-01T00:00:00Z"), + to: Shared.DateTime.fromISO("2023-01-02T00:00:00Z"), + granularity: MeterQueryGranularity.Day, + time_zone: "UTC", +}) +model MeterQueryRequest { + /** + * The start of the period the usage is queried from. + */ + from?: Shared.DateTime; + + /** + * The end of the period the usage is queried to. + */ + to?: Shared.DateTime; + + /** + * The size of the time buckets to group the usage into. If not specified, the + * usage is aggregated over the entire period. + */ + granularity?: MeterQueryGranularity; + + /** + * The value is the name of the time zone as defined in the IANA Time Zone Database + * (http://www.iana.org/time-zones). The time zone is used to determine the start + * and end of the time buckets. If not specified, the UTC timezone will be used. + */ + time_zone?: string = "UTC"; + + /** + * The dimensions to group the results by. + */ + @example(#["model", "type"]) + @maxItems(100) + group_by_dimensions?: string[]; + + /** + * Filters to apply to the query. + */ + filters?: MeterQueryFilters; +} + +/** + * Meter query result. + */ +@friendlyName("MeterQueryResult") +@example(#{ + from: Shared.DateTime.fromISO("2023-01-01T00:00:00Z"), + to: Shared.DateTime.fromISO("2023-01-02T00:00:00Z"), + data: #[ + #{ + value: "12.3456", + from: Shared.DateTime.fromISO("2023-01-01T00:00:00Z"), + to: Shared.DateTime.fromISO("2023-01-02T00:00:00Z"), + dimensions: #{ + customer_id: "01G65Z755AFWAKHE12NY0CQ9FH", + `model`: "gpt-4-turbo", + type: "input", + }, + } + ], +}) +model MeterQueryResult { + /** + * The start of the period the usage is queried from. + */ + from?: Shared.DateTime; + + /** + * The end of the period the usage is queried to. + */ + to?: Shared.DateTime; + + /** + * The usage data. If no data is available, an empty array is returned. + */ + data: MeterQueryRow[]; +} + +/** + * A row in the result of a meter query. + */ +#suppress "@openmeter/api-spec-aip/repeated-prefix-grouping" "keep the row flat" +@friendlyName("MeterQueryRow") +@example(#{ + value: "12.3456", + from: Shared.DateTime.fromISO("2023-01-01T00:00:00Z"), + to: Shared.DateTime.fromISO("2023-01-02T00:00:00Z"), + dimensions: #{ + customer_id: "01G65Z755AFWAKHE12NY0CQ9FH", + `model`: "gpt-4-turbo", + type: "input", + }, +}) +model MeterQueryRow { + /** + * The aggregated value. + */ + value: Shared.Numeric; + + /** + * The start of the time bucket the value is aggregated over. + */ + from: Shared.DateTime; + + /** + * The end of the time bucket the value is aggregated over. + */ + to: Shared.DateTime; + + /** + * The dimensions the value is aggregated over. `subject` and `customer_id` are + * reserved dimensions. + */ + dimensions: Record; +} diff --git a/api/spec/packages/aip/src/openmeter.tsp b/api/spec/packages/aip/src/openmeter.tsp new file mode 100644 index 0000000000000000000000000000000000000000..93efc140694e9cbee7a1af1ba8d89276a4988a95 --- /dev/null +++ b/api/spec/packages/aip/src/openmeter.tsp @@ -0,0 +1,216 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "./shared/index.tsp"; +import "./events/index.tsp"; +import "./meters/index.tsp"; +import "./customers/index.tsp"; +import "./subscriptions/index.tsp"; +import "./apps/index.tsp"; +import "./billing/index.tsp"; +import "./currencies/index.tsp"; +import "./features/index.tsp"; +import "./llmcost/index.tsp"; +import "./productcatalog/index.tsp"; +import "./defaults/index.tsp"; +import "./governance/index.tsp"; +import "./invoices/index.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +/** + * OpenMeter is a cloud native usage metering and billing service. The API allows + * you to ingest events, query meter usage, and manage resources. + */ +@service(#{ title: "OpenMeter and Konnect Metering & Billing API" }) +@info(#{ version: "0.0.1" }) +@server("https://openmeter.cloud/api/v3", "OpenMeter Cloud") +@server( + "https://{region}.api.konghq.com/v3", + "Production region", + { + region: "us" | "eu" | "au" | "me" | "in" = "us", + } +) +@server( + "http://localhost:{port}/api/v3", + "Local", + { + port?: string = "8888", + } +) +@tagMetadata(Shared.MetersTag, #{ description: Shared.MetersDescription }) +@tagMetadata(Shared.EventsTag, #{ description: Shared.EventsDescription }) +@tagMetadata(Shared.CustomersTag, #{ description: Shared.CustomersDescription }) +@tagMetadata( + Shared.SubscriptionsTag, + #{ description: Shared.SubscriptionsDescription } +) +@tagMetadata( + Shared.EntitlementsTag, + #{ description: Shared.EntitlementsDescription } +) +@tagMetadata(Shared.AppsTag, #{ description: Shared.AppsDescription }) +@tagMetadata(Shared.BillingTag, #{ description: Shared.BillingDescription }) +@tagMetadata( + Shared.CurrenciesTag, + #{ description: Shared.CurrenciesDescription } +) +@tagMetadata(Shared.TaxTag, #{ description: Shared.TaxDescription }) +@tagMetadata(Shared.FeaturesTag, #{ description: Shared.FeaturesDescription }) +@tagMetadata(Shared.LLMCostTag, #{ description: Shared.LLMCostDescription }) +@tagMetadata( + Shared.ProductCatalogTag, + #{ description: Shared.ProductCatalogDescription } +) +@tagMetadata(Shared.DefaultsTag, #{ description: Shared.DefaultsDescription }) +@tagMetadata( + Shared.GovernanceTag, + #{ description: Shared.GovernanceDescription } +) +namespace OpenMeter; + +@route("/openmeter/events") +@tag(Shared.EventsTag) +interface EventsEndpoints extends Events.EventsOperations {} + +@route("/openmeter/meters") +@tag(Shared.MetersTag) +interface MetersEndpoints extends Meters.MetersOperations {} + +@route("/openmeter/meters/{meterId}/query") +@tag(Shared.MetersTag) +interface MetersQueryEndpoints extends Meters.MetersQueryOperations {} + +@route("/openmeter/customers") +@tag(Shared.CustomersTag) +interface CustomersEndpoints extends Customers.CustomersOperations {} + +@route("/openmeter/customers/{customerId}/billing") +@tag(Shared.CustomersTag) +interface CustomerBillingEndpoints + extends Customers.Billing.CustomerBillingOperations {} + +@route("/openmeter/customers/{customerId}/entitlement-access") +@tag(Shared.EntitlementsTag) +interface CustomerEntitlementsEndpoints + extends Entitlements.CustomerEntitlementsOperations {} + +@route("/openmeter/customers/{customerId}/credits/grants") +@tag(Shared.CustomersTag) +interface CustomerCreditGrantsEndpoints + extends Customers.Credits.Grants.CustomerCreditGrantsOperations {} + +@route("/openmeter/customers/{customerId}/credits/balance") +@tag(Shared.CustomersTag) +interface CustomerCreditBalanceEndpoints + extends Customers.Credits.Balance.CustomerCreditBalancesOperations {} + +@route("/openmeter/customers/{customerId}/credits/adjustments") +@tag(Shared.CustomersTag) +interface CustomerCreditAdjustmentsEndpoints + extends Customers.Credits.Adjustments.CustomerCreditAdjustmentsOperations {} + +@route("/openmeter/customers/{customerId}/credits/grants/{creditGrantId}") +@tag(Shared.CustomersTag) +interface CustomerCreditGrantEndpoints { + @route("/void") + voidGrant is Customers.Credits.Grants.CustomerCreditGrantVoidOperations.voidGrant; + + @route("/settlement/external") + updateExternalSettlement is Customers.Credits.Grants.CustomerCreditGrantExternalSettlementOperations.updateExternalSettlement; +} + +@route("/openmeter/customers/{customerId}/credits/transactions") +@tag(Shared.CustomersTag) +interface CustomerCreditTransactionEndpoints + extends Customers.Credits.Transactions.CustomerCreditTransactionOperations {} + +@route("/openmeter/customers/{customerId}/charges") +@tag(Shared.CustomersTag) +interface CustomerChargesEndpoints + extends Customers.Charges.CustomerChargesOperations {} + +@route("/openmeter/subscriptions") +@tag(Shared.SubscriptionsTag) +interface SubscriptionsEndpoints + extends Subscriptions.SubscriptionsOperations {} + +@route("/openmeter/subscriptions/{subscriptionId}/addons") +@tag(Shared.SubscriptionsTag) +interface SubscriptionAddonEndpoints + extends Subscriptions.SubscriptionAddonOperations {} + +@route("/openmeter/apps") +@tag(Shared.AppsTag) +interface AppsEndpoints extends Apps.AppsOperations {} + +@route("/openmeter/app-catalog") +@tag(Shared.AppsTag) +interface AppCatalogEndpoints extends Apps.AppCatalogOperations {} + +@route("/openmeter/profiles") +@tag(Shared.BillingTag) +interface BillingProfilesEndpoints extends Billing.BillingProfilesOperations {} + +@route("/openmeter/billing/invoices") +@tag(Shared.BillingTag) +interface BillingInvoicesEndpoints extends Invoices.InvoicesOperations {} + +@route("/openmeter/tax-codes") +@tag(Shared.TaxTag) +interface TaxCodesEndpoints extends Tax.TaxCodesOperations {} + +@route("/openmeter/currencies") +@tag(Shared.CurrenciesTag) +interface CurrenciesEndpoints extends Currencies.CurrenciesOperations {} + +@route("/openmeter/currencies/custom") +@tag(Shared.CurrenciesTag) +interface CurrenciesCustomEndpoints + extends Currencies.CurrenciesCustomOperations {} + +@route("/openmeter/currencies/custom/{currencyId}/cost-bases") +@tag(Shared.CurrenciesTag) +interface CurrenciesCustomCostBasesEndpoints + extends Currencies.CurrenciesCustomCostBasesOperations {} + +@route("/openmeter/features") +@tag(Shared.FeaturesTag) +interface FeaturesEndpoints extends Features.FeatureOperations {} + +@route("/openmeter/features/{featureId}/cost") +@tag(Shared.FeaturesTag) +interface FeatureCostEndpoints extends Features.FeatureCostOperations {} + +@route("/openmeter/llm-cost/prices") +@tag(Shared.LLMCostTag) +interface LLMCostPricesEndpoints extends LLMCost.LLMCostPricesOperations {} + +@route("/openmeter/llm-cost/overrides") +@tag(Shared.LLMCostTag) +interface LLMCostOverridesEndpoints + extends LLMCost.LLMCostOverridesOperations {} + +@route("/openmeter/plans") +@tag(Shared.ProductCatalogTag) +interface PlansEndpoints extends ProductCatalog.PlanOperations {} + +@route("/openmeter/addons") +@tag(Shared.ProductCatalogTag) +interface AddonsEndpoints extends ProductCatalog.AddonOperations {} + +@route("/openmeter/plans/{planId}/addons") +@tag(Shared.ProductCatalogTag) +interface PlanAddonEndpoints extends ProductCatalog.PlanAddonOperations {} + +@route("/openmeter/defaults/tax-codes") +@tag(Shared.DefaultsTag) +interface OrganizationDefaultTaxCodesEndpoints + extends Defaults.OrganizationDefaultTaxCodesOperations {} + +@route("/openmeter/governance") +@tag(Shared.GovernanceTag) +interface GovernanceEndpoints extends Governance.GovernanceOperations {} diff --git a/api/spec/packages/aip/src/productcatalog/addon.tsp b/api/spec/packages/aip/src/productcatalog/addon.tsp new file mode 100644 index 0000000000000000000000000000000000000000..35919b90995eee3b98806c394beb6691d91b3d90 --- /dev/null +++ b/api/spec/packages/aip/src/productcatalog/addon.tsp @@ -0,0 +1,116 @@ +import "../shared/index.tsp"; +import "./ratecard.tsp"; +import "./plan.tsp"; + +namespace ProductCatalog; + +/** + * The status of the add-on defined by the `effective_from` and `effective_to` + * properties. + * + * - `draft`: The add-on has not yet been published and can be edited. + * - `active`: The add-on is published and available for use. + * - `archived`: The add-on is no longer available for use. + */ +@friendlyName("AddonStatus") +enum AddonStatus { + Draft: "draft", + Active: "active", + Archived: "archived", +} + +/** + * The instanceType of the add-on. + * + * - `single`: Can be added to a subscription only once. + * - `multiple`: Can be added to a subscription more than once. + */ +@friendlyName("AddonInstanceType") +enum AddonInstanceType { + Single: "single", + Multiple: "multiple", +} + +/** + * Add-on allows extending subscriptions with compatible plans with additional + * ratecards. + */ +#suppress "@openmeter/api-spec-aip/repeated-prefix-grouping" "effective_from and effective_to are standard AIP temporal fields" +@friendlyName("Addon") +model Addon { + ...Shared.Resource; + + /** + * A key is a semi-unique string that is used to identify the add-on. It is used to + * reference the latest `active` version of the add-on and is unique with the + * version number. + */ + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Key") + key: Shared.ResourceKey; + + /** + * Version of the add-on. Incremented when the add-on is updated. + */ + @summary("Version") + @minValue(1) + @visibility(Lifecycle.Read) + version: integer = 1; + + /** + * The InstanceType of the add-ons. Can be "single" or "multiple". + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("The InstanceType of the add-ons. Can be \"single\" or \"multiple\".") + instance_type: AddonInstanceType; + + /** + * The currency code of the add-on. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Currency") + currency: Currencies.CurrencyCode; + + /** + * The date and time when the add-on becomes effective. When not specified, the + * add-on is a draft. + */ + @visibility(Lifecycle.Read) + @summary("Effective start date") + effective_from?: Shared.DateTime; + + /** + * The date and time when the add-on is no longer effective. When not specified, + * the add-on is effective indefinitely. + */ + @visibility(Lifecycle.Read) + @summary("Effective end date") + effective_to?: Shared.DateTime; + + /** + * The status of the add-on. Computed based on the effective start and end dates: + * + * - `draft`: `effective_from` is not set. + * - `active`: `effective_from <= now` and (`effective_to` is not set or + * `now < effective_to`). + * - `archived`: `effective_to <= now`. + */ + @summary("Status") + @visibility(Lifecycle.Read) + status: AddonStatus; + + /** + * The rate cards of the add-on. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Rate cards") + rate_cards: RateCard[]; + + /** + * List of validation errors. + */ + @visibility(Lifecycle.Read) + @summary("Validation errors") + validation_errors?: ProductCatalogValidationError[]; +} diff --git a/api/spec/packages/aip/src/productcatalog/index.tsp b/api/spec/packages/aip/src/productcatalog/index.tsp new file mode 100644 index 0000000000000000000000000000000000000000..1101edb0f5a5c5fe1fb97721ec124e86fb3883e2 --- /dev/null +++ b/api/spec/packages/aip/src/productcatalog/index.tsp @@ -0,0 +1,7 @@ +import "./price.tsp"; +import "./unitconfig.tsp"; +import "./ratecard.tsp"; +import "./plan.tsp"; +import "./addon.tsp"; +import "./planaddon.tsp"; +import "./operations.tsp"; diff --git a/api/spec/packages/aip/src/productcatalog/operations.tsp b/api/spec/packages/aip/src/productcatalog/operations.tsp new file mode 100644 index 0000000000000000000000000000000000000000..b182f1cc77f475babad37daf2c7e2770f3427c80 --- /dev/null +++ b/api/spec/packages/aip/src/productcatalog/operations.tsp @@ -0,0 +1,341 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "../common/error.tsp"; +import "../common/pagination.tsp"; +import "../common/parameters.tsp"; +import "../shared/index.tsp"; +import "./ratecard.tsp"; +import "./plan.tsp"; +import "./planaddon.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace ProductCatalog; + +/** + * Filter options for listing plans. + */ +@friendlyName("ListPlansParamsFilter") +model ListPlansParamsFilter { + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + key?: Common.StringFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + name?: Common.StringFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + status?: Common.StringFieldFilterExact; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + currency?: Common.StringFieldFilterExact; +} + +interface PlanOperations { + /** + * List all plans. + */ + @get + @operationId("list-plans") + @summary("List plans") + @extension(Shared.UnstableExtension, true) + listPlans( + ...Common.PagePaginationQuery, + + /** + * Sort plans returned in the response. Supported sort attributes are: + * + * - `id` + * - `key` + * - `version` + * - `created_at` (default) + * - `updated_at` + */ + @query(#{ name: "sort" }) + sort?: Common.SortQuery, + + /** + * Filter plans returned in the response. + */ + @query(#{ style: "deepObject", explode: true }) + filter?: ListPlansParamsFilter, + ): Shared.PagePaginatedResponse | Common.ErrorResponses; + + /** + * Create a new plan. + */ + @post + @operationId("create-plan") + @summary("Create plan") + @extension(Shared.UnstableExtension, true) + createPlan(@body plan: Shared.CreateRequest): + | Shared.CreateResponse + | Common.ErrorResponses; + + /** + * Update a plan by id. + */ + @put + @route("/{planId}") + @operationId("update-plan") + @summary("Update plan") + @extension(Shared.UnstableExtension, true) + updatePlan( + @path planId: Shared.ULID, + @body plan: Shared.UpsertRequest, + ): + | Shared.UpsertResponse + | Common.ErrorResponses + | Common.Gone + | Common.NotFound; + + /** + * Get a plan by id. + */ + @get + @route("/{planId}") + @operationId("get-plan") + @summary("Get plan") + @extension(Shared.UnstableExtension, true) + getPlan(@path planId: Shared.ULID): + | Shared.GetResponse + | Common.ErrorResponses + | Common.Gone + | Common.NotFound; + + /** + * Delete a plan by id. + */ + @delete + @route("/{planId}") + @operationId("delete-plan") + @summary("Delete plan") + @extension(Shared.UnstableExtension, true) + deletePlan(@path planId: Shared.ULID): + | Shared.DeleteResponse + | Common.ErrorResponses + | Common.NotFound; + + /** + * Archive a plan version. + */ + @post + @route("/{planId}/archive") + @operationId("archive-plan") + @summary("Archive plan version") + @extension(Shared.UnstableExtension, true) + archivePlan(@path planId: Shared.ULID): + | Shared.UpdateResponse + | Common.ErrorResponses + | Common.NotFound; + + /** + * Publish a plan version. + */ + @post + @route("/{planId}/publish") + @operationId("publish-plan") + @summary("Publish plan version") + @extension(Shared.UnstableExtension, true) + publishPlan(@path planId: Shared.ULID): + | Shared.UpdateResponse + | Common.ErrorResponses + | Common.NotFound; +} + +/** + * Filter options for listing add-ons. + */ +@friendlyName("ListAddonsParamsFilter") +model ListAddonsParamsFilter { + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + id?: Common.ULIDFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + key?: Common.StringFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + name?: Common.StringFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + status?: Common.StringFieldFilterExact; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + currency?: Common.StringFieldFilterExact; +} + +interface AddonOperations { + /** + * List all add-ons. + */ + @get + @operationId("list-addons") + @summary("List add-ons") + @extension(Shared.UnstableExtension, true) + listAddons( + ...Common.PagePaginationQuery, + + /** + * Sort add-ons returned in the response. Supported sort attributes are: + * + * - `id` + * - `key` + * - `name` + * - `created_at` (default) + * - `updated_at` + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ + @query(#{ name: "sort" }) + sort?: Common.SortQuery, + + /** + * Filter add-ons returned in the response. + */ + @query(#{ style: "deepObject", explode: true }) + filter?: ListAddonsParamsFilter, + ): Shared.PagePaginatedResponse | Common.ErrorResponses; + + /** + * Create a new add-on. + */ + @post + @operationId("create-addon") + @summary("Create add-on") + @extension(Shared.UnstableExtension, true) + createAddon(@body addon: Shared.CreateRequest): + | Shared.CreateResponse + | Common.ErrorResponses; + + /** + * Update an add-on by id. + */ + @put + @route("/{addonId}") + @operationId("update-addon") + @summary("Update add-on") + @extension(Shared.UnstableExtension, true) + updateAddon( + @path addonId: Shared.ULID, + @body addon: Shared.UpsertRequest, + ): + | Shared.UpsertResponse + | Common.ErrorResponses + | Common.Gone + | Common.NotFound; + + /** + * Get add-on by id. + */ + @get + @route("/{addonId}") + @operationId("get-addon") + @summary("Get add-on") + @extension(Shared.UnstableExtension, true) + getAddon(@path addonId: Shared.ULID): + | Shared.GetResponse + | Common.ErrorResponses + | Common.Gone + | Common.NotFound; + + /** + * Soft delete add-on by id. + */ + @delete + @route("/{addonId}") + @operationId("delete-addon") + @summary("Soft delete add-on") + @extension(Shared.UnstableExtension, true) + deleteAddon(@path addonId: Shared.ULID): + | Shared.DeleteResponse + | Common.ErrorResponses + | Common.NotFound; + + /** + * Archive an add-on version. + */ + @post + @route("/{addonId}/archive") + @operationId("archive-addon") + @summary("Archive add-on version") + @extension(Shared.UnstableExtension, true) + archiveAddon(@path addonId: Shared.ULID): + | Shared.UpdateResponse + | Common.ErrorResponses + | Common.NotFound; + + /** + * Publish an add-on version. + */ + @post + @route("/{addonId}/publish") + @operationId("publish-addon") + @summary("Publish add-on version") + @extension(Shared.UnstableExtension, true) + publishAddon(@path addonId: Shared.ULID): + | Shared.UpdateResponse + | Common.ErrorResponses + | Common.NotFound; +} + +interface PlanAddonOperations { + /** + * List add-ons associated with a plan. + */ + @get + @operationId("list-plan-addons") + @summary("List add-ons for plan") + @extension(Shared.UnstableExtension, true) + listPlanAddons(@path planId: Shared.ULID, ...Common.PagePaginationQuery): + | Shared.PagePaginatedResponse + | Common.ErrorResponses + | Common.NotFound; + + /** + * Add an add-on to a plan. + */ + @post + @operationId("create-plan-addon") + @summary("Add add-on to plan") + @extension(Shared.UnstableExtension, true) + createPlanAddon( + @path planId: Shared.ULID, + @body plan_addon: Shared.CreateRequest, + ): Shared.CreateResponse | Common.ErrorResponses | Common.NotFound; + + /** + * Get an add-on association for a plan. + */ + @get + @route("/{planAddonId}") + @operationId("get-plan-addon") + @summary("Get add-on association for plan") + @extension(Shared.UnstableExtension, true) + getPlanAddon(@path planId: Shared.ULID, @path planAddonId: Shared.ULID): + | Shared.GetResponse + | Common.ErrorResponses + | Common.NotFound; + + /** + * Update an add-on association for a plan. + */ + @put + @route("/{planAddonId}") + @operationId("update-plan-addon") + @summary("Update add-on association for plan") + @extension(Shared.UnstableExtension, true) + updatePlanAddon( + @path planId: Shared.ULID, + @path planAddonId: Shared.ULID, + @body plan_addon: Shared.UpsertRequest, + ): Shared.UpsertResponse | Common.ErrorResponses | Common.NotFound; + + /** + * Remove an add-on from a plan. + */ + @delete + @route("/{planAddonId}") + @operationId("delete-plan-addon") + @summary("Remove add-on from plan") + @extension(Shared.UnstableExtension, true) + deletePlanAddon(@path planId: Shared.ULID, @path planAddonId: Shared.ULID): + | Shared.DeleteResponse + | Common.ErrorResponses + | Common.NotFound; +} diff --git a/api/spec/packages/aip/src/productcatalog/plan.tsp b/api/spec/packages/aip/src/productcatalog/plan.tsp new file mode 100644 index 0000000000000000000000000000000000000000..8c220283d5f541fbc66d34978f0493fd5ca40e3d --- /dev/null +++ b/api/spec/packages/aip/src/productcatalog/plan.tsp @@ -0,0 +1,170 @@ +import "../shared/index.tsp"; +import "./ratecard.tsp"; + +namespace ProductCatalog; + +/** + * The status of a plan. + * + * - `draft`: The plan has not yet been published and can be edited. + * - `active`: The plan is published and can be used in subscriptions. + * - `archived`: The plan is no longer available for use. + * - `scheduled`: The plan is scheduled to be published at a future date. + */ +@friendlyName("BillingPlanStatus") +enum PlanStatus { + Draft: "draft", + Active: "active", + Archived: "archived", + Scheduled: "scheduled", +} + +/** + * Plans provide a template for subscriptions. + */ +#suppress "@openmeter/api-spec-aip/repeated-prefix-grouping" "effective_from and effective_to are standard AIP temporal fields" +@friendlyName("BillingPlan") +model Plan { + ...Shared.Resource; + + /** + * A key is a semi-unique string that is used to identify the plan. It is used to + * reference the latest `active` version of the plan and is unique with the version + * number. + */ + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Key") + key: Shared.ResourceKey; + + /** + * Plans are versioned to allow you to make changes without affecting running + * subscriptions. + */ + @visibility(Lifecycle.Read) + @summary("Version") + @minValue(1) + version: integer = 1; + + /** + * The currency code of the plan. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Currency") + currency: Shared.CurrencyCode; + + /** + * The billing cadence for subscriptions using this plan. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Billing cadence") + billing_cadence: Shared.ISO8601Duration; + + /** + * Whether pro-rating is enabled for this plan. + */ + // TODO: WIP — pro-rating mode and exact semantics will be defined in a later iteration. + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Pro-rating enabled") + pro_rating_enabled?: boolean = true; + + /** + * The date and time when the plan becomes `active`. When not specified, the plan + * is in `draft` status. + */ + @visibility(Lifecycle.Read) + @summary("Effective start date") + effective_from?: Shared.DateTime; + + /** + * A scheduled date and time when the plan becomes `archived`. When not specified, + * the plan is in `active` status indefinitely. + */ + @visibility(Lifecycle.Read) + @summary("Effective end date") + effective_to?: Shared.DateTime; + + /** + * The status of the plan. Computed based on the effective start and end dates: + * + * - `draft`: `effective_from` is not set. + * - `scheduled`: `now < effective_from`. + * - `active`: `effective_from <= now` and (`effective_to` is not set or + * `now < effective_to`). + * - `archived`: `effective_to <= now`. + */ + @visibility(Lifecycle.Read) + @summary("Status") + status: PlanStatus; + + /** + * The plan phases define the pricing ramp for a subscription. A phase switch + * occurs only at the end of a billing period. At least one phase is required. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Plan phases") + @minItems(1) + phases: PlanPhase[]; + + /** + * Settlement mode for plan. + * + * Values: + * + * - `credit_then_invoice`: Credits are applied first, then any remainder is + * invoiced. + * - `credit_only`: Usage is settled exclusively against credits. + */ + @visibility(Lifecycle.Read) + @summary("Settlement Mode") + settlement_mode?: ProductCatalog.SettlementMode = ProductCatalog.SettlementMode.CreditThenInvoice; + + /** + * List of validation errors in `draft` state that prevent the plan from being + * published. + */ + @visibility(Lifecycle.Read) + @summary("Validation errors") + validation_errors?: ProductCatalogValidationError[]; +} + +/** + * Validation errors providing detailed description of the issue. + */ +@friendlyName("ProductCatalogValidationError") +model ProductCatalogValidationError is Shared.BaseError { + /** + * The path to the field. + */ + @visibility(Lifecycle.Read) + @summary("Field") + @example("addons/pro/ratecards/token/featureKey") + field: string; +} + +/** + * The plan phase or pricing ramp allows changing a plan's rate cards over time as + * a subscription progresses. + */ +@friendlyName("BillingPlanPhase") +model PlanPhase { + ...PickProperties< + Shared.ResourceWithKey, + "key" | "name" | "description" | "labels" + >; + + /** + * The duration of the phase. When not specified, the phase runs indefinitely. Only + * the last phase may omit the duration. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Duration") + duration?: Shared.ISO8601Duration; + + /** + * The rate cards of the plan. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Rate cards") + rate_cards: RateCard[]; +} diff --git a/api/spec/packages/aip/src/productcatalog/planaddon.tsp b/api/spec/packages/aip/src/productcatalog/planaddon.tsp new file mode 100644 index 0000000000000000000000000000000000000000..ce08da8525e0cbb2dd052823f2588a80aa6b4397 --- /dev/null +++ b/api/spec/packages/aip/src/productcatalog/planaddon.tsp @@ -0,0 +1,44 @@ +import "./addon.tsp"; +import "./plan.tsp"; + +namespace ProductCatalog; + +/** + * PlanAddon represents an association between a plan and an add-on, controlling + * which add-ons are available for purchase within a plan. + */ +@friendlyName("PlanAddon") +model PlanAddon { + ...Shared.Resource; + + /** + * The add-on associated with the plan. + */ + @summary("Add-on") + @visibility(Lifecycle.Read, Lifecycle.Create) + addon: Shared.ResourceReference; + + /** + * The key of the plan phase from which the add-on becomes available for purchase. + */ + @summary("From plan phase") + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + from_plan_phase: Shared.ResourceKey; + + /** + * The maximum number of times the add-on can be purchased for the plan. For + * single-instance add-ons this field must be omitted. For multi-instance add-ons + * when omitted, unlimited quantity can be purchased. + */ + @summary("Max quantity") + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @minValue(1) + max_quantity?: integer; + + /** + * List of validation errors. + */ + @summary("Validation errors") + @visibility(Lifecycle.Read) + validation_errors?: ProductCatalogValidationError[]; +} diff --git a/api/spec/packages/aip/src/productcatalog/price.tsp b/api/spec/packages/aip/src/productcatalog/price.tsp new file mode 100644 index 0000000000000000000000000000000000000000..73b470cd05ac8fbb3e35ca1d58fc05a336373672 --- /dev/null +++ b/api/spec/packages/aip/src/productcatalog/price.tsp @@ -0,0 +1,238 @@ +import "../shared/index.tsp"; + +namespace ProductCatalog; + +/** + * The type of the price. + * + * - `free`: No charge, the rate card is included at no cost. + * - `flat`: A fixed amount charged once per billing period, regardless of usage. + * - `unit`: A fixed rate charged per billing unit consumed. + * - `graduated`: Tiered pricing where each tier's rate applies only to usage + * within that tier. + * - `volume`: Tiered pricing where the rate for the highest tier reached applies + * to all units in the period. + */ +@friendlyName("BillingPriceType") +enum PriceType { + Free: "free", + Flat: "flat", + Unit: "unit", + Graduated: "graduated", + Volume: "volume", +} + +/** + * Price. + */ +@friendlyName("BillingPrice") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union Price { + @summary("Free price") + free: PriceFree, + + @summary("Flat price") + flat: PriceFlat, + + @summary("Unit price") + unit: PriceUnit, + + @summary("Graduated price") + graduated: PriceGraduated, + + @summary("Volume price") + volume: PriceVolume, +} + +/** + * Usage-based price types that can appear on a usage-based rate card. + * + * When UnitConfig is present on the rate card, these price types operate on + * billing units (i.e. post-conversion quantities), not raw metered units. + */ +@friendlyName("BillingPriceUsageBased") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union PriceUsageBased { + unit: PriceUnit, + graduated: PriceGraduated, + volume: PriceVolume, +} + +/** + * The payment term of a flat price. + */ +@friendlyName("BillingPricePaymentTerm") +union PricePaymentTerm { + /** + * If in_advance, the rate card will be invoiced in the previous billing cycle. + */ + InAdvance: "in_advance", + + /** + * If in_arrears, the rate card will be invoiced in the current billing cycle. + */ + InArrears: "in_arrears", +} + +/** + * Free price. + */ +@friendlyName("BillingPriceFree") +model PriceFree { + /** + * The type of the price. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Type") + type: PriceType.Free; +} + +/** + * Flat price. + */ +@friendlyName("BillingPriceFlat") +model PriceFlat { + /** + * The type of the price. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Type") + type: PriceType.Flat; + + /** + * The amount of the flat price. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Amount") + amount: Shared.Numeric; +} + +/** + * Unit price. + * + * Charges a fixed rate per billing unit. When UnitConfig is present on the rate + * card, billing units are the converted quantities (e.g. GB instead of bytes). + */ +@friendlyName("BillingPriceUnit") +model PriceUnit { + /** + * The type of the price. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Type") + type: PriceType.Unit; + + /** + * The amount of the unit price. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Amount") + amount: Shared.Numeric; +} + +/** + * Graduated tiered price. + * + * Each tier's rate applies only to the usage within that tier. Pricing can change + * as cumulative usage crosses tier boundaries. + * + * When UnitConfig is present on the rate card, tier boundaries (up_to_amount) are + * expressed in converted billing units. + */ +@friendlyName("BillingPriceGraduated") +model PriceGraduated { + /** + * The type of the price. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Type") + type: PriceType.Graduated; + + /** + * The tiers of the graduated price. At least one tier is required. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Tiers") + @minItems(1) + tiers: PriceTier[]; +} + +/** + * Volume tiered price. + * + * The maximum quantity within a period determines the per-unit price for all units + * in that period. + * + * When UnitConfig is present on the rate card, tier boundaries (up_to_amount) are + * expressed in converted billing units. + */ +@friendlyName("BillingPriceVolume") +model PriceVolume { + /** + * The type of the price. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Type") + type: PriceType.Volume; + + /** + * The tiers of the volume price. At least one tier is required. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Tiers") + @minItems(1) + tiers: PriceTier[]; +} + +/** + * A price tier used in graduated and volume pricing. + * + * At least one price component (flat_price or unit_price) must be set. When + * UnitConfig is present on the rate card, up_to_amount is expressed in converted + * billing units. + */ +@friendlyName("BillingPriceTier") +model PriceTier { + /** + * Up to and including this quantity will be contained in the tier. If undefined, + * the tier is open-ended (the last tier). + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Up to quantity") + up_to_amount?: Shared.Numeric; + + /** + * The flat price component of the tier. Charged once when the tier is entered. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Flat price component") + flat_price?: PriceFlat; + + /** + * The unit price component of the tier. Charged per billing unit within the tier. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Unit price component") + unit_price?: PriceUnit; +} + +/** + * Spend commitments for a rate card. The customer is committed to spend at least + * the minimum amount and at most the maximum amount. + */ +@friendlyName("BillingSpendCommitments") +model SpendCommitments { + /** + * The customer is committed to spend at least the amount. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Minimum amount") + minimum_amount?: Shared.Numeric; + + /** + * The customer is limited to spend at most the amount. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Maximum amount") + maximum_amount?: Shared.Numeric; +} diff --git a/api/spec/packages/aip/src/productcatalog/ratecard.tsp b/api/spec/packages/aip/src/productcatalog/ratecard.tsp new file mode 100644 index 0000000000000000000000000000000000000000..a06036e212913a75404e0bbe94cff7bc1a1dc3de --- /dev/null +++ b/api/spec/packages/aip/src/productcatalog/ratecard.tsp @@ -0,0 +1,171 @@ +import "../shared/index.tsp"; +import "../billing/tax.tsp"; +import "../features/index.tsp"; +import "../tax/codes.tsp"; +import "../entitlements/index.tsp"; +import "./price.tsp"; +import "./unitconfig.tsp"; + +namespace ProductCatalog; + +/** + * Settlement mode for billing. + * + * Values: + * + * - `credit_then_invoice`: Credits are applied first, then any remainder is + * invoiced. + * - `credit_only`: Usage is settled exclusively against credits. + */ +@friendlyName("BillingSettlementMode") +@summary("Settlement mode") +enum SettlementMode { + CreditThenInvoice: "credit_then_invoice", + CreditOnly: "credit_only", +} + +/** + * A rate card defines the pricing and entitlement of a feature or service. + */ +@friendlyName("BillingRateCard") +model RateCard { + ...PickProperties< + Shared.ResourceWithKey, + "key" | "name" | "description" | "labels" + >; + + /** + * The feature associated with the rate card. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Feature reference") + feature?: Shared.ResourceReference; + + /** + * The billing cadence of the rate card. When null, the charge is one-time + * (non-recurring). Only valid for flat prices. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Billing cadence") + billing_cadence?: Shared.ISO8601Duration; + + /** + * The price of the rate card. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Price") + price: Price; + + /** + * Unit conversion configuration for the rate card. + * + * Synthesized on read for plans authored with v1 dynamic or package prices: + * dynamic prices map to a unit price with a multiply unit config, and package + * prices map to a unit price with a divide unit config. + * + * Accepted on create and update only when the UnitConfig feature is enabled on the + * deployment; otherwise rejected. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Unit config") + unit_config?: UnitConfig; + + /** + * The payment term of the rate card. In advance payment term can only be used for + * flat prices. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Payment term") + payment_term?: PricePaymentTerm = PricePaymentTerm.InArrears; + + /** + * Spend commitments for this rate card. Only applicable to usage-based prices + * (unit, graduated, volume). + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Commitments") + commitments?: SpendCommitments; + + /** + * The discounts of the rate card. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Discounts") + discounts?: Discounts; + + /** + * The tax config of the rate card. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Tax config") + tax_config?: RateCardTaxConfig; + + /** + * The entitlement template granted to subscribers of a plan or addon containing + * this rate card. Requires `feature` to be set. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Entitlement template") + entitlement?: Entitlements.RateCardEntitlement; +} + +/** + * The tax config of the rate card. + */ +@friendlyName("BillingRateCardTaxConfig") +model RateCardTaxConfig { + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + behavior?: Billing.TaxBehavior; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + code: Shared.ResourceReference; +} + +/** + * Discount configuration for a rate card. + */ +@friendlyName("BillingRateCardDiscounts") +model Discounts { + /** + * Percentage discount applied to the price (0–100). + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @minValue(0) + @maxValue(100) + percentage?: float; + + /** + * Number of usage units granted free before billing starts. Only applies to + * usage-based lines (not flat fees). Usage is treated as zero until this amount is + * exhausted. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + usage?: Shared.Numeric; +} + +/** + * The proration configuration of the rate card. + */ +@friendlyName("BillingRateCardProrationConfiguration") +model ProrationConfiguration { + /** + * The proration mode of the rate card. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Proration mode") + mode: ProrationMode; +} + +/** + * The proration mode of the rate card. + * + * Values: + * + * - `no_proration`: No proration. + * - `prorate_prices`: Prorate the price based on the time remaining in the billing + * period. + */ +@friendlyName("BillingRateCardProrationMode") +enum ProrationMode { + NoProration: "no_proration", + ProratePrices: "prorate_prices", +} diff --git a/api/spec/packages/aip/src/productcatalog/unitconfig.tsp b/api/spec/packages/aip/src/productcatalog/unitconfig.tsp new file mode 100644 index 0000000000000000000000000000000000000000..b113fc55b8942fe5f7454c902006a7ba1de745a3 --- /dev/null +++ b/api/spec/packages/aip/src/productcatalog/unitconfig.tsp @@ -0,0 +1,158 @@ +import "../shared/index.tsp"; +import "./price.tsp"; + +namespace ProductCatalog; + +/** + * The arithmetic operation used to convert raw metered units into billing units. + * + * - `divide`: Divide the metered quantity by the conversion factor (e.g., bytes ÷ + * 1e9 = GB). + * - `multiply`: Multiply the metered quantity by the conversion factor (e.g., cost + * × 1.2 = cost + 20% margin). + */ +@friendlyName("BillingUnitConfigOperation") +enum UnitConfigOperation { + Divide: "divide", + Multiply: "multiply", +} + +/** + * The rounding mode applied to the converted quantity for invoicing. + * + * Rounding is applied only to the invoiced quantity. Entitlement balance checks + * use the precise decimal value after conversion. + * + * - `ceiling`: Round up to the next integer (typical for package-style billing). + * - `floor`: Round down to the previous integer. + * - `half_up`: Round to the nearest integer, with 0.5 rounding up. + * - `none`: No rounding; the converted value is used as-is. + */ +@friendlyName("BillingUnitConfigRoundingMode") +enum UnitConfigRoundingMode { + Ceiling: "ceiling", + Floor: "floor", + HalfUp: "half_up", + None: "none", +} + +/** + * Unit conversion configuration. + * + * Transforms raw metered quantities into billing-ready units before pricing and + * entitlement evaluation. Applied at the rate card level so the same feature can + * be billed in different units across plans. + * + * Examples: + * + * - Meter bytes, bill GB: operation=divide, conversionFactor=1e9, + * rounding=ceiling, displayUnit="GB" + * - Meter seconds, bill hours: operation=divide, conversionFactor=3600, + * rounding=ceiling, displayUnit="hours" + * - Cost + 20% margin: operation=multiply, conversionFactor=1.2 + * - Bill per million tokens: operation=divide, conversionFactor=1e6, + * rounding=ceiling, displayUnit="M" + * + * v1 equivalents: + * + * - DynamicPrice(multiplier): operation=multiply, conversionFactor=multiplier + + * UnitPrice(amount=1) + * - PackagePrice(amount, quantityPerPkg): operation=divide, + * conversionFactor=quantityPerPkg, rounding=ceiling + UnitPrice(amount) + */ +@friendlyName("BillingUnitConfig") +model UnitConfig { + /** + * The arithmetic operation to apply to the raw metered quantity. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Conversion operation") + operation: UnitConfigOperation; + + /** + * The factor used in the conversion operation. + * + * - For `divide`: `converted = raw / conversionFactor`. + * - For `multiply`: `converted = raw × conversionFactor`. + * + * Must be a positive non-zero value. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Conversion factor") + conversion_factor: Shared.Numeric; + + /** + * The rounding mode applied to the converted quantity for invoicing. + * + * Defaults to none (no rounding). Entitlement checks always use the precise + * (unrounded) value. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Rounding mode") + rounding?: UnitConfigRoundingMode = UnitConfigRoundingMode.None; + + /** + * The number of decimal places to retain after rounding. + * + * Only meaningful when rounding is not "none". Defaults to 0 (round to whole + * numbers). + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Rounding precision (decimal places)") + precision?: integer = 0; + + /** + * A human-readable label for the converted unit shown on invoices and in the + * customer portal (e.g., "GB", "hours", "M tokens"). + * + * Optional. When omitted, no unit label is rendered. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Display unit label") + display_unit?: string; +} + +/** + * Usage quantity details on an invoice line item when UnitConfig is in effect. + * + * Provides the full audit trail from raw meter output to the invoiced amount. + */ +@friendlyName("BillingInvoiceUsageQuantityDetail") +model InvoiceUsageQuantityDetail { + /** + * The raw quantity as reported by the meter (native units). + */ + @visibility(Lifecycle.Read) + @summary("Raw metered quantity") + raw_quantity: Shared.Numeric; + + /** + * The precise decimal value after applying the conversion operation and factor, + * before rounding. + */ + @visibility(Lifecycle.Read) + @summary("Converted quantity (precise)") + converted_quantity: Shared.Numeric; + + /** + * The quantity after rounding, used for pricing. + */ + @visibility(Lifecycle.Read) + @summary("Invoiced quantity (rounded)") + invoiced_quantity: Shared.Numeric; + + /** + * The display unit label (e.g., "GB", "hours", "M tokens"). + */ + @visibility(Lifecycle.Read) + @summary("Display unit") + display_unit?: string; + + /** + * Snapshot of the UnitConfig that was in effect at billing time. Ensures + * historical invoices reflect the config that was actually applied. + */ + @visibility(Lifecycle.Read) + @summary("Applied unit config snapshot") + applied_unit_config: UnitConfig; +} diff --git a/api/spec/packages/aip/src/shared/address.tsp b/api/spec/packages/aip/src/shared/address.tsp new file mode 100644 index 0000000000000000000000000000000000000000..8bb360c8ad9f2b346e419a74af120802c75f9076 --- /dev/null +++ b/api/spec/packages/aip/src/shared/address.tsp @@ -0,0 +1,59 @@ +import "./properties.tsp"; + +namespace Shared; + +/** + * Address + */ +@friendlyName("Address") +model Address { + /** + * Country code in [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) + * alpha-2 format. + */ + @visibility(Lifecycle.Create, Lifecycle.Read, Lifecycle.Update) + @summary("Country") + country?: CountryCode; + + /** + * Postal code. + */ + @visibility(Lifecycle.Create, Lifecycle.Read, Lifecycle.Update) + @summary("Postal Code") + postal_code?: string; + + /** + * State or province. + */ + @visibility(Lifecycle.Create, Lifecycle.Read, Lifecycle.Update) + @summary("State") + state?: string; + + /** + * City. + */ + @visibility(Lifecycle.Create, Lifecycle.Read, Lifecycle.Update) + @summary("City") + city?: string; + + /** + * First line of the address. + */ + @visibility(Lifecycle.Create, Lifecycle.Read, Lifecycle.Update) + @summary("Line 1") + line1?: string; + + /** + * Second line of the address. + */ + @visibility(Lifecycle.Create, Lifecycle.Read, Lifecycle.Update) + @summary("Line 2") + line2?: string; + + /** + * Phone number. + */ + @visibility(Lifecycle.Create, Lifecycle.Read, Lifecycle.Update) + @summary("Phone Number") + phone_number?: string; +} diff --git a/api/spec/packages/aip/src/shared/consts.tsp b/api/spec/packages/aip/src/shared/consts.tsp new file mode 100644 index 0000000000000000000000000000000000000000..b1181a009fd1454466baabfbe3f60c430ddbd073 --- /dev/null +++ b/api/spec/packages/aip/src/shared/consts.tsp @@ -0,0 +1,53 @@ +namespace Shared; + +const MeteringAndBillingTitle = "Metering & Billing"; +const OpenMeterTitle = "OpenMeter"; + +const MetersTag = "Meters"; +const MetersDescription = "Meters specify how to aggregate events for billing and analytics purposes. Meters can be configured with multiple aggregation methods and groupings. Multiple meters can be created for the same event type, enabling flexible metering scenarios."; + +const EventsTag = "Metering Events"; +const EventsDescription = "Metering events are used to track usage of your product or service. Events are processed asynchronously by the meters, so they may not be immediately available for querying."; + +const CustomersTag = "OpenMeter Customers"; +const CustomersDescription = "Customers are used to track usage of your product or service. Customers can be individuals or organizations that can subscribe to plans and have access to features."; + +const EntitlementsTag = "OpenMeter Entitlements"; +const EntitlementsDescription = "Entitlements are used to control access to features for customers."; + +const SubscriptionsTag = "OpenMeter Subscriptions"; +const SubscriptionsDescription = "Subscriptions are used to track usage of your product or service. Subscriptions can be individuals or organizations that can subscribe to plans and have access to features."; + +const AppsTag = "OpenMeter Apps"; +const AppsDescription = "Apps enable you to extend and customize billing and usage workflows by integrating with external systems and services. Apps can automate and enhance your billing ecosystem by supporting capabilities such as synchronizing usage data with third-party platforms, calculating taxes, generating and delivering invoices, handling payment collection, and other billing-related tasks."; + +const BillingTag = "OpenMeter Billing Settings"; +const BillingDescription = "Billing settings manages the billing profiles and invoices for customers."; + +const CurrenciesTag = "OpenMeter Currencies"; +const CurrenciesDescription = "Currencies and cost bases for customers."; + +const TaxTag = "OpenMeter Tax"; +const TaxDescription = "Tax codes are used to calculate taxes for customers."; + +const LLMCostTag = "OpenMeter LLM Cost"; +const LLMCostDescription = "LLM cost database providing normalized pricing data for language models across providers. Prices are synced from multiple external sources and auto-confirmed when they agree."; + +const FeaturesTag = "OpenMeter Features"; +const FeaturesDescription = "Features represent product capabilities backed by meters, with optional per-unit cost configuration."; + +const ProductCatalogTag = "OpenMeter Product Catalog"; +const ProductCatalogDescription = "Product catalog manages plans, add-ons, and their associations for subscription-based billing."; + +const DefaultsTag = "OpenMeter Defaults"; +const DefaultsDescription = "Organization-level default configuration."; + +const GovernanceTag = "OpenMeter Governance"; +const GovernanceDescription = "Governance evaluation of customers to check their feature access."; + +// The functionality should be considered unstable. +const UnstableExtension = "x-unstable"; +// The functionality is internal and should not be used by customers. +const InternalExtension = "x-internal"; +// The functionality is private and should not be exposed to customers. +const PrivateExtension = "x-private"; diff --git a/api/spec/packages/aip/src/shared/enums.tsp b/api/spec/packages/aip/src/shared/enums.tsp new file mode 100644 index 0000000000000000000000000000000000000000..54050b434cb830fd8d5abd2a1a49054a73d5c946 --- /dev/null +++ b/api/spec/packages/aip/src/shared/enums.tsp @@ -0,0 +1,17 @@ +namespace Shared; + +/** + * Identifies whether a resource lifecycle is controlled by OpenMeter or manually + * overridden by the API user. + * + * Values: + * + * - `system`: The resource lifecycle is controlled by OpenMeter. + * - `manual`: The resource lifecycle was manually overridden by the API user. + */ +@friendlyName("BillingLifecycleController") +@summary("Lifecycle controller") +enum LifecycleController { + System: "system", + Manual: "manual", +} diff --git a/api/spec/packages/aip/src/shared/errors.tsp b/api/spec/packages/aip/src/shared/errors.tsp new file mode 100644 index 0000000000000000000000000000000000000000..b86e5ec081af7e328fa003ae3e06d8c90d28485c --- /dev/null +++ b/api/spec/packages/aip/src/shared/errors.tsp @@ -0,0 +1,50 @@ +namespace Shared; + +/** + * Shared properties for inline errors returned inside a 2xx response. + * + * Use for partially successful responses (e.g. per-item failures alongside + * a `data` array) or for pre-flight findings on resources that are not yet + * finalized (e.g. validation errors on a draft resource). + * + * This is **not** an RFC-7807 problem detail. RFC-7807 covers errors that + * fail the whole request; inline errors live as fields on the response or + * resource model. + * + * Compose with `is` and add domain-specific identifying fields as needed: + * + * ```tsp + * @friendlyName("MyOperationError") + * model MyOperationError is Shared.BaseError { + * // domain-specific identifiers, e.g. the input that produced the error + * subject?: string; + * } + * ``` + * + * `T` is the type of the `code` field. Prefer a domain-scoped enum with an + * `Unknown: "unknown"` zero member so codes stay discoverable and stable. + * Use `string` only when the set of codes is open-ended. + */ +@friendlyName("BaseError") +model BaseError { + /** + * Machine-readable error code. + */ + @visibility(Lifecycle.Read) + @summary("Code") + code: T; + + /** + * Human-readable description of the error. + */ + @visibility(Lifecycle.Read) + @summary("Message") + message: string; + + /** + * Additional structured context. + */ + @visibility(Lifecycle.Read) + @summary("Attributes") + attributes?: Record; +} diff --git a/api/spec/packages/aip/src/shared/filters.tsp b/api/spec/packages/aip/src/shared/filters.tsp new file mode 100644 index 0000000000000000000000000000000000000000..586b05f6288a4de0ebe6eec80b625145e0c60a6e --- /dev/null +++ b/api/spec/packages/aip/src/shared/filters.tsp @@ -0,0 +1,286 @@ +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "@typespec/json-schema"; +import "./properties.tsp"; + +using TypeSpec.JsonSchema; + +namespace Shared; + +/** + * A query filter for a string attribute. Operators are mutually exclusive, only + * one operator is allowed at a time. + */ +@friendlyName("QueryFilterString") +@summary("Query String Filter") +model QueryFilterString { + /** + * The attribute equals the provided value. + */ + eq?: string; + + /** + * The attribute does not equal the provided value. + */ + neq?: string; + + /** + * The attribute is one of the provided values. + */ + @minItems(1) + @maxItems(100) + in?: string[]; + + /** + * The attribute is not one of the provided values. + */ + @minItems(1) + @maxItems(100) + nin?: string[]; + + /** + * The attribute contains the provided value. + */ + contains?: string; + + /** + * The attribute does not contain the provided value. + */ + ncontains?: string; + + /** + * Combines the provided filters with a logical AND. + */ + @minItems(1) + @maxItems(10) + and?: QueryFilterString[]; + + /** + * Combines the provided filters with a logical OR. + */ + @minItems(1) + @maxItems(10) + or?: QueryFilterString[]; +} + +/** + * A query filter for an item in a string map attribute. Operators are mutually + * exclusive, only one operator is allowed at a time. + */ +@friendlyName("QueryFilterStringMapItem") +@summary("Query String Map Item Filter") +model QueryFilterStringMapItem { + /** + * The attribute exists. + */ + exists?: boolean; + + ...QueryFilterString; +} + +alias QueryFilterStringMap = Record; + +/** + * A query filter for an integer attribute. Operators are mutually exclusive, only + * one operator is allowed at a time. + */ +@friendlyName("QueryFilterInteger") +@summary("Query Integer Filter") +model QueryFilterInteger { + /** + * The attribute equals the provided value. + */ + eq?: integer; + + /** + * The attribute does not equal the provided value. + */ + neq?: integer; + + /** + * The attribute is one of the provided values. + */ + @minItems(1) + @maxItems(100) + in?: integer[]; + + /** + * The attribute is not one of the provided values. + */ + @minItems(1) + @maxItems(100) + nin?: integer[]; + + /** + * The attribute is greater than the provided value. + */ + gt?: integer; + + /** + * The attribute is greater than or equal to the provided value. + */ + gte?: integer; + + /** + * The attribute is less than the provided value. + */ + lt?: integer; + + /** + * The attribute is less than or equal to the provided value. + */ + lte?: integer; + + /** + * Combines the provided filters with a logical AND. + */ + @minItems(1) + @maxItems(10) + and?: QueryFilterInteger[]; + + /** + * Combines the provided filters with a logical OR. + */ + @minItems(1) + @maxItems(10) + or?: QueryFilterInteger[]; +} + +/** + * A query filter for a float attribute. Operators are mutually exclusive, only one + * operator is allowed at a time. + */ +@friendlyName("QueryFilterFloat") +@summary("Query Float Filter") +model QueryFilterFloat { + /** + * The attribute is greater than the provided value. + */ + gt?: float64; + + /** + * The attribute is greater than or equal to the provided value. + */ + gte?: float64; + + /** + * The attribute is less than the provided value. + */ + lt?: float64; + + /** + * The attribute is less than or equal to the provided value. + */ + lte?: float64; + + /** + * Combines the provided filters with a logical AND. + */ + @minItems(1) + @maxItems(10) + and?: QueryFilterFloat[]; + + /** + * Combines the provided filters with a logical OR. + */ + @minItems(1) + @maxItems(10) + or?: QueryFilterFloat[]; +} + +/** + * A query filter for a numeric attribute. Operators are mutually exclusive, only + * one operator is allowed at a time. + */ +@friendlyName("QueryFilterNumeric") +@summary("Query Numeric Filter") +model QueryFilterNumeric { + /** + * The attribute is greater than the provided value. + */ + gt?: Shared.Numeric; + + /** + * The attribute is greater than or equal to the provided value. + */ + gte?: Shared.Numeric; + + /** + * The attribute is less than the provided value. + */ + lt?: Shared.Numeric; + + /** + * The attribute is less than or equal to the provided value. + */ + lte?: Shared.Numeric; + + /** + * Combines the provided filters with a logical AND. + */ + @minItems(1) + @maxItems(10) + and?: QueryFilterNumeric[]; + + /** + * Combines the provided filters with a logical OR. + */ + @minItems(1) + @maxItems(10) + or?: QueryFilterNumeric[]; +} + +/** + * A query filter for a boolean attribute. Operators are mutually exclusive, only + * one operator is allowed at a time. + */ +@friendlyName("QueryFilterBoolean") +@summary("Query Boolean Filter") +model QueryFilterBoolean { + /** + * The attribute equals the provided value. + */ + eq?: boolean; +} + +/** + * A query filter for a time attribute. Operators are mutually exclusive, only one + * operator is allowed at a time. + */ +@friendlyName("QueryFilterDateTime") +@summary("Query Date-time Filter") +model QueryFilterDateTime { + /** + * The attribute is greater than the provided value. + */ + gt?: DateTime; + + /** + * The attribute is greater than or equal to the provided value. + */ + gte?: DateTime; + + /** + * The attribute is less than the provided value. + */ + lt?: DateTime; + + /** + * The attribute is less than or equal to the provided value. + */ + lte?: DateTime; + + /** + * Combines the provided filters with a logical AND. + */ + @minItems(1) + @maxItems(10) + and?: QueryFilterDateTime[]; + + /** + * Combines the provided filters with a logical OR. + */ + @minItems(1) + @maxItems(10) + or?: QueryFilterDateTime[]; +} diff --git a/api/spec/packages/aip/src/shared/index.tsp b/api/spec/packages/aip/src/shared/index.tsp new file mode 100644 index 0000000000000000000000000000000000000000..306d0993f78b2b94ddbf68a7cffdc2deacc5e8db --- /dev/null +++ b/api/spec/packages/aip/src/shared/index.tsp @@ -0,0 +1,10 @@ +import "./address.tsp"; +import "./consts.tsp"; +import "./enums.tsp"; +import "./errors.tsp"; +import "./filters.tsp"; +import "./parameters.tsp"; +import "./properties.tsp"; +import "./request.tsp"; +import "./resource.tsp"; +import "./responses.tsp"; diff --git a/api/spec/packages/aip/src/shared/parameters.tsp b/api/spec/packages/aip/src/shared/parameters.tsp new file mode 100644 index 0000000000000000000000000000000000000000..58294ce684ff2e44429de330829a44e6eb8406a6 --- /dev/null +++ b/api/spec/packages/aip/src/shared/parameters.tsp @@ -0,0 +1,23 @@ +import "@typespec/http"; +import "../common/parameters.tsp"; + +namespace Shared; + +/** + * Resource filters. + */ +@friendlyName("ResourceFilters") +model ResourceFilters { + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + name?: Common.StringFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + labels?: Common.LabelsFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + public_labels?: Common.LabelsFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + created_at?: Common.DateTimeFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + updated_at?: Common.DateTimeFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + deleted_at?: Common.DateTimeFieldFilter; +} diff --git a/api/spec/packages/aip/src/shared/properties.tsp b/api/spec/packages/aip/src/shared/properties.tsp new file mode 100644 index 0000000000000000000000000000000000000000..59721b0a298474300e3eb74f412ee0290f82e1cf --- /dev/null +++ b/api/spec/packages/aip/src/shared/properties.tsp @@ -0,0 +1,186 @@ +import "../common/properties.tsp"; + +namespace Shared; + +// See: https://github.com/ulid/spec/issues/94 +/** + * ULID (Universally Unique Lexicographically Sortable Identifier). + */ +@pattern("^[0-7][0-9A-HJKMNP-TV-Z]{25}$") +@example("01G65Z755AFWAKHE12NY0CQ9FH") +@friendlyName("ULID") +@summary("ULID") +scalar ULID extends string; + +/** + * A key is a unique string that is used to identify a resource. + */ +@pattern( + "^[a-z0-9]+(?:_[a-z0-9]+)*$", + "Must start with a lowercase letter or a number. Can contain lowercase letters, numbers, and underscores." +) +@minLength(1) +@maxLength(64) +@friendlyName("ResourceKey") +@summary("Resource Key") +@example("resource_key") +scalar ResourceKey extends string; + +/** + * ULID ID or Resource Key. + */ +@friendlyName("ULIDOrResourceKey") +@summary("ULID ID or Resource Key") +union ULIDOrResourceKey { + id: ULID, + key: ResourceKey, +} + +/** + * ExternalResourceKey is a unique string that is used to identify a resource in an + * external system. + */ +@maxLength(256) +@minLength(1) +@friendlyName("ExternalResourceKey") +@summary("External Resource Key") +@example("019ae40f-4258-7f15-9491-842f42a7d6ac") +scalar ExternalResourceKey extends string; + +/** + * ULID ID or External Resource Key. + */ +@friendlyName("ULIDOrExternalResourceKey") +@summary("ULID ID or External Resource Key") +union ULIDOrExternalResourceKey { + id: ULID, + key: ExternalResourceKey, +} + +/** + * [RFC3339](https://tools.ietf.org/html/rfc3339) formatted date-time string in + * UTC. + */ +@encode(DateTimeKnownEncoding.rfc3339) +@friendlyName("DateTime") +@summary("RFC3339 Date-Time") +@example(DateTime.fromISO("2023-01-01T01:01:01.001Z")) +scalar DateTime extends utcDateTime; + +// This is a reasonably good RE2-safe ISO8601 duration pattern that allows fractional components (though overly permissive) +// It matches patterns such as +// - P1Y +// - P1.5Y +// - P1Y2M1D +// - P1Y2MT <= invalid: must have time component defined after T +// - P1Y2MT1H2S +// - P1Y2.3MT1.4H2S <= invalid: spec only allows for a single fractional component +// +// A stricter alternative that doesn't allow fractional components is: ^P(?:\d+Y)?(?:\d+M)?(?:\d+W)?(?:\d+D)?(?:T(?:\d+H)?(?:\d+M)?(?:\d+S)?)?$ +// ^before using the stricter pattern make sure to double escape the backslashes +/** + * [ISO 8601 Duration](https://docs.digi.com/resources/documentation/digidocs/90001488-13/reference/r_iso_8601_duration_format.htm) + * string. + */ +@encode(DurationKnownEncoding.ISO8601) +@pattern("^P(?:\\d+(?:\\.\\d+)?Y)?(?:\\d+(?:\\.\\d+)?M)?(?:\\d+(?:\\.\\d+)?W)?(?:\\d+(?:\\.\\d+)?D)?(?:T(?:\\d+(?:\\.\\d+)?H)?(?:\\d+(?:\\.\\d+)?M)?(?:\\d+(?:\\.\\d+)?S)?)?$") +@friendlyName("ISO8601Duration") +@summary("ISO 8601 Duration") +@example("P1Y") +scalar ISO8601Duration extends string; + +/** + * Three-letter [ISO4217](https://www.iso.org/iso-4217-currency-codes.html) + * currency code. Custom three-letter currency codes are also supported for + * convenience. + */ +@pattern("^[A-Z]{3}$") +@friendlyName("CurrencyCode") +@minLength(3) +@maxLength(3) +@example("USD") +scalar CurrencyCode extends string; + +/** + * [ISO 3166-1](https://www.iso.org/iso-3166-country-codes.html) alpha-2 country + * code. Custom two-letter country codes are also supported for convenience. + */ +@pattern("^[A-Z]{2}$") +@friendlyName("CountryCode") +@minLength(2) +@maxLength(2) +@example("US") +scalar CountryCode extends string; + +/** + * Numeric represents an arbitrary precision number. + */ +@pattern("^\\-?[0-9]+(\\.[0-9]+)?$") +@friendlyName("Numeric") +scalar Numeric extends string; + +/** + * Monetary amount in a specific currency. + */ +@friendlyName("CurrencyAmount") +model CurrencyAmount { + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + amount: Shared.Numeric; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + currency: Shared.CurrencyCode; +} + +/** + * Tax identifier code is a normalized tax code shown on the original identity + * document. + */ +@minLength(1) +@maxLength(32) +@friendlyName("BillingTaxIdentificationCode") +scalar TaxIdentificationCode extends string; + +/** + * Recurring period with an anchor and an interval. + */ +@friendlyName("RecurringPeriod") +model RecurringPeriod { + /** + * A date-time anchor to base the recurring period on. + */ + @summary("Anchor time") + @example(DateTime.fromISO("2023-01-01T01:01:01.001Z")) + anchor: DateTime; + + /** + * The interval duration in ISO 8601 format. + */ + @summary("Interval in ISO 8601 duration format") + @example("P1M") + interval: ISO8601Duration; +} + +/** + * A period with defined start and end dates. + * + * The period is always inclusive at the start and exclusive at the end. + */ +@friendlyName("ClosedPeriod") +model ClosedPeriod { + /** + * The start of the period. + * + * The period is inclusive at the start. + */ + @summary("Start") + @example(DateTime.fromISO("2023-01-01T01:01:01.001Z")) + from: DateTime; + + /** + * The end of the period. + * + * The period is exclusive at the end. + */ + @summary("End") + @example(DateTime.fromISO("2023-01-01T01:01:01.001Z")) + to: DateTime; +} diff --git a/api/spec/packages/aip/src/shared/request.tsp b/api/spec/packages/aip/src/shared/request.tsp new file mode 100644 index 0000000000000000000000000000000000000000..4cdadc71bf13f2686e6c98842e3c1e890321ecaf --- /dev/null +++ b/api/spec/packages/aip/src/shared/request.tsp @@ -0,0 +1,42 @@ +import "@typespec/rest"; + +namespace Shared; + +@doc("{name} create request.", T) +@friendlyName("Create{name}Request", T) +@withVisibility(Lifecycle.Create) +model CreateRequest is DefaultKeyVisibility; + +// Supports visibility filtering for models with nested fields. +@doc("{name} create request.", T) +@friendlyName("Create{name}Request", T) +model CreateRequestNested + is FilterVisibility< + DefaultKeyVisibility, + #{ all: #[Lifecycle.Create] }, + "Create{name}" + >; + +@doc("{name} upsert request.", T) +@friendlyName("Upsert{name}Request", T) +@withVisibility(Lifecycle.Create, Lifecycle.Update) +model UpsertRequest is DefaultKeyVisibility; + +@doc("{name} update request.", T) +@friendlyName("Update{name}Request", T) +@withVisibility(Lifecycle.Update) +model UpdateRequest + is OptionalProperties>>; + +// Supports visibility filtering for models with nested fields. +@doc("{name} update request.", T) +@friendlyName("Update{name}Request", T) +model UpdateRequestNested + is FilterVisibility< + DefaultKeyVisibility, + #{ all: #[Lifecycle.Update] }, + "Update{name}" + >; diff --git a/api/spec/packages/aip/src/shared/resource.tsp b/api/spec/packages/aip/src/shared/resource.tsp new file mode 100644 index 0000000000000000000000000000000000000000..650a67da6189f20a907ccc4356d6892b41d258a2 --- /dev/null +++ b/api/spec/packages/aip/src/shared/resource.tsp @@ -0,0 +1,83 @@ +import "../common/properties.tsp"; +import "./properties.tsp"; + +namespace Shared; + +/** + * Represents common fields of resources. + */ +@friendlyName("Resource") +model Resource { + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + @visibility(Lifecycle.Read) + id: ULID; + + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @minLength(1) + @maxLength(256) + name: string; + + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + @maxLength(1024) + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + description?: string; + + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + labels?: Common.Labels; + + /** + * An ISO-8601 timestamp representation of entity creation date. + */ + @visibility(Lifecycle.Read) + created_at: DateTime; + + /** + * An ISO-8601 timestamp representation of entity last update date. + */ + @visibility(Lifecycle.Read) + updated_at: DateTime; + + /** + * An ISO-8601 timestamp representation of entity deletion date. + */ + @visibility(Lifecycle.Read) + deleted_at?: DateTime; +} + +/** + * Represents common fields of resources with a key. + */ +@friendlyName("ResourceWithKey") +model ResourceWithKey { + ...Resource; + + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + @visibility(Lifecycle.Read, Lifecycle.Create) + key: ResourceKey; +} + +/** + * Represents common fields of immutable resources. + */ +@friendlyName("ResourceImmutable") +model ResourceImmutable { + ...OmitProperties; +} + +@doc("{name} reference.", T) +@friendlyName("{name}Reference", T) +model ResourceReference { + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + id: ULID; +} diff --git a/api/spec/packages/aip/src/shared/responses.tsp b/api/spec/packages/aip/src/shared/responses.tsp new file mode 100644 index 0000000000000000000000000000000000000000..87478fa53b45d194cdc645eb5456699a228ec778 --- /dev/null +++ b/api/spec/packages/aip/src/shared/responses.tsp @@ -0,0 +1,65 @@ +import "@typespec/rest"; +import "@typespec/http"; +import "../common/properties.tsp"; + +namespace Shared; + +@doc("{name} response.", T) +@friendlyName("Get{name}Response", T) +model GetResponse { + @Http.statusCode _: 200; + @Http.body body: T; +} + +@doc("{name} created response.", T) +@friendlyName("Create{name}Response", T) +model CreateResponse { + @Http.statusCode _: 201; + @Http.body body: T; +} + +@doc("{name} upsert response.", T) +@friendlyName("Upsert{name}Response", T) +model UpsertResponse { + @Http.statusCode _: 200; + @Http.body body: T; +} + +@doc("{name} updated response.", T) +@friendlyName("Update{name}Response", T) +model UpdateResponse { + @Http.statusCode _: 200; + @Http.body body: T; +} + +@doc("Deleted response.") +@friendlyName("DeleteResponse") +model DeleteResponse { + @Http.statusCode _: 204; +} + +/** + * Cursor paginated response. + */ +@friendlyName("{name}PaginatedResponse", T) +model CursorPaginatedResponse { + @Http.statusCode _: 200; + + @pageItems + data: T[]; + + meta: Common.CursorMeta; +} + +/** + * Page paginated response. + */ +@friendlyName("{name}PagePaginatedResponse", T) +model PagePaginatedResponse { + @Http.statusCode _: 200; + + @pageItems + data: T[]; + + meta: Common.PageMeta; +} diff --git a/api/spec/packages/aip/src/subscriptions/index.tsp b/api/spec/packages/aip/src/subscriptions/index.tsp new file mode 100644 index 0000000000000000000000000000000000000000..9a7ae7fabf116205453af36f4db973bc07072fce --- /dev/null +++ b/api/spec/packages/aip/src/subscriptions/index.tsp @@ -0,0 +1,5 @@ +import "./subscription.tsp"; +import "./subscriptionaddon.tsp"; +import "./operations.tsp"; +import "./reference.tsp"; +import "./subscriptionaddon.tsp"; diff --git a/api/spec/packages/aip/src/subscriptions/operations.tsp b/api/spec/packages/aip/src/subscriptions/operations.tsp new file mode 100644 index 0000000000000000000000000000000000000000..b2a0274836a87a4c42d4cae8022a0e47bf8cfc92 --- /dev/null +++ b/api/spec/packages/aip/src/subscriptions/operations.tsp @@ -0,0 +1,232 @@ +import "@typespec/http"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "../shared/index.tsp"; +import "../common/error.tsp"; +import "../common/pagination.tsp"; +import "../common/parameters.tsp"; +import "./subscription.tsp"; +import "./subscriptionaddon.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Subscriptions; + +/** + * Request for canceling a subscription. + */ +@friendlyName("BillingSubscriptionCancel") +model SubscriptionCancel { + /** + * If not provided the subscription is canceled immediately. + */ + timing?: SubscriptionEditTiming = SubscriptionEditTimingEnum.Immediate; +} + +/** + * Request for changing a subscription. + */ +@friendlyName("BillingSubscriptionChange") +model SubscriptionChange { + ...OmitProperties; + + /** + * Timing configuration for the change, when the change should take effect. For + * changing a subscription, the accepted values depend on the subscription + * configuration. + */ + timing: SubscriptionEditTiming; +} + +/** + * Response for changing a subscription. + */ +@friendlyName("BillingSubscriptionChangeResponse") +model SubscriptionChangeResponse { + /** + * The current subscription before the change. + */ + current: Subscription; + + /** + * The new state of the subscription after the change. + */ + next: Subscription; +} + +/** + * Filter options for listing subscriptions. + */ +#suppress "@openmeter/api-spec-aip/repeated-prefix-grouping" "plan_id and plan_key should not be grouped" +@friendlyName("ListSubscriptionsParamsFilter") +model ListSubscriptionsParamsFilter { + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + id?: Common.ULIDFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + customer_id?: Common.ULIDFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + status?: Common.StringFieldFilterExact; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + plan_id?: Common.ULIDFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "shared model" + plan_key?: Common.StringFieldFilterExact; +} + +interface SubscriptionsOperations { + @post + @operationId("create-subscription") + @summary("Create subscription") + create(@body subscription: SubscriptionCreate): + | Shared.CreateResponse + | Common.NotFound + | Common.Conflict + | Common.ErrorResponses; + + @get + @operationId("list-subscriptions") + @summary("List subscriptions") + list( + ...Common.PagePaginationQuery, + + /** + * Sort subscriptions returned in the response. Supported sort attributes are: + * + * - `id` + * - `active_from` (default) + * - `active_to` + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ + @query(#{ name: "sort" }) + sort?: Common.SortQuery, + + /** + * Filter subscriptions. + */ + @query(#{ style: "deepObject", explode: true }) + filter?: ListSubscriptionsParamsFilter, + ): + | Shared.PagePaginatedResponse + | Common.NotFound + | Common.ErrorResponses; + + @get + @operationId("get-subscription") + @summary("Get subscription") + get(@path subscriptionId: Shared.ULID): + | Shared.GetResponse + | Common.NotFound + | Common.ErrorResponses; + + /** + * Cancels the subscription. Will result in a scheduling conflict if there are + * other subscriptions scheduled to start after the cancelation time. + */ + @post + @operationId("cancel-subscription") + @summary("Cancel subscription") + @route("/{subscriptionId}/cancel") + cancel(@path subscriptionId: Shared.ULID, @body body: SubscriptionCancel): + | Shared.UpdateResponse + | Common.NotFound + | Common.Conflict + | Common.ErrorResponses; + + /** + * Unschedules the subscription cancelation. + */ + @post + @operationId("unschedule-cancelation") + @summary("Unschedule subscription cancelation") + @route("/{subscriptionId}/unschedule-cancelation") + unscheduleCancelation(@path subscriptionId: Shared.ULID): + | Shared.UpdateResponse + | Common.NotFound + | Common.Conflict + | Common.ErrorResponses; + + /** + * Closes a running subscription and starts a new one according to the + * specification. Can be used for upgrades, downgrades, and plan changes. + */ + @post + @operationId("change-subscription") + @summary("Change subscription") + @route("/{subscriptionId}/change") + change( + @path subscriptionId: Shared.ULID, + + @body + body: SubscriptionChange, + ): + | SubscriptionChangeResponse + | Common.NotFound + | Common.Conflict + | Common.ErrorResponses; +} + +interface SubscriptionAddonOperations { + /** + * Add add-on to a subscription. + */ + @post + @operationId("create-subscription-addon") + @summary("Create a new subscription add-on") + @extension(Shared.UnstableExtension, true) + @extension(Shared.InternalExtension, true) + create( + @path subscriptionId: Shared.ULID, + @body request: Shared.CreateRequest, + ): + | Shared.CreateResponse + | Common.ErrorResponses + | Common.NotFound + | Common.Conflict; + + /** + * List the add-ons of a subscription. + */ + @get + @operationId("list-subscription-addons") + @summary("List subscription addons") + @extension(Shared.UnstableExtension, true) + list( + @path subscriptionId: Shared.ULID, + ...Common.PagePaginationQuery, + + /** + * Sort subscription addons returned in the response. Supported sort attributes + * are: + * + * - `id` + * - `created_at` (default) + * - `updated_at` + * + * The `asc` suffix is optional as the default sort order is ascending. The `desc` + * suffix is used to specify a descending order. + */ + @query(#{ name: "sort" }) + sort?: Common.SortQuery, + ): + | Shared.PagePaginatedResponse + | Common.NotFound + | Common.ErrorResponses; + + /** + * Get an add-on association for a subscription. + */ + @get + @route("/{subscriptionAddonId}") + @operationId("get-subscription-addon") + @summary("Get add-on association for subscription") + @extension(Shared.UnstableExtension, true) + getAddon( + @path subscriptionId: Shared.ULID, + @path subscriptionAddonId: Shared.ULID, + ): + | Shared.GetResponse + | Common.ErrorResponses + | Common.NotFound; +} diff --git a/api/spec/packages/aip/src/subscriptions/reference.tsp b/api/spec/packages/aip/src/subscriptions/reference.tsp new file mode 100644 index 0000000000000000000000000000000000000000..3b5d24c84fabc3f388ddb4d9c6bd7fdd6dfee9fe --- /dev/null +++ b/api/spec/packages/aip/src/subscriptions/reference.tsp @@ -0,0 +1,45 @@ +import "../shared/index.tsp"; + +namespace Subscriptions; + +/** + * Subscription reference represents a reference to the specific subscription item + * this entity represents. + */ +@friendlyName("BillingSubscriptionReference") +model SubscriptionReference { + /** + * The ID of the subscription. + */ + @visibility(Lifecycle.Read) + @summary("Subscription ID") + id: Shared.ULID; + + /** + * The phase of the subscription. + */ + @visibility(Lifecycle.Read) + @summary("Phase ID") + phase: { + /** + * The ID of the phase. + */ + @visibility(Lifecycle.Read) + @summary("Phase ID") + id: Shared.ULID; + + /** + * The item of the phase. + */ + @visibility(Lifecycle.Read) + @summary("Item ID") + item: { + /** + * The ID of the item. + */ + @visibility(Lifecycle.Read) + @summary("Item ID") + id: Shared.ULID; + }; + }; +} diff --git a/api/spec/packages/aip/src/subscriptions/subscription.tsp b/api/spec/packages/aip/src/subscriptions/subscription.tsp new file mode 100644 index 0000000000000000000000000000000000000000..014aec1648edd3e19423e86a08def03cd23ed3aa --- /dev/null +++ b/api/spec/packages/aip/src/subscriptions/subscription.tsp @@ -0,0 +1,183 @@ +import "@typespec/openapi"; +import "../shared/index.tsp"; +import "../productcatalog/ratecard.tsp"; + +using TypeSpec.OpenAPI; + +namespace Subscriptions; + +/** + * Subscription status. + */ +@friendlyName("BillingSubscriptionStatus") +enum SubscriptionStatus { + Active: "active", + Inactive: "inactive", + Canceled: "canceled", + Scheduled: "scheduled", +} + +/** + * Subscription edit timing. When immediate, the requested changes take effect + * immediately. When next_billing_cycle, the requested changes take effect at the + * next billing cycle. + */ +@friendlyName("BillingSubscriptionEditTimingEnum") +enum SubscriptionEditTimingEnum { + Immediate: "immediate", + NextBillingCycle: "next_billing_cycle", +} + +/** + * Subscription edit timing defined when the changes should take effect. If the + * provided configuration is not supported by the subscription, an error will be + * returned. + */ +@oneOf +@friendlyName("BillingSubscriptionEditTiming") +@example(SubscriptionEditTimingEnum.Immediate) +union SubscriptionEditTiming { + Enum: SubscriptionEditTimingEnum, + Custom: Shared.DateTime, +} + +/** + * Subscription create request. + */ +@friendlyName("BillingSubscriptionCreate") +model SubscriptionCreate { + ...Shared.CreateRequest>; + + /** + * The customer to create the subscription for. + */ + customer: { + /** + * The ID of the customer to create the subscription for. + * + * Either customer ID or customer key must be provided. If both are provided, the + * ID will be used. + */ + @visibility(Lifecycle.Create) + @summary("Customer ID") + id?: Shared.ULID; + + /** + * The key of the customer to create the subscription for. + * + * Either customer ID or customer key must be provided. If both are provided, the + * ID will be used. + */ + @visibility(Lifecycle.Create) + @summary("Customer Key") + key?: Shared.ExternalResourceKey; + }; + + /** + * The plan reference of the subscription. + */ + plan: { + /** + * The plan ID of the subscription. Set if subscription is created from a plan. + * + * ID or Key of the plan is required if creating a subscription from a plan. If + * both are provided, the ID will be used. + */ + @visibility(Lifecycle.Create) + @summary("Plan ID") + id?: Shared.ULID; + + /** + * The plan Key of the subscription, if any. Set if subscription is created from a + * plan. + * + * ID or Key of the plan is required if creating a subscription from a plan. If + * both are provided, the ID will be used. + */ + @visibility(Lifecycle.Create) + @summary("Plan Key") + key?: Shared.ResourceKey; + + /** + * The plan version of the subscription, if any. If not provided, the latest + * version of the plan will be used. + */ + @visibility(Lifecycle.Create) + @summary("Plan Version") + version?: integer; + }; + + /** + * A billing anchor is the fixed point in time that determines the subscription's + * recurring billing cycle. It affects when charges occur and how prorations are + * calculated. Common anchors: + * + * - Calendar month (1st of each month): `2025-01-01T00:00:00Z` + * - Subscription anniversary (day customer signed up) + * - Custom date (customer-specified day) + * + * If not provided, the subscription will be created with the subscription's + * creation time as the billing anchor. + */ + @visibility(Lifecycle.Create) + @summary("Billing anchor") + billing_anchor?: Shared.DateTime; +} + +/** + * Subscription. + */ +@friendlyName("BillingSubscription") +model Subscription { + ...OmitProperties; + + /** + * The customer ID of the subscription. + */ + @visibility(Lifecycle.Read) + @summary("Customer ID") + customer_id: Shared.ULID; + + /** + * The plan ID of the subscription. Set if subscription is created from a plan. + */ + @visibility(Lifecycle.Read) + @summary("Plan ID") + plan_id?: Shared.ULID; + + /** + * A billing anchor is the fixed point in time that determines the subscription's + * recurring billing cycle. It affects when charges occur and how prorations are + * calculated. Common anchors: + * + * - Calendar month (1st of each month): `2025-01-01T00:00:00Z` + * - Subscription anniversary (day customer signed up) + * - Custom date (customer-specified day) + */ + @visibility(Lifecycle.Read) + @summary("Billing anchor") + billing_anchor: Shared.DateTime; + + /** + * The status of the subscription. + */ + @visibility(Lifecycle.Read) + @summary("Status") + status: SubscriptionStatus; + + /** + * Settlement mode for billing. + * + * Values: + * + * - `credit_then_invoice`: Credits are applied first, then any remainder is + * invoiced. + * - `credit_only`: Usage is settled exclusively against credits. + */ + @visibility(Lifecycle.Create, Lifecycle.Read) + @summary("Settlement Mode") + settlement_mode?: ProductCatalog.SettlementMode; +} diff --git a/api/spec/packages/aip/src/subscriptions/subscriptionaddon.tsp b/api/spec/packages/aip/src/subscriptions/subscriptionaddon.tsp new file mode 100644 index 0000000000000000000000000000000000000000..9a8409f2a0ad5e45a55e969aa8b82c8ee66d6be6 --- /dev/null +++ b/api/spec/packages/aip/src/subscriptions/subscriptionaddon.tsp @@ -0,0 +1,150 @@ +import "../productcatalog/addon.tsp"; +import "../productcatalog/ratecard.tsp"; + +namespace Subscriptions; + +/** + * Addon purchased with a subscription. + */ +#suppress "@openmeter/api-spec-aip/repeated-prefix-grouping" "active_from and active_to should not be grouped" +@friendlyName("SubscriptionAddon") +model SubscriptionAddon { + ...OmitProperties; + + /** + * Display name of the resource. + * + * Between 1 and 256 characters. + */ + @visibility(Lifecycle.Read) + @minLength(1) + @maxLength(256) + name: string; + + /** + * Optional description of the resource. + * + * Maximum 1024 characters. + */ + @maxLength(1024) + @visibility(Lifecycle.Read) + description?: string; + + /** + * The add-on associated with the subscription. + */ + @summary("Add-on") + @visibility(Lifecycle.Read, Lifecycle.Create) + addon: Shared.ResourceReference; + + /** + * The quantity of the add-on. Always 1 for single instance add-ons. + */ + @summary("Quantity") + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @minValue(1) + quantity: integer; + + /** + * An ISO-8601 timestamp representation of which point in time the quantity was + * resolved to. + */ + @visibility(Lifecycle.Read) + quantity_at: Shared.DateTime; + + /** + * An ISO-8601 timestamp representation of the cadence start of the resource. + */ + @visibility(Lifecycle.Read) + active_from: Shared.DateTime; + + /** + * An ISO-8601 timestamp representation of the cadence end of the resource. + */ + @visibility(Lifecycle.Read) + active_to?: Shared.DateTime; + + /** + * The timing of the operation. After the create or update, a new entry will be + * created in the timeline. + */ + @summary("Timing") + @visibility(Lifecycle.Create, Lifecycle.Update) + timing: SubscriptionEditTiming; + + /** + * The timeline of the add-on. The returned periods are sorted and continuous. + */ + @visibility(Lifecycle.Read) + @summary("Timeline") + @example(#[ + #{ + quantity: 1, + active_from: Shared.DateTime.fromISO("2025-01-01T00:00:00Z"), + active_to: Shared.DateTime.fromISO("2025-01-02T00:00:00Z"), + }, + #{ + quantity: 0, + active_from: Shared.DateTime.fromISO("2025-01-02T00:00:00Z"), + active_to: Shared.DateTime.fromISO("2025-01-03T00:00:00Z"), + }, + #{ + quantity: 1, + active_from: Shared.DateTime.fromISO("2025-01-03T00:00:00Z"), + } + ]) + timeline: SubscriptionAddonTimelineSegment[]; + + /** + * The rate cards of the add-on. + */ + @visibility(Lifecycle.Read) + @summary("Rate cards") + rate_cards: SubscriptionAddonRateCard[]; +} + +/** + * A rate card for a subscription add-on. + */ +@friendlyName("SubscriptionAddonRateCard") +model SubscriptionAddonRateCard { + /** + * The rate card. + */ + @summary("Rate card") + rate_card: ProductCatalog.RateCard; + + /** + * The IDs of the subscription items that this rate card belongs to. + */ + @summary("Affected subscription item IDs") + @visibility(Lifecycle.Read) + affected_subscription_item_ids: Shared.ULID[]; +} + +/** + * A subscription add-on event. + */ +@friendlyName("SubscriptionAddonTimelineSegment") +model SubscriptionAddonTimelineSegment { + /** + * An ISO-8601 timestamp representation of the cadence start of the resource. + */ + @visibility(Lifecycle.Read) + active_from: Shared.DateTime; + + /** + * An ISO-8601 timestamp representation of the cadence end of the resource. + */ + @visibility(Lifecycle.Read) + active_to?: Shared.DateTime; + + /** + * The quantity of the add-on for the given period. + */ + @summary("Quantity") + @visibility(Lifecycle.Read) + @example(1) + @minValue(0) + quantity: integer; +} diff --git a/api/spec/packages/aip/src/tax/codes.tsp b/api/spec/packages/aip/src/tax/codes.tsp new file mode 100644 index 0000000000000000000000000000000000000000..d1b9175a480c831fb00245377827d56178532be4 --- /dev/null +++ b/api/spec/packages/aip/src/tax/codes.tsp @@ -0,0 +1,38 @@ +import "../shared/resource.tsp"; +import "../shared/index.tsp"; +import "../apps/app.tsp"; + +namespace Tax; + +/** + * Mapping of app types to tax codes. + */ +@friendlyName("BillingTaxCodeAppMapping") +model TaxCodeAppMapping { + /** + * The app type that the tax code is associated with. + */ + @summary("App type") + app_type: Apps.AppType; + + /** + * Tax code. + */ + @summary("Tax code") + tax_code: string; +} + +/** + * Tax codes by provider. + */ +@friendlyName("BillingTaxCode") +model TaxCode { + ...Shared.ResourceWithKey; + + /** + * Mapping of app types to tax codes. + */ + @visibility(Lifecycle.Read, Lifecycle.Update, Lifecycle.Create) + @summary("App type to tax code mappings") + app_mappings: TaxCodeAppMapping[]; +} diff --git a/api/spec/packages/aip/src/tax/index.tsp b/api/spec/packages/aip/src/tax/index.tsp new file mode 100644 index 0000000000000000000000000000000000000000..db19db475e50b4ec6f65c2ce62cd34e2c4ff8026 --- /dev/null +++ b/api/spec/packages/aip/src/tax/index.tsp @@ -0,0 +1,2 @@ +import "./codes.tsp"; +import "./operations.tsp"; diff --git a/api/spec/packages/aip/src/tax/operations.tsp b/api/spec/packages/aip/src/tax/operations.tsp new file mode 100644 index 0000000000000000000000000000000000000000..384c1418a049c02a8ca787160203fb9fbc9f84ea --- /dev/null +++ b/api/spec/packages/aip/src/tax/operations.tsp @@ -0,0 +1,72 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "../common/error.tsp"; +import "../common/pagination.tsp"; +import "../common/parameters.tsp"; +import "../shared/index.tsp"; +import "./codes.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace Tax; + +interface TaxCodesOperations { + @post + @operationId("create-tax-code") + @summary("Create tax code") + @extension(Shared.UnstableExtension, true) + create( + @body + tax_code: Shared.CreateRequest, + ): Shared.CreateResponse | Common.ErrorResponses; + + @get + @operationId("get-tax-code") + @summary("Get tax code") + @extension(Shared.UnstableExtension, true) + get(@path taxCodeId: Shared.ULID): + | Shared.GetResponse + | Common.NotFound + | Common.ErrorResponses; + + @get + @operationId("list-tax-codes") + @summary("List tax codes") + @extension(Shared.UnstableExtension, true) + list( + ...Common.PagePaginationQuery, + + /** + * Include deleted tax codes in the response. + */ + @query + include_deleted?: boolean, + ): Shared.PagePaginatedResponse | Common.ErrorResponses; + + @put + @operationId("upsert-tax-code") + @summary("Upsert tax code") + @extension(Shared.UnstableExtension, true) + upsert( + @path taxCodeId: Shared.ULID, + + @body + tax_code: Shared.UpsertRequest, + ): + | Shared.UpsertResponse + | Common.Gone + | Common.NotFound + | Common.ErrorResponses; + + @delete + @operationId("delete-tax-code") + @summary("Delete tax code") + @extension(Shared.UnstableExtension, true) + delete(@path taxCodeId: Shared.ULID): + | Shared.DeleteResponse + | Common.NotFound + | Common.ErrorResponses; +} diff --git a/api/spec/packages/aip/src/test.tsp b/api/spec/packages/aip/src/test.tsp new file mode 100644 index 0000000000000000000000000000000000000000..ffafdcc34408e6f51a7bc53b6b1e39b44504834f --- /dev/null +++ b/api/spec/packages/aip/src/test.tsp @@ -0,0 +1,44 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "./common/parameters.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +@service(#{ title: "Filter Test API" }) +@info(#{ version: "1.0.0" }) +namespace Test; + +/** + * Field filters with all supported types. + */ +@friendlyName("FieldFilters") +model FieldFilters { + #suppress "@openmeter/api-spec-aip/doc-decorator" "test model" + boolean?: Common.BooleanFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "test model" + numeric?: Common.NumericFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "test model" + string?: Common.StringFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "test model" + string_exact?: Common.StringFieldFilterExact; + #suppress "@openmeter/api-spec-aip/doc-decorator" "test model" + ulid?: Common.ULIDFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "test model" + datetime?: Common.DateTimeFieldFilter; + #suppress "@openmeter/api-spec-aip/doc-decorator" "test model" + labels?: Common.LabelsFieldFilter; +} + +@route("/field-filters") +interface FieldFiltersEndpoints { + @get + @operationId("get-field-filters-with-all-supported-types") + @summary("Field filters") + getFieldFilters( + @query(#{ style: "deepObject", explode: true }) + filter?: FieldFilters, + ): void; +} diff --git a/api/spec/packages/aip/test/sort-query-type.test.js b/api/spec/packages/aip/test/sort-query-type.test.js new file mode 100644 index 0000000000000000000000000000000000000000..3f3415cbb92f625e785f3a30b0b2084faf2da265 --- /dev/null +++ b/api/spec/packages/aip/test/sort-query-type.test.js @@ -0,0 +1,84 @@ +import { + createLinterRuleTester, + createTestHost, + createTestRunner, +} from '@typespec/compiler/testing' +import { HttpTestLibrary } from '@typespec/http/testing' +import { beforeEach, describe, it } from 'node:test' +import { sortQueryTypeRule } from '../lib/rules/sort-query-type.js' + +const preamble = ` + import "@typespec/http"; + using TypeSpec.Http; + + namespace Common { + model SortQuery { + by: string; + order?: "asc" | "desc"; + } + } +` + +describe('sortQueryTypeRule', () => { + let ruleTester + + beforeEach(async () => { + const host = await createTestHost({ libraries: [HttpTestLibrary] }) + const runner = await createTestRunner(host) + ruleTester = createLinterRuleTester( + runner, + sortQueryTypeRule, + '@openmeter/api-spec-aip', + ) + }) + + it('accepts a sort query parameter using Common.SortQuery', async () => { + await ruleTester + .expect(`${preamble}\nop list(@query sort?: Common.SortQuery): void;`) + .toBeValid() + }) + + it('rejects a scalar sort query parameter', async () => { + await ruleTester + .expect(`${preamble}\nop list(@query sort?: string): void;`) + .toEmitDiagnostics({ + code: '@openmeter/api-spec-aip/sort-query-type', + message: 'Query parameters named `sort` must use `Common.SortQuery`.', + }) + }) + + it('rejects an alias of Common.SortQuery', async () => { + await ruleTester + .expect( + ` + ${preamble} + model SortAlias is Common.SortQuery; + op list(@query sort?: SortAlias): void; + `, + ) + .toEmitDiagnostics({ + code: '@openmeter/api-spec-aip/sort-query-type', + message: 'Query parameters named `sort` must use `Common.SortQuery`.', + }) + }) + + it('checks the effective query parameter name', async () => { + await ruleTester + .expect( + ` + ${preamble} + op list(@query(#{ name: "sort" }) order?: string): void; + `, + ) + .toEmitDiagnostics({ + code: '@openmeter/api-spec-aip/sort-query-type', + message: 'Query parameters named `sort` must use `Common.SortQuery`.', + }) + }) + + it('ignores unrelated query parameters', async () => { + await ruleTester + .expect(`${preamble}\nop list(@query sorting?: string): void;`) + .toBeValid() + }) +}) diff --git a/api/spec/packages/aip/tspconfig.yaml b/api/spec/packages/aip/tspconfig.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f51f08a6da8064dfec762b08de896e4c3251cc8b --- /dev/null +++ b/api/spec/packages/aip/tspconfig.yaml @@ -0,0 +1,57 @@ +emit: + - '@typespec/openapi3' + - '@openmeter/typespec-typescript' + - '@openmeter/typespec-go' +parameters: + base-dir: + default: '{cwd}' +output-dir: '{base-dir}' +options: + '@typespec/openapi3': + emitter-output-dir: '{output-dir}/output/definitions/metering-and-billing/v3' + omit-unreachable-types: true + seal-object-schemas: true + '@openmeter/typespec-typescript': + emitter-output-dir: '{output-dir}/../aip-client-javascript' + # The npm package name the generated README installs and imports. + package-name: '@openmeter/client' + # Markdown callout inserted after the README intro. + readme-note: | + > **Important:** This SDK is a work in progress. + > + > This SDK targets the [OpenMeter API v3](https://openmeter.io/docs/api/v3), + > a rewrite of the OpenMeter API following AIP (API Improvement Proposal) + > standardization. + # Emit per-operation schemas only for the OpenMeter service. + include-services: + - 'OpenMeter' + # Mirror the TS SDK prefix stripping so the Zod schemas match. + strip-name-prefixes: + - 'Billing' + - 'OpenMeter' + - 'Metering' + '@openmeter/typespec-go': + emitter-output-dir: '{output-dir}/../../../v3/client' + # Go module path (the published import identity, independent of where the client is generated in the repo). + module-path: 'github.com/openmeterio/openmeter/api/v3/client' + # Go package name; deliberately differs from the module path's last segment + # (same precedent as api/client/go), goimports resolves it. + package-name: 'openmeter' + # Markdown callout inserted after the README intro. + readme-note: | + > [!IMPORTANT] + > This SDK is a work in progress. + > + > This SDK targets the [OpenMeter API v3](https://openmeter.io/docs/api/v3), + > a rewrite of the OpenMeter API following AIP (API Improvement Proposal) + > standardization. + include-services: + - 'OpenMeter' + strip-name-prefixes: + - 'Billing' + - 'OpenMeter' + - 'Metering' + go-version: '1.24' +linter: + extends: + - '@openmeter/api-spec-aip/all' diff --git a/api/spec/packages/legacy/README.md b/api/spec/packages/legacy/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bdefc5308fe0649804d2c9cdc54a2f96d97efb5b --- /dev/null +++ b/api/spec/packages/legacy/README.md @@ -0,0 +1,85 @@ +# Legacy API (`packages/legacy`) + +This package defines OpenMeter v1-v2 APIs and OpenMeter Cloud API using TypeSpec, following OpenMeter's existing conventions. + +**Outputs:** `openapi.OpenMeter.yaml`, `openapi.OpenMeterCloud.yaml` + +--- + +## Naming conventions + +- **Models**: `PascalCase` (e.g. `BillingProfile`, `PlanPhase`) +- **Model properties**: `camelCase` (e.g. `createdAt`, `billingProfileId`) +- **Enum names**: `PascalCase`; enum member names: `PascalCase`; enum values: `camelCase` (e.g. `CreatedAt: "createdAt"`) +- **Operation IDs**: `camelCase` verb+noun (e.g. `createMeter`, `listBillingProfiles`) + +--- + +## Use `@visibility` to control property exposure + +`@visibility` controls which properties appear in which request/response shapes, allowing one model to serve multiple contexts. + +- `Lifecycle.Read` — returned by any operation +- `Lifecycle.Create` — accepted in create (POST) operations +- `Lifecycle.Update` — accepted in update (PUT/PATCH) operations + +```tsp +model Meter { + @visibility(Lifecycle.Read) + id: ULID; + + @visibility(Lifecycle.Read, Lifecycle.Create) + slug: Key; + + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + groupBy?: Record; +} +``` + +--- + +## Use Rest resource models for request bodies + +Derive request body models from TypeSpec's built-in REST resource utilities rather than defining ad-hoc types. This ensures correct property filtering by visibility. + +| HTTP method | Template | Naming convention | +| ----------- | ------------------------------------------------------- | ----------------- | +| POST | `TypeSpec.Rest.Resource.ResourceCreateModel` | `{Name}Create` | +| PUT | `TypeSpec.Rest.Resource.ResourceReplaceModel` | `{Name}Update` | +| PATCH | `TypeSpec.Rest.Resource.ResourceCreateOrUpdateModel` | `{Name}Patch` | + +```tsp +@friendlyName("MeterCreate") +model MeterCreate is TypeSpec.Rest.Resource.ResourceCreateModel; + +@friendlyName("MeterUpdate") +model MeterUpdate is TypeSpec.Rest.Resource.ResourceReplaceModel; +``` + +Avoid names like `RequestBody`, `Input`, or `Payload` for CRUD operations. + +--- + +## Use `@friendlyName` with a domain prefix + +Every named model must have a `@friendlyName` with a short domain-scoped name. This name controls the generated OpenAPI schema name. + +--- + +## Suppress linter warnings intentionally + +When you need to deviate from a rule (e.g. preserving existing API values), use `#suppress` with a clear reason. + +--- + +## Route and tag conventions + +- Routes follow the pattern `/api/v1/{resource}` with explicit `@route` decorators. +- Use `@tag` to group operations in the generated spec (e.g. `@tag("Meters")`). +- Use `@sharedRoute` when multiple operation overloads share a path (e.g. JSON vs CSV responses). + +--- + +## Add `@example` to models and operations + +Include realistic `@example` values on models and properties to improve generated documentation and SDK ergonomics. diff --git a/api/spec/packages/legacy/lib/index.js b/api/spec/packages/legacy/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..353a5c053f0c2318e2226a4a0145e6887b8a2b36 --- /dev/null +++ b/api/spec/packages/legacy/lib/index.js @@ -0,0 +1,19 @@ +import { defineLinter } from '@typespec/compiler' +import { casingRule } from './rules/casing.js' +import { docDecoratorRule } from './rules/docs.js' +import { friendlyNameRule } from './rules/friendly-name.js' +import { operationSummaryRule } from './rules/operation-summary.js' +import { compositionOverInheritanceRule } from './rules/composition-over-inheritance.js' + +// See example rules: https://github.com/Azure/typespec-azure/tree/main/packages/typespec-azure-core/src/rules +const rules = [ + casingRule, + docDecoratorRule, + friendlyNameRule, + operationSummaryRule, + compositionOverInheritanceRule, +] + +export const $linter = defineLinter({ + rules, +}) diff --git a/api/spec/packages/legacy/lib/rules/casing.js b/api/spec/packages/legacy/lib/rules/casing.js new file mode 100644 index 0000000000000000000000000000000000000000..96b794323154646c3be14171952a4411f54f7e0e --- /dev/null +++ b/api/spec/packages/legacy/lib/rules/casing.js @@ -0,0 +1,35 @@ +import { createRule, paramMessage } from '@typespec/compiler' +import { isCamelCaseNoAcronyms, isPascalCaseNoAcronyms } from './utils.js' + +export const casingRule = createRule({ + name: 'casing', + severity: 'warning', + description: 'Ensure proper casing style.', + messages: { + name: paramMessage`The names of ${'type'} types must use ${'casing'}`, + value: paramMessage`The values of ${'type'} types must use ${'casing'}`, + }, + create: (context) => ({ + model: (model) => { + if (!isPascalCaseNoAcronyms(model.name)) { + context.reportDiagnostic({ + format: { type: 'Model', casing: 'PascalCase' }, + target: model, + messageId: 'name', + }) + } + }, + modelProperty: (property) => { + if ( + (property.name !== '_' && !isCamelCaseNoAcronyms(property.name)) || + isPascalCaseNoAcronyms(property.name) + ) { + context.reportDiagnostic({ + format: { type: 'Model Property', casing: 'camelCase' }, + target: property, + messageId: 'name', + }) + } + }, + }), +}) diff --git a/api/spec/packages/legacy/lib/rules/composition-over-inheritance.js b/api/spec/packages/legacy/lib/rules/composition-over-inheritance.js new file mode 100644 index 0000000000000000000000000000000000000000..fd04ff867c8134bb75f134590cac7271f0a8395b --- /dev/null +++ b/api/spec/packages/legacy/lib/rules/composition-over-inheritance.js @@ -0,0 +1,44 @@ +import { + createRule, + getDiscriminator, + getTypeName, + isTemplateInstance, + paramMessage, +} from '@typespec/compiler' +import { SyntaxKind } from '@typespec/compiler/ast' + +export const compositionOverInheritanceRule = createRule({ + name: 'composition-over-inheritance', + description: + 'Check that if a model is used in an operation and has derived models that it has a discriminator or recommend to use composition via spread or `is`.', + severity: 'warning', + messages: { + default: paramMessage`Model '${'name'}' is extending '${'baseModel'}' that doesn't define a discriminator. If '${'baseModel'}' is meant to be used: + - For composition consider using spread \`...\` or \`model is\` instead. + - As a polymorphic relation, add the \`@discriminator\` decorator on the base model.`, + instance: paramMessage`Model '${'name'}' is extending a template '${'baseModel'}'. Consider using composition with spread \`...\` or \`model is\` instead.`, + }, + create(context) { + return { + model: (model) => { + if ( + model.baseModel && + model.node?.kind === SyntaxKind.ModelStatement && + model.node.extends && + getDiscriminator(context.program, model.baseModel) === undefined + ) { + context.reportDiagnostic({ + messageId: isTemplateInstance(model.baseModel) + ? 'instance' + : 'default', + format: { + name: model.name, + baseModel: getTypeName(model.baseModel), + }, + target: model.node.extends, + }) + } + }, + } + }, +}) diff --git a/api/spec/packages/legacy/lib/rules/docs.js b/api/spec/packages/legacy/lib/rules/docs.js new file mode 100644 index 0000000000000000000000000000000000000000..bc2398d596fbaa9393ba994111ff734f8d3f2775 --- /dev/null +++ b/api/spec/packages/legacy/lib/rules/docs.js @@ -0,0 +1,62 @@ +import { createRule, paramMessage, getDoc } from '@typespec/compiler' + +export const docDecoratorRule = createRule({ + name: 'doc-decorator', + severity: 'warning', + description: 'Ensure documentation.', + messages: { + default: paramMessage`Missing documentation for ${'name'} ${'type'}`, + }, + create: (context) => ({ + model: (target) => { + if (target.name && !getDoc(context.program, target)) { + context.reportDiagnostic({ + target, + format: { + name: target.name, + }, + }) + } + + if (target.name.endsWith('Response')) { + return + } + + for (const [name, property] of target.properties) { + if ( + target.name && + name && + !['_', 'contentType'].includes(name) && + !getDoc(context.program, property) + ) { + context.reportDiagnostic({ + target: property, + format: { + name: `${target.name}.${name}`, + }, + }) + } + } + }, + enum: (target) => { + if (target.name && !getDoc(context.program, target)) { + context.reportDiagnostic({ + target, + format: { + name: target.name, + }, + }) + } + }, + union: (target) => { + if (target.name && !getDoc(context.program, target)) { + context.reportDiagnostic({ + target, + format: { + name: target.name, + }, + }) + } + }, + }), +}) diff --git a/api/spec/packages/legacy/lib/rules/friendly-name.js b/api/spec/packages/legacy/lib/rules/friendly-name.js new file mode 100644 index 0000000000000000000000000000000000000000..f401c3486cff349566c7fb5f2835e7e524a1115e --- /dev/null +++ b/api/spec/packages/legacy/lib/rules/friendly-name.js @@ -0,0 +1,73 @@ +import { createRule, paramMessage } from '@typespec/compiler' + +export const friendlyNameRule = createRule({ + name: 'friendlyName', + severity: 'error', + description: 'Ensure friendlyName decorator.', + messages: { + default: paramMessage`The ${'type'} ${'name'} must have a friendlyName decorator.`, + }, + create: (context) => ({ + interface: (node) => { + const hasFriendlyName = node.decorators.some( + (d) => d.decorator.name === '$friendlyName', + ) + + if (!hasFriendlyName) { + context.reportDiagnostic({ + format: { + type: node.kind, + name: node.name, + }, + target: node, + messageId: 'default', + }) + } + }, + model: (node) => { + if ( + node.name && + !node.decorators.some((d) => d.decorator.name === '$friendlyName') + ) { + context.reportDiagnostic({ + format: { + type: node.kind, + name: node.name, + }, + target: node, + messageId: 'default', + }) + } + }, + enum: (node) => { + if ( + node.name && + !node.decorators.some((d) => d.decorator.name === '$friendlyName') + ) { + context.reportDiagnostic({ + format: { + type: node.kind, + name: node.name, + }, + target: node, + messageId: 'default', + }) + } + }, + union: (node) => { + if ( + node.name && + !node.decorators.some((d) => d.decorator.name === '$friendlyName') + ) { + context.reportDiagnostic({ + format: { + type: node.kind, + name: node.name, + }, + target: node, + messageId: 'default', + }) + } + }, + }), +}) diff --git a/api/spec/packages/legacy/lib/rules/operation-summary.js b/api/spec/packages/legacy/lib/rules/operation-summary.js new file mode 100644 index 0000000000000000000000000000000000000000..6005c0c8e938740489fa194c25e684b8f77e014e --- /dev/null +++ b/api/spec/packages/legacy/lib/rules/operation-summary.js @@ -0,0 +1,27 @@ +import { createRule, paramMessage } from '@typespec/compiler' + +export const operationSummaryRule = createRule({ + name: 'operation-summary', + severity: 'warning', + description: 'Ensure operation summary.', + messages: { + default: paramMessage`The ${'type'} ${'name'} must have a summary decorator.`, + }, + create: (context) => ({ + operation: (node) => { + if ( + node.name && + !node.decorators.some((d) => d.decorator.name === '$summary') + ) { + context.reportDiagnostic({ + format: { + type: node.kind, + name: node.name, + }, + target: node, + messageId: 'default', + }) + } + }, + }), +}) diff --git a/api/spec/packages/legacy/lib/rules/utils.js b/api/spec/packages/legacy/lib/rules/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..8d0dbad506ac54c2c29e356686d66436f6b6ba4b --- /dev/null +++ b/api/spec/packages/legacy/lib/rules/utils.js @@ -0,0 +1,58 @@ +/** + * Exceptions for PascalCase naming convention. + */ +const pascalCaseExceptions = ['OAuth2', 'URL', 'API', 'UI', 'ID'] + +/** + * Checks whether a given value is in PascalCase + * @param value the value to check + * @returns true if the value is in PascalCase + */ +export function isPascalCaseNoAcronyms(value) { + if (value === undefined || value === null || value === '') { + return true + } + + return new RegExp( + `^(?:[A-Z][a-z0-9]+|${pascalCaseExceptions.join('|')})+[A-Z]?$|^[A-Z]+$`, + ).test(value) +} + +/** + * Checks whether a given value is in camelCase + * @param value the value to check + * @returns true if the value is in camelCase + */ +export function isCamelCaseNoAcronyms(value) { + if (value === undefined || value === null || value === '') { + return true + } + + return /^[^a-zA-Z0-9]?[a-z][a-z0-9]*([A-Z][a-z0-9]+)*[A-Z]?$/.test(value) +} + +/** + * Checks whether a given value is in snake_case + * @param value the value to check + * @returns true if the value is in snake_case + */ +export function isSnakeCase(value) { + if (value === undefined || value === null || value === '') { + return true + } + + return /^([a-z0-9]+_)*[a-z0-9]+$/.test(value) +} + +/** + * Checks whether a given value is in kebab-case + * @param value the value to check + * @returns true if the value is in kebab-case + */ +export function isKebabCase(value) { + if (value === undefined || value === null || value === '') { + return true + } + + return /^([a-z0-9]+(-[a-z0-9]+)*)$/.test(value) +} diff --git a/api/spec/packages/legacy/package.json b/api/spec/packages/legacy/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bba2b6e5e2026722b6314f3b67d1e56046100750 --- /dev/null +++ b/api/spec/packages/legacy/package.json @@ -0,0 +1,36 @@ +{ + "name": "@openmeter/api-spec-legacy", + "version": "0.1.0", + "type": "module", + "scripts": { + "generate": "pnpm generate:openapi && pnpm generate:client", + "generate:openapi": "tsp compile --config tspconfig.yaml ./src/cloud", + "generate:client": "tsp compile --config tspconfig.client.yaml ./src", + "watch:openapi": "tsp compile --watch --config tspconfig.yaml ./src/cloud", + "watch:client": "tsp compile --watch --config tspconfig.client.yaml ./src", + "format": "prettier --ignore-path ../../.prettierignore --list-different --find-config-path --write .", + "lint": "prettier --ignore-path ../../.prettierignore --check .", + "lint:fix": "prettier --ignore-path ../../.prettierignore --write ." + }, + "main": "./lib/index.js", + "exports": { + ".": { + "typespec": "./src/cloud/main.tsp" + } + }, + "devDependencies": { + "@azure-tools/typespec-client-generator-core": "0.68.4", + "@types/node": "25.9.2", + "@typespec/compiler": "1.11.0", + "@typespec/http": "1.11.0", + "@typespec/http-client-python": "0.28.3", + "@typespec/openapi": "1.11.0", + "@typespec/openapi3": "1.11.0", + "@typespec/prettier-plugin-typespec": "1.12.0", + "@typespec/rest": "0.81.0", + "@typespec/streams": "0.81.0", + "@typespec/versioning": "0.81.0" + }, + "private": true, + "packageManager": "pnpm@10.28.0+sha512.05df71d1421f21399e053fde567cea34d446fa02c76571441bfc1c7956e98e363088982d940465fd34480d4d90a0668bc12362f8aa88000a64e83d0b0e47be48" +} diff --git a/api/spec/packages/legacy/src/app/app.tsp b/api/spec/packages/legacy/src/app/app.tsp new file mode 100644 index 0000000000000000000000000000000000000000..0155a1a994624191f9ecd8f19336206f07ba6ce2 --- /dev/null +++ b/api/spec/packages/legacy/src/app/app.tsp @@ -0,0 +1,163 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; + +import "./app.tsp"; +import "./capability.tsp"; +import "../errors.tsp"; +import "./stripe.tsp"; +import "../types.tsp"; +import "../query.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * Installed Apps API. + */ +@route("/api/v1/apps") +@tag("Apps") +@friendlyName("Apps") +interface AppsEndpoints { + /** + * List apps. + */ + @get + @operationId("listApps") + @summary("List apps") + list(...ListAppsRequest): PaginatedResponse | CommonErrors; + + /** + * Get the app. + */ + @get + @route("/{id}") + @operationId("getApp") + @summary("Get app") + get(@path id: ULID): App | NotFoundError | CommonErrors; + + /** + * Update an app. + */ + @put + @route("/{id}") + @operationId("updateApp") + @summary("Update app") + update(@path id: ULID, @body app: AppReplaceUpdate): + | App + | NotFoundError + | CommonErrors; + + /** + * Uninstall an app. + */ + @delete + @route("/{id}") + @operationId("uninstallApp") + @summary("Uninstall app") + uninstall(@path id: ULID): + | { + @statusCode _: 204; + } + | NotFoundError + | CommonErrors; +} + +/** + * Query params for listing installed apps + */ +@friendlyName("ListAppsRequest") +model ListAppsRequest { + ...QueryPagination; +} + +/** + * Type of the app. + */ +@friendlyName("AppType") +enum AppType { + Stripe: "stripe", + Sandbox: "sandbox", + CustomInvoicing: "custom_invoicing", +} + +/** + * App. + * One of: stripe + */ +@friendlyName("App") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union App { + stripe: StripeApp, + sandbox: SandboxApp, + custom_invoicing: CustomInvoicingApp, +} + +/** + * App ReplaceUpdate Model + */ +// TODO: Once we can properly do ReplaceModel we can use that here (right now we cannot do this recursively and it fails on Resource). +@friendlyName("AppReplaceUpdate") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union AppReplaceUpdate { + stripe: TypeSpec.Rest.Resource.ResourceReplaceModel, + sandbox: TypeSpec.Rest.Resource.ResourceReplaceModel, + custom_invoicing: TypeSpec.Rest.Resource.ResourceReplaceModel, +} + +/** + * App reference + * + * Can be used as a short reference to an app if the full app object is not needed. + */ +@friendlyName("AppReference") +model AppReference { + /** + * The ID of the app. + */ + id: ULID; +} + +/** + * Abstract base model for installed apps. + * + * Represent an app installed to the organization. + * This is an actual instance, with its own configuration and credentials. + */ +@friendlyName("AppBase") +model AppBase { + ...Resource; + + /** + * The marketplace listing that this installed app is based on. + */ + @visibility(Lifecycle.Read) + listing: MarketplaceListing; + + /** + * Status of the app connection. + */ + @visibility(Lifecycle.Read) + status: AppStatus; +} + +/** + * App installed status. + */ +@friendlyName("AppStatus") +enum AppStatus { + /** + * The app is ready to be used. + */ + Ready: "ready", + + /** + * The app is unauthorized. + * This usually happens when the app's credentials are revoked or expired. + * To resolve this, the user must re-authorize the app. + */ + Unauthorized: "unauthorized", +} diff --git a/api/spec/packages/legacy/src/app/capability.tsp b/api/spec/packages/legacy/src/app/capability.tsp new file mode 100644 index 0000000000000000000000000000000000000000..a0c0c68458738806a3830ee044aa03953b0d7a68 --- /dev/null +++ b/api/spec/packages/legacy/src/app/capability.tsp @@ -0,0 +1,68 @@ +import "../types.tsp"; + +namespace OpenMeter; + +/** + * App capability. + * + * Capabilities only exist in config so they don't extend the Resource model. + */ +@friendlyName("AppCapability") +@example(#{ + type: AppCapabilityType.CollectPayments, + key: "stripe_collect_payment", + name: "Collect Payments", + description: "Stripe payments collects outstanding revenue with Stripe customer's default payment method.", +}) +model AppCapability { + /** + * The capability type. + */ + type: AppCapabilityType; + + /** + * Key + */ + key: Key; + + /** + * The capability name. + */ + name: string; + + /** + * The capability description. + */ + description: string; +} + +/** + * App capability type. + */ +@friendlyName("AppCapabilityType") +enum AppCapabilityType { + /** + * The app can report aggregated usage. + */ + ReportUsage: "reportUsage", + + /** + * The app can report raw events. + */ + ReportEvents: "reportEvents", + + /** + * The app can calculate tax. + */ + CalculateTax: "calculateTax", + + /** + * The app can invoice customers. + */ + InvoiceCustomers: "invoiceCustomers", + + /** + * The app can collect payments. + */ + CollectPayments: "collectPayments", +} diff --git a/api/spec/packages/legacy/src/app/customer.tsp b/api/spec/packages/legacy/src/app/customer.tsp new file mode 100644 index 0000000000000000000000000000000000000000..08c81798394d9fa9802a333b0a9e8b53a57dc01d --- /dev/null +++ b/api/spec/packages/legacy/src/app/customer.tsp @@ -0,0 +1,106 @@ +import "./app.tsp"; +import "../types.tsp"; + +namespace OpenMeter; + +/** + * CustomerAppData + * Stores the app specific data for the customer. + * One of: stripe, sandbox, custom_invoicing + */ +@friendlyName("CustomerAppData") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union CustomerAppData { + @summary("Stripe") + stripe: StripeCustomerAppData, + + @summary("Sandbox") + sandbox: SandboxCustomerAppData, + + @summary("Custom Invoicing") + custom_invoicing: CustomInvoicingCustomerAppData, +} + +/** + * Customer App Base. + */ +@friendlyName("CustomerAppDataBase") +model CustomerAppBase { + /** + * The app ID. + * If not provided, it will use the global default for the app type. + */ + @summary("App ID") + id?: ULID; + + /** + * The app name. + */ + @summary("App Type") + type: TYPE; +} + +/** + * Sandbox Customer App Data. + */ +@friendlyName("SandboxCustomerAppData") +model SandboxCustomerAppData { + /** + * The installed sandbox app this data belongs to. + */ + @visibility(Lifecycle.Read) + app?: SandboxApp; + + ...CustomerAppBase; +} + +/** + * Stripe Customer App Data. + */ +@example(#{ type: AppType.Stripe, stripeCustomerId: "cus_xxxxxxxxxxxxxx" }) +@friendlyName("StripeCustomerAppData") +model StripeCustomerAppData { + ...CustomerAppBase; + ...StripeCustomerAppDataBase; + + /** + * The installed stripe app this data belongs to. + */ + @visibility(Lifecycle.Read) + app?: StripeApp; +} + +/** + * Stripe Customer App Data Base. + */ +@friendlyName("StripeCustomerAppDataBase") +model StripeCustomerAppDataBase { + /** + * The Stripe customer ID. + */ + stripeCustomerId: string; + + /** + * The Stripe default payment method ID. + */ + stripeDefaultPaymentMethodId?: string; +} + +/** + * Custom Invoicing Customer App Data. + */ +@friendlyName("CustomInvoicingCustomerAppData") +model CustomInvoicingCustomerAppData { + /** + * The installed custom invoicing app this data belongs to. + */ + @visibility(Lifecycle.Read) + app?: CustomInvoicingApp; + + ...CustomerAppBase; + + /** + * Metadata to be used by the custom invoicing provider. + */ + metadata?: Metadata; +} diff --git a/api/spec/packages/legacy/src/app/custominvoicing.tsp b/api/spec/packages/legacy/src/app/custominvoicing.tsp new file mode 100644 index 0000000000000000000000000000000000000000..2dd8d39c10006f9e94d6670716bb4af9a9c07710 --- /dev/null +++ b/api/spec/packages/legacy/src/app/custominvoicing.tsp @@ -0,0 +1,222 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; + +import "../errors.tsp"; +import "../types.tsp"; +import "../billing/invoices/main.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * Custom Invoicing app can be used for interface with any invoicing or payment system. + * + * This app provides ways to manipulate invoices and payments, however the integration + * must rely on Notifications API to get notified about invoice changes. + */ +@friendlyName("CustomInvoicingApp") +model CustomInvoicingApp { + ...AppBase; + + /** + * The app's type is CustomInvoicing. + */ + type: AppType.CustomInvoicing; + + /** + * Enable draft.sync hook. + * + * If the hook is not enabled, the invoice will be progressed to the next state automatically. + */ + enableDraftSyncHook: boolean; + + /** + * Enable issuing.sync hook. + * + * If the hook is not enabled, the invoice will be progressed to the next state automatically. + */ + enableIssuingSyncHook: boolean; +} + +@tag("App: Custom Invoicing") +@friendlyName("AppCustomInvoicing") +interface AppCustomInvoicingEndpoints { + @post + @route("/api/v1/apps/custom-invoicing/{invoiceId}/draft/synchronized") + @operationId("appCustomInvoicingDraftSynchronized") + @summary("Submit draft synchronization results") + draftSyncronized( + @path invoiceId: ULID, + @body body: CustomInvoicingDraftSynchronizedRequest, + ): void | CommonErrors; + + @post + @route("/api/v1/apps/custom-invoicing/{invoiceId}/issuing/synchronized") + @operationId("appCustomInvoicingIssuingSynchronized") + @summary("Submit issuing synchronization results") + finalized( + @path invoiceId: ULID, + @body body: CustomInvoicingFinalizedRequest, + ): void | CommonErrors; + + @post + @route("/api/v1/apps/custom-invoicing/{invoiceId}/payment/status") + @operationId("appCustomInvoicingUpdatePaymentStatus") + @summary("Update payment status") + paymentStatus( + @path invoiceId: ULID, + @body body: CustomInvoicingUpdatePaymentStatusRequest, + ): void | CommonErrors; +} + +/** + * Information to synchronize the invoice. + * + * Can be used to store external app's IDs on the invoice or lines. + */ +@friendlyName("CustomInvoicingSyncResult") +model CustomInvoicingSyncResult { + /** + * If set the invoice's number will be set to this value. + */ + invoiceNumber?: InvoiceNumber; + + /** + * If set the invoice's invoicing external ID will be set to this value. + */ + externalId?: string; + + /** + * If set the invoice's line external IDs will be set to this value. + * + * This can be used to reference the external system's entities in the + * invoice. + */ + lineExternalIds?: CustomInvoicingLineExternalIdMapping[]; + + /** + * If set the invoice's line discount external IDs will be set to this value. + * + * This can be used to reference the external system's entities in the + * invoice. + */ + lineDiscountExternalIds?: CustomInvoicingLineDiscountExternalIdMapping[]; +} + +/** + * Mapping between lines and external IDs. + */ +@friendlyName("CustomInvoicingLineExternalIdMapping") +model CustomInvoicingLineExternalIdMapping { + /** + * The line ID. + */ + lineId: ULID; + + /** + * The external ID (e.g. custom invoicing system's ID). + */ + externalId: string; +} + +/** + * Mapping between line discounts and external IDs. + */ +@friendlyName("CustomInvoicingLineDiscountExternalIdMapping") +model CustomInvoicingLineDiscountExternalIdMapping { + /** + * The line discount ID. + */ + lineDiscountId: ULID; + + /** + * The external ID (e.g. custom invoicing system's ID). + */ + externalId: string; +} + +/** + * Information to finalize the payment details of an invoice. + */ +@friendlyName("CustomInvoicingFinalizedPaymentRequest") +model CustomInvoicingFinalizedPaymentRequest { + /** + * If set the invoice's payment external ID will be set to this value. + */ + externalId?: string; +} + +/** + * Information to finalize the draft details of an invoice. + */ +@friendlyName("CustomInvoicingDraftSynchronizedRequest") +model CustomInvoicingDraftSynchronizedRequest { + /** + * The result of the synchronization. + */ + invoicing?: CustomInvoicingSyncResult; +} + +/** + * Information to finalize the invoicing details of an invoice. + */ +@friendlyName("CustomInvoicingFinalizedInvoicingRequest") +model CustomInvoicingFinalizedInvoicingRequest { + /** + * If set the invoice's number will be set to this value. + */ + invoiceNumber?: InvoiceNumber; + + /** + * If set the invoice's sent to customer at will be set to this value. + */ + sentToCustomerAt?: DateTime; +} + +/** + * Information to finalize the invoice. + * + * If invoicing.invoiceNumber is not set, then a new invoice number will be generated (INV- prefix). + */ +@friendlyName("CustomInvoicingFinalizedRequest") +model CustomInvoicingFinalizedRequest { + /** + * The result of the synchronization. + */ + invoicing?: CustomInvoicingFinalizedInvoicingRequest; + + /** + * The result of the payment synchronization. + */ + payment?: CustomInvoicingFinalizedPaymentRequest; +} + +/** + * Payment trigger to execute on a finalized invoice. + */ +@friendlyName("CustomInvoicingPaymentTrigger") +enum CustomInvoicingPaymentTrigger { + Paid: "paid", + PaymentFailed: "payment_failed", + PaymentUncollectible: "payment_uncollectible", + PaymentOverdue: "payment_overdue", + ActionRequired: "action_required", + Void: "void", +} + +/** + * Update payment status request. + * + * Can be used to manipulate invoice's payment status (when custominvoicing app is being used). + */ +@friendlyName("CustomInvoicingUpdatePaymentStatusRequest") +model CustomInvoicingUpdatePaymentStatusRequest { + /** + * The trigger to be executed on the invoice. + */ + trigger: CustomInvoicingPaymentTrigger; +} diff --git a/api/spec/packages/legacy/src/app/main.tsp b/api/spec/packages/legacy/src/app/main.tsp new file mode 100644 index 0000000000000000000000000000000000000000..4906b514820f7cb14f5bd5c4bff135effdf5e50d --- /dev/null +++ b/api/spec/packages/legacy/src/app/main.tsp @@ -0,0 +1,12 @@ +// Package Contents +import "./app.tsp"; +import "./capability.tsp"; +import "./customer.tsp"; +import "./marketplace.tsp"; + +// Apps +import "./stripe.tsp"; +import "./sandbox.tsp"; +import "./custominvoicing.tsp"; + +namespace OpenMeter; diff --git a/api/spec/packages/legacy/src/app/marketplace.tsp b/api/spec/packages/legacy/src/app/marketplace.tsp new file mode 100644 index 0000000000000000000000000000000000000000..0e53434872dca8ccda34eaf16d6f5a557eeb5a9f --- /dev/null +++ b/api/spec/packages/legacy/src/app/marketplace.tsp @@ -0,0 +1,246 @@ +import "@typespec/http"; +import "@typespec/openapi"; +import "@typespec/openapi3"; + +import "../errors.tsp"; +import "./oauth.tsp"; +import "../types.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * Marketplace API. + */ +@route("/api/v1/marketplace") +@tag("Apps") +@friendlyName("Marketplace") +interface MarketplaceEndpoints { + /** + * List available apps of the app marketplace. + */ + @get + @route("/listings") + @operationId("listMarketplaceListings") + @summary("List available apps") + list(...QueryPagination): + | PaginatedResponse + | CommonErrors; + + /** + * Get a marketplace listing by type. + */ + @get + @route("/listings/{type}") + @operationId("getMarketplaceListing") + @summary("Get app details by type") + get(type: AppType): MarketplaceListing | CommonErrors; + + /* **************** Install App via OAuth2 **************** */ + + /** + * Install an app via OAuth. + * Returns a URL to start the OAuth 2.0 flow. + */ + @get + @route("/listings/{type}/install/oauth2") + @operationId("marketplaceOAuth2InstallGetURL") + @summary("Get OAuth2 install URL") + getOAuth2InstallURL(@path type: AppType): + | OAuth2.ClientAppStartResponse + | CommonErrors; + + /** + * Authorize OAuth2 code. + * Verifies the OAuth code and exchanges it for a token and refresh token + */ + @get + @route("/listings/{type}/install/oauth2/authorize") + @operationId("marketplaceOAuth2InstallAuthorize") + @summary("Install app via OAuth2") + authorizeOAuth2Install(...MarketplaceOAuth2InstallAuthorizeRequest): + | { + @statusCode _: 303; + } + | CommonErrors; + + /* **************** Install App via API Key **************** */ + + /** + * Install an marketplace app via API Key. + */ + @post + @route("/listings/{type}/install/apikey") + @operationId("marketplaceAppAPIKeyInstall") + @summary("Install app via API key") + installWithAPIKey(...MarketplaceApiKeyInstallRequest): + | MarketplaceInstallResponse + | CommonErrors; + + /* **************** Install App **************** */ + + /** + * Install an app from the marketplace. + */ + @post + @route("/listings/{type}/install") + @operationId("marketplaceAppInstall") + @summary("Install app") + install(...MarketplaceInstallRequest): + | MarketplaceInstallResponse + | CommonErrors; +} + +/** + * Marketplace install response. + */ +@friendlyName("MarketplaceInstallResponse") +model MarketplaceInstallResponse { + app: App; + + /** + * Default for capabilities + */ + defaultForCapabilityTypes: AppCapabilityType[]; +} + +/** + * Marketplace OAuth2 install request. + */ +#suppress "@openmeter/api-spec-legacy/casing" "Valid casing" +@friendlyName("MarketplaceOAuth2InstallAuthorizeRequest") +model MarketplaceOAuth2InstallAuthorizeRequest { + ...OAuth2.AuthorizationCodeGrantParams; + + /** + * The type of the app to install. + */ + @path type: AppType; +} + +/** + * Marketplace install request payload. + */ +@friendlyName("MarketplaceInstallRequestPayload") +model MarketplaceInstallRequestPayload { + /** + * Name of the application to install. + * + * If name is not provided defaults to the marketplace listing's name. + */ + name?: string; + + /** + * If true, a billing profile will be created for the app. + * The Stripe app will be also set as the default billing profile if the current default is a Sandbox app. + */ + createBillingProfile?: boolean = true; +} + +/** + * App API key install request. + */ +@friendlyName("MarketplaceApiKeyInstallRequest") +model MarketplaceApiKeyInstallRequest { + /** + * The type of the app to install. + */ + @path type: AppType; + + @body _: { + ...MarketplaceInstallRequestPayload; + + /** + * The API key for the provider. + * For example, the Stripe API key. + */ + apiKey: string; + }; +} + +/** + * Marketplace app install request. + */ +@friendlyName("MarketplaceInstallRequest") +model MarketplaceInstallRequest { + /** + * The type of the app to install. + */ + @path type: AppType; + + @body _: MarketplaceInstallRequestPayload; +} + +/** + * A marketplace listing. + * Represent an available app in the app marketplace that can be installed to the organization. + * + * Marketplace apps only exist in config so they don't extend the Resource model. + */ +@friendlyName("MarketplaceListing") +@example(#{ + type: AppType.Stripe, + name: "Stripe", + description: "Stripe integration allows you to collect payments with Stripe.", + capabilities: #[ + #{ + type: AppCapabilityType.CalculateTax, + key: "stripe_calculate_tax", + name: "Calculate Tax", + description: "Stripe Tax calculates tax portion of the invoices.", + }, + #{ + type: AppCapabilityType.InvoiceCustomers, + key: "stripe_invoice_customers", + name: "Invoice Customers", + description: "Stripe invoices customers with due amount.", + }, + #{ + type: AppCapabilityType.CollectPayments, + key: "stripe_collect_payments", + name: "Collect Payments", + description: "Stripe payments collects outstanding revenue with Stripe customer's default payment method.", + } + ], + installMethods: #[AppInstallMethod.WithOAuth2, AppInstallMethod.WithAPIKey], +}) +model MarketplaceListing { + /** + * The app's type + */ + type: AppType; + + /** + * The app's name. + */ + name: string; + + /** + * The app's description. + */ + description: string; + + /** + * The app's capabilities. + */ + capabilities: AppCapability[]; + + /** + * Install methods. + * + * List of methods to install the app. + */ + installMethods: AppInstallMethod[]; +} + +/** + * Install method of the application. + */ +@friendlyName("InstallMethod") +enum AppInstallMethod { + WithOAuth2: "with_oauth2", + WithAPIKey: "with_api_key", + NoCredentialsRequired: "no_credentials_required", +} diff --git a/api/spec/packages/legacy/src/app/oauth.tsp b/api/spec/packages/legacy/src/app/oauth.tsp new file mode 100644 index 0000000000000000000000000000000000000000..422a21de860e74f9b2a3b1e058a8ae12d8ce64a5 --- /dev/null +++ b/api/spec/packages/legacy/src/app/oauth.tsp @@ -0,0 +1,135 @@ +import "@typespec/http"; + +using TypeSpec.Http; + +namespace OAuth2; + +/** + * Response from the client app (OpenMeter backend) to start the OAuth2 flow. + * + */ +@friendlyName("ClientAppStartResponse") +model ClientAppStartResponse { + /** + * The URL to start the OAuth2 authorization code grant flow. + */ + url: string; +} + +/** + * OAuth2 authorization code grant error types. + */ +@friendlyName("OAuth2AuthorizationCodeGrantErrorType") +enum AuthorizationCodeGrantErrorType { + /** + * The request is missing a required parameter, includes an invalid parameter value, + * includes a parameter more than once, or is otherwise malformed. + */ + invalid_request: "invalid_request", + + /** + * The client is not authorized to request an authorization code using this method. + */ + unauthorized_client: "unauthorized_client", + + /** + * The resource owner or authorization server denied the request. + */ + access_denied: "access_denied", + + /** + * The authorization server does not support obtaining an authorization code using this method. + */ + unsupported_response_type: "unsupported_response_type", + + /** + * The requested scope is invalid, unknown, or malformed. + */ + invalid_scope: "invalid_scope", + + /** + * The authorization server encountered an unexpected condition that prevented it from fulfilling the request. + */ + server_error: "server_error", + + /** + * The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server. + */ + temporarily_unavailable: "temporarily_unavailable", +} + +/** + * OAuth2 authorization code grant params. + * + * We combine the success and error params into a single model. + * Because of this success's `code` and error's `error` are optional fields. + */ +@friendlyName("OAuth2AuthorizationCodeGrantParams") +model AuthorizationCodeGrantParams { + ...AuthorizationCodeGrantSuccessParams; + ...AuthorizationCodeGrantErrorParams; +} + +/** + * OAuth2 authorization code grant success query params. + * + * If the resource owner grants the access request, the authorization + * server issues an authorization code and delivers it to the client by + * adding the following parameters to the query component of the + * redirection URI using the "application/x-www-form-urlencoded" format. + */ +@friendlyName("OAuth2AuthorizationCodeGrantSuccessParams") +model AuthorizationCodeGrantSuccessParams { + /** + * Required if the "state" parameter was present in the client authorization request. + * The exact value received from the client: + * + * Unique, randomly generated, opaque, and non-guessable string that is sent + * when starting an authentication request and validated when processing the response. + */ + @query + state?: string; + + /** + * Authorization code which the client will later exchange for an access token. + * Required with the success response. + */ + @query + code?: string; +} + +/** + * OAuth2 authorization code grant error query params. + * + * If the request fails due to a missing, invalid, or mismatching + * redirection URI, or if the client identifier is missing or invalid, + * the authorization server SHOULD inform the resource owner of the + * error and MUST NOT automatically redirect the user-agent to the + * invalid redirection URI. + */ +@friendlyName("OAuth2AuthorizationCodeGrantErrorParams") +model AuthorizationCodeGrantErrorParams { + /** + * Error code. + * Required with the error response. + */ + @query + error?: AuthorizationCodeGrantErrorType; + + /** + * Optional human-readable text providing additional information, + * used to assist the client developer in understanding the error that occurred. + */ + #suppress "@openmeter/api-spec-legacy/casing" "Use existing values" + @query + error_description?: string; + + /** + * Optional uri identifying a human-readable web page with + * information about the error, used to provide the client + * developer with additional information about the error + */ + #suppress "@openmeter/api-spec-legacy/casing" "Use existing values" + @query + error_uri?: string; +} diff --git a/api/spec/packages/legacy/src/app/sandbox.tsp b/api/spec/packages/legacy/src/app/sandbox.tsp new file mode 100644 index 0000000000000000000000000000000000000000..555ba4a2d4baf410c7fd67982ffb8dc51195a81d --- /dev/null +++ b/api/spec/packages/legacy/src/app/sandbox.tsp @@ -0,0 +1,17 @@ +namespace OpenMeter; + +/** + * Sandbox app can be used for testing OpenMeter features. + * + * The app is not creating anything in external systems, thus it is safe to use for + * verifying OpenMeter features. + */ +@friendlyName("SandboxApp") +model SandboxApp { + ...AppBase; + + /** + * The app's type is Sandbox. + */ + type: AppType.Sandbox; +} diff --git a/api/spec/packages/legacy/src/app/stripe.tsp b/api/spec/packages/legacy/src/app/stripe.tsp new file mode 100644 index 0000000000000000000000000000000000000000..e7c1be4702922731ae9525f5fcfa8501f8e682a2 --- /dev/null +++ b/api/spec/packages/legacy/src/app/stripe.tsp @@ -0,0 +1,783 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; + +import "./app.tsp"; +import "./capability.tsp"; +import "../errors.tsp"; +import "../customer"; +import "../types.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * Stripe specific APIs. + */ +@tag("App: Stripe") +@friendlyName("AppStripe") +interface AppStripeEndpoints { + /** + * Handle stripe webhooks for apps. + */ + @post + @route("/api/v1/apps/{id}/stripe/webhook") + @operationId("appStripeWebhook") + @useAuth(NoAuth) + @summary("Stripe webhook") + webhook(@path id: ULID, @body body: StripeWebhookEvent): + | StripeWebhookResponse + | NotFoundError + | CommonErrors; + + /** + * Update the Stripe API key. + * + * ⚠️ __Deprecated__: Use [`PUT /api/v1/apps/{id}`](#tag/apps/put/api/v1/apps/{id}) instead. + */ + #deprecated "Use `PUT /api/v1/apps/{id}` instead" + @put + @route("/api/v1/apps/{id}/stripe/api-key") + @operationId("updateStripeAPIKey") + @summary("Update Stripe API key") + updateStripeAPIKey(@path id: ULID, @body request: StripeAPIKeyInput): + | void + | CommonErrors; + + /** + * Create checkout session. + */ + @post + @route("/api/v1/stripe/checkout/sessions") + @operationId("createStripeCheckoutSession") + @summary("Create checkout session") + createCheckoutSession(@body body: CreateStripeCheckoutSessionRequest): + | { + @statusCode _: 201; + @body body: CreateStripeCheckoutSessionResult; + } + | NotFoundError + | CommonErrors; +} + +/** + * Stripe webhook response. + */ +@friendlyName("StripeWebhookResponse") +model StripeWebhookResponse { + namespaceId: ULID; + appId: ULID; + customerId?: ULID; + message?: string; +} + +/** + * Create Stripe checkout session with customer ID. + */ +@friendlyName("CustomerId") +model StripeCustomerId { + id: ULID; +} + +/** + * Create Stripe checkout session with customer key. + */ +@friendlyName("CustomerKey") +model StripeCustomerKey { + key: string; +} + +/** + * Create Stripe checkout session request. + */ +@example( + #{ + customer: #{ id: "01G65Z755AFWAKHE12NY0CQ9FH" }, + options: #{ currency: "USD", successURL: "http://example.com" }, + }, + #{ + title: "With existing OpenMeter customer by id", + description: "Create a checkout session with existing customer.", + } +) +@example( + #{ + customer: #{ key: "my-internal-id" }, + options: #{ currency: "USD", successURL: "http://example.com" }, + }, + #{ + title: "With existing OpenMeter customer by key", + description: "Create a checkout session with existing customer.", + } +) +@example( + #{ + customer: #{ id: "01G65Z755AFWAKHE12NY0CQ9FH" }, + stripeCustomerId: "cus_123456789", + options: #{ currency: "USD", successURL: "http://example.com" }, + }, + #{ + title: "With existing OpenMeter and Stripe customer", + description: "Create a checkout session with existing openmeter and customer.", + } +) +@example( + #{ + customer: #{ + name: "ACME, Inc.", + currency: "USD", + usageAttribution: #{ subjectKeys: #["my-identifier"] }, + }, + options: #{ currency: "USD", successURL: "http://example.com" }, + }, + #{ + title: "With customer creation", + description: "Create a checkout session with customer creation.", + } +) +@example( + #{ + customer: #{ + name: "ACME, Inc.", + currency: "USD", + usageAttribution: #{ subjectKeys: #["my-identifier"] }, + }, + options: #{ + currency: "USD", + successURL: "http://example.com", + billingAddressCollection: CreateStripeCheckoutSessionBillingAddressCollection.Required, + taxIdCollection: #{ + enabled: true, + required: CreateCheckoutSessionTaxIdCollectionRequired.IfSupported, + }, + customerUpdate: #{ + name: CreateStripeCheckoutSessionCustomerUpdateBehavior.Auto, + address: CreateStripeCheckoutSessionCustomerUpdateBehavior.Auto, + }, + }, + }, + #{ + title: "With collecting address and tax ID", + description: "Create a checkout session with collecting address and tax ID.", + } +) +@friendlyName("CreateStripeCheckoutSessionRequest") +model CreateStripeCheckoutSessionRequest { + /** + * If not provided, the default Stripe app is used if any. + */ + appId?: ULID; + + /** + * Provide a customer ID or key to use an existing OpenMeter customer. + * or provide a customer object to create a new customer. + */ + customer: + | StripeCustomerId + | StripeCustomerKey + | TypeSpec.Rest.Resource.ResourceCreateModel; + + /** + * Stripe customer ID. + * If not provided OpenMeter creates a new Stripe customer or + * uses the OpenMeter customer's default Stripe customer ID. + */ + stripeCustomerId?: string; + + /** + * Options passed to Stripe when creating the checkout session. + */ + options: CreateStripeCheckoutSessionRequestOptions; +} + +/** + * Create Stripe checkout session options + * See https://docs.stripe.com/api/checkout/sessions/create + */ +@friendlyName("CreateStripeCheckoutSessionRequestOptions") +model CreateStripeCheckoutSessionRequestOptions { + // Note: automaticTax is not supported in setup mode so we don't expose it. + + /** + * Specify whether Checkout should collect the customer’s billing address. Defaults to auto. + */ + billingAddressCollection?: CreateStripeCheckoutSessionBillingAddressCollection; + + /** + * If set, Checkout displays a back button and customers will be directed to this URL if they decide to cancel payment and return to your website. + * This parameter is not allowed if ui_mode is embedded. + */ + cancelURL?: string; + + /** + * A unique string to reference the Checkout Session. This can be a customer ID, a cart ID, or similar, and can be used to reconcile the session with your internal systems. + */ + clientReferenceID?: string; + + /** + * Controls what fields on Customer can be updated by the Checkout Session. + */ + customerUpdate?: CreateStripeCheckoutSessionCustomerUpdate; + + /** + * Configure fields for the Checkout Session to gather active consent from customers. + */ + consentCollection?: CreateStripeCheckoutSessionConsentCollection; + + /** + * Three-letter ISO currency code, in lowercase. + */ + currency?: CurrencyCode; + + /** + * Display additional text for your customers using custom text. + */ + customText?: CheckoutSessionCustomTextParams; + + /** + * The Epoch time in seconds at which the Checkout Session will expire. + * It can be anywhere from 30 minutes to 24 hours after Checkout Session creation. By default, this value is 24 hours from creation. + */ + expiresAt?: int64; + + /* + * The IETF language tag of the locale Checkout is displayed in. If blank or auto, the browser’s locale is used. + */ + locale?: string; + + /** Set of key-value pairs that you can attach to an object. + * This can be useful for storing additional information about the object in a structured format. + * Individual keys can be unset by posting an empty value to them. + * All keys can be unset by posting an empty value to metadata. + */ + metadata?: Record; + + /** + * The URL to redirect your customer back to after they authenticate or cancel their payment on the payment method’s app or site. + * This parameter is required if ui_mode is embedded and redirect-based payment methods are enabled on the session. + */ + returnURL?: string; + + /** + * The URL to which Stripe should send customers when payment or setup is complete. + * This parameter is not allowed if ui_mode is embedded. + * If you’d like to use information from the successful Checkout Session on your page, read the guide on customizing your success page: + * https://docs.stripe.com/payments/checkout/custom-success-page + */ + successURL?: string; + + /** + * The UI mode of the Session. Defaults to hosted. + */ + uiMode?: CheckoutSessionUIMode; + + /** + * A list of the types of payment methods (e.g., card) this Checkout Session can accept. + */ + paymentMethodTypes?: string[]; + + /** + * This parameter applies to ui_mode: embedded. Defaults to always. + * Learn more about the redirect behavior of embedded sessions at + * https://docs.stripe.com/payments/checkout/custom-success-page?payment-ui=embedded-form + */ + redirectOnCompletion?: CreateStripeCheckoutSessionRedirectOnCompletion; + + /** + * Controls tax ID collection during checkout. + */ + taxIdCollection?: CreateCheckoutSessionTaxIdCollection; + + // TODO: Fields we haven't implemented yet. + // Please open an issue or pull request if you need them: + // https://github.com/openmeterio/openmeter/issues + // customFields: unknown; + // paymentIntentData: unknown; + // paymentMethodConfiguration: unknown; + // paymentMethodData: unknown; + // paymentMethodOptions: unknown; + // setupIntentData: unknown; +} + +/** + * Specify whether Checkout should collect the customer’s billing address. + */ +@friendlyName("CreateStripeCheckoutSessionBillingAddressCollection") +enum CreateStripeCheckoutSessionBillingAddressCollection { + /** + * Checkout will only collect the billing address when necessary. + * When using automatic_tax, Checkout will collect the minimum number of fields required for tax calculation. + */ + Auto: "auto", + + /** + * Checkout will always collect the customer’s billing address. + */ + Required: "required", +} + +/** + * Configure fields for the Checkout Session to gather active consent from customers. + */ +@friendlyName("CreateStripeCheckoutSessionConsentCollection") +model CreateStripeCheckoutSessionConsentCollection { + /** + * Determines the position and visibility of the payment method reuse agreement in the UI. + * When set to auto, Stripe’s defaults will be used. When set to hidden, the payment method reuse agreement text will always be hidden in the UI. + */ + paymentMethodReuseAgreement?: CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement; + + /** + * If set to auto, enables the collection of customer consent for promotional communications. + * The Checkout Session will determine whether to display an option to opt into promotional + * communication from the merchant depending on the customer’s locale. Only available to US merchants. + */ + promotions?: CreateStripeCheckoutSessionConsentCollectionPromotions; + + /** + * If set to required, it requires customers to check a terms of service checkbox before being able to pay. + * There must be a valid terms of service URL set in your Stripe Dashboard settings. + * https://dashboard.stripe.com/settings/public + */ + termsOfService?: CreateStripeCheckoutSessionConsentCollectionTermsOfService; +} + +/** + * Controls what fields on Customer can be updated by the Checkout Session. + */ +@friendlyName("CreateStripeCheckoutSessionCustomerUpdate") +model CreateStripeCheckoutSessionCustomerUpdate { + /** + * Describes whether Checkout saves the billing address onto customer.address. + * To always collect a full billing address, use billing_address_collection. + * Defaults to never. + */ + address?: CreateStripeCheckoutSessionCustomerUpdateBehavior; + + /** + * Describes whether Checkout saves the name onto customer.name. + * Defaults to never. + */ + name?: CreateStripeCheckoutSessionCustomerUpdateBehavior; + + /** + * Describes whether Checkout saves shipping information onto customer.shipping. + * To collect shipping information, use shipping_address_collection. + * Defaults to never. + */ + shipping?: CreateStripeCheckoutSessionCustomerUpdateBehavior; +} + +/** + * Create Stripe checkout session customer update behavior. + */ +@friendlyName("CreateStripeCheckoutSessionCustomerUpdateBehavior") +enum CreateStripeCheckoutSessionCustomerUpdateBehavior { + /** + * Checkout will automatically determine whether to update the provided Customer object using details from the session. + */ + Auto: "auto", + + /** + * Checkout will never update the provided Customer object. + */ + Never: "never", +} + +/** + * Create Stripe checkout session payment method reuse agreement. + */ +@friendlyName("CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement") +model CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreement { + position?: CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition; +} + +/** + * Create Stripe checkout session consent collection agreement position. + */ +@friendlyName("CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition") +enum CreateStripeCheckoutSessionConsentCollectionPaymentMethodReuseAgreementPosition { + /** + * Uses Stripe defaults to determine the visibility and position of the payment method reuse agreement. + */ + Auto: "auto", + + /** + * Hides the payment method reuse agreement. + */ + Hidden: "hidden", +} + +/** + * Create Stripe checkout session consent collection promotions. + */ +@friendlyName("CreateStripeCheckoutSessionConsentCollectionPromotions") +enum CreateStripeCheckoutSessionConsentCollectionPromotions { + /** + * Enable the collection of customer consent for promotional communications. + * The Checkout Session will determine whether to display an option to opt into promotional communication from the merchant depending on if a customer is provided, + * and if that customer has consented to receiving promotional communications from the merchant in the past. + */ + Auto: "auto", + + /** + * Checkout will not collect customer consent for promotional communications. + */ + None: "none", +} + +/** + * Create Stripe checkout session consent collection terms of service. + */ +@friendlyName("CreateStripeCheckoutSessionConsentCollectionTermsOfService") +enum CreateStripeCheckoutSessionConsentCollectionTermsOfService { + /** + * Does not display checkbox for the terms of service agreement. + */ + None: "none", + + /** + * Displays a checkbox for the terms of service agreement which requires customer to check before being able to pay. + */ + Required: "required", +} + +/** + * Create Stripe checkout session redirect on completion. + */ +@friendlyName("CreateStripeCheckoutSessionRedirectOnCompletion") +enum CreateStripeCheckoutSessionRedirectOnCompletion { + /** + * The Session will always redirect to the return_url after successful confirmation. + */ + Always: "always", + + /** + * The Session will only redirect to the return_url after a redirect-based payment method is used. + */ + IfRequired: "if_required", + + /** + * The Session will never redirect to the return_url, and redirect-based payment methods will be disabled. + */ + Never: "never", +} + +/** + * Create Stripe checkout session tax ID collection. + */ +@friendlyName("CreateCheckoutSessionTaxIdCollection") +model CreateCheckoutSessionTaxIdCollection { + /** + * Enable tax ID collection during checkout. Defaults to false. + */ + enabled: boolean; + + /** + * Describes whether a tax ID is required during checkout. Defaults to never. + */ + required?: CreateCheckoutSessionTaxIdCollectionRequired; +} + +/** + * Create Stripe checkout session tax ID collection required. + */ +@friendlyName("CreateCheckoutSessionTaxIdCollectionRequired") +enum CreateCheckoutSessionTaxIdCollectionRequired { + /** + * A tax ID will be required if collection is supported for the selected billing address country. + * See: https://docs.stripe.com/tax/checkout/tax-ids#supported-types + */ + IfSupported: "if_supported", + + /** + * Tax ID collection is never required. + */ + Never: "never", +} + +/** + * Create Stripe Checkout Session response. + */ +@friendlyName("CreateStripeCheckoutSessionResult") +model CreateStripeCheckoutSessionResult { + /** + * The OpenMeter customer ID. + */ + customerId: ULID; + + /** + * The Stripe customer ID. + */ + stripeCustomerId: string; + + /** + * The checkout session ID. + */ + sessionId: string; + + /** + * The checkout session setup intent ID. + */ + setupIntentId: string; + + /** + * The client secret of the checkout session. + * This can be used to initialize Stripe.js for your client-side implementation. + * @see https://docs.stripe.com/payments/checkout/custom-success-page + */ + clientSecret?: string; + + /** + * A unique string to reference the Checkout Session. + * This can be a customer ID, a cart ID, or similar, and can be used to reconcile the session with your internal systems. + */ + clientReferenceId?: string; + + /** + * Customer's email address provided to Stripe. + */ + customerEmail?: string; + + /** + * Three-letter ISO currency code, in lowercase. + */ + currency?: CurrencyCode; + + /** + * Timestamp at which the checkout session was created. + */ + createdAt: DateTime; + + /** + * Timestamp at which the checkout session will expire. + */ + expiresAt?: DateTime; + + /** + * Set of key-value pairs attached to the checkout session. + */ + metadata?: Record; + + /** + * The status of the checkout session. + * @see https://docs.stripe.com/api/checkout/sessions/object#checkout_session_object-status + */ + status?: string; + + /** + * URL to show the checkout session. + */ + url?: string; + + /** + * Mode + * Always `setup` for now. + */ + mode: StripeCheckoutSessionMode; + + /** + * Cancel URL. + */ + cancelURL?: string; + + /** + * Success URL. + */ + successURL?: string; + + /** + * Return URL. + */ + returnURL?: string; +} + +/** + * Stripe CheckoutSession.mode + * @see https://docs.stripe.com/api/checkout/sessions/object#checkout_session_object-mode + * + * Stripe checkout session mode. + */ +@friendlyName("StripeCheckoutSessionMode") +enum StripeCheckoutSessionMode { + Setup: "setup", +} + +/** + * Stripe CheckoutSession.ui_mode + * @see https://docs.stripe.com/api/checkout/sessions/object#checkout_session_object-ui_mode + * + * Stripe checkout session UI mode. + */ +@friendlyName("CheckoutSessionUIMode") +enum CheckoutSessionUIMode { + Embedded: "embedded", + Hosted: "hosted", +} + +/** + * Stripe CheckoutSession.custom_text + * @see https://docs.stripe.com/api/checkout/sessions/object#checkout_session_object-custom_text + * + * Display additional text for your customers using custom text. + */ +@friendlyName("CheckoutSessionCustomTextAfterSubmitParams") +model CheckoutSessionCustomTextParams { + /** + * Custom text that should be displayed after the payment confirmation button. + */ + afterSubmit?: { + @maxLength(1200) + message?: string; + }; + + /** + * Custom text that should be displayed alongside shipping address collection. + */ + shippingAddress?: { + @maxLength(1200) + message?: string; + }; + + /** + * Custom text that should be displayed alongside the payment confirmation button. + */ + submit?: { + @maxLength(1200) + message?: string; + }; + + /** + * Custom text that should be displayed in place of the default terms of service agreement text. + */ + termsOfServiceAcceptance?: { + @maxLength(1200) + message?: string; + }; +} + +/** + * A installed Stripe app object. + */ +@friendlyName("StripeApp") +@example(#{ + id: "01G65Z755AFWAKHE12NY0CQ9FH", + type: AppType.Stripe, + name: "Stripe", + status: AppStatus.Ready, + listing: #{ + type: AppType.Stripe, + name: "Stripe", + description: "Stripe integration allows you to collect payments with Stripe.", + capabilities: #[ + #{ + type: AppCapabilityType.CalculateTax, + key: "stripe_calculate_tax", + name: "Calculate Tax", + description: "Stripe Tax calculates tax portion of the invoices.", + }, + #{ + type: AppCapabilityType.InvoiceCustomers, + key: "stripe_invoice_customers", + name: "Invoice Customers", + description: "Stripe invoices customers with due amount.", + }, + #{ + type: AppCapabilityType.CollectPayments, + key: "stripe_collect_payments", + name: "Collect Payments", + description: "Stripe payments collects outstanding revenue with Stripe customer's default payment method.", + } + ], + installMethods: #[AppInstallMethod.WithOAuth2, AppInstallMethod.WithAPIKey], + }, + createdAt: DateTime.fromISO("2024-01-01T01:01:01.001Z"), + updatedAt: DateTime.fromISO("2024-01-01T01:01:01.001Z"), + + // Stripe specific fields + stripeAccountId: "acct_123456789", + + livemode: true, + maskedAPIKey: "sk_live_************abc", +}) +model StripeApp { + ...AppBase; + + /** + * The app's type is Stripe. + */ + type: AppType.Stripe; + + /** + * The Stripe account ID. + */ + @visibility(Lifecycle.Read) + stripeAccountId: string; + + /** + * Livemode, true if the app is in production mode. + */ + @visibility(Lifecycle.Read) + livemode: boolean; + + /** + * The masked API key. + * Only shows the first 8 and last 3 characters. + */ + @visibility(Lifecycle.Read) + maskedAPIKey: string; + + /** + * The Stripe API key. + */ + @visibility(Lifecycle.Create, Lifecycle.Update) + @secret + secretAPIKey?: string; +} + +/** + * Stripe webhook event. + */ +@friendlyName("StripeWebhookEvent") +model StripeWebhookEvent { + /** + * The event ID. + */ + id: string; + + /** + * The event type. + */ + type: string; + + /** + * Live mode. + */ + livemode: boolean; + + /** + * The event created timestamp. + */ + created: int32; + + /** + * The event data. + */ + data: { + // We don't care about the schema of this one as we are serializing this data using + // the stripe-go library, which handles API versioning and schema changes. + object: unknown; + }; +} + +/** + * The Stripe API key input. + * Used to authenticate with the Stripe API. + */ +@friendlyName("StripeAPIKeyInput") +model StripeAPIKeyInput { + secretAPIKey: string; +} diff --git a/api/spec/packages/legacy/src/auth.tsp b/api/spec/packages/legacy/src/auth.tsp new file mode 100644 index 0000000000000000000000000000000000000000..8fa42ec24dcf1de9700076135e6f8de2c8acfefc --- /dev/null +++ b/api/spec/packages/legacy/src/auth.tsp @@ -0,0 +1,7 @@ +using TypeSpec.Http; + +/** + * Consumer portal token. + */ +@friendlyName("PortalTokenAuth") +model PortalTokenAuth is BearerAuth; diff --git a/api/spec/packages/legacy/src/billing/customeroverride.tsp b/api/spec/packages/legacy/src/billing/customeroverride.tsp new file mode 100644 index 0000000000000000000000000000000000000000..0401ed87c465c6da339c63db8e5d36edb88938b4 --- /dev/null +++ b/api/spec/packages/legacy/src/billing/customeroverride.tsp @@ -0,0 +1,299 @@ +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +@route("/api/v1/billing/customers") +@tag("Billing") +@friendlyName("CustomerOverrides") +interface CustomerOverridesEndpoints { + /** + * List customer overrides using the specified filters. + * + * The response will include the customer override values and the merged billing profile values. + * + * If the includeAllCustomers is set to true, the list contains all customers. This mode is + * useful for getting the current effective billing workflow settings for all users regardless + * if they have customer orverrides or not. + */ + @get + @summary("List customer overrides") + @operationId("listBillingProfileCustomerOverrides") + list(...ListCustomerOverridesParams, ...QueryPagination): + | PaginatedResponse + | CommonErrors; + + /** + * The customer override can be used to pin a given customer to a billing profile + * different from the default one. + * + * This can be used to test the effect of different billing profiles before making them + * the default ones or have different workflow settings for example for enterprise customers. + */ + @put + @route("/{customerId}") + @operationId("upsertBillingProfileCustomerOverride") + @summary("Create a new or update a customer override") + upsert( + @path + customerId: ULID, + + @body + request: BillingProfileCustomerOverrideCreate, + ): BillingProfileCustomerOverrideWithDetails | NotFoundError | CommonErrors; + + /** + * Get a customer override by customer id. + * + * The response will include the customer override values and the merged billing profile values. + * + * If the customer override is not found, the default billing profile's values are returned. This behavior + * allows for getting a merged profile regardless of the customer override existence. + */ + @get + @route("/{customerId}") + @summary("Get a customer override") + @operationId("getBillingProfileCustomerOverride") + get( + @path + customerId: ULID, + + @query(#{ explode: true }) + expand?: BillingProfileCustomerOverrideExpand[], + ): BillingProfileCustomerOverrideWithDetails | NotFoundError | CommonErrors; + + /** + * Delete a customer override by customer id. + * + * This will remove the customer override and the customer will be subject to the default + * billing profile's settings again. + */ + @delete + @route("/{customerId}") + @summary("Delete a customer override") + @operationId("deleteBillingProfileCustomerOverride") + delete( + @path + customerId: ULID, + ): + | { + @statusCode _: 204; + } + | NotFoundError + | CommonErrors; +} + +/** + * Order by options for customers. + */ +@friendlyName("BillingProfileCustomerOverrideOrderBy") +enum BillingProfileCustomerOverrideOrderBy { + customerId: "customerId", + customerName: "customerName", + customerKey: "customerKey", + customerPrimaryEmail: "customerPrimaryEmail", + customerCreatedAt: "customerCreatedAt", +} + +/** + * CustomerOverrideExpand specifies the parts of the profile to expand. + */ +@friendlyName("BillingProfileCustomerOverrideExpand") +enum BillingProfileCustomerOverrideExpand { + apps: "apps", + customer: "customer", +} + +/** + * Customer override values. + */ +@friendlyName("BillingProfileCustomerOverride") +model BillingProfileCustomerOverride { + ...OmitProperties< + ResourceTimestamps, + "deletedAt" // This is not interesting as we are not allowing deleted listing + >; + + // TODO: this is not supported yet, let's enable it once we choose to add wrokflow overrides here. + // workflow?: BillingProfileCustomerWorkflowOverride; + + /** + * The billing profile this override is associated with. + * + * If empty the default profile is looked up dynamically. + */ + billingProfileId?: ULID; + + /** + * The customer id this override is associated with. + */ + customerId: ULID; +} + +/** + * Customer specific merged profile. + * + * This profile is calculated from the customer override and the billing profile it references or the default. + * + * Thus this does not have any kind of resource fields, only the calculated values. + */ +@friendlyName("BillingCustomerProfile") +model BillingCustomerProfile { + /** + * The name and contact information for the supplier this billing profile represents + */ + @visibility(Lifecycle.Read) + supplier: BillingParty; + + /** + * The billing workflow settings for this profile + */ + @visibility(Lifecycle.Read) + workflow: BillingWorkflow; + + /** + * The applications used by this billing profile. + * + * Expand settings govern if this includes the whole app object or just the ID references. + */ + @visibility(Lifecycle.Read) + apps: BillingProfileAppsOrReference; +} + +/** + * Customer specific workflow overrides. + */ +@friendlyName("BillingProfileCustomerOverrideWithDetails") +model BillingProfileCustomerOverrideWithDetails { + /** + * The customer override values. + * + * If empty the merged values are calculated based on the default profile. + */ + customerOverride?: BillingProfileCustomerOverride; + + /** + * The billing profile the customerProfile is associated with at the time of query. + * + * customerOverride contains the explicit mapping set in the customer override object. If that is + * empty, then the baseBillingProfileId is the default profile. + */ + baseBillingProfileId: ULID; + + /** + * Merged billing profile with the customer specific overrides. + */ + customerProfile?: BillingCustomerProfile; + + /** + * The customer this override belongs to. + */ + customer?: Customer; +} + +/** + * List customer overrides query parameters. + */ +@friendlyName("BillingProfileListCustomerOverridesParams") +model ListCustomerOverridesParams { + /** + * Filter by billing profile. + */ + @query(#{ explode: true }) + billingProfile?: ULID[]; + + /** + * Only return customers without pinned billing profiles. This implicitly sets includeAllCustomers to true. + */ + @query(#{ explode: true }) + customersWithoutPinnedProfile?: boolean; + + /** + * Include customers without customer overrides. + * + * If set to false only the customers specifically associated with a billing profile will be returned. + * + * If set to true, in case of the default billing profile, all customers will be returned. + */ + @query(#{ explode: true }) + includeAllCustomers?: boolean = true; + + /** + * Filter by customer id. + */ + @query(#{ explode: true }) + customerId?: ULID[]; + + /** + * Filter by customer name. + */ + @query + customerName?: string; + + /** + * Filter by customer key + */ + @query + customerKey?: string; + + /** + * Filter by customer primary email + */ + @query + customerPrimaryEmail?: string; + + /** + * Expand the response with additional details. + */ + @query(#{ explode: true }) + expand?: BillingProfileCustomerOverrideExpand[]; + + /** + * Order the response by. + */ + ...QueryOrdering; +} +/** + * Payload for creating a new or updating an existing customer override. + */ +@friendlyName("BillingProfileCustomerOverrideCreate") +model BillingProfileCustomerOverrideCreate { + // TODO: this is not supported yet, let's enable it once we choose to add workflow overrides here. + // workflow?: Rest.Resource.ResourceCreateModel; + + /** + * The billing profile this override is associated with. + * + * If not provided, the default billing profile is chosen if available. + */ + billingProfileId?: ULID; +} + +/** + * Customer specific workflow overrides. + */ +@friendlyName("BillingProfileCustomerWorkflowOverride") +model BillingProfileCustomerWorkflowOverride { + ...BillingWorkflow; + + // Note: these are only available for read, as provider override is not supported via the customer override. + // to do that the customer should be assocatied with a new billing profile instead. + + /** + * The tax app used for this workflow + */ + @visibility(Lifecycle.Read) + taxApp: App; + + /** + * The invoicing app used for this workflow + */ + @visibility(Lifecycle.Read) + invoicingApp: App; + + /** + * The payment app used for this workflow + */ + @visibility(Lifecycle.Read) + paymentApp: App; +} diff --git a/api/spec/packages/legacy/src/billing/invoices.tsp b/api/spec/packages/legacy/src/billing/invoices.tsp new file mode 100644 index 0000000000000000000000000000000000000000..47a7fa34a899665c8a9a43b550d5356fe8080f31 --- /dev/null +++ b/api/spec/packages/legacy/src/billing/invoices.tsp @@ -0,0 +1,728 @@ +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * InvoicesEndpoints is a collection of endpoints that allow invoice operations without prior + * knowledge of the invoice ID. + */ +@route("/api/v1/billing/invoices") +@tag("Billing") +@friendlyName("Invoices") +interface InvoicesEndpoints { + /** + * Create a new invoice from the pending line items. + * + * This should be only called if for some reason we need to invoice a customer outside of the normal billing cycle. + * + * When creating an invoice, the pending line items will be marked as invoiced and the invoice will be created with the total amount of the pending items. + * + * New pending line items will be created for the period between now() and the next billing cycle's begining date for any metered item. + * + * The call can return multiple invoices if the pending line items are in different currencies. + */ + @post + @route("/invoice") + @summary("Invoice a customer based on the pending line items") + @operationId("invoicePendingLinesAction") + invoicePendingLinesAction( + @body + request: InvoicePendingLinesActionInput, + ): + | { + @statusCode _: 201; + + @body + body: Invoice[]; + } + | CommonErrors; + + /** + * List invoices based on the specified filters. + * + * The expand option can be used to include additional information (besides the invoice header and totals) + * in the response. For example by adding the expand=lines option the invoice lines will be included in the response. + * + * Gathering invoices will always show the current usage calculated on the fly. + */ + @get + @summary("List invoices") + @operationId("listInvoices") + list( + ...InvoiceListParams, + ...QueryPagination, + ...QueryOrdering, + ): PaginatedResponse | CommonErrors; +} + +/** + * CustomerInvoice is a collection of endpoints that allow operations on a specific invoice. + */ +@route("/api/v1/billing/invoices/{invoiceId}") +@tag("Billing") +@friendlyName("Invoice") +interface InvoiceEndpoints { + /** + * Get an invoice by ID. + * + * Gathering invoices will always show the current usage calculated on the fly. + */ + @get + @summary("Get an invoice") + @operationId("getInvoice") + getInvoice( + @path + invoiceId: ULID, + + @query(#{ explode: true }) + expand?: InvoiceExpand[] = #[InvoiceExpand.lines], + + @query + includeDeletedLines?: boolean = false, + ): Invoice | NotFoundError | CommonErrors; + + /** + * Delete an invoice + * + * Only invoices that are in the draft (or earlier) status can be deleted. + * + * Invoices that are post finalization can only be voided. + */ + @delete + @summary("Delete an invoice") + @operationId("deleteInvoice") + deleteInvoice( + @path + invoiceId: ULID, + ): + | { + @statusCode _: 204; + } + | NotFoundError + | CommonErrors; + + /** + * Update an invoice + * + * Only invoices in draft or earlier status can be updated. + */ + @put + @summary("Update an invoice") + @operationId("updateInvoice") + updateInvoice( + @path + invoiceId: ULID, + + @body + request: InvoiceReplaceUpdate, + ): Invoice | NotFoundError | CommonErrors; + + /** + * Recalculate an invoice's tax amounts (using the app set in the customer's billing profile) + * + * Note: charges might apply, depending on the tax provider. + */ + @post + @route("/taxes/recalculate") + @summary("Recalculate an invoice's tax amounts") + @operationId("recalculateInvoiceTaxAction") + recalculateTaxAction( + @path + invoiceId: ULID, + ): Invoice | NotFoundError | CommonErrors; + + /** + * Approve an invoice and start executing the payment workflow. + * + * This call instantly sends the invoice to the customer using the configured billing profile app. + * + * This call is valid in two invoice statuses: + * - `draft`: the invoice will be sent to the customer, the invluce state becomes issued + * - `manual_approval_needed`: the invoice will be sent to the customer, the invoice state becomes issued + */ + @post + @route("/approve") + @summary("Send the invoice to the customer") + @operationId("approveInvoiceAction") + approveAction( + @path + invoiceId: ULID, + ): Invoice | NotFoundError | CommonErrors; + + /** + * Void an invoice + * + * Only invoices that have been alread issued can be voided. + * + * Voiding an invoice will mark it as voided, the user can specify how to handle the voided line items. + */ + @post + @route("/void") + @summary("Void an invoice") + @operationId("voidInvoiceAction") + voidInvoiceAction( + @path + invoiceId: ULID, + + @body + request: VoidInvoiceActionInput, + ): Invoice | NotFoundError | CommonErrors; + + /** + * Advance the invoice's state to the next status. + * + * The call doesn't "approve the invoice", it only advances the invoice to the next status if the transition would be automatic. + * + * The action can be called when the invoice's statusDetails' actions field contain the "advance" action. + */ + @post + @route("/advance") + @summary("Advance the invoice's state to the next status") + @operationId("advanceInvoiceAction") + advanceAction( + @path + invoiceId: ULID, + ): Invoice | NotFoundError | CommonErrors; + + /** + * Retry advancing the invoice after a failed attempt. + * + * The action can be called when the invoice's statusDetails' actions field contain the "retry" action. + */ + @post + @route("/retry") + @summary("Retry advancing the invoice after a failed attempt.") + @operationId("retryInvoiceAction") + retryAction( + @path + invoiceId: ULID, + ): Invoice | NotFoundError | CommonErrors; + + /** + * Snapshot quantities for usage based line items. + * + * This call will snapshot the quantities for all usage based line items in the invoice. + * + * This call is only valid in `draft.waiting_for_collection` status, where the collection period + * can be skipped using this action. + */ + @post + @route("/snapshot-quantities") + @summary("Snapshot quantities for usage based line items") + @operationId("snapshotQuantitiesInvoiceAction") + snapshotQuantitiesAction( + @path + invoiceId: ULID, + ): Invoice | NotFoundError | CommonErrors; +} + +@route("/api/v1/billing/customers/{customerId}/invoices") +@tag("Billing") +@friendlyName("CustomerInvoice") +interface CustomerInvoiceEndpoints { + /** + * Simulate an invoice for a customer. + * + * This call will simulate an invoice for a customer based on the pending line items. + * + * The call will return the total amount of the invoice and the line items that will be included in the invoice. + */ + @post + @summary("Simulate an invoice for a customer") + @route("/simulate") + @operationId("simulateInvoice") + simulateInvoice( + @path + customerId: ULID, + + @body + request: InvoiceSimulationInput, + ): Invoice | CommonErrors; + + // TODO[later]: Let's add a @get to list upcoming charges without the gathering invoices + /** + * Create a new pending line item (charge). + * + * This call is used to create a new pending line item for the customer if required a new + * gathering invoice will be created. + * + * A new invoice will be created if: + * - there is no invoice in gathering state + * - the currency of the line item doesn't match the currency of any invoices in gathering state + */ + @post + @summary("Create pending line items") + @route("/pending-lines") + @operationId("createPendingInvoiceLine") + createPendingInvoiceLine( + @path + customerId: ULID, + + @body + request: InvoicePendingLineCreateInput, + ): + | { + @statusCode _: 201; + @body body: InvoicePendingLineCreateResponse; + } + | CommonErrors; +} + +/** + * InvoiceOrderBy specifies the ordering options for invoice listing. + */ +@friendlyName("InvoiceOrderBy") +enum InvoiceOrderBy { + customerName: "customer.name", + issuedAt: "issuedAt", + status: "status", + createdAt: "createdAt", + updatedAt: "updatedAt", + periodStart: "periodStart", +} + +/** + * Request to void an invoice + */ +@friendlyName("VoidInvoiceActionInput") +model VoidInvoiceActionInput { + /** + * The action to take on the voided line items. + */ + @visibility(Lifecycle.Create) + action: VoidInvoiceAction; + + /** + * The reason for voiding the invoice. + */ + @visibility(Lifecycle.Create) + reason: string; + + /** + * Per line item overrides for the action. + * + * If not specified, the `action` will be applied to all line items. + */ + @visibility(Lifecycle.Create) + overrides?: VoidInvoiceActionLineOverride[] | null; +} + +/** + * InvoiceVoidAction describes how to handle the voided line items. + */ +@friendlyName("VoidInvoiceAction") +model VoidInvoiceAction { + /** + * How much of the total line items to be voided? (e.g. 100% means all charges are voided) + */ + @visibility(Lifecycle.Create) + percentage: Percentage; + + /** + * The action to take on the line items. + */ + action: VoidInvoiceLineAction; +} + +/** + * VoidInvoiceLineActionType describes how to handle the voidied line item in the invoice. + */ +@friendlyName("VoidInvoiceLineActionType") +enum VoidInvoiceLineActionType { + /** + * The line items will never be charged for again + */ + discard: "discard", + + /** + * Queue the line items into the pending state, they will be included in the next invoice. (We want to generate an invoice right now) + */ + pending: "pending", +} + +/** + * VoidInvoiceLineAction describes how to handle a specific line item in the invoice when voiding. + */ +@friendlyName("VoidInvoiceLineAction") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union VoidInvoiceLineAction { + discard: VoidInvoiceLineDiscardAction, + pending: VoidInvoiceLinePendingAction, +} + +/** + * VoidInvoiceLineDiscardAction describes how to handle the voidied line item in the invoice. + */ +@friendlyName("VoidInvoiceLineDiscardAction") +model VoidInvoiceLineDiscardAction { + /** + * The action to take on the line item. + */ + type: VoidInvoiceLineActionType.discard; +} + +/** + * VoidInvoiceLinePendingAction describes how to handle the voidied line item in the invoice. + */ +@friendlyName("VoidInvoiceLinePendingAction") +model VoidInvoiceLinePendingAction { + /** + * The action to take on the line item. + */ + type: VoidInvoiceLineActionType.pending; + + /** + * The time at which the line item should be invoiced again. + * + * If not provided, the line item will be re-invoiced now. + */ + @visibility(Lifecycle.Create) + nextInvoiceAt?: DateTime; +} + +/** + * VoidInvoiceLineOverride describes how to handle a specific line item in the invoice when voiding. + */ +@friendlyName("VoidInvoiceActionLineOverride") +model VoidInvoiceActionLineOverride { + /** + * The line item ID to override. + */ + @visibility(Lifecycle.Create) + lineId: ULID; + + /** + * The action to take on the line item. + */ + @visibility(Lifecycle.Create) + action: VoidInvoiceAction; +} + +/** + * Common parameters for listing invoices + */ +@friendlyName("InvoiceListParams") +model InvoiceListParams { + /** + * Filter by the invoice status. + */ + @query(#{ explode: true }) + statuses?: InvoiceStatus[]; + + /** + * Filter by invoice extended statuses + */ + @query(#{ explode: true }) + extendedStatuses?: InvoiceExtendedStatus[]; + + /** + * Filter by invoice issued time. + * Inclusive. + */ + @query(#{ explode: true }) + issuedAfter?: DateTime; + + /** + * Filter by invoice issued time. + * Inclusive. + */ + @query(#{ explode: true }) + issuedBefore?: DateTime; + + /** + * Filter by period start time. + * Inclusive. + */ + @query(#{ explode: true }) + periodStartAfter?: DateTime; + + /** + * Filter by period start time. + * Inclusive. + */ + @query(#{ explode: true }) + periodStartBefore?: DateTime; + + /** + * Filter by invoice created time. + * Inclusive. + */ + @query(#{ explode: true }) + createdAfter?: DateTime; + + /** + * Filter by invoice created time. + * Inclusive. + */ + @query(#{ explode: true }) + createdBefore?: DateTime; + + /** + * What parts of the list output to expand in listings + */ + @query(#{ explode: true }) + expand?: InvoiceExpand[]; + + /** + * Filter by customer ID + */ + @query(#{ explode: true }) + customers?: ULID[]; + + /** + * Include deleted invoices + */ + @query + includeDeleted?: boolean; +} + +/** + * InvoiceExpand specifies the parts of the invoice to expand in the list output. + */ +@friendlyName("InvoiceExpand") +enum InvoiceExpand { + lines: "lines", + preceding: "preceding", + + /** + * @deprecated We are always expanding the workflow apps. + */ + workflowApps: "workflow.apps", +} + +/** + * BillingInvoiceActionInput is the input for creating an invoice. + * + * Invoice creation is always based on already pending line items created by the billingCreateLineByCustomer + * operation. Empty invoices are not allowed. + */ +@friendlyName("InvoicePendingLinesActionInput") +model InvoicePendingLinesActionInput { + /** + * Filters to apply when creating the invoice. + */ + @visibility(Lifecycle.Create) + filters?: InvoicePendingLinesActionFiltersInput; + + /** + * The time as of which the invoice is created. + * + * If not provided, the current time is used. + */ + @visibility(Lifecycle.Create) + asOf?: DateTime; + + /** + * The customer ID for which to create the invoice. + */ + @visibility(Lifecycle.Create) + customerId: ULID; + + /** + * Override the progressive billing setting of the customer. + * + * Can be used to disable/enable progressive billing in case the business logic + * requires it, if not provided the billing profile's progressive billing setting will be used. + */ + @visibility(Lifecycle.Create) + progressiveBillingOverride?: boolean; +} + +/** + * InvoicePendingLinesActionFiltersInput specifies which lines to include in the invoice. + */ +@friendlyName("InvoicePendingLinesActionFiltersInput") +model InvoicePendingLinesActionFiltersInput { + /** + * The pending line items to include in the invoice, if not provided: + * - all line items that have invoice_at < asOf will be included + * - [progressive billing only] all usage based line items will be included up to asOf, new + * usage-based line items will be staged for the rest of the billing cycle + * + * All lineIDs present in the list, must exists and must be invoicable as of asOf, or the action will fail. + */ + @visibility(Lifecycle.Create) + lineIds?: ULID[]; +} + +/** + * InvoiceSimulationInput is the input for simulating an invoice. + */ +@friendlyName("InvoiceSimulationInput") +model InvoiceSimulationInput { + /** + * The number of the invoice. + */ + @visibility(Lifecycle.Create) + number?: InvoiceNumber; + + /** + * Currency for all invoice line items. + * + * Multi currency invoices are not supported yet. + */ + @visibility(Lifecycle.Create) + currency: CurrencyCode; + + /** + * Lines to be included in the generated invoice. + */ + @visibility(Lifecycle.Create) + lines: InvoiceSimulationLine[]; +} + +/** + * InvoiceSimulationLine represents a usage-based line item that can be input to the simulation endpoint. + */ +@friendlyName("InvoiceSimulationLine") +model InvoiceSimulationLine { + ...TypeSpec.Rest.Resource.ResourceCreateModel>; + + /** + * The quantity of the item being sold. + */ + @visibility(Lifecycle.Create) + quantity: Numeric; + + /** + * The quantity of the item used before this line's period, if the line is billed progressively. + */ + @visibility(Lifecycle.Create) + preLinePeriodQuantity?: Numeric; + + /** + * ID of the line. If not specified it will be auto-generated. + * + * When discounts are specified, this must be provided, so that the discount can reference it. + */ + @visibility(Lifecycle.Create) + id?: ULID; +} + +/** + * InvoiceReplaceUpdate represents the update model for an invoice. + */ +@friendlyName("InvoiceReplaceUpdate") +model InvoiceReplaceUpdate { + ...TypeSpec.Rest.Resource.ResourceReplaceModel>; + + /** + * The supplier of the lines included in the invoice. + */ + @visibility(Lifecycle.Update) + supplier: TypeSpec.Rest.Resource.ResourceReplaceModel; + + /** + * The customer the invoice is sent to. + */ + @visibility(Lifecycle.Update) + customer: TypeSpec.Rest.Resource.ResourceReplaceModel; + + /** + * The lines included in the invoice. + */ + @visibility(Lifecycle.Update) + lines: InvoiceLineReplaceUpdate[]; + + /** + * The workflow settings for the invoice. + */ + @visibility(Lifecycle.Update) + workflow: InvoiceWorkflowReplaceUpdate; +} + +/** + * InvoiceWorkflowReplaceUpdate represents the update model for an invoice workflow. + * + * Fields that are immutable a re removed from the model. This is based on InvoiceWorkflowSettings. + */ +@friendlyName("InvoiceWorkflowReplaceUpdate") +model InvoiceWorkflowReplaceUpdate { + /** + * The workflow used for this invoice. + */ + workflow: InvoiceWorkflowSettingsReplaceUpdate; +} + +/** + * Mutable workflow settings for an invoice. + * + * Other fields on the invoice's workflow are not mutable, they serve as a history of the invoice's workflow + * at creation time. + */ +@friendlyName("InvoiceWorkflowSettingsReplaceUpdate") +model InvoiceWorkflowSettingsReplaceUpdate { + /** + * The invoicing settings for this workflow + */ + @visibility(Lifecycle.Update) + invoicing: InvoiceWorkflowInvoicingSettingsReplaceUpdate; + + /** + * The payment settings for this workflow + */ + @visibility(Lifecycle.Update) + payment: BillingWorkflowPaymentSettings; +} + +/** + * InvoiceWorkflowInvoicingSettingsReplaceUpdate represents the update model for the invoicing settings of an invoice workflow. + */ +@friendlyName("InvoiceWorkflowInvoicingSettingsReplaceUpdate") +model InvoiceWorkflowInvoicingSettingsReplaceUpdate { + ...TypeSpec.Rest.Resource.ResourceReplaceModel>; +} + +/** + * InvoicePendingLineCreate represents the create model for a pending invoice line. + */ +@friendlyName("InvoicePendingLineCreateInput") +model InvoicePendingLineCreateInput { + /** + * The currency of the lines to be created. + */ + @visibility(Lifecycle.Create) + currency: CurrencyCode; + + /** + * The lines to be created. + */ + @visibility(Lifecycle.Create) + @minItems(1) + lines: InvoicePendingLineCreate[]; +} + +/** + * InvoicePendingLineCreateResponse represents the response from the create pending line endpoint. + */ +@friendlyName("InvoicePendingLineCreateResponse") +model InvoicePendingLineCreateResponse { + /** + * The lines that were created. + */ + @visibility(Lifecycle.Read) + lines: InvoiceLine[]; + + // TODO: For the V3 api let's not return the invoice + /** + * The invoice containing the created lines. + */ + @visibility(Lifecycle.Read) + invoice: Invoice; + + /** + * Whether the invoice was newly created. + */ + @visibility(Lifecycle.Read) + isInvoiceNew: boolean; +} diff --git a/api/spec/packages/legacy/src/billing/invoices/README.md b/api/spec/packages/legacy/src/billing/invoices/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a36b8b656b829151dc33bd26720aca3067f27fe5 --- /dev/null +++ b/api/spec/packages/legacy/src/billing/invoices/README.md @@ -0,0 +1,9 @@ +# Invoice specification structure + +This directory contains the invoice specification based on [GOBL](https://docs.gobl.org/). We are fond of the universal nature of GOBL as a great schema for describing complex invoicing problems. + +Unfortunately for our use-case we had to change/extend the schema. Firstly OpenMeter operates on draft invoices too, and would want to represent the state as part of the Invoice object. GOBL is intended for invoice generation, we on the other hand should support special line item groups (such as tiered pricing). GOBL's representation is good when considering the invoicing use-case, but until we split the tiered prices into seperate line items we should group them together. + +Furthermore it would be somewhat inconvinient to represent time series data in the [cbc.Meta object](https://docs.gobl.org/draft-0/cbc/meta). + +GOBL can express way more things that we need for now: by removing the unsupported parts from the schema we can use gobl for PUT/POST request payloads. diff --git a/api/spec/packages/legacy/src/billing/invoices/credits.tsp b/api/spec/packages/legacy/src/billing/invoices/credits.tsp new file mode 100644 index 0000000000000000000000000000000000000000..1b336472460e9159b6fe5d4abac702a5b846ea96 --- /dev/null +++ b/api/spec/packages/legacy/src/billing/invoices/credits.tsp @@ -0,0 +1,24 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +namespace OpenMeter; + +/** + * InvoiceLineCreditAllocation represents a credit amount allocated to the line before taxes are applied. + */ +@friendlyName("InvoiceLineCreditAllocation") +model InvoiceLineCreditAllocation { + /** + * Amount allocated from credits. + */ + @visibility(Lifecycle.Read) + @summary("Amount in the currency of the invoice") + amount: Money; + + /** + * Text description as to why the credit was allocated. + */ + @visibility(Lifecycle.Read) + description?: string; +} diff --git a/api/spec/packages/legacy/src/billing/invoices/discounts.tsp b/api/spec/packages/legacy/src/billing/invoices/discounts.tsp new file mode 100644 index 0000000000000000000000000000000000000000..c1ba41975ce4dc6c435cb7e0da54983d484a3180 --- /dev/null +++ b/api/spec/packages/legacy/src/billing/invoices/discounts.tsp @@ -0,0 +1,196 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +namespace OpenMeter; + +/** + * InvoiceDiscountBase represents a charge or discount that can be applied to a line or the entire invoice. + */ +@friendlyName("InvoiceDiscountBase") +model InvoiceDiscountBase { + ...ResourceTimestamps; + + /** + * ID of the charge or discount. + */ + @visibility(Lifecycle.Read) + id: ULID; + + /** + * Reason code. + */ + @visibility(Lifecycle.Read) + reason: BillingDiscountReason; + + /** + * Text description as to why the discount was applied. + */ + @visibility(Lifecycle.Read) + description?: string; + + /** + * External IDs of the invoice in other apps such as Stripe. + */ + @visibility(Lifecycle.Read) + externalIds?: InvoiceLineAppExternalIds; +} + +/** + * InvoiceLineDiscounts represents the discounts applied to the invoice line by type. + */ +@friendlyName("InvoiceLineDiscounts") +model InvoiceLineDiscounts { + /** + * Amount based discounts applied to the line. + * + * Amount based discounts are deduced from the total price of the line. + */ + amount?: InvoiceLineAmountDiscount[]; + + /** + * Usage based discounts applied to the line. + * + * Usage based discounts are deduced from the usage of the line before price calculations are applied. + */ + usage?: InvoiceLineUsageDiscount[]; +} + +/** + * InvoiceLineUsageDiscount represents an usage-based discount applied to the line. + * + * The deduction is done before the pricing algorithm is applied. + */ +@friendlyName("InvoiceLineUsageDiscount") +model InvoiceLineUsageDiscount { + ...InvoiceDiscountBase; + + /** + * The usage to apply. + */ + @summary("Usage quantity in the unit of the underlying meter") + @visibility(Lifecycle.Read) + quantity: Numeric; + + /** + * The usage discount already applied to the previous split lines. + * + * Only set if progressive billing is enabled and the line is a split line. + */ + @summary("Usage quantity in the unit of the underlying meter") + @visibility(Lifecycle.Read) + preLinePeriodQuantity?: Numeric; +} + +/** + * InvoiceLineAmountDiscount represents an amount deducted from the line, and will be applied before taxes. + */ +@friendlyName("InvoiceLineAmountDiscount") +model InvoiceLineAmountDiscount { + ...InvoiceDiscountBase; + + /** + * Fixed discount amount to apply (calculated if percent present). + */ + @visibility(Lifecycle.Read) + @summary("Amount in the currency of the invoice") + amount: Money; +} + +/** + * Billing specific fields for product catalog discounts. + */ +@friendlyName("BillingDiscountMetadata") +model BillingDiscountMetadata { + /** + * Correlation ID for the discount. + * + * This is used to link discounts across different invoices (progressive billing use case). + * + * If not provided, the invoicing engine will auto-generate one. When editing an invoice line, + * please make sure to keep the same correlation ID of the discount or in progressive billing + * setups the discount amounts might be incorrect. + */ + correlationId?: ULID; +} + +/** + * A percentage discount. + */ +@friendlyName("BillingDiscountPercentage") +model BillingDiscountPercentage { + ...DiscountPercentage; + ...BillingDiscountMetadata; +} + +/** + * A usage discount. + */ +@friendlyName("BillingDiscountUsage") +model BillingDiscountUsage { + ...DiscountUsage; + ...BillingDiscountMetadata; +} + +/** + * A discount by type. + */ +@friendlyName("BillingDiscounts") +model BillingDiscounts { + /** + * The percentage discount. + */ + percentage?: BillingDiscountPercentage; + + /** + * The usage discount. + */ + usage?: BillingDiscountUsage; +} + +/** + * The type of the discount reason. + */ +@friendlyName("DiscountReasonType") +enum DiscountReasonType { + maximumSpend: "maximum_spend", + ratecardPercentage: "ratecard_percentage", + ratecardUsage: "ratecard_usage", +} + +/** + * The reason for the discount. + */ +@friendlyName("BillingDiscountReason") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union BillingDiscountReason { + maximum_spend: DiscountReasonMaximumSpend, + ratecard_percentage: DiscountReasonRatecardPercentage, + ratecard_usage: DiscountReasonRatecardUsage, +} + +/** + * The reason for the discount is a maximum spend. + */ +@friendlyName("DiscountReasonMaximumSpend") +model DiscountReasonMaximumSpend { + type: DiscountReasonType.maximumSpend; +} + +/** + * The reason for the discount is a ratecard percentage. + */ +@friendlyName("DiscountReasonRatecardPercentage") +model DiscountReasonRatecardPercentage { + type: DiscountReasonType.ratecardPercentage; + ...BillingDiscountPercentage; +} + +/** + * The reason for the discount is a ratecard usage. + */ +@friendlyName("DiscountReasonRatecardUsage") +model DiscountReasonRatecardUsage { + type: DiscountReasonType.ratecardUsage; + ...BillingDiscountUsage; +} diff --git a/api/spec/packages/legacy/src/billing/invoices/docref.tsp b/api/spec/packages/legacy/src/billing/invoices/docref.tsp new file mode 100644 index 0000000000000000000000000000000000000000..f2af6fe298bef65090d174293b025406b54a91d1 --- /dev/null +++ b/api/spec/packages/legacy/src/billing/invoices/docref.tsp @@ -0,0 +1,83 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +using TypeSpec.Http; +using TypeSpec.Rest; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * InvoiceDocumentRefType defines the type of document that is being referenced. + */ +@friendlyName("InvoiceDocumentRefType") +enum InvoiceDocumentRefType { + creditNoteOriginalInvoice: "credit_note_original_invoice", +} + +/** + * Omitted fields: + * period: Tax period in which the referred document had an effect required by some tax regimes and formats. + * stamps: Seals of approval from other organisations that may need to be listed. + * ext: Extensions for additional codes that may be required. + */ +@summary("InvoiceGenericDocumentRef is used to describe an existing document or a specific part of it's contents.") +@friendlyName("InvoiceGenericDocumentRef") +model InvoiceGenericDocumentRef { + /** + * Type of the document referenced. + */ + @visibility(Lifecycle.Read) + type: InvoiceDocumentRefType; + + /** + * Human readable description on why this reference is here or needs to be used. + */ + @visibility(Lifecycle.Read) + reason?: string; + + /** + * Additional details about the document. + */ + @visibility(Lifecycle.Read) + description?: string; +} + +/** + * CreditNoteOriginalInvoiceRef is used to reference the original invoice that a credit note is based on. + */ +@friendlyName("CreditNoteOriginalInvoiceRef") +model InvoiceCreditNoteOriginalInvoiceRef extends InvoiceGenericDocumentRef { + /** + * Type of the invoice. + */ + type: InvoiceDocumentRefType.creditNoteOriginalInvoice; + + /** + * IssueAt reflects the time the document was issued. + */ + @visibility(Lifecycle.Read) + issuedAt?: DateTime; + + /** + * (Serial) Number of the referenced document. + */ + @visibility(Lifecycle.Read) + number?: InvoiceNumber; + + /** + * Link to the source document. + */ + @format("uri") + @visibility(Lifecycle.Read) + url: string; +} + +/** + * InvoiceDocumentRef is used to describe a reference to an existing document (invoice). + */ +@friendlyName("InvoiceDocumentRef") +union InvoiceDocumentRef { + creditNoteOriginalInvoice: InvoiceCreditNoteOriginalInvoiceRef, +} diff --git a/api/spec/packages/legacy/src/billing/invoices/invoice.tsp b/api/spec/packages/legacy/src/billing/invoices/invoice.tsp new file mode 100644 index 0000000000000000000000000000000000000000..80fad7deb51379ed5c2e21d682cb6f1790fc6265 --- /dev/null +++ b/api/spec/packages/legacy/src/billing/invoices/invoice.tsp @@ -0,0 +1,1057 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +using TypeSpec.Http; +using TypeSpec.Rest; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * InvoiceNumber is a unique identifier for the invoice, generated by the + * invoicing app. + * + * The uniqueness depends on a lot of factors: + * - app setting (unique per app or unique per customer) + * - multiple app scenarios (multiple apps generating invoices with the same prefix) + */ +@example("INV-2024-01-01-01") +@minLength(1) +@maxLength(256) +@friendlyName("InvoiceNumber") +scalar InvoiceNumber extends string; + +/* Omitted fields (not required yet, from GOBL schema): + * op_date: Date when the operation defined by the invoice became effective. + * value_date: When the taxes of this invoice become accountable, if none set, the issue date is used. + * exchange_rates: Exchange rates to be used when converting the invoices monetary values into other currencies. + * -> We are not supporting multi-currency invoices yet, so this is not supported. + * charges: Charges or surcharges applied to the complete invoice. + * -> We are not supporting this yet. + * outlays: Expenses paid for by the supplier but invoiced directly to the customer. + * -> We are not supporting this yet. + * ordering: Ordering details including document references and buyer or seller parties. + * -> We are not supporting this yet (e.g. order handled by seperate entity, physical goods delivery details, etc.) + * delivery: Specific details on delivery of the goods referenced in the invoice. + * -> We are not supporting physical goods delivery yet. + * tax: Special tax configuration for billing. + * -> The prices include is the meaningful part, but we should make that an array, let's see if we need this as we implement more features. + */ +/** + * Invoice represents an invoice in the system. + */ +@friendlyName("Invoice") +model Invoice { + ...OmitProperties; + + /** + * Type of the invoice. + * + * The type of invoice determines the purpose of the invoice and how it should be handled. + * + * Supported types: + * - standard: A regular commercial invoice document between a supplier and customer. + * - credit_note: Reflects a refund either partial or complete of the preceding document. A credit note effectively *extends* the previous document. + */ + @visibility(Lifecycle.Read) + type: InvoiceType; + + /** + * The taxable entity supplying the goods or services. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + supplier: BillingParty; + + /** + * Legal entity receiving the goods or services. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + customer: BillingInvoiceCustomerExtendedDetails; + + /** + * Number specifies the human readable key used to reference this Invoice. + * + * The invoice number can change in the draft phases, as we are allocating temporary draft + * invoice numbers, but it's final as soon as the invoice gets finalized (issued state). + * + * Please note that the number is (depending on the upstream settings) either unique for the + * whole organization or unique for the customer, or in multi (stripe) account setups unique for the + * account. + */ + @visibility(Lifecycle.Read) + number: InvoiceNumber; + + /** + * Currency for all invoice line items. + * + * Multi currency invoices are not supported yet. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + currency: CurrencyCode; + + /** + * Key information regarding previous invoices and potentially details as to why they were corrected. + */ + @visibility(Lifecycle.Read) + preceding?: InvoiceDocumentRef[]; + + /** + * Summary of all the invoice totals, including taxes (calculated). + */ + @visibility(Lifecycle.Read) + totals: InvoiceTotals; + + /** + * The status of the invoice. + * + * This field only conatins a simplified status, for more detailed information use the statusDetails field. + */ + @visibility(Lifecycle.Read) + status: InvoiceStatus; + + /** + * The details of the current invoice status. + */ + @visibility(Lifecycle.Read) + statusDetails: InvoiceStatusDetails; + + /** + * The time the invoice was issued. + * + * Depending on the status of the invoice this can mean multiple things: + * - draft, gathering: The time the invoice will be issued based on the workflow settings. + * - issued: The time the invoice was issued. + */ + @visibility(Lifecycle.Read) + issuedAt?: DateTime; + + /** + * The time until the invoice is in draft status. + * + * On draft invoice creation it is calculated from the workflow settings. + * + * If manual approval is required, the draftUntil time is set. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + draftUntil?: DateTime; + + /** + * The time when the quantity snapshots on the invoice lines were taken. + */ + @visibility(Lifecycle.Read) + quantitySnapshotedAt?: DateTime; + + /** + * The time when the invoice will be/has been collected. + */ + @visibility(Lifecycle.Read) + collectionAt?: DateTime; + + /** + * Due time of the fulfillment of the invoice (if available). + */ + @visibility(Lifecycle.Read) + dueAt?: DateTime; + + /** + * The period the invoice covers. If the invoice has no line items, it's not set. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + period?: Period; + + /** + * The time the invoice was voided. + * + * If the invoice was voided, this field will be set to the time the invoice was voided. + */ + @visibility(Lifecycle.Read) + voidedAt?: DateTime; + + /** + * The time the invoice was sent to customer. + */ + @visibility(Lifecycle.Read) + sentToCustomerAt?: DateTime; + + /** + * The workflow associated with the invoice. + * + * It is always a snapshot of the workflow settings at the time of invoice creation. The + * field is optional as it should be explicitly requested with expand options. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + workflow: InvoiceWorkflowSettings; + + /** + * List of invoice lines representing each of the items sold to the customer. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + lines?: InvoiceLine[]; + + /** + * Information on when, how, and to whom the invoice should be paid. + */ + @visibility(Lifecycle.Read) + payment?: InvoicePaymentTerms; + + /** + * Validation issues reported by the invoice workflow. + */ + @visibility(Lifecycle.Read) + validationIssues?: ValidationIssue[]; + + /** + * External IDs of the invoice in other apps such as Stripe. + */ + @visibility(Lifecycle.Read) + externalIds?: InvoiceAppExternalIds; +} + +/** + * InvoiceAvailableActions represents the actions that can be performed on the invoice. + */ +@friendlyName("InvoiceAvailableActions") +model InvoiceAvailableActions { + /** + * Advance the invoice to the next status. + */ + @visibility(Lifecycle.Read) + advance?: InvoiceAvailableActionDetails; + + /** + * Approve an invoice that requires manual approval. + */ + @visibility(Lifecycle.Read) + approve?: InvoiceAvailableActionDetails; + + /** + * Delete the invoice (only non-issued invoices can be deleted). + */ + @visibility(Lifecycle.Read) + delete?: InvoiceAvailableActionDetails; + + /** + * Retry an invoice issuing step that failed. + */ + @visibility(Lifecycle.Read) + retry?: InvoiceAvailableActionDetails; + + /** + * Snapshot quantities for usage based line items. + */ + @visibility(Lifecycle.Read) + snapshotQuantities?: InvoiceAvailableActionDetails; + + /** + * Void an already issued invoice. + */ + @visibility(Lifecycle.Read) + `void`?: InvoiceAvailableActionDetails; + + /** + * Invoice a gathering invoice + */ + @visibility(Lifecycle.Read) + invoice?: InvoiceAvailableActionInvoiceDetails; +} + +/** + * InvoiceAvailableActionInvoiceDetails represents the details of the invoice action for + * non-gathering invoices. + */ +@friendlyName("InvoiceAvailableActionDetails") +model InvoiceAvailableActionDetails { + /** + * The state the invoice will reach if the action is activated and + * all intermediate steps are successful. + * + * For example advancing a draft_created invoice will result in a draft_manual_approval_needed invoice. + */ + @visibility(Lifecycle.Read) + resultingState: InvoiceExtendedStatus; +} + +/** + * InvoiceAvailableActionInvoiceDetails represents the details of the invoice action for + * gathering invoices. + */ +// Note: this is a placeholder for future extensibility +@friendlyName("InvoiceAvailableActionInvoiceDetails") +model InvoiceAvailableActionInvoiceDetails {} + +/** + * InvoiceStatusDetails represents the details of the invoice status. + * + * API users are encouraged to rely on the immutable/failed/avaliableActions fields to determine + * the next steps of the invoice instead of the extendedStatus field. + */ +@friendlyName("InvoiceStatusDetails") +model InvoiceStatusDetails { + /** + * Is the invoice editable? + */ + @visibility(Lifecycle.Read) + immutable: boolean; + + /** + * Is the invoice in a failed state? + */ + @visibility(Lifecycle.Read) + failed: boolean; + + /** + * Extended status information for the invoice. + */ + @visibility(Lifecycle.Read) + extendedStatus: InvoiceExtendedStatus; + + /** + * The actions that can be performed on the invoice. + */ + availableActions: InvoiceAvailableActions; +} + +// TODO[later]: we can make this an enum, but only if we have reached a stable state with the statuses. +@extension("x-inline", true) +scalar InvoiceExtendedStatus extends string; + +/** + * InvoiceWorkflowSettings represents the workflow settings used by the invoice. + * + * This is a clone of the billing profile's workflow settings at the time of invoice creation + * with customer overrides considered. + */ +@friendlyName("InvoiceWorkflowSettings") +model InvoiceWorkflowSettings { + /** + * The apps that will be used to orchestrate the invoice's workflow. + */ + @visibility(Lifecycle.Read) + apps?: BillingProfileAppsOrReference; + + /** + * sourceBillingProfileID is the billing profile on which the workflow was based on. + * + * The profile is snapshotted on invoice creation, after which it can be altered independently + * of the profile itself. + */ + @visibility(Lifecycle.Read) + sourceBillingProfileId: ULID; + + /** + * The workflow details used by this invoice. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + workflow: BillingWorkflow; +} + +/** + * InvoiceStatus describes the status of an invoice. + */ +@friendlyName("InvoiceStatus") +enum InvoiceStatus { + /** + * The list of line items for the next invoice is being gathered. + */ + gathering: "gathering", + + /** + * The invoice is in draft status. + */ + draft: "draft", + + /** + * The invoice is in the process of being issued. + */ + issuing: "issuing", + + /** + * The invoice has been issued to the customer. + */ + issued: "issued", + + /** + * The payment for the invoice is being processed. + */ + paymentProcessing: "payment_processing", + + /** + * The invoice's payment is overdue. + */ + overdue: "overdue", + + /** + * The invoice has been paid. + */ + paid: "paid", + + /** + * The invoice has been marked uncollectible. + */ + uncollectible: "uncollectible", + + /** + * The invoice has been voided. + */ + voided: "voided", +} + +/* + * Omitted types: proforma, corrected, debit-note, other + */ +/** + * InvoiceType represents the type of invoice. + * + * The type of invoice determines the purpose of the invoice and how it should be handled. + */ +@friendlyName("InvoiceType") +enum InvoiceType { + /** + * A regular commercial invoice document between a supplier and customer. + */ + standard: "standard", + + /** + * Reflects a refund either partial or complete of the preceding document. A credit note effectively *extends* the previous document. + */ + creditNote: "credit_note", +} + +/** + * InvoiceLineReplaceUpdate represents the update model for an UBP invoice line. + * + * This type makes ID optional to allow for creating new lines as part of the update. + */ +@friendlyName("InvoiceLineReplaceUpdate") +model InvoiceLineReplaceUpdate { + ...TypeSpec.Rest.Resource.ResourceReplaceModel>; + + /** + * The ID of the line. + */ + @visibility(Lifecycle.Update) + id?: ULID; +} + +/** + * InvoicePendingLineCreate represents the create model for an invoice line that is sold to the customer based on usage. + */ +@friendlyName("InvoicePendingLineCreate") +model InvoicePendingLineCreate { + // Note: invoice is omitted as the line is assigned a new or existing gathering invoice + ...TypeSpec.Rest.Resource.ResourceCreateModel>; +} + +/** + * LineTypes represents the different types of lines that can be used in an invoice. + */ +#deprecated "We are moving to a coherent invoice line structure" +@friendlyName("InvoiceLineTypes") +enum InvoiceLineTypes { + flatFee: "flat_fee", + usageBased: "usage_based", +} + +/** + * Line status specifies the status of the line. + */ +@friendlyName("InvoiceLineStatus") +enum InvoiceLineStatus { + /** + * The line is valid and can be used in the invoice. + */ + valid: "valid", + + /** + * The line is a detail line which is used to detail the individual + * charges and discounts of a valid line. + */ + detailed: "detailed", + + /** + * The line has been split into multiple valid lines due to progressive + * billing. + */ + split: "split", +} + +/** + * InvoiceLineManagedBy specifies who manages the line. + */ +@friendlyName("InvoiceLineManagedBy") +enum InvoiceLineManagedBy { + /** + * The line is managed by the susbcription engine of + * + * If there are any changes to the subscription the line will be updated accordingly. + */ + subscription: "subscription", + + /** + * The line is managed by the billing system of the + * + * The line is immutable. + */ + system: "system", + + /** + * The line is managed via our API. + * + * If the line is coming from a subscription we will not update the line if the subscription changes. + * + * The only exception is that the period and invoiceAt fields will be updated in case of progressively billed + * usage-based lines to maintain the coherence of the line structure. Any other fields edited will be kept as is. + */ + manual: "manual", +} + +/** + * InvoiceLine represents a single item or service sold to the customer. + * + * This is a base class for all line types, and should not be used directly. + * */ +@friendlyName("InvoiceLineBase") +model InvoiceLineBase { + // Note: ID has updated visibility as we support batch line creations and upserts + ...OmitProperties; + + /** + * ID of the line. + */ + @visibility(Lifecycle.Read, Lifecycle.Update) + id: ULID; + + /** + * Type of the line. + * + * A line's type cannot be changed after creation. + */ + #deprecated "We are moving to a coherent invoice line structure" + @visibility(Lifecycle.Read) + type: InvoiceLineTypes; + + /** + * managedBy specifies if the line is manually added via the api or managed by OpenMeter. + */ + @visibility(Lifecycle.Read) + managedBy: InvoiceLineManagedBy; + + /** + * Status of the line. + * + * External calls always create valid lines, other line types are managed by the + * billing engine of OpenMeter. + */ + @visibility(Lifecycle.Read) + status: InvoiceLineStatus; + + /** + * Discounts detailes applied to this line. + * + * New discounts can be added via the invoice's discounts API, to facilitate + * discounts that are affecting multiple lines. + */ + @visibility(Lifecycle.Read) + discounts?: InvoiceLineDiscounts; + + /** + * Credit allocations applied to this line. + * + * Credits are deducted from the line total before taxes are applied. + */ + @visibility(Lifecycle.Read) + creditAllocations?: InvoiceLineCreditAllocation[]; + + /** + * The invoice this item belongs to. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + invoice?: InvoiceReference; + + /** + * The currency of this line. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + currency: CurrencyCode; + + /** + * Taxes applied to the invoice totals. + */ + @visibility(Lifecycle.Read) // Tax is handled by the tax provider, we only need to show the output of that here + taxes?: InvoiceLineTaxItem[]; + + /** + * Tax config specify the tax configuration for this line. + */ + #deprecated "Use rateCard.taxConfig instead" + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + taxConfig?: TaxConfig; + + /** + * Totals for this line. + */ + @visibility(Lifecycle.Read) + totals: InvoiceTotals; + + /** + * Period of the line item applies to for revenue recognition pruposes. + * + * Billing always treats periods as start being inclusive and end being exclusive. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + period: Period; + + /** + * The time this line item should be invoiced. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + invoiceAt: DateTime; + + /** + * External IDs of the invoice in other apps such as Stripe. + */ + @visibility(Lifecycle.Read) + externalIds?: InvoiceLineAppExternalIds; + + /** + * Subscription are the references to the subscritpions that this line is related to. + */ + @visibility(Lifecycle.Read) + subscription?: InvoiceLineSubscriptionReference; +} + +/** + * Reference to an invoice. + */ +@friendlyName("InvoiceReference") +model InvoiceReference { + /** + * The ID of the invoice. + */ + @visibility(Lifecycle.Read) + id: ULID; + + /** + * The number of the invoice. + */ + @visibility(Lifecycle.Read) + number?: InvoiceNumber; +} + +/** + * InvoiceUsageBasedRateCard represents the rate card (intent) for an usage-based line. + */ +@friendlyName("InvoiceUsageBasedRateCard") +model InvoiceUsageBasedRateCard { + // TODO: Once the deprecation is done, let's make featureKey and price required + ...PickProperties; + + /** + * The discounts that are applied to the line. + */ + #deprecated "V1 invoice responses do not expose persisted rate card discounts" + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + discounts?: BillingDiscounts; +} + +/** + * InvoiceUsageBasedLine represents a line item that is sold to the customer based on usage. */ +@friendlyName("InvoiceLine") +model InvoiceLine { + ...OmitProperties; + + /** + * Type of the line. + */ + #deprecated "Invoice always has usage-based line children" + @visibility(Lifecycle.Read) + type: InvoiceLineTypes.usageBased; + + /** + * Price of the usage-based item being sold. + */ + #deprecated "Use rateCard.price instead" + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + price?: RateCardUsageBasedPrice; + + /** + * The feature that the usage is based on. + */ + #deprecated "Use rateCard.featureKey instead" + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + featureKey?: Key; + + /** + * The lines detailing the item or service sold. + */ + @visibility(Lifecycle.Read) + children?: InvoiceDetailedLine[]; + + /** + * The rate card that is used for this line. + * + * The rate card captures the intent of the price and discounts for the usage-based item. + */ + // TODO: Once the deprecation is done, let's make rateCard required + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + rateCard?: InvoiceUsageBasedRateCard; + + /** + * The quantity of the item being sold. + * + * Any usage discounts applied previously are deducted from this quantity. + */ + @visibility(Lifecycle.Read) + quantity?: Numeric; + + /** + * The quantity of the item that has been metered for the period before any discounts were applied. + */ + @visibility(Lifecycle.Read) + meteredQuantity?: Numeric; + + /** + * The quantity of the item used before this line's period. + * + * It is non-zero in case of progressive billing, when this shows how much of the usage was already billed. + * + * Any usage discounts applied previously are deducted from this quantity. + */ + @visibility(Lifecycle.Read) + preLinePeriodQuantity?: Numeric; + + /** + * The metered quantity of the item used in before this line's period without any discounts applied. + * + * It is non-zero in case of progressive billing, when this shows how much of the usage was already billed. + */ + @visibility(Lifecycle.Read) + meteredPreLinePeriodQuantity?: Numeric; +} + +/** + * InvoiceDetailedLineRateCard represents the rate card (intent) for a flat fee line. + */ +@friendlyName("InvoiceDetailedLineRateCard") +model InvoiceDetailedLineRateCard { + // TODO[v2]: Once the deprecation is done, let's make price required + ...PickProperties; + + /** + * Quantity of the item being sold. + * + * Default: 1 + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + quantity?: Numeric; + + /** + * The discounts that are applied to the line. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + discounts?: BillingDiscounts; +} + +/** + * InvoiceDetailedLine represents a line item that is sold to the customer as a manually added fee. + */ +@friendlyName("InvoiceDetailedLine") +model InvoiceDetailedLine { + ...OmitProperties; + + /** + * The time this line item should be invoiced. + */ + #deprecated "Use invoiceAt from the parent line instead, this field will be removed in the future versions of the API" + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + invoiceAt: DateTime; + + /** + * Type of the line. + */ + #deprecated "Invoice line's children are always detailed lines" + @visibility(Lifecycle.Read) + type: InvoiceLineTypes.flatFee; + + /** + * Price of the item being sold. + */ + #deprecated "Use rateCard.perUnitAmount instead" + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + perUnitAmount?: Money; + + /** + * Payment term of the line. + */ + #deprecated "Use rateCard.paymentTerm instead" + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + paymentTerm?: PricePaymentTerm = PricePaymentTerm.inAdvance; + + /** + * Quantity of the item being sold. + */ + #deprecated "Use rateCard.quantity instead" + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + quantity?: Numeric; + + /** + * The rate card that is used for this line. + */ + // TODO[v2]: Once the deprecation is done, let's make rateCard required + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + rateCard?: InvoiceDetailedLineRateCard; + + /** + * Category of the flat fee. + */ + @visibility(Lifecycle.Read) + category?: InvoiceDetailedLineCostCategory = InvoiceDetailedLineCostCategory.regular; +} + +/** + * InvoiceDetailedLineCostCategory determines if the flat fee is a regular fee due to use due to a + * commitment. + */ +@friendlyName("InvoiceDetailedLineCostCategory") +union InvoiceDetailedLineCostCategory { + /** + * The fee is a regular fee due to usage. + */ + regular: "regular", + + /** + * The fee is a fee due to a commitment (e.g. minimum spend). + */ + commitment: "commitment", +} + +/* + * Omitted fields: + * - taxes: Summary of all the taxes included in the invoice. + * We don't need that detailed information here, as we only need the total tax amount. + */ +/** + * Totals contains the summaries of all calculations for the invoice. + */ +@friendlyName("InvoiceTotals") +model InvoiceTotals { + /** + * The total value of the line before taxes, discounts and commitments. + */ + @visibility(Lifecycle.Read) + amount: Numeric; + + /** + * The amount of value of the line that are due to additional charges. + */ + @visibility(Lifecycle.Read) + chargesTotal: Numeric; + + /** + * The amount of value of the line that are due to discounts. + */ + @visibility(Lifecycle.Read) + discountsTotal: Numeric; + + /** + * The amount of value of the line that are due to credits. + */ + @visibility(Lifecycle.Read) + creditsTotal: Numeric; + + /** + * The total amount of taxes that are included in the line. + */ + @visibility(Lifecycle.Read) + taxesInclusiveTotal: Numeric; + + /** + * The total amount of taxes that are added on top of amount from the line. + */ + @visibility(Lifecycle.Read) + taxesExclusiveTotal: Numeric; + + /** + * The total amount of taxes for this line. + */ + @visibility(Lifecycle.Read) + taxesTotal: Numeric; + + /** + * The total amount value of the line after taxes, discounts and commitments. + */ + @visibility(Lifecycle.Read) + total: Numeric; +} + +/* + * Omitted fields: + * - payee: The party responsible for receiving payment of the invoice, if not the supplier. + * We don't need this information here, as we only need the payment terms. + * - advances: Any amounts that have been paid in advance and should be deducted from the amount due. + * We are not supporting prepayments yet. + * - instructions: Details on how payment should be made. + * This is deferred to the payment provider for now, if we start supporing more payment providers, + * we might need this information. + */ +/** + * Payment contains details as to how the invoice should be paid. + */ +@friendlyName("InvoicePaymentTerms") +model InvoicePaymentTerms { + /** + * The terms of payment for the invoice. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + terms?: PaymentTerms; +} + +/** + * ValidationIssueSeverity describes the severity of a validation issue. + * + * Issues with severity "critical" will prevent the invoice from being issued. + */ +@friendlyName("ValidationIssueSeverity") +enum ValidationIssueSeverity { + critical: "critical", + warning: "warning", +} + +/** + * ValidationIssue captures any validation issues related to the invoice. + * + * Issues with severity "critical" will prevent the invoice from being issued. + */ +@friendlyName("ValidationIssue") +model ValidationIssue { + ...ResourceTimestamps; + + /** + * ID of the charge or discount. + */ + @visibility(Lifecycle.Read) + id: ULID; + + /** + * The severity of the issue. + */ + @visibility(Lifecycle.Read) + severity: ValidationIssueSeverity; + + /** + * The field that the issue is related to, if available in JSON path format. + */ + @visibility(Lifecycle.Read) + field?: string; + + /** + * Machine indentifiable code for the issue, if available. + */ + @visibility(Lifecycle.Read) + code?: string; + + /** + * Component reporting the issue. + */ + @visibility(Lifecycle.Read) + component: string; + + /** + * A human-readable description of the issue. + */ + @visibility(Lifecycle.Read) + message: string; + + /** + * Additional context for the issue. + */ + @visibility(Lifecycle.Read) + metadata?: Metadata; +} + +/** + * InvoiceAppExternalIds contains the external IDs of the invoice in other apps such as Stripe. + */ +@friendlyName("InvoiceAppExternalIds") +model InvoiceAppExternalIds { + /** + * The external ID of the invoice in the invoicing app if available. + */ + @visibility(Lifecycle.Read) + invoicing?: string; + + /** + * The external ID of the invoice in the tax app if available. + */ + @visibility(Lifecycle.Read) + tax?: string; + + /** + * The external ID of the invoice in the payment app if available. + */ + @visibility(Lifecycle.Read) + payment?: string; +} + +/** + * InvoiceLineAppExternalIds contains the external IDs of the invoice in other apps such as Stripe. + */ +@friendlyName("InvoiceLineAppExternalIds") +model InvoiceLineAppExternalIds { + /** + * The external ID of the invoice in the invoicing app if available. + */ + @visibility(Lifecycle.Read) + invoicing?: string; + + /** + * The external ID of the invoice in the tax app if available. + */ + @visibility(Lifecycle.Read) + tax?: string; +} + +/** + * InvoiceLineSubscriptionReference contains the references to the subscription that this line is related to. + */ +@friendlyName("InvoiceLineSubscriptionReference") +model InvoiceLineSubscriptionReference { + /** + * The subscription. + */ + @visibility(Lifecycle.Read) + subscription: IDResource; + + /** + * The phase of the subscription. + */ + @visibility(Lifecycle.Read) + phase: IDResource; + + /** + * The item this line is related to. + */ + @visibility(Lifecycle.Read) + item: IDResource; + + /** + * The billing period of the subscription. In case the subscription item's billing period is different + * from the subscription's billing period, this field will contain the billing period of the subscription itself. + * + * For example, in case of: + * - A monthly billed subscription anchored to 2025-01-01 + * - A subscription item billed daily + * + * An example line would have the period of 2025-01-02 to 2025-01-03 as the item is billed daily, but the subscription's billing period + * will be 2025-01-01 to 2025-01-31. + */ + @visibility(Lifecycle.Read) + billingPeriod: Period; +} diff --git a/api/spec/packages/legacy/src/billing/invoices/main.tsp b/api/spec/packages/legacy/src/billing/invoices/main.tsp new file mode 100644 index 0000000000000000000000000000000000000000..827d7d88d8b66fa7ba96f7ade812f8e38565b80b --- /dev/null +++ b/api/spec/packages/legacy/src/billing/invoices/main.tsp @@ -0,0 +1,24 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "@typespec/versioning"; + +import "../.."; +import "../../productcatalog"; + +// Package Contents +import "./invoice.tsp"; +import "./tax.tsp"; +import "./party.tsp"; +import "./pay.tsp"; +import "./docref.tsp"; +import "./discounts.tsp"; +import "./credits.tsp"; + +using TypeSpec.Http; +using TypeSpec.Rest; +using TypeSpec.OpenAPI; +using TypeSpec.Versioning; + +namespace OpenMeter; diff --git a/api/spec/packages/legacy/src/billing/invoices/party.tsp b/api/spec/packages/legacy/src/billing/invoices/party.tsp new file mode 100644 index 0000000000000000000000000000000000000000..7958fa90c791dbe553dfe1a43292359dced32d6f --- /dev/null +++ b/api/spec/packages/legacy/src/billing/invoices/party.tsp @@ -0,0 +1,94 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +import "../../customer"; + +using TypeSpec.Http; +using TypeSpec.Rest; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/* + * Omitted fields + * + * identities: Set of codes used to identify the party in other systems. + * -> This is maintained by apps, and for now we don't see any reason to have this included. + * people: Details of physical people who represent the party. + * -> We don't need this level of detail for now, the name is enough if we deal with a person. + * inboxes: Digital inboxes used for forwarding electronic versions of documents + * -> We don't support this. + * emails: + * -> We don't need this on the invoice. + * websites: Public websites that provide further information about the party. + * telephones: Telephone numbers for contacting the party. + * registration: Additional registration details about the company that may need to be included in a document. + * logos: Images that can be used to identify the party visually. + * ext: (tax) Extension code map for any additional regime specific codes that may be required. + */ +/** + * Party represents a person or business entity. + */ +@friendlyName("BillingParty") +model BillingParty { + /** + * Unique identifier for the party (if available) + */ + @visibility(Lifecycle.Read) + id?: string; + + /** + * An optional unique key of the party (if available) + */ + @summary("Key") + key?: ExternalKey; + + /** + * Legal name or representation of the organization. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + name?: string; + + /** + * The entity's legal ID code used for tax purposes. They may have + * other numbers, but we're only interested in those valid for tax purposes. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + taxId?: BillingPartyTaxIdentity; + + /** + * Regular post addresses for where information should be sent if needed. + */ + @maxItems(1) + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + addresses?: Address[]; +} + +/** + * BillingInvoiceCustomerExtendedDetails is a collection of fields that are used to extend the billing party details for invoices. + * + * These fields contain the OpenMeter specific details for the customer, that are not strictly required for the invoice itself. + */ +@friendlyName("BillingInvoiceCustomerExtendedDetails") +model BillingInvoiceCustomerExtendedDetails { + ...BillingParty; + + /** + * Mapping to attribute metered usage to the customer + */ + @summary("Usage Attribution") + usageAttribution: CustomerUsageAttribution; +} + +/** + * Identity stores the details required to identify an entity for tax purposes in a specific country. + */ +@friendlyName("BillingPartyTaxIdentity") +model BillingPartyTaxIdentity { + /** + * Normalized tax code shown on the original identity document. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + code?: TaxIdentificationCode; +} diff --git a/api/spec/packages/legacy/src/billing/invoices/pay.tsp b/api/spec/packages/legacy/src/billing/invoices/pay.tsp new file mode 100644 index 0000000000000000000000000000000000000000..5a9ba677e14fe6993a31764ec92a3ebbac4e3f53 --- /dev/null +++ b/api/spec/packages/legacy/src/billing/invoices/pay.tsp @@ -0,0 +1,118 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +using TypeSpec.Http; +using TypeSpec.Rest; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * PaymentDueDate contains an amount that should be paid by the given date. + */ +@friendlyName("PaymentDueDate") +model PaymentDueDate { + /** + * When the payment is due. + */ + // Note: This is a date-time, but we should use a date-time string to be more specific. (original schema has a Date field) + @visibility(Lifecycle.Read) + dueAt: DateTime; + + /** + * Other details to take into account for the due date. + */ + @visibility(Lifecycle.Read) + notes?: string; + + /** + * How much needs to be paid by the date. + */ + @visibility(Lifecycle.Read) + amount: Money; + + /** + * Percentage of the total that should be paid by the date. + */ + @visibility(Lifecycle.Read) + percent?: Percentage; + + /** + * If different from the parent document's base currency. + */ + @visibility(Lifecycle.Read) + currency?: CurrencyCode; +} + +/* + * Most of the allowed values are omited, please see https://docs.gobl.org/draft-0/pay/terms + */ +/** + * PaymentTermType defines the type of terms to be applied. + */ +@friendlyName("PaymentTermType") +enum PaymentTermType { + /** + * Due on a specific date. + */ + dueDate: "due_date", + + /** + * On receipt of invoice + */ + instant: "instant", +} + +@summary("Terms defines when we expect the customer to pay, or have paid, for the contents of the document.") +@friendlyName("GenericPaymentTerms") +model GenericPaymentTerms { + /** + * Type of terms to be applied. + */ + type: T; + + /** + * Text detail of the chosen payment terms. + */ + @visibility(Lifecycle.Read) + detail?: string; + + /** + * Description of the conditions for payment. + */ + @visibility(Lifecycle.Read) + notes?: string; +} + +/** + * PaymentTermInstant defines the terms for payment on receipt of invoice. + */ +@friendlyName("PaymentTermInstant") +model PaymentTermInstant { + ...GenericPaymentTerms; +} + +/** + * PaymentTermDueDate defines the terms for payment on a specific date. + */ +@friendlyName("PaymentTermDueDate") +model PaymentTermDueDate { + ...GenericPaymentTerms; + + /** + * When the payment is due. + */ + @minItems(1) + @visibility(Lifecycle.Read) + dueAt: PaymentDueDate[]; +} + +/** + * PaymentTerms defines the terms for payment. + */ +@friendlyName("PaymentTerms") +union PaymentTerms { + instant: PaymentTermInstant, + dueDate: PaymentTermDueDate, +} diff --git a/api/spec/packages/legacy/src/billing/invoices/tax.tsp b/api/spec/packages/legacy/src/billing/invoices/tax.tsp new file mode 100644 index 0000000000000000000000000000000000000000..627f79a0a77a3fdde35a11c73e7aeb4299b21539 --- /dev/null +++ b/api/spec/packages/legacy/src/billing/invoices/tax.tsp @@ -0,0 +1,60 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +using TypeSpec.Http; +using TypeSpec.Rest; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * TaxConfig stores the configuration for a tax line relative to an invoice line. + */ +@friendlyName("InvoiceLineTaxItem") +model InvoiceLineTaxItem { + /** + * Tax provider configuration. + */ + @visibility(Lifecycle.Read) + config?: TaxConfig; + + /** + * Percent defines the percentage set manually or determined from + * the rate key (calculated if rate present). A nil percent implies that + * this tax combo is **exempt** from tax.") + */ + @visibility(Lifecycle.Read) + percent?: Percentage; + + /** + * Some countries require an additional surcharge (calculated if rate present). + */ + @visibility(Lifecycle.Read) + surcharge?: Numeric; + + /** + * Is the tax item inclusive or exclusive of the base amount. + */ + @visibility(Lifecycle.Read) + behavior?: InvoiceLineTaxBehavior; +} + +/** + * InvoiceLineTaxBehavior details how the tax item is applied to the base amount. + * + * Inclusive means the tax is included in the base amount. + * Exclusive means the tax is added to the base amount. + */ +@friendlyName("InvoiceLineTaxBehavior") +enum InvoiceLineTaxBehavior { + /** + * Tax is included in the base amount. + */ + inclusive: "inclusive", + + /** + * Tax is added to the base amount. + */ + exclusive: "exclusive", +} diff --git a/api/spec/packages/legacy/src/billing/main.tsp b/api/spec/packages/legacy/src/billing/main.tsp new file mode 100644 index 0000000000000000000000000000000000000000..fe9d0180ed1d9105557759f3833975fdc787ea07 --- /dev/null +++ b/api/spec/packages/legacy/src/billing/main.tsp @@ -0,0 +1,20 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "@typespec/versioning"; + +import ".."; +import "./invoices/main.tsp"; + +// Package Contents +import "./profile.tsp"; +import "./customeroverride.tsp"; +import "./invoices.tsp"; + +using TypeSpec.Http; +using TypeSpec.Rest; +using TypeSpec.OpenAPI; +using TypeSpec.Versioning; + +namespace OpenMeter; diff --git a/api/spec/packages/legacy/src/billing/profile.tsp b/api/spec/packages/legacy/src/billing/profile.tsp new file mode 100644 index 0000000000000000000000000000000000000000..a6d417c29c18e4efaeaee2c9e743a90b0a88af03 --- /dev/null +++ b/api/spec/packages/legacy/src/billing/profile.tsp @@ -0,0 +1,542 @@ +import "../rest.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +@route("/api/v1/billing/profiles") +@tag("Billing") +@friendlyName("BillingProfiles") +interface BillingProfilesEndpoints { + /** + * List all billing profiles matching the specified filters. + * + * The expand option can be used to include additional information (besides the billing profile) + * in the response. For example by adding the expand=apps option the apps used by the billing profile + * will be included in the response. + */ + @get + @operationId("listBillingProfiles") + @summary("List billing profiles") + list( + @query + includeArchived?: boolean = false, + + @query(#{ explode: true }) + expand?: BillingProfileExpand[], + + ...QueryPagination, + ...QueryOrdering, + ): PaginatedResponse | CommonErrors; + + /** + * Create a new billing profile + * + * Billing profiles are representations of a customer's billing information. Customer overrides + * can be applied to a billing profile to customize the billing behavior for a specific customer. + */ + @post + @summary("Create a new billing profile") + @operationId("createBillingProfile") + create(@body profile: BillingProfileCreate): + | { + @statusCode _: 201; + @body profile: BillingProfile; + } + | CommonErrors; + + /** + * Delete a billing profile by id. + * + * Only such billing profiles can be deleted that are: + * - not the default one + * - not pinned to any customer using customer overrides + * - only have finalized invoices + */ + @route("/{id}") + @delete + @summary("Delete a billing profile") + @operationId("deleteBillingProfile") + delete( + @path + id: ULID, + ): + | { + @statusCode _: 204; + } + | NotFoundError + | CommonErrors; + + /** + * Get a billing profile by id. + * + * The expand option can be used to include additional information (besides the billing profile) + * in the response. For example by adding the expand=apps option the apps used by the billing profile + * will be included in the response. + */ + @route("/{id}") + @get + @summary("Get a billing profile") + @operationId("getBillingProfile") + get( + @path + id: ULID, + + @query(#{ explode: true }) + expand?: BillingProfileExpand[], + ): BillingProfile | NotFoundError | CommonErrors; + + /** + * Update a billing profile by id. + * + * The apps field cannot be updated directly, if an app change is desired a new + * profile should be created. + */ + @route("/{id}") + @put + @summary("Update a billing profile") + @operationId("updateBillingProfile") + update( + @path + id: ULID, + + @body profile: BillingProfileReplaceUpdate, + ): BillingProfile | NotFoundError | CommonErrors; +} + +/** + * BillingProfileOrderBy specifies the ordering options for profiles + */ +@friendlyName("BillingProfileOrderBy") +enum BillingProfileOrderBy { + createdAt: "createdAt", + updatedAt: "updatedAt", + default: "default", + name: "name", +} + +/** + * BillingProfileExpand details what profile fields to expand + */ +@friendlyName("BillingProfileExpand") +enum BillingProfileExpand { + apps: "apps", +} + +/** + * BillingProfile represents a billing profile + */ +@friendlyName("BillingProfile") +model BillingProfile { + ...global.Resource; + + /** + * The name and contact information for the supplier this billing profile represents + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + supplier: BillingParty; + + /** + * The billing workflow settings for this profile + */ + @visibility(Lifecycle.Read) + workflow: BillingWorkflow; + + /** + * The applications used by this billing profile. + * + * Expand settings govern if this includes the whole app object or just the ID references. + */ + @visibility(Lifecycle.Read) + apps: BillingProfileAppsOrReference; + + /** + * Is this the default profile? + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + default: boolean; +} + +/** + * BillingProfileCreate represents the input for creating a billing profile + */ +@friendlyName("BillingProfileCreate") +model BillingProfileCreate + is TypeSpec.Rest.Resource.ResourceCreateModel { + /** + * The billing workflow settings for this profile. + */ + @visibility(Lifecycle.Create) + workflow: TypeSpec.Rest.Resource.ResourceCreateModel; + + /** + * The apps used by this billing profile. + */ + @visibility(Lifecycle.Create) + apps: BillingProfileAppsCreate; +} + +/** + * BillingProfileReplaceUpdate represents the input for updating a billing profile + * + * The apps field cannot be updated directly, if an app change is desired a new + * profile should be created. + */ +// Note: Rest.Resource.ResourceReplaceModel yields a BillingProfileReplaceUpdate that's why we +// need a different friendly name here. +@friendlyName("BillingProfileReplaceUpdateWithWorkflow") +model BillingProfileReplaceUpdate + is TypeSpec.Rest.Resource.ResourceReplaceModel { + /** + * The billing workflow settings for this profile. + */ + @visibility(Lifecycle.Update) + workflow: BillingWorkflow; +} + +/** + * BillingProfileApps represents the applications used by a billing profile + */ +@friendlyName("BillingProfileApps") +model BillingProfileApps { + /** + * The tax app used for this workflow + */ + @visibility(Lifecycle.Read) + tax: App; + + /** + * The invoicing app used for this workflow + */ + @visibility(Lifecycle.Read) + invoicing: App; + + /** + * The payment app used for this workflow + */ + @visibility(Lifecycle.Read) + payment: App; +} + +/** + * BillingProfileAppReferences represents the references (id, type) to the apps used by a billing profile + */ +@friendlyName("BillingProfileAppReferences") +model BillingProfileAppReferences { + /** + * The tax app used for this workflow + */ + @visibility(Lifecycle.Read) + tax: AppReference; + + /** + * The invoicing app used for this workflow + */ + @visibility(Lifecycle.Read) + invoicing: AppReference; + + /** + * The payment app used for this workflow + */ + @visibility(Lifecycle.Read) + payment: AppReference; +} + +/** + * ProfileAppsOrReference represents the union of ProfileApps and ProfileAppReferences + * for a billing profile. + */ +@friendlyName("BillingProfileAppsOrReference") +union BillingProfileAppsOrReference { + profileApps: BillingProfileApps, + profileAppReferences: BillingProfileAppReferences, +} + +/** + * App reference type specifies the type of reference inside an app reference + */ +@friendlyName("BillingWorkflowAppReferenceType") +enum BillingWorkflowAppReferenceType { + appId: "app_id", + appType: "app_type", +} + +/** + * BillingProfileAppsCreate represents the input for creating a billing profile's apps + */ +@friendlyName("BillingProfileAppsCreate") +model BillingProfileAppsCreate { + /** + * The tax app used for this workflow + */ + @visibility(Lifecycle.Create) + @extension("x-go-type", "string") + tax: ULID; + + /** + * The invoicing app used for this workflow + */ + @extension("x-go-type", "string") + @visibility(Lifecycle.Create) + invoicing: ULID; + + /** + * The payment app used for this workflow + */ + @extension("x-go-type", "string") + @visibility(Lifecycle.Create) + payment: ULID; +} + +/** + * BillingWorkflow represents the settings for a billing workflow. + */ +@friendlyName("BillingWorkflow") +model BillingWorkflow { + /** + * The collection settings for this workflow + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + collection?: BillingWorkflowCollectionSettings; + + /** + * The invoicing settings for this workflow + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + invoicing?: BillingWorkflowInvoicingSettings; + + /** + * The payment settings for this workflow + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + payment?: BillingWorkflowPaymentSettings; + + /** + * The tax settings for this workflow + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + tax?: BillingWorkflowTaxSettings; +} + +/** + * Workflow collection specifies how to collect the pending line items for an invoice + */ +@friendlyName("BillingWorkflowCollectionSettings") +model BillingWorkflowCollectionSettings { + /** + * The alignment for collecting the pending line items into an invoice. + */ + alignment?: BillingWorkflowCollectionAlignment = DefaultBillingWorkflowCollectionAlignment; + + /** + * This grace period can be used to delay the collection of the pending line items specified in + * alignment. + * + * This is useful, in case of multiple subscriptions having slightly different billing periods. + */ + @encode(DurationKnownEncoding.ISO8601) + @example("P1D") + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + interval?: string = "PT1H"; +} + +/** + * BillingCollectionAlignment specifies when the pending line items should be collected into + * an invoice. + */ +@friendlyName("BillingCollectionAlignment") +@summary("Collection alignment") +enum BillingCollectionAlignmentType { + /** + * Align the collection to the start of the subscription period. + */ + subscription: "subscription", + + /** + * Align the collection to the anchor time and cadence. + */ + anchored: "anchored", +} + +const DefaultBillingWorkflowCollectionAlignment: BillingWorkflowCollectionAlignmentSubscription = #{ + type: BillingCollectionAlignmentType.subscription, +}; + +/** + * The alignment for collecting the pending line items into an invoice. + * + * Defaults to subscription, which means that we are to create a new invoice every time the + * a subscription period starts (for in advance items) or ends (for in arrears items). + */ +@friendlyName("BillingWorkflowCollectionAlignment") +@discriminated(#{ discriminatorPropertyName: "type", envelope: "none" }) +union BillingWorkflowCollectionAlignment { + subscription: BillingWorkflowCollectionAlignmentSubscription, + anchored: BillingWorkflowCollectionAlignmentAnchored, +} + +/** + * BillingWorkflowCollectionAlignmentAnchored specifies the alignment for collecting the pending line items + * into an invoice. + */ +@friendlyName("BillingWorkflowCollectionAlignmentAnchored") +model BillingWorkflowCollectionAlignmentAnchored { + /** + * The type of alignment. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + type: BillingCollectionAlignmentType.anchored; + + /** + * The recurring period for the alignment. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + recurringPeriod: RecurringPeriodV2; +} + +/** + * BillingWorkflowCollectionAlignmentSubscription specifies the alignment for collecting the pending line items + * into an invoice. + */ +@friendlyName("BillingWorkflowCollectionAlignmentSubscription") +model BillingWorkflowCollectionAlignmentSubscription { + /** + * The type of alignment. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + type: BillingCollectionAlignmentType.subscription; +} + +/** + * BillingWorkflowPaymentSettings represents the payment settings for a billing workflow + */ +@summary("Workflow payment settings") +@friendlyName("BillingWorkflowPaymentSettings") +model BillingWorkflowPaymentSettings { + /** + * The payment method for the invoice. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + collectionMethod?: CollectionMethod = CollectionMethod.chargeAutomatically; +} + +/** + * BillingWorkflowInvoicingSettings represents the invoice settings for a billing workflow + */ +@summary("Workflow invoice settings") +@friendlyName("BillingWorkflowInvoicingSettings") +model BillingWorkflowInvoicingSettings { + /** + * Whether to automatically issue the invoice after the draftPeriod has passed. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + autoAdvance?: boolean = true; + + /** + * The period for the invoice to be kept in draft status for manual reviews. + */ + @encode(DurationKnownEncoding.ISO8601) + @example("P1D") + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + draftPeriod?: string = "P0D"; + + /** + * The period after which the invoice is due. + * With some payment solutions it's only applicable for manual collection method. + */ + @encode(DurationKnownEncoding.ISO8601) + @example("P30D") + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + dueAfter?: string = "P30D"; + + /** + * Should progressive billing be allowed for this workflow? + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + progressiveBilling?: boolean = true; + + /** + * Controls how subscription-ending shortened service periods are billed. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + subscriptionEndProrationMode?: BillingWorkflowInvoicingSubscriptionEndProrationMode = BillingWorkflowInvoicingSubscriptionEndProrationMode.billActualPeriod; + + /** + * Default tax configuration to apply to the invoices. + * + * Setting a tax code (`stripe.code` / `taxCodeId`) on a profile's default tax config is + * deprecated and can no longer be added or changed: the organization default tax code is + * used instead. Existing tax-code values may still be removed, and `behavior` remains + * fully supported. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + defaultTaxConfig?: TaxConfig; +} + +/** + * Billing workflow subscription end proration mode. + */ +@friendlyName("BillingWorkflowInvoicingSubscriptionEndProrationMode") +enum BillingWorkflowInvoicingSubscriptionEndProrationMode { + /** + * Bill the full billing period amount for terminal lines even when the actual + * service period is shorter. + */ + billFullPeriod: "bill_full_period", + + /** + * Bill the amount for the actual terminal service period. + */ + billActualPeriod: "bill_actual_period", +} + +/** + * BillingWorkflowTaxSettings represents the tax settings for a billing workflow + */ +@summary("Workflow tax settings") +@friendlyName("BillingWorkflowTaxSettings") +model BillingWorkflowTaxSettings { + /** + * Enable automatic tax calculation when tax is supported by the app. + * For example, with Stripe Invoicing when enabled, tax is calculated via Stripe Tax. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + enabled?: boolean = true; + + /** + * Enforce tax calculation when tax is supported by the app. + * When enabled, OpenMeter will not allow to create an invoice without tax calculation. + * Enforcement is different per apps, for example, Stripe app requires customer + * to have a tax location when starting a paid subscription. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + enforced?: boolean = false; +} + +/** + * CollectionMethod specifies how the invoice should be collected (automatic vs manual) + */ +@friendlyName("CollectionMethod") +@summary("Collection method") +enum CollectionMethod { + chargeAutomatically: "charge_automatically", + sendInvoice: "send_invoice", +} + +/** + * BillingWorkflowLineResolution specifies how the line items should be resolved in the invoice + */ +@friendlyName("BillingWorkflowLineResolution") +@summary("Item resolution") +enum BillingWorkflowLineResolution { + /** + * Create line items for each day in the billing period. + */ + day: "day", + + /** + * Create one line item for the entire billing period. + */ + period: "period", +} diff --git a/api/spec/packages/legacy/src/cloud/auth.tsp b/api/spec/packages/legacy/src/cloud/auth.tsp new file mode 100644 index 0000000000000000000000000000000000000000..5d613a271e7409fc44249a7a6b7669fcaa1d6df9 --- /dev/null +++ b/api/spec/packages/legacy/src/cloud/auth.tsp @@ -0,0 +1,19 @@ +using TypeSpec.Http; + +/** + * Cloud API token. + */ +@friendlyName("CloudTokenAuth") +model CloudTokenAuth is BearerAuth; + +/** + * Cloud API web app cookie. + */ +@friendlyName("CloudCookieAuth") +model CloudCookieAuth is ApiKeyAuth; + +/** + * Cloud consumer portal token. + */ +@friendlyName("CloudPortalTokenAuth") +model CloudPortalTokenAuth is BearerAuth; diff --git a/api/spec/packages/legacy/src/cloud/main.tsp b/api/spec/packages/legacy/src/cloud/main.tsp new file mode 100644 index 0000000000000000000000000000000000000000..04516ac64b5fce053d75f404689a821048bb9d2a --- /dev/null +++ b/api/spec/packages/legacy/src/cloud/main.tsp @@ -0,0 +1,331 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; + +import ".."; + +import "./auth.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +/** + * OpenMeter is a cloud native usage metering service. + * The OpenMeter API allows you to ingest events, query meter usage, and manage resources. + */ +@service(#{ title: "OpenMeter Cloud API" }) +@info(#{ + version: "1.0.0", + license: #{ + name: "Apache 2.0", + url: "http://www.apache.org/licenses/LICENSE-2.0.html", + }, + termsOfService: "https://openmeter.cloud/terms-of-service", +}) +@server("https://127.0.0.1:8888", "Local") +@server("https://openmeter.cloud", "Cloud") +@useAuth(CloudTokenAuth | CloudCookieAuth) +// Tags will appear in alphabetical order in the API documentation +@tagMetadata( + "Apps", + #{ + description: "Manage integrations for extending OpenMeter's functionality. ", + } +) +@tagMetadata("App: Stripe", #{ description: "Support for Stripe billing." }) +@tagMetadata( + "App: Custom Invoicing", + #{ description: "Interface third party invoicing and payment systems." } +) +@tagMetadata( + "Billing", + #{ description: "Manage your billing profiles and invoices. " } +) +@tagMetadata( + "Customers", + #{ + description: "Manage customer subscription lifecycles and plan assignments. ", + } +) +@tagMetadata("Debug", #{ description: "Debugging and testing endpoints." }) +@tagMetadata( + "Entitlements", + #{ + description: "With Entitlements, you can define and enforce usage limits, implement quota-based pricing, and manage access to features in your application.", + } +) +@tagMetadata( + "Events", + #{ + description: "Events are used to track usage of your product or service. Events are processed asynchronously by the meters, so they may not be immediately available for querying.", + } +) +@tagMetadata( + "Lookup Information", + #{ description: "Lookup information for static data like currencies" } +) +@tagMetadata( + "Meters", + #{ + description: "Meters specify how to aggregate events for billing and analytics purposes. Meters can be configured with multiple aggregation methods and groupings. Multiple meters can be created for the same event type, enabling flexible metering scenarios.", + } +) +@tagMetadata( + "Notifications", + #{ + description: "Notifications provide automated triggers when specific entitlement balances and usage thresholds are reached, ensuring that your customers and sales teams are always informed. Notify customers and internal teams when specific conditions are met, like reaching 75%, 100%, and 150% of their monthly usage allowance. [Read more](https://openmeter.io/docs/guides/notifications/overview).", + } +) +@tagMetadata( + "Portal", + #{ + description: "With the Consumer Portal, you can build in-app user-facing dashboards where your users can track their usage in real-time. Subject scoped portal tokens can be generated on your behalf to allow restricted access to the OpenMeter API.", + } +) +@tagMetadata( + "Product Catalog", + #{ + description: "Configure and manage your product plans, pricing tiers, and subscription offerings. ", + } +) +@tagMetadata( + "Subjects", + #{ + description: "⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. \n\n Subjects are entities that consume resources you wish to meter. These can range from users, servers, and services to devices. The design of subjects is intentionally generic, enabling flexible application across various metering scenarios. Typically, a subject acts as a unique identifier within your system for a user or customer. Meters are aggregating events for each subject.", + } +) +@tagMetadata( + "Subscriptions", + #{ + description: "With Subscriptions, you can easily start, cancel, and manage customer subscriptions. For example, provisioning them on a specific plan or assigning custom rate cards.", + } +) +namespace OpenMeterCloud; + +@route("/api/v1/events") +@tag("Events") +@friendlyName("Events") +interface EventsEndpoints extends OpenMeter.EventsEndpoints {} + +@route("/api/v2/events") +@tag("Events") +@friendlyName("EventsV2") +interface EventsV2Endpoints extends OpenMeter.EventsV2Endpoints {} + +@route("/api/v1/meters") +@tag("Meters") +@friendlyName("Meters") +interface MetersEndpoints extends OpenMeter.MetersEndpoints {} + +namespace OpenMeterCloud.Portal { + @route("/api/v1/portal/tokens") + @tag("Portal") + @friendlyName("PortalTokens") + interface TokensEndpoints extends OpenMeter.Portal.TokensEndpoints {} + + @route("/api/v1/portal/meters") + @tag("Portal") + @useAuth(CloudPortalTokenAuth) + @friendlyName("PortalMeters") + interface MetersEndpoints extends OpenMeter.Portal.MetersEndpoints {} +} + +@route("/api/v1/debug") +@tag("Debug") +@friendlyName("Debug") +interface DebugEndpoints extends OpenMeter.DebugEndpoints {} + +namespace OpenMeterCloud { + @route("/api/v1/marketplace") + @tag("Apps") + @friendlyName("Marketplace") + interface MarketplaceEndpoints extends OpenMeter.MarketplaceEndpoints {} + + @route("/api/v1/apps") + @tag("Apps") + @friendlyName("Apps") + interface AppsEndpoints extends OpenMeter.AppsEndpoints {} + + @tag("App: Stripe") + @friendlyName("AppStripe") + interface AppStripeEndpoints extends OpenMeter.AppStripeEndpoints {} + + @tag("App: Custom Invoicing") + @friendlyName("AppCustomInvoicing") + interface AppCustomInvoicingEndpoints + extends OpenMeter.AppCustomInvoicingEndpoints {} +} + +namespace OpenMeterCloud { + @route("/api/v1/notification/channels") + @tag("Notifications") + @friendlyName("NotificationChannels") + interface ChannelsEndpoints extends OpenMeter.NotificationChannelsEndpoints {} + + @route("/api/v1/notification/rules") + @tag("Notifications") + @friendlyName("NotificationRules") + interface RulesEndpoints extends OpenMeter.NotificationRulesEndpoints {} + + @route("/api/v1/notification/events") + @tag("Notifications") + @friendlyName("NotificationEvents") + interface EventsEndpoints extends OpenMeter.NotificationEventsEndpoints {} +} + +namespace OpenMeterCloud { + @route("/api/v1/entitlements") + @tag("Entitlements") + @friendlyName("Entitlements") + interface EntitlementsEndpoints extends OpenMeter.EntitlementsEndpoints {} + + @route("/api/v1/grants") + @tag("Entitlements") + @friendlyName("Grants") + interface GrantsEndpoints extends OpenMeter.GrantsEndpoints {} + + @route("/api/v1/subjects/{subjectIdOrKey}/entitlements") + @tag("Entitlements") + @friendlyName("Subjects") + interface SubjectEntitlementsEndpoints + extends OpenMeter.SubjectEntitlementsEndpoints {} + + @route("/api/v1/customers/{customerIdOrKey}") + @tag("Entitlements") + @tag("Customers") + @friendlyName("Customer") + interface CustomerEndpoints extends OpenMeter.CustomerEndpoints {} + + @route("/api/v1/customers/{customerIdOrKey}/apps") + @tag("Customers") + @tag("Apps") + @friendlyName("CustomerApps") + interface CustomerAppsEndpoints extends OpenMeter.CustomerAppsEndpoints {} + + @route("/api/v1/customers/{customerIdOrKey}/stripe") + @tag("Customers") + @friendlyName("CustomerStripe") + interface CustomerStripeEndpoints extends OpenMeter.CustomerStripeEndpoints {} + + @route("/api/v1/customers/{customerIdOrKey}/entitlements/{featureKey}") + @tag("Entitlements") + @tag("Customers") + @friendlyName("CustomerEntitlement") + interface CustomerEntitlementEndpoints + extends OpenMeter.CustomerEntitlementEndpoints {} + + namespace V2 { + @route("/api/v2/customers/{customerIdOrKey}/entitlements") + @tag("Entitlements") + @tag("Customers") + @friendlyName("CustomerEntitlementsV2") + interface CustomerEntitlementsV2Endpoints + extends OpenMeter.CustomerEntitlementsV2Endpoints {} + + @route("/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}") + @tag("Entitlements") + @tag("Customers") + @friendlyName("CustomerEntitlementV2") + interface CustomerEntitlementEndpoints + extends OpenMeter.CustomerEntitlementV2Endpoints {} + + @route("/api/v2/grants") + @tag("Entitlements") + @friendlyName("GrantsV2") + interface GrantsV2Endpoints extends OpenMeter.GrantsV2Endpoints {} + + @route("/api/v2/entitlements") + @tag("Entitlements") + @friendlyName("EntitlementsV2") + interface EntitlementsV2Endpoints + extends OpenMeter.EntitlementsV2Endpoints {} + } +} + +namespace OpenMeterCloud { + @route("/api/v1/customers") + @tag("Customers") + @friendlyName("Customers") + interface CustomersEndpoints extends OpenMeter.CustomersEndpoints {} + + @route("/api/v1/billing/customers") + @tag("Billing") + @friendlyName("CustomerOverrides") + interface CustomerOverridesEndpoints + extends OpenMeter.CustomerOverridesEndpoints {} + + @route("/api/v1/billing/profiles") + @tag("Billing") + @friendlyName("BillingProfiles") + interface BillingProfilesEndpoints + extends OpenMeter.BillingProfilesEndpoints {} + + @route("/api/v1/billing/invoices") + @tag("Billing") + @friendlyName("Invoices") + interface InvoicesEndpoints extends OpenMeter.InvoicesEndpoints {} + + @route("/api/v1/billing/invoices/{invoiceId}") + @tag("Billing") + @friendlyName("Invoice") + interface InvoiceEndpoints extends OpenMeter.InvoiceEndpoints {} + + @route("/api/v1/billing/customers/{customerId}/invoices") + @tag("Billing") + @friendlyName("CustomerInvoice") + interface CustomerInvoiceEndpoints + extends OpenMeter.CustomerInvoiceEndpoints {} +} + +namespace OpenMeterCloud { + @route("/api/v1/features") + @tag("Product Catalog") + @friendlyName("Features") + interface FeaturesEndpoints extends OpenMeter.FeaturesEndpoints {} + + @route("/api/v1/plans") + @tag("Product Catalog") + @friendlyName("Plans") + interface PlansEndpoints extends OpenMeter.PlansEndpoints {} + + @route("/api/v1/addons") + @tag("Product Catalog") + @friendlyName("Addons") + interface AddonsEndpoints extends OpenMeter.AddonsEndpoints {} + + @route("/api/v1/plans/{planId}/addons") + @tag("Product Catalog") + @friendlyName("PlanAddons") + interface PlanAddonsEndpoints extends OpenMeter.PlanAddonsEndpoints {} + + @route("/api/v1/subscriptions") + @tag("Subscriptions") + @friendlyName("Subscriptions") + interface SubscriptionsEndpoints extends OpenMeter.SubscriptionsEndpoints {} + + @route("/api/v1/subscriptions/{subscriptionId}/addons") + @tag("Subscriptions") + @friendlyName("SubscriptionAddons") + interface SubscriptionAddonsEndpoints + extends OpenMeter.SubscriptionAddonsEndpoints {} +} + +namespace OpenMeterCloud { + @route("/api/v1/subjects") + @tag("Subjects") + @friendlyName("Subjects") + interface SubjectsEndpoints extends OpenMeter.SubjectsEndpoints {} +} + +namespace OpenMeterCloud { + @route("/api/v1/info/currencies") + @tag("Lookup Information") + @friendlyName("Currencies") + interface CurrenciesEndpoints extends OpenMeter.CurrenciesEndpoints {} + + @route("/api/v1/info/progress") + @tag("Lookup Information") + @friendlyName("Progress") + interface ProgressEndpoints extends OpenMeter.ProgressEndpoints {} +} diff --git a/api/spec/packages/legacy/src/customer/app.tsp b/api/spec/packages/legacy/src/customer/app.tsp new file mode 100644 index 0000000000000000000000000000000000000000..aefd37ae294184aa2bf2b5f26db6aa2cd2594c57 --- /dev/null +++ b/api/spec/packages/legacy/src/customer/app.tsp @@ -0,0 +1,74 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +import "../app"; +import "../rest.tsp"; +import "../errors.tsp"; +import "../types.tsp"; +import "../query.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * Customer App Data API. + */ +@route("/api/v1/customers/{customerIdOrKey}/apps") +@tag("Customers") +@tag("Apps") +@friendlyName("CustomerApps") +interface CustomerAppsEndpoints { + /** + * List customers app data. + */ + @get + @operationId("listCustomerAppData") + @summary("List customer app data") + listAppData( + @path customerIdOrKey: ULIDOrExternalKey, + ...ListCustomerAppDataParams, + ): PaginatedResponse | NotFoundError | CommonErrors; + + /** + * Upsert customer app data. + */ + @put + @operationId("upsertCustomerAppData") + @summary("Upsert customer app data") + upsertAppData( + @path customerIdOrKey: ULIDOrExternalKey, + @body appData: CustomerAppData[], + ): CustomerAppData[] | NotFoundError | CommonErrors; + + /** + * Delete customer app data. + */ + @delete + @route("/{appId}") + @operationId("deleteCustomerAppData") + @summary("Delete customer app data") + deleteAppData(@path customerIdOrKey: ULIDOrExternalKey, @path appId: ULID): + | { + @statusCode _: 204; + } + | NotFoundError + | CommonErrors; +} + +/** + * Query params for listing customers app data. + */ +@friendlyName("listCustomerAppDataParams") +model ListCustomerAppDataParams { + ...QueryPagination; + + /** + * Filter customer data by app type. + */ + @query + @example(AppType.Stripe) + type?: AppType; +} diff --git a/api/spec/packages/legacy/src/customer/customer.tsp b/api/spec/packages/legacy/src/customer/customer.tsp new file mode 100644 index 0000000000000000000000000000000000000000..56665b03a8a4898f0065a35673f2eae44ece521d --- /dev/null +++ b/api/spec/packages/legacy/src/customer/customer.tsp @@ -0,0 +1,294 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +import "../productcatalog"; +import "../rest.tsp"; +import "../errors.tsp"; +import "../types.tsp"; +import "../query.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * Customer API. + */ +@route("/api/v1/customers") +@tag("Customers") +@friendlyName("Customers") +interface CustomersEndpoints { + /** + * Create a new customer. + */ + @post + @operationId("createCustomer") + @summary("Create customer") + create(@body customer: TypeSpec.Rest.Resource.ResourceCreateModel): + | { + @statusCode _: 201; + @body body: Customer; + } + | CommonErrors; + + /** + * List customers. + */ + @get + @operationId("listCustomers") + @summary("List customers") + list(...ListCustomersParams): PaginatedResponse | CommonErrors; + + /** + * Get a customer by ID or key. + */ + @get + @route("/{customerIdOrKey}") + @operationId("getCustomer") + @summary("Get customer") + get(@path customerIdOrKey: ULIDOrExternalKey, ...GetCustomerParams): + | Customer + | NotFoundError + | CommonErrors; + + /** + * Update a customer by ID. + */ + @put + @route("/{customerIdOrKey}") + @operationId("updateCustomer") + @summary("Update customer") + update( + @path customerIdOrKey: ULIDOrExternalKey, + @body customer: TypeSpec.Rest.Resource.ResourceReplaceModel, + ): Customer | NotFoundError | CommonErrors; + + /** + * Delete a customer by ID. + */ + @delete + @route("/{customerIdOrKey}") + @operationId("deleteCustomer") + @summary("Delete customer") + delete(@path customerIdOrKey: ULIDOrExternalKey): + | { + @statusCode _: 204; + } + | NotFoundError + | CommonErrors; + + /** + * Lists all subscriptions for a customer. + */ + @get + @route("/{customerIdOrKey}/subscriptions") + @operationId("listCustomerSubscriptions") + @summary("List customer subscriptions") + listCustomerSubscriptions( + @path customerIdOrKey: ULIDOrExternalKey, + @query(#{ explode: true }) status?: SubscriptionStatus[], + ...QueryOrdering, + ...QueryPagination, + ): PaginatedResponse | NotFoundError | CommonErrors; +} + +/** + * Order by options for customer subscriptions. + */ +@friendlyName("CustomerSubscriptionOrderBy") +enum CustomerSubscriptionOrderBy { + activeFrom: "activeFrom", + activeTo: "activeTo", +} + +/** + * Query params for get customer. + */ +@friendlyName("queryCustomerGet") +model GetCustomerParams { + /** + * What parts of the customer output to expand + */ + @query(#{ explode: true }) + expand?: CustomerExpand[]; +} + +/** + * Query params for listing customers. + */ +@friendlyName("queryCustomerList") +model ListCustomersParams { + ...QueryPagination; + + /** + * Order customers by. + * @TODO: set default value to CustomerOrderBy.name + */ + ...QueryOrdering; + + /** + * Include deleted customers. + */ + @query + includeDeleted?: boolean = false; + + /** + * Filter customers by key. + * Case-insensitive partial match. + */ + @query + key?: string; + + /** + * Filter customers by name. + * Case-insensitive partial match. + */ + @query + @example("ACME") + name?: string; + + /** + * Filter customers by primary email. + * Case-insensitive partial match. + */ + @query + @example("acme@test.com") + primaryEmail?: string; + + /** + * Filter customers by usage attribution subject. + * Case-insensitive partial match. + */ + @query + @example("my_subject_key") + subject?: string; + + /** + * Filter customers by the plan key of their susbcription. + */ + @query + @example("pro_plan") + planKey?: string; + + /** + * What parts of the list output to expand in listings + */ + @query(#{ explode: true }) + expand?: CustomerExpand[]; +} + +/** + * CustomerExpand specifies the parts of the customer to expand in the list output. + */ +@friendlyName("CustomerExpand") +enum CustomerExpand { + subscriptions: "subscriptions", +} + +/** + * Order by options for customers. + */ +@friendlyName("CustomerOrderBy") +enum CustomerOrderBy { + id: "id", + name: "name", + createdAt: "createdAt", +} + +/** + * A customer object. + */ +@friendlyName("Customer") +@example(#{ + id: "01G65Z755AFWAKHE12NY0CQ9FH", + name: "ACME Inc.", + usageAttribution: #{ subjectKeys: #["my_subject_key"] }, + createdAt: DateTime.fromISO("2024-01-01T01:01:01.001Z"), + updatedAt: DateTime.fromISO("2024-01-01T01:01:01.001Z"), +}) +model Customer { + ...Resource; + + /** + * An optional unique key of the customer. + * Either key or usageAttribution.subjectKeys must be provided. + * Useful to reference the customer in external systems. + * For example, your database ID. + */ + @summary("Key") + key?: ExternalKey; + + /** + * Mapping to attribute metered usage to the customer + * Either key or usageAttribution.subjectKeys must be provided. + */ + @summary("Usage Attribution") + usageAttribution?: CustomerUsageAttribution; + + /** + * The primary email address of the customer. + */ + @summary("Primary Email") + primaryEmail?: string; + + /** + * Currency of the customer. + * Used for billing, tax and invoicing. + */ + @summary("Currency") + currency?: CurrencyCode; + + /** + * The billing address of the customer. + * Used for tax and invoicing. + */ + @summary("Billing Address") + billingAddress?: Address; + + /** + * The ID of the Subscription if the customer has one. + */ + @summary("Current Subscription ID") + @visibility(Lifecycle.Read) + currentSubscriptionId?: ULID; + + /** + * The subscriptions of the customer. + * Only with the `subscriptions` expand option. + */ + @summary("Subscriptions") + @visibility(Lifecycle.Read) + subscriptions?: Subscription[]; + + /** + * Set of key-value pairs managed by the system. Cannot be modified by user. + */ + @summary("Annotations") + @visibility(Lifecycle.Read) + annotations?: Annotations; +} + +/** + * Mapping to attribute metered usage to the customer. + * One customer can have zero or more subjects, + * but one subject can only belong to one customer. + */ +@friendlyName("CustomerUsageAttribution") +model CustomerUsageAttribution { + /** + * The subjects that are attributed to the customer. + * Can be empty when no subjects are associated with the customer. + */ + @summary("SubjectKeys") + @minItems(0) + subjectKeys: SubjectKey[]; +} + +/** + * SubjectKey is a key that is used to identify a subject. + */ +@minLength(1) +@extension("x-inline", true) +scalar SubjectKey extends string; diff --git a/api/spec/packages/legacy/src/customer/main.tsp b/api/spec/packages/legacy/src/customer/main.tsp new file mode 100644 index 0000000000000000000000000000000000000000..893b9e48bf5696e1169f9b2dd34c3693a6fb51f4 --- /dev/null +++ b/api/spec/packages/legacy/src/customer/main.tsp @@ -0,0 +1,5 @@ +import "./app.tsp"; +import "./customer.tsp"; +import "./stripe.tsp"; + +namespace OpenMeter; diff --git a/api/spec/packages/legacy/src/customer/stripe.tsp b/api/spec/packages/legacy/src/customer/stripe.tsp new file mode 100644 index 0000000000000000000000000000000000000000..8105c6c5d0cfc505bedbf2c4e1f7ec74b41c216b --- /dev/null +++ b/api/spec/packages/legacy/src/customer/stripe.tsp @@ -0,0 +1,167 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +import "../rest.tsp"; +import "../errors.tsp"; +import "../types.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; +/** + * Customer Stripe API. + */ +@route("/api/v1/customers/{customerIdOrKey}/stripe") +@tag("Customers") +@tag("Apps") +@friendlyName("CustomerStripe") +interface CustomerStripeEndpoints { + /** + * Get stripe app data for a customer. + * Only returns data if the customer billing profile is linked to a stripe app. + */ + @get + @operationId("getCustomerStripeAppData") + @summary("Get customer stripe app data") + get(@path customerIdOrKey: ULIDOrExternalKey): + | StripeCustomerAppData + | NotFoundError + | CommonErrors; + + /** + * Upsert stripe app data for a customer. + * Only updates data if the customer billing profile is linked to a stripe app. + */ + @put + @operationId("upsertCustomerStripeAppData") + @summary("Upsert customer stripe app data") + upsert( + @path customerIdOrKey: ULIDOrExternalKey, + @body appData: StripeCustomerAppDataBase, + ): StripeCustomerAppData | NotFoundError | CommonErrors; + + /** + * Create Stripe customer portal session. + * Only returns URL if the customer billing profile is linked to a stripe app and customer. + * + * Useful to redirect the customer to the Stripe customer portal to manage their payment methods, + * change their billing address and access their invoice history. + */ + @post + @route("/portal") + @operationId("createCustomerStripePortalSession") + @summary("Create Stripe customer portal session") + createPortalSession( + @path customerIdOrKey: ULIDOrExternalKey, + @body params: CreateStripeCustomerPortalSessionParams, + ): + | { + @statusCode _: 201; + @body body: StripeCustomerPortalSession; + } + | NotFoundError + | CommonErrors; +} + +/** + * Stripe customer portal request params. + */ +@friendlyName("CreateStripeCustomerPortalSessionParams") +model CreateStripeCustomerPortalSessionParams { + /** + * The ID of an existing configuration to use for this session, + * describing its functionality and features. + * If not specified, the session uses the default configuration. + * + * See https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-configuration + */ + @summary("Configuration") + configurationId?: string; + + /** + * The IETF language tag of the locale customer portal is displayed in. + * If blank or auto, the customer’s preferred_locales or browser’s locale is used. + * + * See: https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-locale + */ + @summary("Locale") + locale?: string; + + /** + * The URL to redirect the customer to after they have completed + * their requested actions. + * + * See: https://docs.stripe.com/api/customer_portal/sessions/create#create_portal_session-return_url + */ + @summary("ReturnUrl") + returnUrl?: string; +} + +/** + * Stripe customer portal session. + * + * See: https://docs.stripe.com/api/customer_portal/sessions/object + */ +@friendlyName("StripeCustomerPortalSession") +model StripeCustomerPortalSession { + /** + * The ID of the customer portal session. + * + * See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-id + */ + id: string; + + /** + * The ID of the stripe customer. + */ + stripeCustomerId: string; + + /** + * Configuration used to customize the customer portal. + * + * See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-configuration + */ + configurationId: string; + + /** + * Livemode. + * + * See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-livemode + */ + livemode: boolean; + + /** + * Created at. + * + * See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-created + */ + createdAt: DateTime; + + /** + * Return URL. + * + * See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-return_url + */ + returnUrl: string; + + /** + * Status. + /** + * The IETF language tag of the locale customer portal is displayed in. + * + * See: https://docs.stripe.com/api/customer_portal/sessions/object#portal_session_object-locale + */ + locale: string; + + /** + /** + * The ID of the customer. + */ + /** + * The URL to redirect the customer to after they have completed + * their requested actions. + */ + url: string; +} diff --git a/api/spec/packages/legacy/src/debug.tsp b/api/spec/packages/legacy/src/debug.tsp new file mode 100644 index 0000000000000000000000000000000000000000..4f6449322fd57a6c625a00234eeccdbb7de184ce --- /dev/null +++ b/api/spec/packages/legacy/src/debug.tsp @@ -0,0 +1,37 @@ +import "@typespec/http"; +import "@typespec/openapi3"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +@route("/api/v1/debug") +@tag("Debug") +@friendlyName("Debug") +interface DebugEndpoints { + /** + * Returns debug metrics (in OpenMetrics format) like the number of ingested events since mindnight UTC. + * + * The OpenMetrics Counter(s) reset every day at midnight UTC. + */ + @get + @route("/metrics") + @operationId("getDebugMetrics") + @summary("Get event metrics") + metrics(): + | { + @header contentType: "text/plain"; + @statusCode _: 200; + + @body + @example(""" + # HELP openmeter_events Number of ingested events + # TYPE openmeter_events counter + openmeter_events_total{subject="customer-1"} 12345.0 + openmeter_events_total{subject="customer-1",error="true"} 1.0 + """) + body: string; + } + | CommonErrors; +} diff --git a/api/spec/packages/legacy/src/entitlements/customer.tsp b/api/spec/packages/legacy/src/entitlements/customer.tsp new file mode 100644 index 0000000000000000000000000000000000000000..618c6dd8e33890520be0b319356929c513a4aaeb --- /dev/null +++ b/api/spec/packages/legacy/src/entitlements/customer.tsp @@ -0,0 +1,58 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +@route("/api/v1/customers/{customerIdOrKey}") +@tag("Entitlements") +@tag("Customers") +@friendlyName("Customer") +interface CustomerEndpoints { + /** + * Get the overall access of a customer. + */ + @get + @operationId("getCustomerAccess") + @route("/access") + @summary("Get customer access") + getCustomerAccess(@path customerIdOrKey: ULIDOrExternalKey): + | CustomerAccess + | CommonErrors + | NotFoundError; +} + +@route("/api/v1/customers/{customerIdOrKey}/entitlements/{featureKey}") +@tag("Entitlements") +@tag("Customers") +@friendlyName("CustomerEntitlement") +interface CustomerEntitlementEndpoints { + /** + * Checks customer access to a given feature (by key). All entitlement types share the hasAccess property in their value response, but multiple other properties are returned based on the entitlement type. + */ + @get + @operationId("getCustomerEntitlementValue") + @route("/value") + @summary("Get customer entitlement value") + getCustomerEntitlementValue( + @path customerIdOrKey: ULIDOrExternalKey, + @path featureKey: Key, + @query(#{ explode: true }) time?: DateTime, + ): EntitlementValue | CommonErrors | NotFoundError; +} + +/** + * CustomerAccess describes what features the customer has access to. + */ +@friendlyName("CustomerAccess") +model CustomerAccess { + /** + * Map of entitlements the customer has access to. + * The key is the feature key, the value is the entitlement value + the entitlement ID. + */ + @visibility(Lifecycle.Read) + entitlements: Record; +} diff --git a/api/spec/packages/legacy/src/entitlements/entitlements.tsp b/api/spec/packages/legacy/src/entitlements/entitlements.tsp new file mode 100644 index 0000000000000000000000000000000000000000..c0676e9786e0058dd9b80231130561d830b725ce --- /dev/null +++ b/api/spec/packages/legacy/src/entitlements/entitlements.tsp @@ -0,0 +1,436 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * Order by options for entitlements. + */ +@friendlyName("EntitlementOrderBy") +enum EntitlementOrderBy { + #suppress "@openmeter/api-spec-legacy/casing" "Use existing values" + CreatedAt: "createdAt", + #suppress "@openmeter/api-spec-legacy/casing" "Use existing values" + UpdatedAt: "updatedAt", +} + +@route("/api/v1/entitlements") +@tag("Entitlements") +@friendlyName("Entitlements") +interface EntitlementsEndpoints { + /** + * List all entitlements for all the subjects and features. This endpoint is intended for administrative purposes only. + * To fetch the entitlements of a specific subject please use the /api/v1/subjects/{subjectKeyOrID}/entitlements endpoint. + * If page is provided that takes precedence and the paginated response is returned. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/entitlements`](#tag/entitlements/get/api/v2/entitlements) instead. + */ + #deprecated "Use `GET /api/v2/entitlements` instead" + #suppress "deprecated" "V1 Entitlements APIs will be removed on December 1st, 2025" + @get + @operationId("listEntitlements") + @summary("List all entitlements") + @extension("x-internal", true) + list( + /** + * Filtering by multiple features. + * + * Usage: `?feature=feature-1&feature=feature-2` + */ + @query(#{ explode: true }) + feature?: string[], + + /** + * Filtering by multiple subjects. + * + * Usage: `?subject=customer-1&subject=customer-2` + */ + @query(#{ explode: true }) + subject?: string[], + + /** + * Filtering by multiple entitlement types. + * + * Usage: `?entitlementType=metered&entitlementType=boolean` + */ + @query(#{ explode: true }) + entitlementType?: EntitlementType[], + + /** + * Exclude inactive entitlements in the response (those scheduled for later or earlier) + */ + @query + excludeInactive?: boolean = false, + + ...QueryPagination, + ...QueryLimitOffset, + ...QueryOrdering, + ): + | { + @statusCode _: 200; + @body body: ListEntitlementsResult; + } + | CommonErrors; + + /** + * Get entitlement by ID. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/entitlements/{entitlementId}`](#tag/entitlements/get/api/v2/entitlements/{entitlementId}) instead. + */ + #deprecated "Use `GET /api/v2/entitlements/{entitlementId}` instead" + #suppress "deprecated" "V1 Entitlements APIs will be removed on December 1st, 2025" + @get + @operationId("getEntitlementById") + @summary("Get entitlement by ID") + get( + @path + entitlementId: ULID, + ): Entitlement | NotFoundError | CommonErrors; +} + +// TODO: Remove in v2 + +/** + * List entitlements result + */ +@oneOf +@friendlyName("ListEntitlementsResult") +union ListEntitlementsResult { + Entitlement[], + PaginatedResponse, +} + +/** + * Type of the entitlement. + */ +#deprecated "Use EntitlementsV2 instead" +#suppress "deprecated" "V1 Entitlements APIs will be removed on December 1st, 2025" +@friendlyName("EntitlementType") +@extension("x-go-type", "string") +enum EntitlementType { + metered: "metered", + boolean: "boolean", + static: "static", +} + +// NOTE: use OmitProperties for templates once entitlement models are defined + +/** + * Entitlement templates are used to define the entitlements of a plan. + * Features are omitted from the entitlement template, as they are defined in the rate card. + */ +#deprecated "Use EntitlementV2 instead" +#suppress "deprecated" "V1 Entitlements APIs will be removed on December 1st, 2025" +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +@friendlyName("Entitlement") +union Entitlement { + metered: EntitlementMetered, + static: EntitlementStatic, + boolean: EntitlementBoolean, +} + +/** + * Shared fields for entitlement creation + */ +@friendlyName("EntitlementCreateSharedFields") +model EntitlementCreateSharedFields { + /** + * The feature the subject is entitled to use. + * Either featureKey or featureId is required. + */ + @example("example-feature-key") + featureKey?: Key; + + /** + * The feature the subject is entitled to use. + * Either featureKey or featureId is required. + */ + @example("01ARZ3NDEKTSV4RRFFQ69G5FAV") + featureId?: ULID; + + /** + * Additional metadata for the feature. + */ + metadata?: Metadata; + + /** + * The usage period associated with the entitlement. + */ + usagePeriod?: RecurringPeriodCreateInput; +} + +/** + * Create inpurs for metered entitlement + */ +#deprecated "Use EntitlementMeteredV2CreateInputs instead" +#suppress "deprecated" "V1 Entitlements APIs will be removed on December 1st, 2025" +@friendlyName("EntitlementMeteredCreateInputs") +model EntitlementMeteredCreateInputs { + ...OmitProperties; + type: EntitlementType.metered; + + /** + * If softLimit=true the subject can use the feature even if the entitlement is exhausted, hasAccess will always be true. + */ + @summary("Soft limit") + isSoftLimit?: boolean = false; + + /** + * Deprecated, ignored by the backend. Please use isSoftLimit instead; this field will be removed in the future. + */ + #deprecated "Use isSoftLimit instead" + isUnlimited?: boolean = false; + + /** + * The usage period associated with the entitlement. + */ + usagePeriod: RecurringPeriodCreateInput; + + /** + * Defines the time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + */ + measureUsageFrom?: MeasureUsageFrom; + + /** + * You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + * If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + * That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + * Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + */ + @minValue(0) + @summary("Initial grant amount") + issueAfterReset?: float64; + + /** + * Defines the grant priority for the default grant. + */ + @minValue(1) + @maxValue(255) + @summary("Issue grant after reset priority") + issueAfterResetPriority?: uint8 = 1; + + /** + * If true, the overage is preserved at reset. If false, the usage is reset to 0. + */ + @summary("Preserve overage at reset") + preserveOverageAtReset?: boolean = false; +} + +/** + * Create inputs for static entitlement + */ +#deprecated "Use EntitlementStaticV2CreateInputs instead" +#suppress "deprecated" "V1 Entitlements APIs will be removed on December 1st, 2025" +@friendlyName("EntitlementStaticCreateInputs") +model EntitlementStaticCreateInputs { + ...EntitlementCreateSharedFields; + type: EntitlementType.static; + + /** + * The JSON parsable config of the entitlement. This value is also returned when checking entitlement access and it is useful for configuring fine-grained access settings to the feature, implemented in your own system. Has to be an object. + */ + @example("{ \"integrations\": [\"github\"] }") + @encode("json") + config: string; +} + +/** + * Create inputs for boolean entitlement + */ +#deprecated "Use EntitlementBooleanV2CreateInputs instead" +#suppress "deprecated" "V1 Entitlements APIs will be removed on December 1st, 2025" +@friendlyName("EntitlementBooleanCreateInputs") +model EntitlementBooleanCreateInputs { + ...EntitlementCreateSharedFields; + type: EntitlementType.boolean; +} + +/** + * Create inputs for entitlement + */ +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +@friendlyName("EntitlementCreateInputs") +union EntitlementCreateInputs { + metered: EntitlementMeteredCreateInputs, + static: EntitlementStaticCreateInputs, + boolean: EntitlementBooleanCreateInputs, +} + +/** + * Shared fields of the entitlement templates. + */ +@friendlyName("EntitlementBaseTemplate") +model EntitlementSharedFields { + ...ResourceTimestamps; + ...OmitProperties< + EntitlementCreateSharedFields, + "featureKey" | "featureId" | "usagePeriod" + >; + ...CadencedResource; + + /** + * The annotations of the entitlement. + */ + @example(#{ `subscription.id`: "sub_123" }) + @visibility(Lifecycle.Read) + annotations?: Annotations; + + /** + * Readonly unique ULID identifier. + */ + @example("01ARZ3NDEKTSV4RRFFQ69G5FAV") + @visibility(Lifecycle.Read) + id: ULID; + + /** + * The type of the entitlement. + */ + @summary("Type") + type: EntitlementType; + + /** + * The identifier key unique to the subject. + * NOTE: Subjects are being deprecated, please use the new customer APIs. + */ + @example("customer-1") + subjectKey: Key; + + /** + * The feature the subject is entitled to use. + */ + @example("example-feature-key") + featureKey: Key; + + /** + * The feature the subject is entitled to use. + */ + @example("01ARZ3NDEKTSV4RRFFQ69G5FAV") + featureId: ULID; + + /** + * The current usage period. + */ + currentUsagePeriod?: Period; + + /** + * The defined usage period of the entitlement + */ + usagePeriod?: RecurringPeriod; +} + +/** + * Calculated fields for metered entitlements. + */ +@friendlyName("EntitlementMeteredCalculatedFields") +model EntitlementMeteredCalculatedFields { + /** + * The time the last reset happened. + */ + @example(DateTime.fromISO("2023-01-01T01:01:01.001Z")) + @visibility(Lifecycle.Read) + lastReset: DateTime; + + /** + * The current usage period. + */ + @visibility(Lifecycle.Read) + currentUsagePeriod: Period; + + /** + * The time from which usage is measured. If not specified on creation, defaults to entitlement creation time. + */ + @visibility(Lifecycle.Read) + measureUsageFrom: DateTime; + + /** + * THe usage period of the entitlement. + */ + @visibility(Lifecycle.Read) + usagePeriod: RecurringPeriod; +} + +/** + * Metered entitlements are useful for many different use cases, from setting up usage based access to implementing complex credit systems. + * Access is determined based on feature usage using a balance calculation (the "usage allowance" provided by the issued grants is "burnt down" by the usage). + */ +#deprecated "Use EntitlementMeteredV2 instead" +#suppress "deprecated" "V1 Entitlements APIs will be removed on December 1st, 2025" +@friendlyName("EntitlementMetered") +model EntitlementMetered { + type: EntitlementType.metered; + ...OmitProperties< + EntitlementMeteredCreateInputs, + + | "type" + | "measureUsageFrom" + | "metadata" + | "usagePeriod" + | "featureKey" + | "featureId" + | "currentUsagePeriod" + >; + ...OmitProperties< + EntitlementSharedFields, + "type" | "currentUsagePeriod" | "usagePeriod" + >; + ...EntitlementMeteredCalculatedFields; +} + +/** + * Entitlement template of a boolean entitlement. + */ +#deprecated "Use EntitlementBooleanV2 instead" +#suppress "deprecated" "V1 Entitlements APIs will be removed on December 1st, 2025" +@friendlyName("EntitlementBoolean") +model EntitlementBoolean { + type: EntitlementType.boolean; + ...OmitProperties< + EntitlementBooleanCreateInputs, + "type" | "metadata" | "usagePeriod" | "featureKey" | "featureId" + >; + ...OmitProperties; +} + +/** + * A static entitlement. + */ +#deprecated "Use EntitlementStaticV2 instead" +#suppress "deprecated" "V1 Entitlements APIs will be removed on December 1st, 2025" +@friendlyName("EntitlementStatic") +model EntitlementStatic { + type: EntitlementType.static; + ...OmitProperties< + EntitlementStaticCreateInputs, + "type" | "metadata" | "usagePeriod" | "featureKey" | "featureId" + >; + ...OmitProperties; +} + +/** + * Start of measurement options + */ +@friendlyName("MeasureUsageFromPreset") +@extension("x-enum-varnames", #["CurrentPeriodStart", "Now"]) +enum MeasureUsageFromPreset { + #suppress "@openmeter/api-spec-legacy/casing" "Use existing values" + CURRENT_PERIOD_START: "CURRENT_PERIOD_START", + #suppress "@openmeter/api-spec-legacy/casing" "Use existing values" + NOW: "NOW", +} + +@friendlyName("MeasureUsageFromTime") +scalar MeasureUsageFromTime extends DateTime; + +/** + * Measure usage from + */ +@friendlyName("MeasureUsageFrom") +@oneOf +union MeasureUsageFrom { + preset: MeasureUsageFromPreset, + time: MeasureUsageFromTime, +} diff --git a/api/spec/packages/legacy/src/entitlements/grant.tsp b/api/spec/packages/legacy/src/entitlements/grant.tsp new file mode 100644 index 0000000000000000000000000000000000000000..0630bd8168e91b2b60c19db6f5802a6c6cbbab7c --- /dev/null +++ b/api/spec/packages/legacy/src/entitlements/grant.tsp @@ -0,0 +1,243 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * Order by options for grants. + */ +@friendlyName("GrantOrderBy") +enum GrantOrderBy { + ID: "id", + #suppress "@openmeter/api-spec-legacy/casing" "Use existing values" + CreatedAt: "createdAt", + #suppress "@openmeter/api-spec-legacy/casing" "Use existing values" + UpdatedAt: "updatedAt", +} + +@route("/api/v1/grants") +@tag("Entitlements") +@friendlyName("Grants") +interface GrantsEndpoints { + /** + * List all grants for all the subjects and entitlements. This endpoint is intended for administrative purposes only. + * To fetch the grants of a specific entitlement please use the /api/v1/subjects/{subjectKeyOrID}/entitlements/{entitlementOrFeatureID}/grants endpoint. + * If page is provided that takes precedence and the paginated response is returned. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/grants`](#tag/entitlements/get/api/v2/grants) instead. + */ + #deprecated "Use `GET /api/v2/grants` instead" + #suppress "deprecated" "V1 Grants APIs will be removed on December 1st, 2025" + @get + @operationId("listGrants") + @summary("List grants") + list( + /** + * Filtering by multiple features. + * + * Usage: `?feature=feature-1&feature=feature-2` + */ + @query(#{ explode: true }) + feature?: string[], + + /** + * Filtering by multiple subjects. + * + * Usage: `?subject=customer-1&subject=customer-2` + */ + @query(#{ explode: true }) + subject?: string[], + + /** + * Include deleted + */ + @query includeDeleted?: boolean = false, + + ...QueryPagination, + ...QueryLimitOffset, + ...QueryOrdering, + ): Grant[] | PaginatedResponse | CommonErrors; + + /** + * Voiding a grant means it is no longer valid, it doesn't take part in further balance calculations. Voiding a grant does not retroactively take effect, meaning any usage that has already been attributed to the grant will remain, but future usage cannot be burnt down from the grant. + * For example, if you have a single grant for your metered entitlement with an initial amount of 100, and so far 60 usage has been metered, the grant (and the entitlement itself) would have a balance of 40. If you then void that grant, balance becomes 0, but the 60 previous usage will not be affected. + */ + @delete + @operationId("voidGrant") + @summary("Void grant") + delete( + @path grantId: string, + + /** + * The time at which the grant should be voided. + * Must not be in the future and must be within the current usage period of the entitlement. + * Defaults to the current time if not specified. + */ + @query(#{ explode: true }) at?: DateTime, + ): + | { + @statusCode _: 204; + } + | NotFoundError + | CommonErrors + | ConflictError; +} + +/** + * The grant. + */ +#deprecated "Use GrantV2 instead" +#suppress "deprecated" "V1 Grants APIs will be removed on December 1st, 2025" +@friendlyName("EntitlementGrant") +model Grant { + ...ResourceTimestamps; + ...OmitProperties; + + /** + * Readonly unique ULID identifier. + */ + @example("01ARZ3NDEKTSV4RRFFQ69G5FAV") + @visibility(Lifecycle.Read) + id: ULID; + + /** + * The unique entitlement ULID that the grant is associated with. + */ + @example("01ARZ3NDEKTSV4RRFFQ69G5FAV") + @visibility(Lifecycle.Read) + entitlementId: string; + + /** + * The next time the grant will recurr. + */ + @example(DateTime.fromISO("2023-01-01T01:01:01.001Z")) + nextRecurrence?: DateTime; + + /** + * The time the grant expires. + */ + @example(DateTime.fromISO("2023-01-01T01:01:01.001Z")) + @visibility(Lifecycle.Read) + expiresAt?: DateTime; + + /** + * The time the grant was voided. + */ + @example(DateTime.fromISO("2023-01-01T01:01:01.001Z")) + voidedAt?: DateTime; + + /** + * The recurrence period of the grant. + */ + recurrence?: RecurringPeriod; + + /** + * Grant annotations + */ + @example(#{ issueAfterReset: true }) + annotations?: Annotations; +} + +/** + * The grant creation input. + */ +#deprecated "Use GrantCreateInputV2 instead" +#suppress "deprecated" "V1 Grants APIs will be removed on December 1st, 2025" +@friendlyName("EntitlementGrantCreateInput") +model GrantCreateInput { + /** + * The amount to grant. Should be a positive number. + */ + @minValue(0) + @example(100.0) + amount: float64; + + /** + * The priority of the grant. Grants with higher priority are applied first. + * Priority is a positive decimal numbers. With lower numbers indicating higher importance. + * For example, a priority of 1 is more urgent than a priority of 2. + * When there are several grants available for the same subject, the system selects the grant with the highest priority. + * In cases where grants share the same priority level, the grant closest to its expiration will be used first. + * In the case of two grants have identical priorities and expiration dates, the system will use the grant that was created first. + */ + @minValue(1) + @maxValue(255) + @example(1) + priority?: uint8; + + /** + * Effective date for grants and anchor for recurring grants. Provided value will be ceiled to metering windowSize (minute). + */ + effectiveAt: DateTime; + + /** + * The grant expiration definition + */ + expiration: ExpirationPeriod; + + /** + * Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + * Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + */ + @example(100.0) + maxRolloverAmount?: float64 = 0; + + /** + * Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. + * Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + */ + @example(100.0) + minRolloverAmount?: float64 = 0; + + /** + * The grant metadata. + */ + @example(#{ stripePaymentId: "pi_4OrAkhLvyihio9p51h9iiFnB" }) + metadata?: Metadata; + + /** + * The subject of the grant. + */ + recurrence?: RecurringPeriodCreateInput; +} + +/** + * The expiration duration enum + */ +@friendlyName("ExpirationDuration") +enum ExpirationDuration { + #suppress "@openmeter/api-spec-legacy/casing" "Use existing values" + HOUR: "HOUR", + #suppress "@openmeter/api-spec-legacy/casing" "Use existing values" + DAY: "DAY", + #suppress "@openmeter/api-spec-legacy/casing" "Use existing values" + WEEK: "WEEK", + #suppress "@openmeter/api-spec-legacy/casing" "Use existing values" + MONTH: "MONTH", + #suppress "@openmeter/api-spec-legacy/casing" "Use existing values" + YEAR: "YEAR", +} + +/** + * The grant expiration definition + */ +@friendlyName("ExpirationPeriod") +model ExpirationPeriod { + /** + * The unit of time for the expiration period. + */ + duration: ExpirationDuration; + + /** + * The number of time units in the expiration period. + */ + @example(12) + @minValue(1) + @maxValue(1000) + count: uint32; +} diff --git a/api/spec/packages/legacy/src/entitlements/main.tsp b/api/spec/packages/legacy/src/entitlements/main.tsp new file mode 100644 index 0000000000000000000000000000000000000000..a040e7e481a9870048f05654ca3b3fe810e70985 --- /dev/null +++ b/api/spec/packages/legacy/src/entitlements/main.tsp @@ -0,0 +1,16 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "@typespec/versioning"; + +import ".."; + +// Package Contents +import "./entitlements.tsp"; +import "../productcatalog/features.tsp"; +import "./grant.tsp"; +import "./subjects.tsp"; +import "./customer.tsp"; + +namespace OpenMeter; diff --git a/api/spec/packages/legacy/src/entitlements/subjects.tsp b/api/spec/packages/legacy/src/entitlements/subjects.tsp new file mode 100644 index 0000000000000000000000000000000000000000..b2b05046ef44d1393154fb5eaa1b3d42045645b5 --- /dev/null +++ b/api/spec/packages/legacy/src/entitlements/subjects.tsp @@ -0,0 +1,443 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +@route("/api/v1/subjects/{subjectIdOrKey}/entitlements") +@tag("Entitlements") +@friendlyName("Subjects") +interface SubjectEntitlementsEndpoints { + /** + * OpenMeter has three types of entitlements: metered, boolean, and static. The type property determines the type of entitlement. The underlying feature has to be compatible with the entitlement type specified in the request (e.g., a metered entitlement needs a feature associated with a meter). + * + * - Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * - Static entitlements let you pass along a configuration while granting access, e.g. "Using this feature with X Y settings" (passed in the config). + * - Metered entitlements have many use cases, from setting up usage-based access to implementing complex credit systems. Example: The customer can use 10000 AI tokens during the usage period of the entitlement. + * + * A given subject can only have one active (non-deleted) entitlement per featureKey. If you try to create a new entitlement for a featureKey that already has an active entitlement, the request will fail with a 409 error. + * + * Once an entitlement is created you cannot modify it, only delete it. + * + * ⚠️ __Deprecated__: Use [`POST /api/v2/customers/{customerIdOrKey}/entitlements`](#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements) instead. + */ + #deprecated "Use `POST /api/v1/customers/{customerIdOrKey}/entitlements` instead" + #suppress "deprecated" "Subjects APIs will be removed on December 1st, 2025" + @post + @summary("Create a subject entitlement") + @operationId("createEntitlement") + post( + @path subjectIdOrKey: string, + @body entitlement: EntitlementCreateInputs, + ): + | { + @statusCode _: 201; + @body body: Entitlement; + } + | CommonErrors + | ConflictError; + + /** + * List all entitlements for a subject. For checking entitlement access, use the /value endpoint instead. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements) instead. + */ + #deprecated "Use `GET /api/v2/customers/{customerIdOrKey}/entitlements` instead" + #suppress "deprecated" "Subjects APIs will be removed on December 1st, 2025" + @get + @operationId("listSubjectEntitlements") + @summary("List subject entitlements") + list(@path subjectIdOrKey: string, @query includeDeleted?: boolean = false): + | Entitlement[] + | CommonErrors; + + /** + * Get entitlement by id. For checking entitlement access, use the /value endpoint instead. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}) instead. + */ + #deprecated "Use `GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}` instead" + #suppress "deprecated" "Subjects APIs will be removed on December 1st, 2025" + @get + @operationId("getEntitlement") + @summary("Get subject entitlement") + get(@path subjectIdOrKey: string, @path entitlementId: string): + | Entitlement + | CommonErrors + | NotFoundError; + + /** + * Deleting an entitlement revokes access to the associated feature. As a single subject can only have one entitlement per featureKey, when "migrating" features you have to delete the old entitlements as well. + * As access and status checks can be historical queries, deleting an entitlement populates the deletedAt timestamp. When queried for a time before that, the entitlement is still considered active, you cannot have retroactive changes to access, which is important for, among other things, auditing. + * + * ⚠️ __Deprecated__: Use [`DELETE /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}`](#tag/entitlements/delete/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}) instead. + */ + #deprecated "Use `DELETE /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}` instead" + #suppress "deprecated" "Subjects APIs will be removed on December 1st, 2025" + @delete + @operationId("deleteEntitlement") + @summary("Delete subject entitlement") + delete(@path subjectIdOrKey: string, @path entitlementId: string): + | { + @statusCode _: 204; + } + | CommonErrors + | NotFoundError; + + /** + * Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes the previous entitlement for the provided subject-feature pair. If the previous entitlement is already deleted or otherwise doesnt exist, the override will fail. + * + * This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require a new entitlement to be created with zero downtime. + * + * ⚠️ __Deprecated__: Use [`PUT /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override`](#tag/entitlements/put/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override) instead. + */ + #deprecated "Use `PUT /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override` instead" + #suppress "deprecated" "Subjects APIs will be removed on December 1st, 2025" + @put + @operationId("overrideEntitlement") + @route("/{entitlementIdOrFeatureKey}/override") + @summary("Override subject entitlement") + override( + @path subjectIdOrKey: string, + @path entitlementIdOrFeatureKey: string, + @body entitlement: EntitlementCreateInputs, + ): + | { + @statusCode _: 201; + @body body: Entitlement; + } + | CommonErrors + | ConflictError + | NotFoundError; + + /** + * List all grants issued for an entitlement. The entitlement can be defined either by its id or featureKey. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants) instead. + */ + #deprecated "Use `GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants` instead" + #suppress "deprecated" "Subjects APIs will be removed on December 1st, 2025" + @get + @operationId("listEntitlementGrants") + @route("/{entitlementIdOrFeatureKey}/grants") + @summary("List subject entitlement grants") + getGrants( + @path subjectIdOrKey: string, + @path entitlementIdOrFeatureKey: string, + @query includeDeleted?: boolean = false, + @query orderBy?: GrantOrderBy = GrantOrderBy.UpdatedAt, + ): Grant[] | CommonErrors; + + /** + * Grants define a behavior of granting usage for a metered entitlement. They can have complicated recurrence and rollover rules, thanks to which you can define a wide range of access patterns with a single grant, in most cases you don't have to periodically create new grants. You can only issue grants for active metered entitlements. + * + * A grant defines a given amount of usage that can be consumed for the entitlement. The grant is in effect between its effective date and its expiration date. Specifying both is mandatory for new grants. + * + * Grants have a priority setting that determines their order of use. Lower numbers have higher priority, with 0 being the highest priority. + * + * Grants can have a recurrence setting intended to automate the manual reissuing of grants. For example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover settings). + * + * Rollover settings define what happens to the remaining balance of a grant at a reset. Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + * + * Grants cannot be changed once created, only deleted. This is to ensure that balance is deterministic regardless of when it is queried. + * + * ⚠️ __Deprecated__: Use [`POST /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants`](#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants) instead. + */ + #deprecated "Use `POST /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants` instead" + #suppress "deprecated" "Subjects APIs will be removed on December 1st, 2025" + @post + @operationId("createGrant") + @route("/{entitlementIdOrFeatureKey}/grants") + @summary("Create subject entitlement grant") + createGrant( + @path subjectIdOrKey: string, + @path entitlementIdOrFeatureKey: string, + @body grant: GrantCreateInput, + ): + | { + @statusCode _: 201; + @body body: Grant; + } + | CommonErrors + | ConflictError; + + /** + * This endpoint should be used for access checks and enforcement. All entitlement types share the hasAccess property in their value response, but multiple other properties are returned based on the entitlement type. + * + * For convenience reasons, /value works with both entitlementId and featureKey. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value) instead. + */ + #deprecated "Use `GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value` instead" + #suppress "deprecated" "Subjects APIs will be removed on December 1st, 2025" + @get + @operationId("getEntitlementValue") + @route("/{entitlementIdOrFeatureKey}/value") + @summary("Get subject entitlement value") + getEntitlementValue( + @path subjectIdOrKey: string, + @path entitlementIdOrFeatureKey: string, + @query(#{ explode: true }) time?: DateTime, + ): EntitlementValue | CommonErrors | NotFoundError; + + /** + * Returns historical balance and usage data for the entitlement. The queried history can span accross multiple reset events. + * + * BurndownHistory returns a continous history of segments, where the segments are seperated by events that changed either the grant burndown priority or the usage period. + * + * WindowedHistory returns windowed usage data for the period enriched with balance information and the list of grants that were being burnt down in that window. + * + * ⚠️ __Deprecated__: Use [`GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history`](#tag/entitlements/get/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history) instead. + */ + #deprecated "Use `GET /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/history` instead" + #suppress "deprecated" "Subjects APIs will be removed on December 1st, 2025" + @get + @operationId("getEntitlementHistory") + @route("/{entitlementId}/history") + @summary("Get subject entitlement history") + getEntitlementHistory( + @path subjectIdOrKey: string, + @path entitlementId: string, + + /** + * Start of time range to query entitlement: date-time in RFC 3339 format. Defaults to the last reset. Gets truncated to the granularity of the underlying meter. + */ + @query(#{ explode: true }) from?: DateTime, + + /** + * End of time range to query entitlement: date-time in RFC 3339 format. Defaults to now. + * If not now then gets truncated to the granularity of the underlying meter. + */ + @query(#{ explode: true }) to?: DateTime, + + /** + * Windowsize + */ + @query windowSize: WindowSize, + + /** + * The timezone used when calculating the windows. + */ + @query windowTimeZone?: string = "UTC", + ): WindowedBalanceHistory | CommonErrors | NotFoundError; + + /** + * Reset marks the start of a new usage period for the entitlement and initiates grant rollover. At the start of a period usage is zerod out and grants are rolled over based on their rollover settings. It would typically be synced with the subjects billing period to enforce usage based on their subscription. + * + * Usage is automatically reset for metered entitlements based on their usage period, but this endpoint allows to manually reset it at any time. When doing so the period anchor of the entitlement can be changed if needed. + * + * ⚠️ __Deprecated__: Use [`POST /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset`](#tag/entitlements/post/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset) instead. + */ + #deprecated "Use `POST /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/reset` instead" + #suppress "deprecated" "Subjects APIs will be removed on December 1st, 2025" + @post + @operationId("resetEntitlementUsage") + @route("/{entitlementId}/reset") + @summary("Reset subject entitlement") + reset( + @path subjectIdOrKey: string, + @path entitlementId: string, + @body reset: ResetEntitlementUsageInput, + ): + | { + @statusCode _: 204; + } + | CommonErrors + | NotFoundError; +} + +/** + * Entitlements are the core of OpenMeter access management. They define access to features for subjects. Entitlements can be metered, boolean, or static. + */ +@friendlyName("EntitlementValue") +model EntitlementValue { + /** + * Whether the subject has access to the feature. Shared accross all entitlement types. + */ + @visibility(Lifecycle.Read) + @example(true) + hasAccess: boolean; + + /** + * Only available for metered entitlements. Metered entitlements are built around a balance calculation where feature usage is deducted from the issued grants. Balance represents the remaining balance of the entitlement, it's value never turns negative. + */ + @example(100) + @visibility(Lifecycle.Read) + balance?: float64; + + /** + * Only available for metered entitlements. Returns the total feature usage in the current period. + */ + @example(50) + @visibility(Lifecycle.Read) + usage?: float64; + + /** + * Only available for metered entitlements. Overage represents the usage that wasn't covered by grants, e.g. if the subject had a total feature usage of 100 in the period but they were only granted 80, there would be 20 overage. + */ + @example(0) + @visibility(Lifecycle.Read) + overage?: float64; + + /** + * Only available for metered entitlements. The summed amount of all grant active at query time PLUS the used amount of since inactive grants. + */ + @example(100) + @visibility(Lifecycle.Read) + totalAvailableGrantAmount?: float64; + + /** + * Only available for static entitlements. The JSON parsable config of the entitlement. + */ + @example("{ key: \"value\" }") + @visibility(Lifecycle.Read) + config?: string; +} + +/** + * The windowed balance history. + */ +@friendlyName("WindowedBalanceHistory") +model WindowedBalanceHistory { + /** + * The windowed balance history. + * - It only returns rows for windows where there was usage. + * - The windows are inclusive at their start and exclusive at their end. + * - The last window may be smaller than the window size and is inclusive at both ends. + */ + windowedHistory: BalanceHistoryWindow[]; + + /** + * Grant burndown history. + */ + burndownHistory: GrantBurnDownHistorySegment[]; +} + +/** + * The balance history window. + */ +@friendlyName("BalanceHistoryWindow") +model BalanceHistoryWindow { + period: Period; + + /** + * The total usage of the feature in the period. + */ + @example(100) + @visibility(Lifecycle.Read) + usage: float64; + + /** + * The entitlement balance at the start of the period. + */ + @example(100) + @visibility(Lifecycle.Read) + balanceAtStart: float64; +} + +/** + * A segment of the grant burn down history. + * + * A given segment represents the usage of a grant between events that changed either the grant burn down priority order or the usag period. + */ +@friendlyName("GrantBurnDownHistorySegment") +model GrantBurnDownHistorySegment { + /** + * The period of the segment. + */ + period: Period; + + /** + * The total usage of the grant in the period. + */ + @example(100) + @visibility(Lifecycle.Read) + usage: float64; + + /** + * Overuse that wasn't covered by grants. + */ + @example(100) + @visibility(Lifecycle.Read) + overage: float64; + + /** + * entitlement balance at the start of the period. + */ + @example(100) + @visibility(Lifecycle.Read) + balanceAtStart: float64; + + /** + * The balance breakdown of each active grant at the start of the period: GrantID: Balance + */ + @example(#{ `01G65Z755AFWAKHE12NY0CQ9FH`: 100 }) + @visibility(Lifecycle.Read) + grantBalancesAtStart: Record; + + /** + * The entitlement balance at the end of the period. + */ + @example(100) + @visibility(Lifecycle.Read) + balanceAtEnd: float64; + + /** + * The balance breakdown of each active grant at the end of the period: GrantID: Balance + */ + @example(#{ `01G65Z755AFWAKHE12NY0CQ9FH`: 100 }) + @visibility(Lifecycle.Read) + grantBalancesAtEnd: Record; + + /** + * Which grants were actually burnt down in the period and by what amount. + */ + @visibility(Lifecycle.Read) + grantUsages: GrantUsageRecord[]; +} + +/** + * Usage Record + */ +@friendlyName("GrantUsageRecord") +model GrantUsageRecord { + /** + * The id of the grant + */ + @example("01G65Z755AFWAKHE12NY0CQ9FH") + grantId: ULID; + + /** + * The usage in the period + */ + @example(100) + usage: float64; +} + +/** + * Reset parameters + */ +@friendlyName("ResetEntitlementUsageInput") +model ResetEntitlementUsageInput { + /** + * The time at which the reset takes effect, defaults to now. The reset cannot be in the future. The provided value is truncated to the minute due to how historical meter data is stored. + */ + effectiveAt?: DateTime; + + /** + * Determines whether the usage period anchor is retained or reset to the effectiveAt time. + * - If true, the usage period anchor is retained. + * - If false, the usage period anchor is reset to the effectiveAt time. + */ + retainAnchor?: boolean; + + /** + * Determines whether the overage is preserved or forgiven, overriding the entitlement's default behavior. + * - If true, the overage is preserved. + * - If false, the overage is forgiven. + */ + preserveOverage?: boolean; +} diff --git a/api/spec/packages/legacy/src/entitlements/v2/customer.tsp b/api/spec/packages/legacy/src/entitlements/v2/customer.tsp new file mode 100644 index 0000000000000000000000000000000000000000..e0809f468c32e1a334182bb6b7ea5b3e0bfd4a70 --- /dev/null +++ b/api/spec/packages/legacy/src/entitlements/v2/customer.tsp @@ -0,0 +1,283 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; +import ".."; +import "../.."; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +@route("/api/v2/customers/{customerIdOrKey}/entitlements") +@tag("Entitlements") +@friendlyName("CustomerEntitlementsV2") +interface CustomerEntitlementsV2Endpoints { + /** + * OpenMeter has three types of entitlements: metered, boolean, and static. The type property determines the type of entitlement. The underlying feature has to be compatible with the entitlement type specified in the request (e.g., a metered entitlement needs a feature associated with a meter). + * + * - Boolean entitlements define static feature access, e.g. "Can use SSO authentication". + * - Static entitlements let you pass along a configuration while granting access, e.g. "Using this feature with X Y settings" (passed in the config). + * - Metered entitlements have many use cases, from setting up usage-based access to implementing complex credit systems. Example: The customer can use 10000 AI tokens during the usage period of the entitlement. + * + * A given customer can only have one active (non-deleted) entitlement per featureKey. If you try to create a new entitlement for a featureKey that already has an active entitlement, the request will fail with a 409 error. + * + * Once an entitlement is created you cannot modify it, only delete it. + */ + @tag("Customers") + @post + @summary("Create a customer entitlement") + @operationId("createCustomerEntitlementV2") + post( + @path customerIdOrKey: ULIDOrExternalKey, + @body entitlement: EntitlementV2CreateInputs, + ): + | { + @statusCode _: 201; + @body body: EntitlementV2; + } + | CommonErrors + | ConflictError; + + /** + * List all entitlements for a customer. For checking entitlement access, use the /value endpoint instead. + */ + @get + @operationId("listCustomerEntitlementsV2") + @summary("List customer entitlements") + list( + @path customerIdOrKey: ULIDOrExternalKey, + @query includeDeleted?: boolean = false, + ...QueryPagination, + ...QueryOrdering, + ): PaginatedResponse | CommonErrors; + + /** + * Get entitlement by feature key. For checking entitlement access, use the /value endpoint instead. + * If featureKey is used, the entitlement is resolved for the current timestamp. + */ + @get + @operationId("getCustomerEntitlementV2") + @summary("Get customer entitlement") + @route("/{entitlementIdOrFeatureKey}") + get( + @path customerIdOrKey: ULIDOrExternalKey, + @path entitlementIdOrFeatureKey: ULIDOrKey, + ): EntitlementV2 | CommonErrors | NotFoundError; + + /** + * Deleting an entitlement revokes access to the associated feature. As a single customer can only have one entitlement per featureKey, when "migrating" features you have to delete the old entitlements as well. + * As access and status checks can be historical queries, deleting an entitlement populates the deletedAt timestamp. When queried for a time before that, the entitlement is still considered active, you cannot have retroactive changes to access, which is important for, among other things, auditing. + */ + @delete + @operationId("deleteCustomerEntitlementV2") + @summary("Delete customer entitlement") + @route("/{entitlementIdOrFeatureKey}") + delete( + @path customerIdOrKey: ULIDOrExternalKey, + @path entitlementIdOrFeatureKey: ULIDOrKey, + ): + | { + @statusCode _: 204; + } + | CommonErrors + | NotFoundError; + + /** + * Overriding an entitlement creates a new entitlement from the provided inputs and soft deletes the previous entitlement for the provided customer-feature pair. If the previous entitlement is already deleted or otherwise doesnt exist, the override will fail. + * + * This endpoint is useful for upgrades, downgrades, or other changes to entitlements that require a new entitlement to be created with zero downtime. + */ + @put + @operationId("overrideCustomerEntitlementV2") + @route("/{entitlementIdOrFeatureKey}/override") + @summary("Override customer entitlement") + override( + @path customerIdOrKey: ULIDOrExternalKey, + @path entitlementIdOrFeatureKey: ULIDOrExternalKey, + @body entitlement: EntitlementV2CreateInputs, + ): + | { + @statusCode _: 201; + @body body: EntitlementV2; + } + | CommonErrors + | ConflictError + | NotFoundError; +} + +@route("/api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}") +@tag("Entitlements") +@tag("Customers") +@friendlyName("CustomerEntitlementV2") +interface CustomerEntitlementV2Endpoints { + /** + * List all grants issued for an entitlement. The entitlement can be defined either by its id or featureKey. + */ + @get + @operationId("listCustomerEntitlementGrantsV2") + @route("/grants") + @summary("List customer entitlement grants") + getGrants( + @path customerIdOrKey: ULIDOrExternalKey, + @path entitlementIdOrFeatureKey: ULIDOrKey, + @query includeDeleted?: boolean = false, + ...QueryPagination, + ...QueryLimitOffset, + ...QueryOrdering, + ): PaginatedResponse | CommonErrors; + + /** + * Grants define a behavior of granting usage for a metered entitlement. They can have complicated recurrence and rollover rules, thanks to which you can define a wide range of access patterns with a single grant, in most cases you don't have to periodically create new grants. You can only issue grants for active metered entitlements. + * + * A grant defines a given amount of usage that can be consumed for the entitlement. The grant is in effect between its effective date and its expiration date. Specifying both is mandatory for new grants. + * + * Grants have a priority setting that determines their order of use. Lower numbers have higher priority, with 0 being the highest priority. + * + * Grants can have a recurrence setting intended to automate the manual reissuing of grants. For example, a daily recurrence is equal to reissuing that same grant every day (ignoring rollover settings). + * + * Rollover settings define what happens to the remaining balance of a grant at a reset. Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + * + * Grants cannot be changed once created, only deleted. This is to ensure that balance is deterministic regardless of when it is queried. + */ + @post + @operationId("createCustomerEntitlementGrantV2") + @route("/grants") + @summary("Create customer entitlement grant") + createCustomerEntitlementGrant( + @path customerIdOrKey: ULIDOrExternalKey, + @path entitlementIdOrFeatureKey: ULIDOrKey, + @body grant: GrantCreateInputV2, + ): + | { + @statusCode _: 201; + @body body: GrantV2; + } + | CommonErrors + | ConflictError; + + /** + * Checks customer access to a given feature (by key). All entitlement types share the hasAccess property in their value response, but multiple other properties are returned based on the entitlement type. + */ + @get + @operationId("getCustomerEntitlementValueV2") + @route("/value") + @summary("Get customer entitlement value") + getCustomerEntitlementValue( + @path customerIdOrKey: ULIDOrExternalKey, + @path entitlementIdOrFeatureKey: ULIDOrKey, + @query(#{ explode: true }) time?: DateTime, + ): EntitlementValueV2 | CommonErrors | NotFoundError; + + /** + * Returns historical balance and usage data for the entitlement. The queried history can span accross multiple reset events. + * + * BurndownHistory returns a continous history of segments, where the segments are seperated by events that changed either the grant burndown priority or the usage period. + * + * WindowedHistory returns windowed usage data for the period enriched with balance information and the list of grants that were being burnt down in that window. + */ + @get + @operationId("getCustomerEntitlementHistoryV2") + @route("/history") + @summary("Get customer entitlement history") + getCustomerEntitlementHistory( + @path customerIdOrKey: ULIDOrExternalKey, + @path entitlementIdOrFeatureKey: ULIDOrKey, + + /** + * Start of time range to query entitlement: date-time in RFC 3339 format. Defaults to the last reset. Gets truncated to the granularity of the underlying meter. + */ + @query(#{ explode: true }) from?: DateTime, + + /** + * End of time range to query entitlement: date-time in RFC 3339 format. Defaults to now. + * If not now then gets truncated to the granularity of the underlying meter. + */ + @query(#{ explode: true }) to?: DateTime, + + /** + * Windowsize + */ + @query windowSize: WindowSize, + + /** + * The timezone used when calculating the windows. + */ + @query windowTimeZone?: string = "UTC", + ): WindowedBalanceHistory | CommonErrors | NotFoundError; + + /** + * Reset marks the start of a new usage period for the entitlement and initiates grant rollover. At the start of a period usage is zerod out and grants are rolled over based on their rollover settings. It would typically be synced with the customers billing period to enforce usage based on their subscription. + * + * Usage is automatically reset for metered entitlements based on their usage period, but this endpoint allows to manually reset it at any time. When doing so the period anchor of the entitlement can be changed if needed. + */ + @post + @operationId("resetCustomerEntitlementUsageV2") + @route("/reset") + @summary("Reset customer entitlement") + resetCustomerEntitlement( + @path customerIdOrKey: ULIDOrExternalKey, + @path entitlementIdOrFeatureKey: ULIDOrKey, + @body reset: ResetEntitlementUsageInput, + ): + | { + @statusCode _: 204; + } + | CommonErrors + | NotFoundError; +} + +/** + * EntitlementValueV2 returns entitlement access state and value fields for customer-scoped V2 APIs. + */ +@friendlyName("EntitlementValueV2") +model EntitlementValueV2 { + /** + * Whether the subject has access to the feature. Shared accross all entitlement types. + */ + @visibility(Lifecycle.Read) + @example(true) + hasAccess: boolean; + + /** + * Only available for metered entitlements. Metered entitlements are built around a balance calculation where feature usage is deducted from the issued grants. Balance represents the remaining balance of the entitlement, it's value never turns negative. + */ + @example(100) + @visibility(Lifecycle.Read) + balance?: float64; + + /** + * Only available for metered entitlements. Returns the total feature usage in the current period. + */ + @example(50) + @visibility(Lifecycle.Read) + usage?: float64; + + /** + * Only available for metered entitlements. Overage represents the usage that wasn't covered by grants, e.g. if the subject had a total feature usage of 100 in the period but they were only granted 80, there would be 20 overage. + */ + @example(0) + @visibility(Lifecycle.Read) + overage?: float64; + + /** + * Only available for metered entitlements. The summed amount of all grant active at query time PLUS the used amount of since inactive grants. + */ + @example(100) + @visibility(Lifecycle.Read) + totalAvailableGrantAmount?: float64; + + /** + * Only available for static entitlements. The JSON parsable config of the entitlement. + */ + @example("{ key: \"value\" }") + @visibility(Lifecycle.Read) + config?: string; + + /** + * Only available for metered entitlements. The closing balance of each active grant at query time. + * The key is the grant ID and the value is the remaining balance. + */ + @visibility(Lifecycle.Read) + grantBalances?: Record; +} diff --git a/api/spec/packages/legacy/src/entitlements/v2/entitlements.tsp b/api/spec/packages/legacy/src/entitlements/v2/entitlements.tsp new file mode 100644 index 0000000000000000000000000000000000000000..8e796da6ce3aabeb24a63c195f4e96b76c0237b2 --- /dev/null +++ b/api/spec/packages/legacy/src/entitlements/v2/entitlements.tsp @@ -0,0 +1,237 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; +import ".."; +import "../.."; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +@route("/api/v2/entitlements") +@tag("Entitlements") +@friendlyName("EntitlementsV2") +interface EntitlementsV2Endpoints { + /** + * List all entitlements for all the customers and features. This endpoint is intended for administrative purposes only. + * To fetch the entitlements of a specific subject please use the /api/v2/customers/{customerIdOrKey}/entitlements endpoint. + */ + @get + @operationId("listEntitlementsV2") + @summary("List all entitlements") + list( + /** + * Filtering by multiple features. + * + * Usage: `?feature=feature-1&feature=feature-2` + */ + @query(#{ explode: true }) + feature?: string[], + + /** + * Filtering by multiple customers. + * + * Usage: `?customerKeys=customer-1&customerKeys=customer-3` + */ + @query(#{ explode: true }) + customerKeys?: string[], + + /** + * Filtering by multiple customers. + * + * Usage: `?customerIds=01K4WAQ0J99ZZ0MD75HXR112H8&customerIds=01K4WAQ0J99ZZ0MD75HXR112H9` + */ + @query(#{ explode: true }) + customerIds?: string[], + + /** + * Filtering by multiple entitlement types. + * + * Usage: `?entitlementType=metered&entitlementType=boolean` + */ + @query(#{ explode: true }) + entitlementType?: EntitlementType[], + + /** + * Exclude inactive entitlements in the response (those scheduled for later or earlier) + */ + @query + excludeInactive?: boolean = false, + + ...QueryPagination, + ...QueryLimitOffset, + ...QueryOrdering, + ): PaginatedResponse | CommonErrors; + + /** + * Get entitlement by ID. + */ + @get + @operationId("getEntitlementByIdV2") + @summary("Get entitlement by ID") + get( + @path + entitlementId: ULID, + ): EntitlementV2 | NotFoundError | CommonErrors; +} + +/** + * Entitlement templates are used to define the entitlements of a plan. + * Features are omitted from the entitlement template, as they are defined in the rate card. + */ +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +@friendlyName("EntitlementV2") +union EntitlementV2 { + metered: EntitlementMeteredV2, + static: EntitlementStaticV2, + boolean: EntitlementBooleanV2, +} + +/** + * Create inputs for entitlement + */ +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +@friendlyName("EntitlementV2CreateInputs") +union EntitlementV2CreateInputs { + metered: EntitlementMeteredV2CreateInputs, + static: EntitlementStaticCreateInputs, + boolean: EntitlementBooleanCreateInputs, +} + +/** + * Customer fields for entitlements + */ +@friendlyName("EntitlementCustomerFields") +model EntitlementCustomerFields { + /** + * The identifier key unique to the customer + */ + @example("customer-1") + customerKey?: string; + + /** + * The identifier unique to the customer + */ + @example("01ARZ3NDEKTSV4RRFFQ69G5FAV") + customerId: ULID; +} + +/** + * Issue after reset + */ +@friendlyName("IssueAfterReset") +model IssueAfterReset { + /** + * The initial grant amount + */ + @summary("Initial grant amount") + @minValue(0) + amount: float64; + + /** + * The priority of the issue after reset + */ + @summary("Issue grant after reset priority") + @minValue(1) + @maxValue(255) + priority?: uint8 = 1; +} + +/** + * Create inputs for metered entitlement + */ +@friendlyName("EntitlementMeteredV2CreateInputs") +model EntitlementMeteredV2CreateInputs { + ...OmitProperties< + EntitlementMeteredCreateInputs, + "isUnlimited" | "issueAfterReset" | "issueAfterResetPriority" + >; + + /** + * You can grant usage automatically alongside the entitlement, the example scenario would be creating a starting balance. + * If an amount is specified here, a grant will be created alongside the entitlement with the specified amount. + * That grant will have it's rollover settings configured in a way that after each reset operation, the balance will return the original amount specified here. + * Manually creating such a grant would mean having the "amount", "minRolloverAmount", and "maxRolloverAmount" fields all be the same. + */ + #deprecated "Use issue.Amount instead, will be removed in next major version." + @minValue(0) + @summary("Initial grant amount") + issueAfterReset?: float64; + + /** + * Defines the grant priority for the default grant. + */ + #deprecated "Use issue.Priority instead, will be removed in next major version." + @minValue(1) + @maxValue(255) + @summary("Issue grant after reset priority") + issueAfterResetPriority?: uint8 = 1; + + /** + * Issue after reset + */ + @summary("Issue after reset") + issue?: IssueAfterReset; + + /** + * Grants + */ + @summary("Grants") + grants?: GrantCreateInputV2[]; +} + +/** + * Metered entitlements are useful for many different use cases, from setting up usage based access to implementing complex credit systems. + * Access is determined based on feature usage using a balance calculation (the "usage allowance" provided by the issued grants is "burnt down" by the usage). + */ +@friendlyName("EntitlementMeteredV2") +model EntitlementMeteredV2 { + type: EntitlementType.metered; + ...OmitProperties< + EntitlementMeteredV2CreateInputs, + + | "type" + | "measureUsageFrom" + | "metadata" + | "usagePeriod" + | "featureKey" + | "featureId" + | "currentUsagePeriod" + | "grants" + >; + ...OmitProperties< + EntitlementSharedFields, + "type" | "currentUsagePeriod" | "usagePeriod" | "subjectKey" + >; + ...EntitlementMeteredCalculatedFields; + ...EntitlementCustomerFields; +} + +/** + * Entitlement template of a boolean entitlement. + */ +@friendlyName("EntitlementBooleanV2") +model EntitlementBooleanV2 { + type: EntitlementType.boolean; + ...OmitProperties< + EntitlementBooleanCreateInputs, + "type" | "metadata" | "usagePeriod" | "featureKey" | "featureId" + >; + ...OmitProperties; + ...EntitlementCustomerFields; +} + +/** + * A static entitlement. + */ +@friendlyName("EntitlementStaticV2") +model EntitlementStaticV2 { + type: EntitlementType.static; + ...OmitProperties< + EntitlementStaticCreateInputs, + "type" | "metadata" | "usagePeriod" | "featureKey" | "featureId" + >; + ...OmitProperties; + ...EntitlementCustomerFields; +} diff --git a/api/spec/packages/legacy/src/entitlements/v2/grant.tsp b/api/spec/packages/legacy/src/entitlements/v2/grant.tsp new file mode 100644 index 0000000000000000000000000000000000000000..12c39c28596be530b9b1131ce8f0eb659fddf910 --- /dev/null +++ b/api/spec/packages/legacy/src/entitlements/v2/grant.tsp @@ -0,0 +1,80 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; +import ".."; +import "../.."; + +namespace OpenMeter; + +/** + * The grant. + */ +@friendlyName("EntitlementGrantV2") +model GrantV2 { + ...ResourceTimestamps; + ...OmitProperties; + + /** + * Readonly unique ULID identifier. + */ + @example("01ARZ3NDEKTSV4RRFFQ69G5FAV") + @visibility(Lifecycle.Read) + id: ULID; + + /** + * The unique entitlement ULID that the grant is associated with. + */ + @example("01ARZ3NDEKTSV4RRFFQ69G5FAV") + @visibility(Lifecycle.Read) + entitlementId: string; + + /** + * The next time the grant will recurr. + */ + @example(DateTime.fromISO("2023-01-01T01:01:01.001Z")) + nextRecurrence?: DateTime; + + /** + * The time the grant expires. + */ + @example(DateTime.fromISO("2023-01-01T01:01:01.001Z")) + @visibility(Lifecycle.Read) + expiresAt?: DateTime; + + /** + * The time the grant was voided. + */ + @example(DateTime.fromISO("2023-01-01T01:01:01.001Z")) + voidedAt?: DateTime; + + /** + * The recurrence period of the grant. + */ + recurrence?: RecurringPeriod; +} + +/** + * The grant creation input. + */ +@friendlyName("EntitlementGrantCreateInputV2") +model GrantCreateInputV2 { + ...OmitProperties; + + /** + * Grants are rolled over at reset, after which they can have a different balance compared to what they had before the reset. The default value equals grant amount. + * Balance after the reset is calculated as: Balance_After_Reset = MIN(MaxRolloverAmount, MAX(Balance_Before_Reset, MinRolloverAmount)) + */ + @example(100.0) + maxRolloverAmount?: float64; + + /** + * The grant expiration definition. If no expiration is provided, the grant can be active indefinitely. + */ + expiration?: ExpirationPeriod; + + /** + * Grant annotations + */ + @example(#{ internal_reference: "internal_reference" }) + annotations?: Annotations; +} diff --git a/api/spec/packages/legacy/src/entitlements/v2/grants.tsp b/api/spec/packages/legacy/src/entitlements/v2/grants.tsp new file mode 100644 index 0000000000000000000000000000000000000000..e15a9f4d7d9012c900cc0d25e8a684dc9e26359f --- /dev/null +++ b/api/spec/packages/legacy/src/entitlements/v2/grants.tsp @@ -0,0 +1,50 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; +import ".."; +import "../.."; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +@route("/api/v2/grants") +@tag("Entitlements") +@friendlyName("GrantsV2") +interface GrantsV2Endpoints { + /** + * List all grants for all the customers and entitlements. This endpoint is intended for administrative purposes only. + * To fetch the grants of a specific entitlement please use the /api/v2/customers/{customerIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants endpoint. + * If page is provided that takes precedence and the paginated response is returned. + */ + @get + @operationId("listGrantsV2") + @summary("List grants") + list( + /** + * Filtering by multiple features. + * + * Usage: `?feature=feature-1&feature=feature-2` + */ + @query(#{ explode: true }) + feature?: string[], + + /** + * Filtering by multiple customers (either by ID or key). + * + * Usage: `?customer=customer-1&customer=customer-2` + */ + @query(#{ explode: true }) + customer?: ULIDOrExternalKey[], + + /** + * Include deleted + */ + @query includeDeleted?: boolean = false, + + ...QueryPagination, + ...QueryLimitOffset, + ...QueryOrdering, + ): PaginatedResponse | CommonErrors; +} diff --git a/api/spec/packages/legacy/src/entitlements/v2/main.tsp b/api/spec/packages/legacy/src/entitlements/v2/main.tsp new file mode 100644 index 0000000000000000000000000000000000000000..a4f5bca4af3412b6da89caf41431235299ec3919 --- /dev/null +++ b/api/spec/packages/legacy/src/entitlements/v2/main.tsp @@ -0,0 +1,22 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "@typespec/versioning"; + +import ".."; + +// Package Contents +import "./entitlements.tsp"; +import "./customer.tsp"; +import "./grants.tsp"; +import "./grant.tsp"; + +using TypeSpec.Http; +using TypeSpec.Rest; +using TypeSpec.OpenAPI; +using TypeSpec.Versioning; + +namespace OpenMeter; + +// NOTE: Public types, operationIDs and friendlyNames of versioned packages should will use the version suffix. diff --git a/api/spec/packages/legacy/src/errors.tsp b/api/spec/packages/legacy/src/errors.tsp new file mode 100644 index 0000000000000000000000000000000000000000..f169a054d0cfc68ef9effc01a04252bc54f3e75d --- /dev/null +++ b/api/spec/packages/legacy/src/errors.tsp @@ -0,0 +1,257 @@ +import "@typespec/http"; +import "@typespec/openapi3"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * A Problem Details object (RFC 7807). + * Additional properties specific to the problem type may be present. + */ +@error +@extension("x-go-type", "models.StatusProblem") +@extension( + "x-go-type-import", + #{ path: "github.com/openmeterio/openmeter/pkg/models" } +) +@friendlyName("UnexpectedProblemResponse") +model Error { + @header contentType: "application/problem+json"; + + /** + * Type contains a URI that identifies the problem type. + */ + @example("about:blank") + type: url = "about:blank"; + + /** + * A a short, human-readable summary of the problem type. + */ + @example("Bad Request") + title: string; + + /** + * The HTTP status code generated by the origin server for this occurrence of the problem. + */ + @minValue(400) + @maxValue(599) + @example(400) + status?: int16; + + /** + * A human-readable explanation specific to this occurrence of the problem. + */ + @example("The request body must be a JSON object.") + detail: string; + + /** + * A URI reference that identifies the specific occurrence of the problem. + */ + @example("urn:request:local/JMOlctsKV8-000001") + instance: url; + + /** + * Additional properties specific to the problem type may be present. + */ + @example(#{ + validationErrors: #[ + #{ code: "validation_error", message: "Validation error" } + ], + otherAttribute: "otherValue", + }) + extensions?: Record; + + /** + * Additional properties specific to the problem type may be present. + */ + ...Record; +} + +alias CommonErrorsWithValidation = + | ValidationErrorResponse + | UnauthorizedError + | ForbiddenError + | InternalServerErrorError + | ServiceUnavailableError + | PreconditionFailedError + | Error; + +alias CommonErrors = + | BadRequestError + | UnauthorizedError + | ForbiddenError + | InternalServerErrorError + | ServiceUnavailableError + | PreconditionFailedError + | Error; + +/** + * The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). + */ +@error +@friendlyName("BadRequestProblemResponse") +model BadRequestError extends Error { + @statusCode _: 400; +} + +/** + * A BadRequestError with a validationErrors extension. + */ +@error +@friendlyName("ValidationErrorProblemResponse") +model ValidationErrorResponse { + ...OmitProperties; + + /** + * Validation issues. + */ + @visibility(Lifecycle.Read) + extensions?: { + validationErrors?: ValidationError[]; + }; +} + +/** + * Validation errors providing detailed description of the issue. + */ +@friendlyName("ValidationError") +model ValidationError { + /** + * The path to the field. + */ + @visibility(Lifecycle.Read) + @example("addons/pro/ratecards/token/featureKey") + field: string; + + /** + * The machine readable description of the error. + */ + @visibility(Lifecycle.Read) + @example("invalid_feature_key") + code: string; + + /** + * The human readable description of the error. + */ + @visibility(Lifecycle.Read) + @example("not found feature by key") + message: string; + + /** + * Additional attributes. + */ + @visibility(Lifecycle.Read) + attributes?: Annotations; +} + +/** + * Generic ErrorExtension as part of HTTPProblem.Extensions.[StatusCode] + */ +@friendlyName("ErrorExtension") +model ErrorExtension { + /** + * The path to the field. + */ + @visibility(Lifecycle.Read) + @example("addons/pro/ratecards/token/featureKey") + field: string; + + /** + * The machine readable description of the error. + */ + @visibility(Lifecycle.Read) + @example("invalid_feature_key") + code: string; + + /** + * The human readable description of the error. + */ + @visibility(Lifecycle.Read) + @example("not found feature by key") + message: string; + + ...Record; +} + +/** + * The request has not been applied because it lacks valid authentication credentials for the target resource. + */ +@error +@friendlyName("UnauthorizedProblemResponse") +model UnauthorizedError extends Error { + @statusCode _: 401; +} + +/** + * The server understood the request but refuses to authorize it. + */ +@error +@friendlyName("ForbiddenProblemResponse") +model ForbiddenError extends Error { + @statusCode _: 403; +} + +/** + * The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. + */ +@error +@friendlyName("NotFoundProblemResponse") +model NotFoundError extends Error { + @statusCode _: 404; +} + +/** + * The request could not be completed due to a conflict with the current state of the target resource. + */ +@error +@friendlyName("ConflictProblemResponse") +model ConflictError extends Error { + @statusCode _: 409; +} + +/** + * One or more conditions given in the request header fields evaluated to false when tested on the server. + */ +@error +@friendlyName("PreconditionFailedProblemResponse") +model PreconditionFailedError extends Error { + @statusCode _: 412; +} + +/** + * The server encountered an unexpected condition that prevented it from fulfilling the request. + */ +@error +@friendlyName("InternalServerErrorProblemResponse") +model InternalServerErrorError extends Error { + @statusCode _: 500; +} + +/** + * The server does not support the functionality required to fulfill the request. + */ +@error +@friendlyName("NotImplementedProblemResponse") +model NotImplementedError extends Error { + @statusCode _: 501; +} + +/** + * The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. + */ +@error +@friendlyName("ServiceUnavailableProblemResponse") +model ServiceUnavailableError extends Error { + @statusCode _: 503; +} + +/** + * The server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request. + */ +@error +@friendlyName("GatewayTimeoutProblemResponse") +model GatewayTimeoutError extends Error { + @statusCode _: 504; +} diff --git a/api/spec/packages/legacy/src/events.tsp b/api/spec/packages/legacy/src/events.tsp new file mode 100644 index 0000000000000000000000000000000000000000..122c9aced5996f0c94a9966342b9289249862d52 --- /dev/null +++ b/api/spec/packages/legacy/src/events.tsp @@ -0,0 +1,336 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +@route("/api/v1/events") +@tag("Events") +@friendlyName("Events") +interface EventsEndpoints { + /** + * List ingested events within a time range. + * + * If the from query param is not provided it defaults to last 72 hours. + */ + @get + @operationId("listEvents") + @summary("List ingested events") + list( + /** + * Client ID + * Useful to track progress of a query. + */ + @query + @example("f74e58ed-94ce-4041-ae06-cf45420451a3") + @minLength(1) + @maxLength(36) + clientId?: string, + + /** + * Start date-time in RFC 3339 format. + * + * Inclusive. + */ + @query(#{ explode: true }) + @example(utcDateTime.fromISO("2023-01-01T00:00:00Z")) + ingestedAtFrom?: utcDateTime, + + /** + * End date-time in RFC 3339 format. + * + * Inclusive. + */ + @query(#{ explode: true }) + @example(utcDateTime.fromISO("2023-01-01T00:00:00Z")) + ingestedAtTo?: utcDateTime, + + /** + * The event ID. + * + * Accepts partial ID. + */ + @query + @example("my-event-id") + id?: string, + + /** + * The event subject. + * + * Accepts partial subject. + */ + @query + @example("customer-1") + subject?: string, + + /** + * The event customer ID. + */ + @query(#{ explode: true }) + @example(#["01HZXABCD3M6E7K8J9PQRS1TUV", "01HZXABCDE3M6E7K8J9PQRSTUV"]) + customerId?: ULID[], + + /** + * Start date-time in RFC 3339 format. + * + * Inclusive. + */ + @query(#{ explode: true }) + @example(utcDateTime.fromISO("2023-01-01T00:00:00Z")) + from?: utcDateTime, + + /** + * End date-time in RFC 3339 format. + * + * Inclusive. + */ + @query(#{ explode: true }) + @example(utcDateTime.fromISO("2023-01-01T00:00:00Z")) + to?: utcDateTime, + + /** + * Number of events to return. + */ + @query + @minValue(1) + @maxValue(100) + @example(100) + limit?: integer = 100, + ): IngestedEvent[] | CommonErrors; + + /** + * Ingests an event or batch of events following the CloudEvents specification. + */ + @post + @operationId("ingestEvents") + @summary("Ingest events") + @sharedRoute + ingestEvent( + @header contentType: "application/cloudevents+json", + @body body: Event, + ): + | { + @statusCode _: 204; + } + | CommonErrors; + + @post + @operationId("ingestEvents") + @summary("") + @sharedRoute + ingestEvents( + @header contentType: "application/cloudevents-batch+json", + @body body: Event[], + ): + | { + @statusCode _: 204; + } + | CommonErrors; + + @post + @operationId("ingestEvents") + @summary("") + @sharedRoute + ingestEventsJson( + @header contentType: "application/json", + @body body: IngestEventsBody, + ): + | { + @statusCode _: 204; + } + | CommonErrors; +} + +@route("/api/v2/events") +@tag("Events") +@friendlyName("EventsV2") +interface EventsV2Endpoints { + /** + * List ingested events with advanced filtering and cursor pagination. + */ + @list + @operationId("listEventsV2") + @summary("List ingested events") + list( + ...QueryCursorPagination, + + /** + * Client ID + * Useful to track progress of a query. + */ + @query + @example("f74e58ed-94ce-4041-ae06-cf45420451a3") + @minLength(1) + @maxLength(36) + clientId?: string, + + /** + * The filter for the events encoded as JSON string. + */ + @example(#{ + id: #{ $eq: "my-event-id" }, + source: #{ $eq: "my-event-source" }, + subject: #{ $eq: "my-event-subject" }, + type: #{ $eq: "my-event-type" }, + time: #{ + $and: #[ + #{ $gte: DateTime.fromISO("2025-01-01T00:00:00Z") }, + #{ $lte: DateTime.fromISO("2025-01-02T00:00:00Z") } + ], + }, + }) + @query + @encode("application/json") + filter?: { + id?: FilterString; + source?: FilterString; + subject?: FilterString; + customerId?: FilterIDExact; + type?: FilterString; + time?: FilterTime; + ingestedAt?: FilterTime; + }, + ): CursorPaginatedResponse | CommonErrors; +} + +/** + * The body of the events request. + * Either a single event or a batch of events. + */ +@friendlyName("IngestEventsBody") +union IngestEventsBody { + @friendlyName("Event") + Event: Event, + + @friendlyName("Events") + Events: Event[], +} + +/** + * CloudEvents Specification JSON Schema + * + * Optional properties are nullable according to the CloudEvents specification: + * OPTIONAL not omitted attributes MAY be represented as a null JSON value. + */ +@extension("x-go-type", "event.Event") +@extension( + "x-go-type-import", + #{ path: "github.com/cloudevents/sdk-go/v2/event" } +) +@friendlyName("Event") +@example(#{ + id: "5c10fade-1c9e-4d6c-8275-c52c36731d3c", + source: "service-name", + specversion: "1.0", + type: "prompt", + subject: "customer-id", + time: DateTime.fromISO("2023-01-01T01:01:01.001Z"), +}) +model Event { + /** + * Identifies the event. + */ + @minLength(1) + @example("5c10fade-1c9e-4d6c-8275-c52c36731d3c") + id: string; + + /** + * Identifies the context in which an event happened. + */ + @minLength(1) + @format("uri-reference") + @example("service-name") + source: string; + + /** + * The version of the CloudEvents specification which the event uses. + */ + @minLength(1) + @example("1.0") + specversion: string = "1.0"; + + /** + * Contains a value describing the type of event related to the originating occurrence. + */ + @minLength(1) + @example("com.example.someevent") + type: string; + + /** + * Content type of the CloudEvents data value. Only the value "application/json" is allowed over HTTP. + */ + @example("application/json") + datacontenttype?: "application/json" | null; + + /** + * Identifies the schema that data adheres to. + */ + @minLength(1) + dataschema?: url | null; + + /** + * Describes the subject of the event in the context of the event producer (identified by source). + */ + @minLength(1) + @example("customer-id") + subject: string; + + /** + * Timestamp of when the occurrence happened. Must adhere to RFC 3339. + */ + @example(DateTime.fromISO("2023-01-01T01:01:01.001Z")) + time?: DateTime | null; + + /** + * The event payload. + * Optional, if present it must be a JSON object. + */ + @oneOf + data?: Record | null; +} + +/** + * An ingested event with optional validation error. + */ +@friendlyName("IngestedEvent") +@example(#{ + event: #{ + id: "5c10fade-1c9e-4d6c-8275-c52c36731d3c", + source: "service-name", + specversion: "1.0", + type: "prompt", + subject: "customer-id", + time: DateTime.fromISO("2023-01-01T01:01:01.001Z"), + }, + ingestedAt: DateTime.fromISO("2023-01-01T01:01:01.001Z"), + storedAt: DateTime.fromISO("2023-01-01T01:01:02.001Z"), +}) +model IngestedEvent { + /** + * The original event ingested. + */ + event: Event; + + /** + * The customer ID if the event is associated with a customer. + */ + customerId?: ULID; + + /** + * The validation error if the event failed validation. + */ + validationError?: string; + + /** + * The date and time the event was ingested. + */ + ingestedAt: DateTime; + + /** + * The date and time the event was stored. + */ + storedAt: DateTime; +} diff --git a/api/spec/packages/legacy/src/filter.tsp b/api/spec/packages/legacy/src/filter.tsp new file mode 100644 index 0000000000000000000000000000000000000000..7bd64d049699b761b95a057017d24e7e42280339 --- /dev/null +++ b/api/spec/packages/legacy/src/filter.tsp @@ -0,0 +1,303 @@ +import "@typespec/openapi3"; + +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * A filter for a string field. + */ +@friendlyName("FilterString") +model FilterString { + /** + * The field must be equal to the provided value. + */ + @extension("x-omitempty", true) + $eq?: string | null; + + /** + * The field must not be equal to the provided value. + */ + @extension("x-omitempty", true) + $ne?: string | null; + + /** + * The field must be in the provided list of values. + */ + // Not supported for nullable types + // @minItems(1) + // @maxItems(100) + @extension("x-omitempty", true) + $in?: string[] | null; + + /** + * The field must not be in the provided list of values. + */ + // Not supported for nullable types + // @minItems(1) + // @maxItems(100) + @extension("x-omitempty", true) + $nin?: string[] | null; + + /** + * The field must match the provided value. + */ + @extension("x-omitempty", true) + $like?: string | null; + + /** + * The field must not match the provided value. + */ + @extension("x-omitempty", true) + $nlike?: string | null; + + /** + * The field must match the provided value, ignoring case. + */ + @extension("x-omitempty", true) + $ilike?: string | null; + + /** + * The field must not match the provided value, ignoring case. + */ + @extension("x-omitempty", true) + $nilike?: string | null; + + /** + * The field must be greater than the provided value. + */ + @extension("x-omitempty", true) + $gt?: string | null; + + /** + * The field must be greater than or equal to the provided value. + */ + @extension("x-omitempty", true) + $gte?: string | null; + + /** + * The field must be less than the provided value. + */ + @extension("x-omitempty", true) + $lt?: string | null; + + /** + * The field must be less than or equal to the provided value. + */ + @extension("x-omitempty", true) + $lte?: string | null; + + /** + * Provide a list of filters to be combined with a logical AND. + */ + // Not supported for nullable types + // @minItems(1) + // @maxItems(10) + @extension("x-omitempty", true) + $and?: FilterString[] | null; + + /** + * Provide a list of filters to be combined with a logical OR. + */ + // Not supported for nullable types + // @minItems(1) + // @maxItems(10) + @extension("x-omitempty", true) + $or?: FilterString[] | null; +} + +/** + * A filter for a ID (ULID) field allowing only equality or inclusion. + */ +#suppress "@openmeter/api-spec-legacy/casing" "ID" +@friendlyName("FilterIDExact") +model FilterIDExact { + /** + * The field must be in the provided list of values. + */ + // Not supported for nullable types + // @minItems(1) + // @maxItems(100) + @extension("x-omitempty", true) + $in?: ULID[] | null; +} + +/** + * A filter for an integer field. + */ +@friendlyName("FilterInteger") +model FilterInteger { + /** + * The field must be equal to the provided value. + */ + @extension("x-omitempty", true) + $eq?: integer | null; + + /** + * The field must not be equal to the provided value. + */ + @extension("x-omitempty", true) + $ne?: integer | null; + + /** + * The field must be greater than the provided value. + */ + @extension("x-omitempty", true) + $gt?: integer | null; + + /** + * The field must be greater than or equal to the provided value. + */ + @extension("x-omitempty", true) + $gte?: integer | null; + + /** + * The field must be less than the provided value. + */ + @extension("x-omitempty", true) + $lt?: integer | null; + + /** + * The field must be less than or equal to the provided value. + */ + @extension("x-omitempty", true) + $lte?: integer | null; + + /** + * Provide a list of filters to be combined with a logical AND. + */ + // Not supported for nullable types + // @minItems(1) + // @maxItems(10) + @extension("x-omitempty", true) + $and?: FilterInteger[] | null; + + /** + * Provide a list of filters to be combined with a logical OR. + */ + // Not supported for nullable types + // @minItems(1) + // @maxItems(10) + @extension("x-omitempty", true) + $or?: FilterInteger[] | null; +} + +/** + * A filter for a float field. + */ +@friendlyName("FilterFloat") +model FilterFloat { + /** + * The field must be equal to the provided value. + */ + @extension("x-omitempty", true) + $eq?: float64 | null; + + /** + * The field must not be equal to the provided value. + */ + @extension("x-omitempty", true) + $ne?: float64 | null; + + /** + * The field must be greater than the provided value. + */ + @extension("x-omitempty", true) + $gt?: float64 | null; + + /** + * The field must be greater than or equal to the provided value. + */ + @extension("x-omitempty", true) + $gte?: float64 | null; + + /** + * The field must be less than the provided value. + */ + @extension("x-omitempty", true) + $lt?: float64 | null; + + /** + * The field must be less than or equal to the provided value. + */ + @extension("x-omitempty", true) + $lte?: float64 | null; + + /** + * Provide a list of filters to be combined with a logical AND. + */ + // Not supported for nullable types + // @minItems(1) + // @maxItems(10) + @extension("x-omitempty", true) + $and?: FilterFloat[] | null; + + /** + * Provide a list of filters to be combined with a logical OR. + */ + // Not supported for nullable types + // @minItems(1) + // @maxItems(10) + @extension("x-omitempty", true) + $or?: FilterFloat[] | null; +} + +/** + * A filter for a boolean field. + */ +@friendlyName("FilterBoolean") +model FilterBoolean { + /** + * The field must be equal to the provided value. + */ + @extension("x-omitempty", true) + $eq?: boolean | null; +} + +/** + * A filter for a time field. + */ +@friendlyName("FilterTime") +model FilterTime { + /** + * The field must be greater than the provided value. + */ + @extension("x-omitempty", true) + $gt?: utcDateTime | null; + + /** + * The field must be greater than or equal to the provided value. + */ + @extension("x-omitempty", true) + $gte?: utcDateTime | null; + + /** + * The field must be less than the provided value. + */ + @extension("x-omitempty", true) + $lt?: utcDateTime | null; + + /** + * The field must be less than or equal to the provided value. + */ + @extension("x-omitempty", true) + $lte?: utcDateTime | null; + + /** + * Provide a list of filters to be combined with a logical AND. + */ + // Not supported for nullable types + // @minItems(1) + // @maxItems(10) + @extension("x-omitempty", true) + $and?: FilterTime[] | null; + + /** + * Provide a list of filters to be combined with a logical OR. + */ + // Not supported for nullable types + // @minItems(1) + // @maxItems(10) + @extension("x-omitempty", true) + $or?: FilterTime[] | null; +} diff --git a/api/spec/packages/legacy/src/info/currencies.tsp b/api/spec/packages/legacy/src/info/currencies.tsp new file mode 100644 index 0000000000000000000000000000000000000000..4f0faff1bdb974f6da53762eef812d1dc7a9bbbc --- /dev/null +++ b/api/spec/packages/legacy/src/info/currencies.tsp @@ -0,0 +1,27 @@ +namespace OpenMeter; + +/** + * Currency describes a currency supported by OpenMeter. + */ +@friendlyName("Currency") +model Currency { + /** + * The currency ISO code. + */ + code: CurrencyCode; + + /** + * The currency name. + */ + name: string; + + /** + * The currency symbol. + */ + symbol: string; + + /** + * Subunit of the currency. + */ + subunits: uint32; +} diff --git a/api/spec/packages/legacy/src/info/main.tsp b/api/spec/packages/legacy/src/info/main.tsp new file mode 100644 index 0000000000000000000000000000000000000000..b1e8b82833207021d1d52616b16f0b59893832fd --- /dev/null +++ b/api/spec/packages/legacy/src/info/main.tsp @@ -0,0 +1,12 @@ +import "@typespec/http"; +import "@typespec/openapi"; +import "@typespec/openapi3"; + +import ".."; + +// Package Contents +import "./currencies.tsp"; +import "./progress.tsp"; +import "./routes.tsp"; + +namespace OpenMeter; diff --git a/api/spec/packages/legacy/src/info/progress.tsp b/api/spec/packages/legacy/src/info/progress.tsp new file mode 100644 index 0000000000000000000000000000000000000000..a58a45c12da26d002922ec353f943ce78453e4f7 --- /dev/null +++ b/api/spec/packages/legacy/src/info/progress.tsp @@ -0,0 +1,44 @@ +namespace OpenMeter; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +@route("/api/v1/info/progress") +@tag("Lookup Information") +@friendlyName("Progress") +interface ProgressEndpoints { + /** + * Get progress + */ + @get + @route("/{id}") + @operationId("getProgress") + @summary("Get progress") + getProgress(id: string): Progress | NotFoundError | CommonErrors; +} + +/** + * Progress describes a progress of a task. + */ +@friendlyName("Progress") +model Progress { + /** + * Success is the number of items that succeeded + */ + success: uint64; + + /** + * Failed is the number of items that failed + */ + failed: uint64; + + /** + * The total number of items to process + */ + total: uint64; + + /** + * The time the progress was last updated + */ + updatedAt: DateTime; +} diff --git a/api/spec/packages/legacy/src/info/routes.tsp b/api/spec/packages/legacy/src/info/routes.tsp new file mode 100644 index 0000000000000000000000000000000000000000..dd5c4495bd3991645b7251c80e9fb32a214bb932 --- /dev/null +++ b/api/spec/packages/legacy/src/info/routes.tsp @@ -0,0 +1,19 @@ +import "../rest.tsp"; + +namespace OpenMeter; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +@route("/api/v1/info/currencies") +@tag("Lookup Information") +@friendlyName("Currencies") +interface CurrenciesEndpoints { + /** + * List all supported currencies. + */ + @get + @operationId("listCurrencies") + @summary("List supported currencies") + listCurrencies(): Currency[] | CommonErrors; +} diff --git a/api/spec/packages/legacy/src/main.tsp b/api/spec/packages/legacy/src/main.tsp new file mode 100644 index 0000000000000000000000000000000000000000..df6d6c22b8523913764b11e2ea55bc4e07b204a6 --- /dev/null +++ b/api/spec/packages/legacy/src/main.tsp @@ -0,0 +1,118 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "@typespec/versioning"; + +import "./auth.tsp"; +import "./errors.tsp"; +import "./types.tsp"; +import "./filter.tsp"; + +import "./app"; +import "./query.tsp"; +import "./customer"; +import "./events.tsp"; +import "./meters.tsp"; +import "./portal.tsp"; +import "./subjects.tsp"; +import "./debug.tsp"; +import "./notification"; +import "./entitlements"; +import "./entitlements/v2"; +import "./billing"; +import "./productcatalog"; +import "./info"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +/** + * OpenMeter is a cloud native usage metering service. + * The OpenMeter API allows you to ingest events, query meter usage, and manage resources. + */ +@service(#{ title: "OpenMeter API" }) +@info(#{ + version: "1.0.0", + license: #{ + name: "Apache 2.0", + url: "http://www.apache.org/licenses/LICENSE-2.0.html", + }, +}) +@server("https://127.0.0.1", "Local") +// Tags will appear in alphabetical order in the API documentation +@tagMetadata( + "Apps", + #{ + description: "Manage integrations for extending OpenMeter's functionality. ", + } +) +@tagMetadata("App: Stripe", #{ description: "Support for Stripe billing." }) +@tagMetadata( + "App: Custom Invoicing", + #{ description: "Interface third party invoicing and payment systems." } +) +@tagMetadata( + "Billing", + #{ description: "Manage your billing profiles and invoices. " } +) +@tagMetadata( + "Customers", + #{ + description: "Manage customer subscription lifecycles and plan assignments. ", + } +) +@tagMetadata("Debug", #{ description: "Debugging and testing endpoints." }) +@tagMetadata( + "Entitlements", + #{ + description: "With Entitlements, you can define and enforce usage limits, implement quota-based pricing, and manage access to features in your application.", + } +) +@tagMetadata( + "Events", + #{ + description: "Events are used to track usage of your product or service. Events are processed asynchronously by the meters, so they may not be immediately available for querying.", + } +) +@tagMetadata( + "Lookup Information", + #{ description: "Lookup information for static data like currencies" } +) +@tagMetadata( + "Meters", + #{ + description: "Meters specify how to aggregate events for billing and analytics purposes. Meters can be configured with multiple aggregation methods and groupings. Multiple meters can be created for the same event type, enabling flexible metering scenarios.", + } +) +@tagMetadata( + "Notifications", + #{ + description: "Notifications provide automated triggers when specific entitlement balances and usage thresholds are reached, ensuring that your customers and sales teams are always informed. Notify customers and internal teams when specific conditions are met, like reaching 75%, 100%, and 150% of their monthly usage allowance. [Read more](https://openmeter.io/docs/guides/notifications/overview).", + } +) +@tagMetadata( + "Portal", + #{ + description: "With the Consumer Portal, you can build in-app user-facing dashboards where your users can track their usage in real-time. Subject scoped portal tokens can be generated on your behalf to allow restricted access to the OpenMeter API.", + } +) +@tagMetadata( + "Product Catalog", + #{ + description: "Configure and manage your product plans, pricing tiers, and subscription offerings. ", + } +) +@tagMetadata( + "Subjects", + #{ + description: "⚠️ __Deprecated__: Subjects as managable entities are being depracated, use customers with subject key usage attribution instead. \n\n Subjects are entities that consume resources you wish to meter. These can range from users, servers, and services to devices. The design of subjects is intentionally generic, enabling flexible application across various metering scenarios. Typically, a subject acts as a unique identifier within your system for a user or customer. Meters are aggregating events for each subject.", + } +) +@tagMetadata( + "Subscriptions", + #{ + description: "With Subscriptions, you can easily start, cancel, and manage customer subscriptions. For example, provisioning them on a specific plan or assigning custom rate cards.", + } +) +namespace OpenMeter; diff --git a/api/spec/packages/legacy/src/meters.tsp b/api/spec/packages/legacy/src/meters.tsp new file mode 100644 index 0000000000000000000000000000000000000000..449da5e46c9e5eff4a98312bdeacf39d174babfb --- /dev/null +++ b/api/spec/packages/legacy/src/meters.tsp @@ -0,0 +1,695 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +import "./types.tsp"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * Query params for listing meters. + */ +@friendlyName("queryMeterList") +model ListMetersParams { + ...QueryPagination; + + /** + * Order meters by. + * @TODO: set default value to MeterOrderBy.key + */ + ...QueryOrdering; + + /** + * Include deleted meters. + */ + @query + includeDeleted?: boolean = false; +} + +/** + * Order by options for meters. + */ +@friendlyName("MeterOrderBy") +enum MeterOrderBy { + Key: "key", + Name: "name", + Aggregation: "aggregation", + #suppress "@openmeter/api-spec-legacy/casing" "Use existing values" + CreatedAt: "createdAt", + #suppress "@openmeter/api-spec-legacy/casing" "Use existing values" + UpdatedAt: "updatedAt", +} + +@route("/api/v1/meters") +@tag("Meters") +@friendlyName("Meters") +interface MetersEndpoints { + /** + * List meters. + */ + @get + @operationId("listMeters") + @summary("List meters") + list(...ListMetersParams): Meter[] | CommonErrors; + + /** + * Get a meter by ID or slug. + */ + @get + @route("/{meterIdOrSlug}") + @operationId("getMeter") + @summary("Get meter") + get(@path meterIdOrSlug: MeterIdentifier): + | Meter + | NotFoundError + | CommonErrors; + + /** + * Create a meter. + */ + @post + @operationId("createMeter") + @summary("Create meter") + create( + @body + meter: MeterCreate, + ): + | { + @statusCode _: 201; + @body body: Meter; + } + | CommonErrors; + + /** + * Update a meter. + */ + @put + @route("/{meterIdOrSlug}") + @operationId("updateMeter") + @summary("Update meter") + update( + @path meterIdOrSlug: MeterIdentifier, + + @body + meter: MeterUpdate, + ): + | { + @body body: Meter; + } + | CommonErrors; + + /** + * Delete a meter. + */ + @delete + @route("/{meterIdOrSlug}") + @operationId("deleteMeter") + @summary("Delete meter") + delete(@path meterIdOrSlug: MeterIdentifier): void | CommonErrors; + + /** + * Query meter for usage. + */ + @get + @route("/{meterIdOrSlug}/query") + @operationId("queryMeter") + @summary("Query meter") + @sharedRoute + queryJson(@path meterIdOrSlug: MeterIdentifier, ...MeterQuery): + | { + @header contentType: "application/json"; + @body _: MeterQueryResult; + } + | NotFoundError + | CommonErrors; + + #suppress "@openmeter/api-spec-legacy/operation-summary" "Avoid duplicating the summary in OpenAPI yaml" + @get + @route("/{meterIdOrSlug}/query") + @operationId("queryMeter") + @sharedRoute + queryCsv(@path meterIdOrSlug: MeterIdentifier, ...MeterQuery): + | { + @header contentType: "text/csv"; + + @body + @example(""" + window_start,window_end,subject,model,type,value + 2023-01-01T00:00:00Z,2023-01-01T00:01:00Z,customer_1,gpt-4-turbo,input,12 + 2023-01-01T00:01:00Z,2023-01-02T00:02:00Z,customer_1,gpt-4-turbo,input,20 + 2023-01-01T00:02:00Z,2023-01-02T00:03:00Z,customer_2,gpt-4-turbo,output,4 + """) + _: string; + } + | NotFoundError + | CommonErrors; + + @post + @route("/{meterIdOrSlug}/query") + @operationId("queryMeterPost") + @summary("Query meter") + @sharedRoute + query( + @path meterIdOrSlug: MeterIdentifier, + @body request: MeterQueryRequest, + ): + | { + @header contentType: "application/json"; + @body _: MeterQueryResult; + } + | NotFoundError + | CommonErrors; + + #suppress "@openmeter/api-spec-legacy/operation-summary" "Avoid duplicating the summary in OpenAPI yaml" + @post + @route("/{meterIdOrSlug}/query") + @operationId("queryMeterPost") + @sharedRoute + queryCsvPost( + @path meterIdOrSlug: MeterIdentifier, + // @body request: MeterQueryRequest, + ): + | { + @header contentType: "text/csv"; + + @body + @example(""" + window_start,window_end,subject,model,type,value + 2023-01-01T00:00:00Z,2023-01-01T00:01:00Z,customer_1,gpt-4-turbo,input,12 + 2023-01-01T00:01:00Z,2023-01-02T00:02:00Z,customer_1,gpt-4-turbo,input,20 + 2023-01-01T00:02:00Z,2023-01-02T00:03:00Z,customer_2,gpt-4-turbo,output,4 + """) + _: string; + } + | NotFoundError + | CommonErrors; + + /** + * List subjects for a meter. + */ + @get + @route("/{meterIdOrSlug}/subjects") + @operationId("listMeterSubjects") + @summary("List meter subjects") + listSubjects( + @path meterIdOrSlug: MeterIdentifier, + + /** + * Start date-time in RFC 3339 format. + * + * Inclusive. Defaults to the beginning of time. + * + * For example: ?from=2025-01-01T00%3A00%3A00.000Z + */ + @query(#{ explode: true }) + from?: DateTime, + + /** + * End date-time in RFC 3339 format. + * + * Inclusive. + * + * For example: ?to=2025-02-01T00%3A00%3A00.000Z + */ + @query(#{ explode: true }) + to?: DateTime, + ): + | { + @body + @example(#["customer_1", "customer_2"]) + _: string[]; + } + | CommonErrors; + + /** + * List meter group by values. + */ + @get + @route("/{meterIdOrSlug}/group-by/{groupByKey}/values") + @operationId("listMeterGroupByValues") + @summary("List meter group by values") + listGroupByValues( + @path meterIdOrSlug: MeterIdentifier, + @path groupByKey: string, + + /** + * Start date-time in RFC 3339 format. + * + * Inclusive. Defaults to 24 hours ago. + * + * For example: ?from=2025-01-01T00%3A00%3A00.000Z + */ + @query(#{ explode: true }) + from?: DateTime, + + /** + * End date-time in RFC 3339 format. + * + * Inclusive. + * + * For example: ?to=2025-02-01T00%3A00%3A00.000Z + */ + @query(#{ explode: true }) + to?: DateTime, + ): + | { + @body + @example(#["gpt-4-turbo", "gpt-4o"]) + _: string[]; + } + | CommonErrors; +} + +/** + * A meter create model. + */ +@friendlyName("MeterCreate") +@example(#{ + slug: "tokens_total", + name: "Tokens Total", + description: "AI Token Usage", + aggregation: MeterAggregation.SUM, + eventType: "prompt", + valueProperty: "$.tokens", + groupBy: #{ `model`: "$.model", type: "$.type" }, +}) +model MeterCreate is TypeSpec.Rest.Resource.ResourceCreateModel; + +/** + * A meter update model. + * + * Only the properties that can be updated are included. + * For example, the slug and aggregation cannot be updated. + */ +@friendlyName("MeterUpdate") +@example(#{ + name: "Tokens Total", + description: "AI Token Usage", + groupBy: #{ `model`: "$.model", type: "$.type" }, +}) +model MeterUpdate is TypeSpec.Rest.Resource.ResourceReplaceModel; + +/** + * A meter is a configuration that defines how to match and aggregate events. + */ +@friendlyName("Meter") +@example(#{ + id: "01G65Z755AFWAKHE12NY0CQ9FH", + slug: "tokens_total", + name: "Tokens Total", + description: "AI Token Usage", + aggregation: MeterAggregation.SUM, + eventType: "prompt", + valueProperty: "$.tokens", + groupBy: #{ `model`: "$.model", type: "$.type" }, + createdAt: DateTime.fromISO("2024-01-01T01:01:01.001Z"), + updatedAt: DateTime.fromISO("2024-01-01T01:01:01.001Z"), +}) +model Meter { + // We omit name from the global.Resource as name is optional in the Meter model to avoid breaking changes for now. + ...OmitProperties; + + /** + * Human-readable name for the resource. Between 1 and 256 characters. + * Defaults to the slug if not specified. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Display name") + @minLength(1) + @maxLength(256) + name?: string; + + /** + * A unique, human-readable identifier for the meter. + * Must consist only alphanumeric and underscore characters. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @example("tokens_total") + slug: Key; + + /** + * The aggregation type to use for the meter. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @example(MeterAggregation.SUM) + aggregation: MeterAggregation; + + /** + * The event type to aggregate. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @minLength(1) + @example("prompt") + eventType: string; + + /** + * The date since the meter should include events. + * Useful to skip old events. + * If not specified, all historical events are included. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + eventFrom?: DateTime; + + /** + * JSONPath expression to extract the value from the ingested event's data property. + * + * The ingested value for SUM, AVG, MIN, and MAX aggregations is a number or a string that can be parsed to a number. + * + * For UNIQUE_COUNT aggregation, the ingested value must be a string. For COUNT aggregation the valueProperty is ignored. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @minLength(1) + @example("$.tokens") + valueProperty?: string; + + /** + * Named JSONPath expressions to extract the group by values from the event data. + * + * Keys must be unique and consist only alphanumeric and underscore characters. + * + */ + // TODO: add key format enforcement + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @example(#{ type: "$.type" }) + groupBy?: Record; + + /** + * Set of key-value pairs managed by the system. Cannot be modified by user. + */ + @visibility(Lifecycle.Read) + @summary("Annotations") + annotations?: Annotations | null; +} + +/** + * The aggregation type to use for the meter. + */ +@friendlyName("MeterAggregation") +@extension( + "x-enum-varnames", + #["Sum", "Count", "UniqueCount", "Avg", "Min", "Max", "Latest"] +) +enum MeterAggregation { + SUM, + COUNT, + UNIQUE_COUNT, + AVG, + MIN, + MAX, + LATEST, +} + +/** + * Aggregation window size. + */ +@friendlyName("WindowSize") +@extension("x-enum-varnames", #["Minute", "Hour", "Day", "Month"]) +enum WindowSize { + MINUTE, + HOUR, + DAY, + MONTH, +} + +/** + * A unique meter identifier. + */ +alias MeterIdentifier = ULIDOrKey; + +/** + * Meter query parameters. + */ +@friendlyName("MeterQuery") +model MeterQuery { + /** + * Client ID + * Useful to track progress of a query. + */ + @query + @example("f74e58ed-94ce-4041-ae06-cf45420451a3") + @minLength(1) + @maxLength(36) + clientId?: string; + + /** + * Start date-time in RFC 3339 format. + * + * Inclusive. + * + * For example: ?from=2025-01-01T00%3A00%3A00.000Z + */ + @query(#{ explode: true }) + from?: DateTime; + + /** + * End date-time in RFC 3339 format. + * + * Inclusive. + * + * For example: ?to=2025-02-01T00%3A00%3A00.000Z + */ + @query(#{ explode: true }) + to?: DateTime; + + /** + * If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group. + * + * For example: ?windowSize=DAY + */ + @query + windowSize?: WindowSize; + + /** + * The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones). + * If not specified, the UTC timezone will be used. + * + * For example: ?windowTimeZone=UTC + */ + @query + @example("America/New_York") + windowTimeZone?: string = "UTC"; + + /** + * Filtering by multiple subjects. + * + * For example: ?subject=subject-1&subject=subject-2 + */ + @query(#{ explode: true }) + @example(#["subject-1", "subject-2"]) + subject?: string[]; + + /** + * Filtering by multiple customers. + * + * For example: ?filterCustomerId=customer-1&filterCustomerId=customer-2 + */ + @query(#{ explode: true }) + @maxItems(100) + @example(#["customer-1", "customer-2"]) + filterCustomerId?: string[]; + + /** + * Simple filter for group bys with exact match. + * + * For example: ?filterGroupBy[vendor]=openai&filterGroupBy[model]=gpt-4-turbo + * + * ⚠️ __Deprecated__: Use `advancedMeterGroupByFilters` instead + */ + #deprecated "Use advancedMeterGroupByFilters instead" + @query(#{ explode: true, style: "deepObject" }) + filterGroupBy?: Record; + + /** + * Optional advanced meter group by filters. + * You can use this to filter for values of the meter groupBy fields. + */ + @query + @summary("Advanced meter group by filters") + @example(#{ + `model`: #{ $in: #["gpt-4", "gpt-4o"] }, + type: #{ $eq: "input" }, + }) + @encode("application/json") + advancedMeterGroupByFilters?: Record; + + /** + * If not specified a single aggregate will be returned for each subject and time window. + * `subject` is a reserved group by value. + * + * For example: ?groupBy=subject&groupBy=model + */ + @query(#{ explode: true }) + @example(#["model", "type"]) + groupBy?: string[]; +} + +/** + * A meter query request. + */ +@friendlyName("MeterQueryRequest") +model MeterQueryRequest { + /** + * Client ID + * Useful to track progress of a query. + */ + @example("f74e58ed-94ce-4041-ae06-cf45420451a3") + @minLength(1) + @maxLength(36) + clientId?: string; + + /** + * Start date-time in RFC 3339 format. + * + * Inclusive. + */ + from?: DateTime; + + /** + * End date-time in RFC 3339 format. + * + * Inclusive. + */ + to?: DateTime; + + /** + * If not specified, a single usage aggregate will be returned for the entirety of the specified period for each subject and group. + */ + @example(WindowSize.DAY) + windowSize?: WindowSize; + + /** + * The value is the name of the time zone as defined in the IANA Time Zone Database (http://www.iana.org/time-zones). + * If not specified, the UTC timezone will be used. + */ + @example("UTC") + windowTimeZone?: string = "UTC"; + + /** + * Filtering by multiple subjects. + */ + @example(#["subject-1", "subject-2"]) + @maxItems(100) + subject?: string[]; + + /** + * Filtering by multiple customers. + */ + @example(#["id-1", "id-2"]) + @maxItems(100) + filterCustomerId?: string[]; + + /** + * Simple filter for group bys with exact match. + */ + @example(#{ `model`: #["gpt-4-turbo", "gpt-4o"], type: #["prompt"] }) + filterGroupBy?: Record; + + /** + * Optional advanced meter group by filters. + * You can use this to filter for values of the meter groupBy fields. + */ + @example(#{ + `model`: #{ $in: #["gpt-4", "gpt-4o"] }, + type: #{ $eq: "input" }, + }) + advancedMeterGroupByFilters?: Record; + + /** + * If not specified a single aggregate will be returned for each subject and time window. + * `subject` is a reserved group by value. + */ + @example(#["model", "type"]) + @maxItems(100) + groupBy?: string[]; +} + +/** + * The result of a meter query. + */ +@friendlyName("MeterQueryResult") +@example(#{ + from: DateTime.fromISO("2023-01-01T00:00:00Z"), + to: DateTime.fromISO("2023-01-02T00:00:00Z"), + windowSize: WindowSize.DAY, + data: #[ + #{ + value: 12, + windowStart: DateTime.fromISO("2023-01-01T00:00:00Z"), + windowEnd: DateTime.fromISO("2023-01-02T00:00:00Z"), + subject: "customer-1", + groupBy: #{ `model`: "gpt-4-turbo", type: "prompt" }, + } + ], +}) +model MeterQueryResult { + /** + * The start of the period the usage is queried from. + * If not specified, the usage is queried from the beginning of time. + */ + from?: DateTime; + + /** + * The end of the period the usage is queried to. + * If not specified, the usage is queried up to the current time. + */ + to?: DateTime; + + /** + * The window size that the usage is aggregated. + * If not specified, the usage is aggregated over the entire period. + */ + windowSize?: WindowSize; + + /** + * The usage data. + * If no data is available, an empty array is returned. + */ + data: MeterQueryRow[]; +} + +/** + * A row in the result of a meter query. + */ +@friendlyName("MeterQueryRow") +@example(#{ + value: 12, + windowStart: DateTime.fromISO("2023-01-01T00:00:00Z"), + windowEnd: DateTime.fromISO("2023-01-02T00:00:00Z"), + subject: "customer-1", + groupBy: #{ `model`: "gpt-4-turbo", type: "prompt" }, +}) +model MeterQueryRow { + /** + * The aggregated value. + */ + value: float64; + + /** + * The start of the window the value is aggregated over. + */ + windowStart: DateTime; + + /** + * The end of the window the value is aggregated over. + */ + windowEnd: DateTime; + + /** + * The subject the value is aggregated over. + * If not specified, the value is aggregated over all subjects. + */ + subject: string | null; + + /** + * The customer ID the value is aggregated over. + */ + customerId?: string; + + /** + * The group by values the value is aggregated over. + */ + groupBy: Record; +} diff --git a/api/spec/packages/legacy/src/notification/channel.tsp b/api/spec/packages/legacy/src/notification/channel.tsp new file mode 100644 index 0000000000000000000000000000000000000000..75c8a3abe0eb4b6afb86d8597fdecf3eb0601320 --- /dev/null +++ b/api/spec/packages/legacy/src/notification/channel.tsp @@ -0,0 +1,252 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * Type of the notification channel. + */ +@friendlyName("NotificationChannelType") +@extension("x-enum-varnames", #["Webhook"]) +enum NotificationChannelType { + #suppress "@openmeter/api-spec-legacy/casing" "Ignore due to backward compatibility" + webhook: "WEBHOOK", +} + +/** + * Metadata only fields of a notification channel. + */ +@friendlyName("NotificationChannelMeta") +model NotificationChannelMeta { + /** + * Identifies the notification channel. + */ + @visibility(Lifecycle.Read) + @summary("Channel Unique Identifier") + @example("01ARZ3NDEKTSV4RRFFQ69G5FAV") + id: ULID; + + /** + * Notification channel type. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Channel Type") + type: NotificationChannelType; +} + +/** + * Common fields of a notificaiton channel. + */ +@friendlyName("NotificationChannelCommon") +model NotificationChannelCommon { + ...ResourceTimestamps; + ...OmitProperties; + + /** + * Notification channel type. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Channel Type") + type: T; + + /** + * User friendly name of the channel. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Channel Name") + @example("customer-webhook") + @minLength(1) + @maxLength(256) + name: string; + + /** + * Whether the channel is disabled or not. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Channel Disabled") + @example(true) + disabled?: boolean = false; + + /** + * Set of key-value pairs managed by the system. Cannot be modified by user. + */ + @visibility(Lifecycle.Read) + @summary("Annotations") + annotations?: Annotations; + + /** + * Additional metadata for the resource. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Metadata") + metadata?: Metadata | null; +} + +/** + * Notification channel with webhook type. + */ +@friendlyName("NotificationChannelWebhook") +model NotificationChannelWebhook { + ...NotificationChannelCommon; + + /** + * Webhook URL where the notification is sent. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Webhook URL") + @example("https://example.com/webhook") + url: string; + + /** + * Custom HTTP headers sent as part of the webhook request. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Custom HTTP Headers") + customHeaders?: Record; + + /** + * Signing secret used for webhook request validation on the receiving end. + * + * Format: `base64` encoded random bytes optionally prefixed with `whsec_`. Recommended size: 24 + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Signing Secret") + @pattern("^(whsec_)?[a-zA-Z0-9+/=]{32,100}$") + @example("whsec_S6g2HLnTwd9AhHwUIMFggVS9OfoPafN8") + signingSecret?: string; +} + +/** + * Notification channel. + */ +@friendlyName("NotificationChannel") +union NotificationChannel { + NotificationChannelWebhook, +} + +/** + * Union type for requests creating new notification channel with certain type. + */ +@friendlyName("NotificationChannelCreateRequest") +union NotificationChannelCreateRequest { + NotificationChannelWebhookCreateRequest, +} + +/** + * Request with input parameters for creating new notification channel with webhook type. + */ +@friendlyName("NotificationChannelWebhookCreateRequest") +model NotificationChannelWebhookCreateRequest + is TypeSpec.Rest.Resource.ResourceCreateModel; + +/** + * Order by options for notification channels. + */ +@friendlyName("NotificationChannelOrderBy") +enum NotificationChannelOrderBy { + #suppress "@openmeter/api-spec-legacy/casing" "Ignore due to backward compatibility" + id: "id", + #suppress "@openmeter/api-spec-legacy/casing" "Ignore due to backward compatibility" + type: "type", + #suppress "@openmeter/api-spec-legacy/casing" "Ignore due to backward compatibility" + createdAt: "createdAt", + #suppress "@openmeter/api-spec-legacy/casing" "Ignore due to backward compatibility" + updatedAt: "updatedAt", +} + +@route("/api/v1/notification/channels") +@tag("Notifications") +@friendlyName("NotificationChannels") +interface NotificationChannelsEndpoints { + /** + * List all notification channels. + */ + @get + @operationId("listNotificationChannels") + @summary("List notification channels") + list( + /** + * Include deleted notification channels in response. + * + * Usage: `?includeDeleted=true` + */ + @query + @example(true) + includeDeleted?: boolean = false, + + /** + * Include disabled notification channels in response. + * + * Usage: `?includeDisabled=false` + */ + @query + @example(false) + includeDisabled?: boolean = false, + + ...QueryPagination, + ...QueryOrdering, + ): PaginatedResponse | CommonErrors; + + /** + * Create a new notification channel. + */ + @post + @operationId("createNotificationChannel") + @summary("Create a notification channel") + create(@body request: NotificationChannelCreateRequest): + | { + @statusCode _: 201; + @body body: NotificationChannel; + } + | CommonErrors; + + /** + * Update notification channel. + */ + @put + @operationId("updateNotificationChannel") + @summary("Update a notification channel") + update( + @path channelId: ULID, + @body request: NotificationChannelCreateRequest, + ): + | { + @statusCode _: 200; + @body body: NotificationChannel; + } + | NotFoundError + | CommonErrors; + + /** + * Get a notification channel by id. + */ + @get + @operationId("getNotificationChannel") + @summary("Get notification channel") + get(@path channelId: ULID): + | { + @statusCode _: 200; + @body body: NotificationChannel; + } + | NotFoundError + | CommonErrors; + + /** + * Soft delete notification channel by id. + * + * Once a notification channel is deleted it cannot be undeleted. + */ + @delete + @operationId("deleteNotificationChannel") + @summary("Delete a notification channel") + delete(@path channelId: ULID): + | { + @statusCode _: 204; + } + | NotFoundError + | CommonErrors; +} diff --git a/api/spec/packages/legacy/src/notification/entitlements.tsp b/api/spec/packages/legacy/src/notification/entitlements.tsp new file mode 100644 index 0000000000000000000000000000000000000000..06d4e308133a7d9f8eb6c0e668b19aad54700cb3 --- /dev/null +++ b/api/spec/packages/legacy/src/notification/entitlements.tsp @@ -0,0 +1,275 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * Payload for notification event with `entitlements.balance.threshold` type. + */ +@friendlyName("NotificationEventBalanceThresholdPayload") +model NotificationEventBalanceThresholdPayload { + /** + * A unique identifier for the notification event the payload belongs to. + */ + @visibility(Lifecycle.Read) + @summary("Notification Event Identifier") + @example("01J2KNP1YTXQRXHTDJ4KPR7PZ0") + id: ULID; + + /** + * Type of the notification event. + */ + @visibility(Lifecycle.Read) + @summary("Notification Event Type") + type: NotificationEventType.entitlementsBalanceThreshold; + + /** + * Timestamp when the notification event was created in RFC 3339 format. + */ + @visibility(Lifecycle.Read) + @summary("Creation Time") + @example(DateTime.fromISO("2023-01-01T01:01:01.001Z")) + timestamp: DateTime; + + /** + * The data of the payload. + */ + @visibility(Lifecycle.Read) + @summary("Payload Data") + data: NotificationEventBalanceThresholdPayloadData; +} + +/** + * Base data for any payload with entitlement entitlement value. + */ +@friendlyName("NotificationEventEntitlementValuePayloadBase") +model NotificationEventEntitlementValuePayloadBase { + @visibility(Lifecycle.Read) + @summary("Entitlement") + entitlement: EntitlementMetered; + + @visibility(Lifecycle.Read) + @summary("Feature") + feature: Feature; + + @visibility(Lifecycle.Read) + @summary("Subject") + subject: Subject; + + @visibility(Lifecycle.Read) + @summary("Entitlement Value") + value: EntitlementValue; + + @visibility(Lifecycle.Read) + @summary("Customer") + customer?: Customer; +} + +/** + * Data of the payload for notification event with `entitlements.balance.threshold` type. + */ +@friendlyName("NotificationEventBalanceThresholdPayloadData") +model NotificationEventBalanceThresholdPayloadData { + ...NotificationEventEntitlementValuePayloadBase; + + @visibility(Lifecycle.Read) + @summary("Threshold") + threshold: NotificationRuleBalanceThresholdValue; +} + +/** + * Payload for notification event with `entitlements.reset` type. + */ +@friendlyName("NotificationEventResetPayload") +model NotificationEventResetPayload { + /** + * A unique identifier for the notification event the payload belongs to. + */ + @visibility(Lifecycle.Read) + @summary("Notification Event Identifier") + @example("01J2KNP1YTXQRXHTDJ4KPR7PZ0") + id: ULID; + + /** + * Type of the notification event. + */ + @visibility(Lifecycle.Read) + @summary("Notification Event Type") + type: NotificationEventType.entitlementsReset; + + /** + * Timestamp when the notification event was created in RFC 3339 format. + */ + @visibility(Lifecycle.Read) + @summary("Creation Time") + @example(DateTime.fromISO("2023-01-01T01:01:01.001Z")) + timestamp: DateTime; + + /** + * The data of the payload. + */ + @visibility(Lifecycle.Read) + @summary("Payload Data") + data: NotificationEventEntitlementValuePayloadBase; +} + +/** + * Threshold value with multiple supported types. + */ +@friendlyName("NotificationRuleBalanceThresholdValue") +model NotificationRuleBalanceThresholdValue { + /** + * Value of the threshold. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Threshold Value") + @example(100) + value: float64; + + /** + * Type of the threshold. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @example(NotificationRuleBalanceThresholdValueType.usage_value) + type: NotificationRuleBalanceThresholdValueType; +} + +/** + * Type of the rule in the balance threshold specification: + * * `balance_value`: threshold defined by the remaining balance value based on usage and the total of grants in the current usage period + * * `usage_percentage`: threshold defined by the usage percentage compared to the total of grants in the current usage period + * * `usage_value`: threshold defined by the usage value in the current usage period + * * `NUMBER` (**deprecated**): see `usage_value` + * * `PERCENT` (**deprecated**): see `usage_percentage` + */ +@summary("Notification balance threshold type") +@friendlyName("NotificationRuleBalanceThresholdValueType") +@extension( + "x-enum-varnames", + #["Percent", "Number", "BalanceValue", "UsagePercentage", "UsageValue"] +) +enum NotificationRuleBalanceThresholdValueType { + PERCENT, + NUMBER, + balance_value, + usage_percentage, + usage_value, +} + +/** + * Limited representation of a feature resource which includes only its unique identifiers (id, key). + */ +@friendlyName("FeatureMeta") +model FeatureMeta { + /** + * Unique identifier of a feature. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Feature Unique Identifier") + @example("01ARZ3NDEKTSV4RRFFQ69G5FAV") + id: ULID; + + /** + * The key is an immutable unique identifier of the feature used throughout the API, + * for example when interacting with a subject's entitlements. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Feature Key") + @example("gpt4_tokens") + key: string; +} + +/** + * Notification rule with entitlements.balance.threshold type. + */ +@friendlyName("NotificationRuleBalanceThreshold") +model NotificationRuleBalanceThreshold { + ...NotificationRuleCommon; + + /** + * List of thresholds the rule suppose to be triggered. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Entitlement Balance Thresholds") + @minItems(1) + @maxItems(10) + thresholds: Array; + + /** + * Optional field containing list of features the rule applies to. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Features") + @minItems(1) + features?: Array; +} + +/** + * Request with input parameters for creating new notification rule with entitlements.balance.threshold type. + */ +@friendlyName("NotificationRuleBalanceThresholdCreateRequest") +@withVisibility(Lifecycle.Create, Lifecycle.Update) +model NotificationRuleBalanceThresholdCreateRequest { + ...OmitProperties; + + /** + * List of notification channels the rule is applied to. + */ + @visibility(Lifecycle.Create, Lifecycle.Update) + @summary("Channels") + @minItems(1) + channels: Array; + + /** + * Optional field for defining the scope of notification by feature. It may contain features by id or key. + */ + @visibility(Lifecycle.Create, Lifecycle.Update) + @summary("Features") + @minItems(1) + features?: Array; +} + +/** + * Notification rule with entitlements.reset type. + */ +@friendlyName("NotificationRuleEntitlementReset") +model NotificationRuleEntitlementReset { + ...NotificationRuleCommon; + + /** + * Optional field containing list of features the rule applies to. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Features") + @minItems(1) + features?: Array; +} + +/** + * Request with input parameters for creating new notification rule with entitlements.reset type. + */ +@friendlyName("NotificationRuleEntitlementResetCreateRequest") +@withVisibility(Lifecycle.Create, Lifecycle.Update) +model NotificationRuleEntitlementResetCreateRequest { + ...OmitProperties; + + /** + * List of notification channels the rule is applied to. + */ + @visibility(Lifecycle.Create, Lifecycle.Update) + @summary("Channels") + @minItems(1) + channels: Array; + + /** + * Optional field for defining the scope of notification by feature. It may contain features by id or key. + */ + @visibility(Lifecycle.Create, Lifecycle.Update) + @summary("Features") + @minItems(1) + features?: Array; +} diff --git a/api/spec/packages/legacy/src/notification/event.tsp b/api/spec/packages/legacy/src/notification/event.tsp new file mode 100644 index 0000000000000000000000000000000000000000..6ea74e9ad2e194bd0fd8745ade7489d8d75fcceb --- /dev/null +++ b/api/spec/packages/legacy/src/notification/event.tsp @@ -0,0 +1,342 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * Type of the notification event. + */ +@friendlyName("NotificationEventType") +enum NotificationEventType { + #suppress "@openmeter/api-spec-legacy/casing" "Ignore due to backward compatibility" + entitlementsBalanceThreshold: "entitlements.balance.threshold", + #suppress "@openmeter/api-spec-legacy/casing" "Ignore due to backward compatibility" + entitlementsReset: "entitlements.reset", + #suppress "@openmeter/api-spec-legacy/casing" "Ignore due to backward compatibility" + invoiceCreated: "invoice.created", + #suppress "@openmeter/api-spec-legacy/casing" "Ignore due to backward compatibility" + invoiceUpdated: "invoice.updated", +} + +/** + * The delivery status of the notification event. + */ +@friendlyName("NotificationEventDeliveryStatus") +model NotificationEventDeliveryStatus { + /** + * Delivery state of the notification event to the channel. + */ + @visibility(Lifecycle.Read) + @example(NotificationEventDeliveryStatusState.Success) + state: NotificationEventDeliveryStatusState; + + /** + * The reason of the last deliverry state update. + */ + @visibility(Lifecycle.Read) + @summary("State Reason") + @example("Failed to dispatch event due to provider error.") + reason: string; + + /** + * Timestamp of when the status was last updated in RFC 3339 format. + */ + @visibility(Lifecycle.Read) + @summary("Last Update Time") + @example(DateTime.fromISO("2023-01-01T01:01:01.001Z")) + updatedAt: DateTime; + + /** + * Notification channel the delivery status associated with. + */ + @visibility(Lifecycle.Read) + @summary("Notification Channel") + channel: NotificationChannelMeta; + + /** + * Set of key-value pairs managed by the system. Cannot be modified by user. + */ + @visibility(Lifecycle.Read) + @summary("Annotations") + annotations?: Annotations; + + /** + * Timestamp of the next delivery attempt. If null it means there will be no more delivery attempts. + */ + @visibility(Lifecycle.Read) + @summary("Timestamp of the next delivery attempt") + @example(DateTime.fromISO("2023-01-01T01:01:01.001Z")) + nextAttempt?: DateTime; + + /** + * List of delivery attempts. + */ + @visibility(Lifecycle.Read) + @summary("Delivery Attempts") + attempts: Array; +} + +/** + * The response of the event delivery attempt. + */ +@friendlyName("EventDeliveryAttemptResponse") +model EventDeliveryAttemptResponse { + /** + * Status code of the response if available. + */ + @visibility(Lifecycle.Read) + @summary("Status Code") + statusCode?: integer; + + /** + * The body of the response. + */ + @visibility(Lifecycle.Read) + @summary("Response Body") + body: string; + + /** + * The duration of the response in milliseconds. + */ + @visibility(Lifecycle.Read) + @summary("Response Duration") + durationMs: integer; + + /** + * URL where the event was sent in case of notification channel with webhook type. + */ + @visibility(Lifecycle.Read) + @summary("URL") + url?: string; +} + +/** + * The delivery attempt of the notification event. + */ +@friendlyName("NotificationEventDeliveryAttempt") +model NotificationEventDeliveryAttempt { + /** + * State of teh delivery attempt. + */ + @visibility(Lifecycle.Read) + @summary("State of teh delivery attempt") + @example(NotificationEventDeliveryStatusState.Success) + state: NotificationEventDeliveryStatusState; + + /** + * Response returned by the notification event recipient. + */ + @visibility(Lifecycle.Read) + @summary("Response returned by the notification event recipient") + response: EventDeliveryAttemptResponse; + + /** + * Timestamp of the delivery attempt. + */ + @visibility(Lifecycle.Read) + @summary("Timestamp of the delivery attempt") + @example(DateTime.fromISO("2023-01-01T01:01:01.001Z")) + timestamp: DateTime; +} + +/** + * A notification event that will be re-sent. + */ +@friendlyName("NotificationEventResendRequest") +model NotificationEventResendRequest { + /** + * Notification channels to which the event should be re-sent. + */ + @visibility(Lifecycle.Create) + @summary("Channels") + channels?: Array; +} + +/** + * The delivery state of the notification event to the channel. + */ +@friendlyName("NotificationEventDeliveryStatusState") +@summary("Delivery State") +@extension( + "x-enum-varnames", + #["Success", "Failed", "Sending", "Pending", "Resending"] +) +enum NotificationEventDeliveryStatusState { + Success: "SUCCESS", + Failed: "FAILED", + Sending: "SENDING", + Pending: "PENDING", + Resending: "RESENDING", +} + +/** + * The delivery status of the notification event. + */ +@friendlyName("NotificationEventPayload") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union NotificationEventPayload { + `entitlements.reset`: NotificationEventResetPayload, + `entitlements.balance.threshold`: NotificationEventBalanceThresholdPayload, + `invoice.created`: NotificationEventInvoiceCreatedPayload, + `invoice.updated`: NotificationEventInvoiceUpdatedPayload, +} + +/** + * Type of the notification event. + */ +@friendlyName("NotificationEvent") +model NotificationEvent { + /** + * A unique identifier of the notification event. + */ + @visibility(Lifecycle.Read) + @summary("Event Identifier") + @example("01J2KNP1YTXQRXHTDJ4KPR7PZ0") + id: ULID; + + /** + * Type of the notification event. + */ + @visibility(Lifecycle.Read) + @summary("Event Type") + type: NotificationEventType; + + /** + * Timestamp when the notification event was created in RFC 3339 format. + */ + @visibility(Lifecycle.Read) + @summary("Creation Time") + @example(DateTime.fromISO("2023-01-01T01:01:01.001Z")) + createdAt: DateTime; + + /** + * The nnotification rule which generated this event. + */ + @visibility(Lifecycle.Read) + rule: NotificationRule; + + /** + * The delivery status of the notification event. + */ + @visibility(Lifecycle.Read) + @summary("Delivery Status") + deliveryStatus: Array; + + /** + * Timestamp when the notification event was created in RFC 3339 format. + */ + @visibility(Lifecycle.Read) + payload: NotificationEventPayload; + + /** + * Set of key-value pairs managed by the system. Cannot be modified by user. + */ + @visibility(Lifecycle.Read) + @summary("Annotations") + annotations?: Annotations; +} + +/** + * Order by options for notification channels. + */ +@friendlyName("NotificationEventOrderBy") +enum NotificationEventOrderBy { + #suppress "@openmeter/api-spec-legacy/casing" "Ignore due to backward compatibility" + id: "id", + #suppress "@openmeter/api-spec-legacy/casing" "Ignore due to backward compatibility" + createdAt: "createdAt", +} + +@route("/api/v1/notification/events") +@tag("Notifications") +@friendlyName("NotificationEvents") +interface NotificationEventsEndpoints { + /** + * List all notification events. + */ + @get + @operationId("listNotificationEvents") + @summary("List notification events") + list( + /** + * Start date-time in RFC 3339 format. + * Inclusive. + */ + @query(#{ explode: true }) + @example(DateTime.fromISO("2023-01-01T01:01:01.001Z")) + from?: DateTime, + + /** + * End date-time in RFC 3339 format. + * Inclusive. + */ + @query(#{ explode: true }) + @example(DateTime.fromISO("2023-02-01T01:01:01.001Z")) + to?: DateTime, + + // TODO(chrisgacsal): figure out if there is a way to use union type for attribute like this + // where the code generation results a less complicated/more idiomatic code. + // + // alias IdOrKey = ULID | Key; + // const features = Array; + // + + /** + * Filtering by multiple feature ids or keys. + * + * Usage: `?feature=feature-1&feature=feature-2` + */ + @query(#{ explode: true }) + feature?: Array, + + /** + * Filtering by multiple subject ids or keys. + * + * Usage: `?subject=subject-1&subject=subject-2` + */ + @query(#{ explode: true }) + subject?: Array, + + /** + * Filtering by multiple rule ids. + * + * Usage: `?rule=01J8J2XYZ2N5WBYK09EDZFBSZM&rule=01J8J4R4VZH180KRKQ63NB2VA5` + */ + @query(#{ explode: true }) + rule?: Array, + + /** + * Filtering by multiple channel ids. + * + * Usage: `?channel=01J8J4RXH778XB056JS088PCYT&channel=01J8J4S1R1G9EVN62RG23A9M6J` + */ + @query(#{ explode: true }) + channel?: Array, + + ...QueryPagination, + ...QueryOrdering, + ): PaginatedResponse | CommonErrors; + + /** + * Get a notification event by id. + */ + @get + @operationId("getNotificationEvent") + @summary("Get notification event") + get(@path eventId: string): NotificationEvent | NotFoundError | CommonErrors; + + @post + @route("/{eventId}/resend") + @operationId("resendNotificationEvent") + @summary("Re-send notification event") + resend(@path eventId: ULID, @body request: NotificationEventResendRequest): + | { + @statusCode _: 202; + } + | OpenMeter.NotFoundError + | OpenMeter.CommonErrors; +} diff --git a/api/spec/packages/legacy/src/notification/invoice.tsp b/api/spec/packages/legacy/src/notification/invoice.tsp new file mode 100644 index 0000000000000000000000000000000000000000..c598a36a146616f934ec7b08469d9503bb129432 --- /dev/null +++ b/api/spec/packages/legacy/src/notification/invoice.tsp @@ -0,0 +1,112 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * Payload for notification event with `invoice.*` type. + */ +@friendlyName("NotificationEventInvoicePayload") +model NotificationEventInvoicePayload { + /** + * A unique identifier for the notification event the payload belongs to. + */ + @visibility(Lifecycle.Read) + @summary("Notification Event Identifier") + @example("01J2KNP1YTXQRXHTDJ4KPR7PZ0") + id: ULID; + + /** + * Type of the notification event. + */ + @visibility(Lifecycle.Read) + @summary("Notification Event Type") + type: T; + + /** + * Timestamp when the notification event was created in RFC 3339 format. + */ + @visibility(Lifecycle.Read) + @summary("Creation Time") + @example(DateTime.fromISO("2023-01-01T01:01:01.001Z")) + timestamp: DateTime; + + /** + * The data of the payload. + */ + @visibility(Lifecycle.Read) + @summary("Payload Data") + data: Invoice; +} + +/** + * Payload for notification event with `invoice.created` type. + */ +@friendlyName("NotificationEventInvoiceCreatedPayload") +model NotificationEventInvoiceCreatedPayload { + ...NotificationEventInvoicePayload; +} + +/** + * Payload for notification event with `invoice.updated` type. + */ +@friendlyName("NotificationEventInvoiceUpdatedPayload") +model NotificationEventInvoiceUpdatedPayload { + ...NotificationEventInvoicePayload; +} + +/** + * Notification rule with invoice.created type. + */ +@friendlyName("NotificationRuleInvoiceCreated") +model NotificationRuleInvoiceCreated { + ...NotificationRuleCommon; +} + +/** + * Notification rule with invoice.updated type. + */ +@friendlyName("NotificationRuleInvoiceUpdated") +model NotificationRuleInvoiceUpdated { + ...NotificationRuleCommon; +} + +/** + * Request with input parameters for creating new notification rule with invoice.created type. + */ +@friendlyName("NotificationRuleInvoiceCreatedCreateRequest") +@withVisibility(Lifecycle.Create, Lifecycle.Update) +model NotificationRuleInvoiceCreatedCreateRequest { + ...OmitProperties; + + /** + * List of notification channels the rule is applied to. + */ + @visibility(Lifecycle.Create, Lifecycle.Update) + @summary("Channels") + @minItems(1) + channels: Array; +} + +/** + * Request with input parameters for creating new notification rule with invoice.updated type. + */ +@friendlyName("NotificationRuleInvoiceUpdatedCreateRequest") +@withVisibility(Lifecycle.Create, Lifecycle.Update) +model NotificationRuleInvoiceUpdatedCreateRequest { + ...OmitProperties; + + /** + * List of notification channels the rule is applied to. + */ + @visibility(Lifecycle.Create, Lifecycle.Update) + @summary("Channels") + @minItems(1) + channels: Array; +} diff --git a/api/spec/packages/legacy/src/notification/main.tsp b/api/spec/packages/legacy/src/notification/main.tsp new file mode 100644 index 0000000000000000000000000000000000000000..040748981e90bdcceaa691dfa057598220326103 --- /dev/null +++ b/api/spec/packages/legacy/src/notification/main.tsp @@ -0,0 +1,21 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; +import "@typespec/versioning"; + +import ".."; + +// Package Contents +import "./channel.tsp"; +import "./rule.tsp"; +import "./event.tsp"; +import "./entitlements.tsp"; +import "./invoice.tsp"; + +using TypeSpec.Http; +using TypeSpec.Rest; +using TypeSpec.OpenAPI; +using TypeSpec.Versioning; + +namespace OpenMeter; diff --git a/api/spec/packages/legacy/src/notification/rule.tsp b/api/spec/packages/legacy/src/notification/rule.tsp new file mode 100644 index 0000000000000000000000000000000000000000..562da0575a9cfbc4488ccabb866b08ba3d1b96fa --- /dev/null +++ b/api/spec/packages/legacy/src/notification/rule.tsp @@ -0,0 +1,238 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * Metadata only fields of a notification channel. + */ +@friendlyName("NotificationRuleMeta") +model NotificationRuleMeta { + /** + * Identifies the notification rule. + */ + @visibility(Lifecycle.Read) + @summary("Rule Unique Identifier") + @example("01ARZ3NDEKTSV4RRFFQ69G5FAV") + id: ULID; + + /** + * Notification rule type. + */ + @visibility(Lifecycle.Read) + @summary("Rule Type") + type: NotificationEventType; +} + +/** + * Common fields of a notificaiton channel. + */ +@friendlyName("NotificationRuleCommon") +model NotificationRuleCommon { + ...ResourceTimestamps; + ...OmitProperties; + + /** + * Notification rule type. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Rule Type") + type: T; + + /** + * The user friendly name of the notification rule. + */ + @summary("Rule Name") + @example("Balance threshold reached") + @minLength(1) + @maxLength(256) + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + name: string; + + /** + * Whether the rule is disabled or not. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Rule Disabled") + @example(true) + disabled?: boolean = false; + + /** + * List of notification channels the rule applies to. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Channels assigned to Rule") + channels: Array; + + /** + * Set of key-value pairs managed by the system. Cannot be modified by user. + */ + @visibility(Lifecycle.Read) + @summary("Annotations") + annotations?: Annotations; + + /** + * Additional metadata for the resource. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Metadata") + metadata?: Metadata | null; +} + +/** + * Notification Rule. + */ +@friendlyName("NotificationRule") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union NotificationRule { + `entitlements.balance.threshold`: NotificationRuleBalanceThreshold, + `entitlements.reset`: NotificationRuleEntitlementReset, + `invoice.created`: NotificationRuleInvoiceCreated, + `invoice.updated`: NotificationRuleInvoiceUpdated, +} + +/** + * Union type for requests creating new notification rule with certain type. + */ +@friendlyName("NotificationRuleCreateRequest") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union NotificationRuleCreateRequest { + `entitlements.balance.threshold`: NotificationRuleBalanceThresholdCreateRequest, + `entitlements.reset`: NotificationRuleEntitlementResetCreateRequest, + `invoice.created`: NotificationRuleInvoiceCreatedCreateRequest, + `invoice.updated`: NotificationRuleInvoiceUpdatedCreateRequest, +} + +/** + * Order by options for notification channels. + */ +@friendlyName("NotificationRuleOrderBy") +enum NotificationRuleOrderBy { + #suppress "@openmeter/api-spec-legacy/casing" "Ignore due to backward compatibility" + id: "id", + #suppress "@openmeter/api-spec-legacy/casing" "Ignore due to backward compatibility" + type: "type", + #suppress "@openmeter/api-spec-legacy/casing" "Ignore due to backward compatibility" + createdAt: "createdAt", + #suppress "@openmeter/api-spec-legacy/casing" "Ignore due to backward compatibility" + updatedAt: "updatedAt", +} + +@route("/api/v1/notification/rules") +@tag("Notifications") +@friendlyName("NotificationRules") +interface NotificationRulesEndpoints { + /** + * List all notification rules. + */ + @get + @operationId("listNotificationRules") + @summary("List notification rules") + list( + /** + * Include deleted notification rules in response. + * + * Usage: `?includeDeleted=true` + */ + @query + @example(true) + includeDeleted?: boolean = false, + + /** + * Include disabled notification rules in response. + * + * Usage: `?includeDisabled=false` + */ + @query + @example(false) + includeDisabled?: boolean = false, + + /** + * Filtering by multiple feature ids/keys. + * + * Usage: `?feature=feature-1&feature=feature-2` + */ + @query(#{ explode: true }) + feature?: Array, + + /** + * Filtering by multiple notifiaction channel ids. + * + * Usage: `?channel=01ARZ3NDEKTSV4RRFFQ69G5FAV&channel=01J8J2Y5X4NNGQS32CF81W95E3` + */ + @query(#{ explode: true }) + channel?: Array, + + ...QueryPagination, + ...QueryOrdering, + ): PaginatedResponse | CommonErrors; + + /** + * Create a new notification rule. + */ + @post + @operationId("createNotificationRule") + @summary("Create a notification rule") + create(@body request: NotificationRuleCreateRequest): + | { + @statusCode _: 201; + @body body: NotificationRule; + } + | CommonErrors; + + /** + * Update notification rule. + */ + @put + @operationId("updateNotificationRule") + @summary("Update a notification rule") + update(@path ruleId: ULID, @body request: NotificationRuleCreateRequest): + | { + @statusCode _: 200; + @body body: NotificationRule; + } + | NotFoundError + | CommonErrors; + + /** + * Get a notification rule by id. + */ + @get + @operationId("getNotificationRule") + @summary("Get notification rule") + get(@path ruleId: ULID): NotificationRule | NotFoundError | CommonErrors; + + /** + * Soft delete notification rule by id. + * + * Once a notification rule is deleted it cannot be undeleted. + */ + @delete + @operationId("deleteNotificationRule") + @summary("Delete a notification rule") + delete(@path ruleId: ULID): + | { + @statusCode _: 204; + } + | NotFoundError + | CommonErrors; + + /** + * Test a notification rule by sending a test event with random data. + */ + @post + @route("/{ruleId}/test") + @operationId("testNotificationRule") + @summary("Test notification rule") + test(@path ruleId: ULID): + | { + @statusCode _: 201; + @body body: NotificationEvent; + } + | NotFoundError + | CommonErrors; +} diff --git a/api/spec/packages/legacy/src/portal.tsp b/api/spec/packages/legacy/src/portal.tsp new file mode 100644 index 0000000000000000000000000000000000000000..8036fcbf028a85050256f65fb0fdcd978c74256d --- /dev/null +++ b/api/spec/packages/legacy/src/portal.tsp @@ -0,0 +1,148 @@ +import "@typespec/http"; +import "@typespec/openapi"; +import "@typespec/openapi3"; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +namespace OpenMeter.Portal; + +@route("/api/v1/portal/tokens") +@tag("Portal") +@friendlyName("PortalTokens") +interface TokensEndpoints { + /** + * Create a consumer portal token. + */ + @post + @operationId("createPortalToken") + @summary("Create consumer portal token") + create(@body token: Token): + | { + // TODO: Should be 201 + @statusCode _: 200; + + @body body: Token; + } + | CommonErrors; + + /** + * List tokens. + */ + @get + @operationId("listPortalTokens") + @summary("List consumer portal tokens") + list( + @query + @minValue(1) + @maxValue(100) + limit?: integer = 25, + ): Token[] | CommonErrors; + + /** + * Invalidates consumer portal tokens by ID or subject. + */ + @route("/invalidate") + @post + @operationId("invalidatePortalTokens") + @summary("Invalidate portal tokens") + invalidate( + /** + * Invalidate a portal token by ID. + */ + id?: string, + + /** + * Invalidate all portal tokens for a subject. + */ + subject?: string, + ): void | OpenMeter.CommonErrors; +} + +/** + * A consumer portal token. + * + * Validator doesn't obey required for readOnly properties + * See: https://github.com/stoplightio/spectral/issues/1274 + */ +@friendlyName("PortalToken") +model Token { + @visibility(Lifecycle.Read) + @example("01G65Z755AFWAKHE12NY0CQ9FH") + id?: ULID; + + @example("customer-1") + subject: string; + + @visibility(Lifecycle.Read) + expiresAt?: DateTime; + + @visibility(Lifecycle.Read) + expired?: boolean; + + @visibility(Lifecycle.Read) + createdAt?: DateTime; + + // TODO: technically the visibility is incorrect, because the token is only returned at creation. + + /** + * The token is only returned at creation. + */ + @visibility(Lifecycle.Read) + @example("om_portal_IAnD3PpWW2A2Wr8m9jfzeHlGX8xmCXwG.y5q4S-AWqFu6qjfaFz0zQq4Ez28RsnyVwJffX5qxMvo") + token?: string; + + // TODO: make sure items are unique + + /** + * Optional, if defined only the specified meters will be allowed. + */ + @example(#["tokens_total"]) + allowedMeterSlugs?: string[]; +} + +@route("/api/v1/portal/meters") +@tag("Portal") +@useAuth(PortalTokenAuth) +@friendlyName("PortalMeters") +interface MetersEndpoints { + /** + * Query meter for consumer portal. This endpoint is publicly exposable to consumers. + */ + @get + @route("/{meterSlug}/query") + @operationId("queryPortalMeter") + @summary("Query meter") + @sharedRoute + queryJson(@path meterSlug: Key, ...OmitProperties): + | { + @header contentType: "application/json"; + @body _: MeterQueryResult; + } + | NotFoundError + | CommonErrors; + + /** + * Query meter for consumer portal. This endpoint is publicly exposable to consumers. + */ + @get + @route("/{meterSlug}/query") + @operationId("queryPortalMeter") + @summary("Query meter") + @sharedRoute + queryCsv(@path meterSlug: Key, ...OmitProperties): + | { + @header contentType: "text/csv"; + + @body + @example(""" + window_start,window_end,subject,model,type,value + 2023-01-01T00:00:00Z,2023-01-01T00:01:00Z,customer_1,gpt-4-turbo,input,12 + 2023-01-01T00:01:00Z,2023-01-02T00:02:00Z,customer_1,gpt-4-turbo,input,20 + 2023-01-01T00:02:00Z,2023-01-02T00:03:00Z,customer_2,gpt-4-turbo,output,4 + """) + _: string; + } + | NotFoundError + | CommonErrors; +} diff --git a/api/spec/packages/legacy/src/productcatalog/addon.tsp b/api/spec/packages/legacy/src/productcatalog/addon.tsp new file mode 100644 index 0000000000000000000000000000000000000000..66d843cce7876f7c60b6fc442f8d24e28a8b4fd1 --- /dev/null +++ b/api/spec/packages/legacy/src/productcatalog/addon.tsp @@ -0,0 +1,113 @@ +import "@typespec/http"; +import "../types.tsp"; +import "./ratecards.tsp"; + +namespace OpenMeter; + +/** + * The status of the add-on defined by the effectiveFrom and effectiveTo properties. + */ +@friendlyName("AddonStatus") +enum AddonStatus { + draft: "draft", + active: "active", + archived: "archived", +} + +/** + * The instanceType of the add-on. + * Single instance add-ons can be added to subscription only once while add-ons with multiple type can be added more then once. + */ +@friendlyName("AddonInstanceType") +enum AddonInstanceType { + single: "single", + multiple: "multiple", +} + +/** + * Add-on allows extending subscriptions with compatible plans with additional ratecards. + */ +@friendlyName("Addon") +model Addon { + ...UniqueResource; + + /** + * Set of key-value pairs managed by the system. Cannot be modified by user. + */ + @visibility(Lifecycle.Read) + @summary("Annotations") + annotations?: Annotations; + + /** + * Version of the add-on. Incremented when the add-on is updated. + */ + @summary("Version") + @minValue(1) + @visibility(Lifecycle.Read) + version: integer = 1; + + /** + * The instanceType of the add-ons. Can be "single" or "multiple". + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("InstanceType") + instanceType: AddonInstanceType; + + /** + * The currency code of the add-on. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Currency") + currency: CurrencyCode = "USD"; + + /** + * The date and time when the add-on becomes effective. When not specified, the add-on is a draft. + */ + @visibility(Lifecycle.Read) + @summary("Effective start date") + effectiveFrom?: DateTime; + + /** + * The date and time when the add-on is no longer effective. When not specified, the add-on is effective indefinitely. + */ + @visibility(Lifecycle.Read) + @summary("Effective end date") + effectiveTo?: DateTime; + + /** + * The status of the add-on. + * Computed based on the effective start and end dates: + * - draft = no effectiveFrom + * - active = effectiveFrom <= now < effectiveTo + * - archived = effectiveTo <= now + */ + @summary("Status") + @visibility(Lifecycle.Read) + status: AddonStatus; + + /** + * The rate cards of the add-on. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Rate cards") + rateCards: RateCard[]; + + /** + * List of validation errors. + */ + @visibility(Lifecycle.Read) + @summary("Validation errors") + validationErrors: ValidationError[] | null; +} + +/** + * Order by options for add-ons. + */ +@friendlyName("AddonOrderBy") +enum AddonOrderBy { + id: "id", + key: "key", + version: "version", + createdAt: "created_at", + updatedAt: "updated_at", +} diff --git a/api/spec/packages/legacy/src/productcatalog/alignment.tsp b/api/spec/packages/legacy/src/productcatalog/alignment.tsp new file mode 100644 index 0000000000000000000000000000000000000000..cefe11fa3d3f064df3496f36bc73704131c152cc --- /dev/null +++ b/api/spec/packages/legacy/src/productcatalog/alignment.tsp @@ -0,0 +1,20 @@ +import "@typespec/http"; +import "../types.tsp"; +import "./ratecards.tsp"; + +namespace OpenMeter; + +/** + * Alignment configuration for a plan or subscription. + */ +#deprecated "Not used anymore" +@friendlyName("Alignment") +model Alignment { + /** + * Whether all Billable items and RateCards must align. + * Alignment means the Price's BillingCadence must align for both duration and anchor time. + */ + #deprecated "Not used anymore" + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + billablesMustAlign?: boolean; +} diff --git a/api/spec/packages/legacy/src/productcatalog/discounts.tsp b/api/spec/packages/legacy/src/productcatalog/discounts.tsp new file mode 100644 index 0000000000000000000000000000000000000000..4452deb30e805d6a39a9b266d7daeb0fc9431aa4 --- /dev/null +++ b/api/spec/packages/legacy/src/productcatalog/discounts.tsp @@ -0,0 +1,71 @@ +namespace OpenMeter; + +/** + * Percentage discount. + */ +@friendlyName("DiscountPercentage") +model DiscountPercentage { + /** + * The percentage of the discount. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Percentage") + @minValue(0) + @maxValue(100) + percentage: Percentage; +} + +// NOTE(chrisgacsal): amount discount is going to be implemented in future releases +// /** +// * Amount discount. +// */ +// @friendlyName("DiscountAmount") +// model DiscountAmount { +// /** +// * The type of the discount. +// */ +// @summary("Type") +// type: DiscountType.amount; + +// /** +// * The amount of the discount. +// */ +// @summary("Amount") +// amount: Money; +// } + +/** + * Usage discount. + * + * Usage discount means that the first N items are free. From billing perspective + * this means that any usage on a specific feature is considered 0 until this discount + * is exhausted. + */ +@friendlyName("DiscountUsage") +model DiscountUsage { + /** + * The quantity of the usage discount. + * + * Must be positive. + */ + @summary("Usage") + quantity: Numeric; +} + +/** + * Discount by type on a price + */ +@friendlyName("Discounts") +model Discounts { + /** + * The percentage discount. + */ + percentage?: DiscountPercentage; + + /** + * The usage discount. + */ + usage?: DiscountUsage; + + // amount?: DiscountAmount, +} diff --git a/api/spec/packages/legacy/src/productcatalog/errors.tsp b/api/spec/packages/legacy/src/productcatalog/errors.tsp new file mode 100644 index 0000000000000000000000000000000000000000..c31d1b1690c97a8f4ce3f1c76996d514d0f84894 --- /dev/null +++ b/api/spec/packages/legacy/src/productcatalog/errors.tsp @@ -0,0 +1,58 @@ +import "@typespec/http"; +import "../types.tsp"; +import "../errors.tsp"; +import "./ratecards.tsp"; + +namespace OpenMeter; + +/** + * Common errors for the product catalog API. + */ +alias CommonSubscriptionErrors = + | SubscriptionBadRequestErrorResponse + | SubscriptionConflictErrorResponse + | UnauthorizedError + | ForbiddenError + | InternalServerErrorError + | ServiceUnavailableError + | PreconditionFailedError + | Error; + +/** + * Error extensions for the Subscription Errors. + */ +@friendlyName("SubscriptionErrorExtensions") +union SubscriptionErrorExtensions { + generic: { + validationErrors: ErrorExtension[], + }, +} + +/** + * The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). Variants with ErrorExtensions specific to subscriptions. + */ +@error +@friendlyName("SubscriptionBadRequestErrorResponse") +model SubscriptionBadRequestErrorResponse { + ...OmitProperties; + + /** + * Additional properties specific to the problem type may be present. + */ + extensions?: SubscriptionErrorExtensions; +} + +/** + * The request could not be completed due to a conflict with the current state of the target resource. + * Variants with ErrorExtensions specific to subscriptions. + */ +@error +@friendlyName("SubscriptionConflictErrorResponse") +model SubscriptionConflictErrorResponse { + ...OmitProperties; + + /** + * Additional properties specific to the problem type may be present. + */ + extensions?: SubscriptionErrorExtensions; +} diff --git a/api/spec/packages/legacy/src/productcatalog/features.tsp b/api/spec/packages/legacy/src/productcatalog/features.tsp new file mode 100644 index 0000000000000000000000000000000000000000..04edfed6356f6715a28e452abd901d42a9043cc4 --- /dev/null +++ b/api/spec/packages/legacy/src/productcatalog/features.tsp @@ -0,0 +1,238 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * Order by options for features. + */ +@friendlyName("FeatureOrderBy") +enum FeatureOrderBy { + ID: "id", + Key: "key", + Name: "name", + #suppress "@openmeter/api-spec-legacy/casing" "Use existing values" + CreatedAt: "createdAt", + #suppress "@openmeter/api-spec-legacy/casing" "Use existing values" + UpdatedAt: "updatedAt", +} + +/** + * Represents a feature that can be enabled or disabled for a plan. + * Used both for product catalog and entitlements. + */ +@friendlyName("FeatureCreateInputs") +model FeatureCreateInputs { + @summary("The unique key of the feature") + key: Key; + + @summary("The human-readable name of the feature") + name: string; + + @summary("Optional metadata") + @example(#{ key: "value" }) + metadata?: Metadata; + + // /** + // * The meter that the feature is associated with and and based on which usage is calculated. + // * The meter selected must have one of the following aggregations: SUM, COUNT, UNIQUE_COUNT, LATEST + // */ + // @summary("Meter key") + // @example("tokens_total") + // meterKey?: Key; + + @summary("Meter slug") + @example("tokens_total") + meterSlug?: Key; + + /** + * Optional meter group by filters. + * Useful if the meter scope is broader than what feature tracks. + * Example scenario would be a meter tracking all token use with groupBy fields for the model, + * then the feature could filter for model=gpt-4. + * + * ⚠️ __Deprecated__: Use advancedMeterGroupByFilters instead + */ + #deprecated "Use advancedMeterGroupByFilters instead" + @summary("Meter group by filters") + @example(#{ `model`: "gpt-4", type: "input" }) + meterGroupByFilters?: Record; + + /** + * Optional advanced meter group by filters. + * You can use this to filter for values of the meter groupBy fields. + */ + @summary("Advanced meter group by filters") + @example(#{ + `model`: #{ $in: #["gpt-4", "gpt-4o"] }, + type: #{ $eq: "input" }, + }) + advancedMeterGroupByFilters?: Record; + + /** + * Optional per-unit cost configuration. + * Use "manual" for a fixed per-unit cost, or "llm" to look up cost + * from the LLM cost database based on meter group-by properties. + */ + @summary("Unit cost") + unitCost?: FeatureUnitCost; +} + +/** + * The type of unit cost. + */ +@friendlyName("FeatureUnitCostType") +enum FeatureUnitCostType { + llm: "llm", + manual: "manual", +} + +/** + * A fixed per-unit cost amount. + */ +@friendlyName("FeatureManualUnitCost") +model FeatureManualUnitCost { + type: FeatureUnitCostType.manual; + + /** Fixed per-unit cost amount in USD. */ + amount: Numeric; +} + +/** + * LLM cost lookup configuration. + * Maps meter group-by dimensions to LLM cost database fields. + */ +@friendlyName("FeatureLLMUnitCost") +model FeatureLLMUnitCost { + type: FeatureUnitCostType.llm; + + /** + * Meter group-by property that holds the LLM provider. + * Use this when the meter has a group-by dimension for provider. + * Mutually exclusive with `provider`. + */ + @summary("Provider property") + providerProperty?: string; + + /** + * Static LLM provider value (e.g., "openai", "anthropic"). + * Use this when the feature tracks a single provider. + * Mutually exclusive with `providerProperty`. + */ + @summary("Provider") + provider?: string; + + /** + * Meter group-by property that holds the model ID. + * Use this when the meter has a group-by dimension for model. + * Mutually exclusive with `model`. + */ + @summary("Model property") + modelProperty?: string; + + /** + * Static model ID value (e.g., "gpt-4", "claude-3-5-sonnet"). + * Use this when the feature tracks a single model. + * Mutually exclusive with `modelProperty`. + */ + @summary("Model") + `model`?: string; + + /** + * Meter group-by property that holds the token type. + * Use this when the meter has a group-by dimension for token type. + * Mutually exclusive with `tokenType`. + */ + @summary("Token type property") + tokenTypeProperty?: string; + + /** + * Static token type value. + * Use this when the feature tracks a single token type (e.g., only input tokens). + * Expected values: input, output, cache_read, reasoning, cache_write, request, response. + * `request` is an alias for `input`, `response` is an alias for `output`. + * Mutually exclusive with `tokenTypeProperty`. + */ + @summary("Token type") + tokenType?: string; + + /** + * Resolved per-token pricing from the LLM cost database. + * Only populated in responses when the feature's meter group-by filters + * specify exact provider and model values. + */ + @summary("Resolved pricing") + @visibility(Lifecycle.Read) + pricing?: FeatureLLMUnitCostPricing; +} + +/** + * Resolved per-token pricing from the LLM cost database. + */ +@friendlyName("FeatureLLMUnitCostPricing") +model FeatureLLMUnitCostPricing { + /** Cost per input token in USD. */ + @summary("Input per token") + inputPerToken: Numeric; + + /** Cost per output token in USD. */ + @summary("Output per token") + outputPerToken: Numeric; + + /** Cost per cache read token in USD. */ + @summary("Cache read per token") + cacheReadPerToken?: Numeric; + + /** Cost per reasoning token in USD. */ + @summary("Reasoning per token") + reasoningPerToken?: Numeric; + + /** Cost per cache write token in USD. */ + @summary("Cache write per token") + cacheWritePerToken?: Numeric; +} + +/** + * Per-unit cost configuration for a feature. + * Either a fixed manual amount or a dynamic LLM cost lookup. + */ +@friendlyName("FeatureUnitCost") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union FeatureUnitCost { + @summary("Manual unit cost") + manual: FeatureManualUnitCost, + + @summary("LLM unit cost") + llm: FeatureLLMUnitCost, +} + +/** + * List features result + */ +@oneOf +@friendlyName("ListFeaturesResult") +union ListFeaturesResult { + Feature[], + PaginatedResponse, +} + +/** + * Represents a feature that can be enabled or disabled for a plan. + * Used both for product catalog and entitlements. + */ +@friendlyName("Feature") +model Feature { + ...ResourceTimestamps; + ...Archiveable; + ...FeatureCreateInputs; + + /** + * Readonly unique ULID identifier. + */ + @example("01ARZ3NDEKTSV4RRFFQ69G5FAV") + @visibility(Lifecycle.Read) + id: ULID; +} diff --git a/api/spec/packages/legacy/src/productcatalog/main.tsp b/api/spec/packages/legacy/src/productcatalog/main.tsp new file mode 100644 index 0000000000000000000000000000000000000000..4717c2058d5a0084f85ecace3ea5bb521b1fc952 --- /dev/null +++ b/api/spec/packages/legacy/src/productcatalog/main.tsp @@ -0,0 +1,19 @@ +import "@typespec/http"; +import "@typespec/openapi"; +import "@typespec/openapi3"; + +import ".."; + +// Package Contents +import "./discounts.tsp"; +import "./plan.tsp"; +import "./prices.tsp"; +import "./ratecards.tsp"; +import "./routes.tsp"; +import "./tax.tsp"; +import "./subscription.tsp"; +import "./alignment.tsp"; +import "./addon.tsp"; +import "./planaddon.tsp"; + +namespace OpenMeter; diff --git a/api/spec/packages/legacy/src/productcatalog/plan.tsp b/api/spec/packages/legacy/src/productcatalog/plan.tsp new file mode 100644 index 0000000000000000000000000000000000000000..a9c3c554744cbd6f5e1786630e5ca9acbb864158 --- /dev/null +++ b/api/spec/packages/legacy/src/productcatalog/plan.tsp @@ -0,0 +1,230 @@ +import "@typespec/http"; +import "../types.tsp"; +import "./ratecards.tsp"; +import "./prorating.tsp"; + +namespace OpenMeter; + +/** + * The status of a plan. + */ +@friendlyName("PlanStatus") +enum PlanStatus { + draft: "draft", + active: "active", + archived: "archived", + scheduled: "scheduled", +} + +/** + * The settlement mode of a plan. + * It determines how the billing system generates invoices and credits for the subscriptions using this plan. + * - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. This is the default and most common settlement mode. + * - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + */ +@friendlyName("BillingSettlementMode") +enum SettlementMode { + CreditThenInvoice: "credit_then_invoice", + CreditOnly: "credit_only", +} + +/** + * References an exact plan defaulting to the current active version. + */ +@friendlyName("PlanReferenceInput") +model PlanReferenceInput { + /** + * The plan key. + */ + key: Key; + + /** + * The plan version. + */ + version?: integer; +} + +/** + * References an exact plan. + */ +@friendlyName("PlanReference") +model PlanReference { + /** + * The plan ID. + */ + id: ULID; + + /** + * The plan key. + */ + key: Key; + + /** + * The plan version. + */ + version: integer; +} + +/** + * Plans provide a template for subscriptions. + */ +@friendlyName("Plan") +model Plan { + ...UniqueResource; + + /** + * Alignment configuration for the plan. + */ + alignment?: Alignment; + + /** + * Version of the plan. Incremented when the plan is updated. + */ + @summary("Version") + @minValue(1) + @visibility(Lifecycle.Read) + version: integer = 1; + + /** + * The currency code of the plan. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Currency") + currency: CurrencyCode = "USD"; + + /** + * The default billing cadence for subscriptions using this plan. + * Defines how often customers are billed using ISO8601 duration format. + * Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Billing cadence") + @encode(DurationKnownEncoding.ISO8601) + @example(duration.fromISO("P1M")) + billingCadence: duration; + + /** + * Default pro-rating configuration for subscriptions using this plan. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Pro-rating configuration") + proRatingConfig?: ProRatingConfig = #{ + enabled: true, + mode: ProRatingMode.proratePrices, + }; + + /** + * The date and time when the plan becomes effective. When not specified, the plan is a draft. + */ + @visibility(Lifecycle.Read) + @summary("Effective start date") + effectiveFrom?: DateTime; + + /** + * The date and time when the plan is no longer effective. When not specified, the plan is effective indefinitely. + */ + @visibility(Lifecycle.Read) + @summary("Effective end date") + effectiveTo?: DateTime; + + /** + * The status of the plan. + * Computed based on the effective start and end dates: + * - draft = no effectiveFrom + * - active = effectiveFrom <= now < effectiveTo + * - archived / inactive = effectiveTo <= now + * - scheduled = now < effectiveFrom < effectiveTo + */ + @summary("Status") + @visibility(Lifecycle.Read) + status: PlanStatus; + + /** + * The settlement mode of the plan. + * It determines how the billing system generates invoices and credits for the subscriptions using this plan. + * - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + * - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + * This is the default and most common settlement mode. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Settlement mode") + settlementMode?: SettlementMode = SettlementMode.CreditThenInvoice; + + /** + * The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + * A phase switch occurs only at the end of a billing period, ensuring that a single subscription invoice will not include charges from different phase prices. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Plan phases") + @minItems(1) + phases: PlanPhase[]; + + /** + * List of validation errors. + */ + @visibility(Lifecycle.Read) + @summary("Validation errors") + validationErrors: ValidationError[] | null; +} + +/** + * The plan phase or pricing ramp allows changing a plan's rate cards over time as a subscription progresses. + */ +@friendlyName("PlanPhase") +model PlanPhase { + /** + * A semi-unique identifier for the resource. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Key") + key: Key; + + /** + * Human-readable name for the resource. Between 1 and 256 characters. + */ + @summary("Display name") + @minLength(1) + @maxLength(256) + name: string; + + /** + * Optional description of the resource. Maximum 1024 characters. + */ + @maxLength(1024) + @summary("Description") + description?: string; + + /** + * Additional metadata for the resource. + */ + @summary("Metadata") + metadata?: Metadata | null; + + /** + * The duration of the phase. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Duration") + @encode(DurationKnownEncoding.ISO8601) + @example(duration.fromISO("P1Y")) + duration: duration | null; + + /** + * The rate cards of the plan. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Rate cards") + rateCards: RateCard[]; +} + +/** + * Order by options for plans. + */ +@friendlyName("PlanOrderBy") +enum PlanOrderBy { + id: "id", + key: "key", + version: "version", + createdAt: "created_at", + updatedAt: "updated_at", +} diff --git a/api/spec/packages/legacy/src/productcatalog/planaddon.tsp b/api/spec/packages/legacy/src/productcatalog/planaddon.tsp new file mode 100644 index 0000000000000000000000000000000000000000..09284d50793ad0356df21513dbd3360dbd76b998 --- /dev/null +++ b/api/spec/packages/legacy/src/productcatalog/planaddon.tsp @@ -0,0 +1,84 @@ +import "@typespec/http"; +import "../types.tsp"; +import "./ratecards.tsp"; + +namespace OpenMeter; + +/** + * The PlanAddon describes the association between a plan and add-on. + */ +@friendlyName("PlanAddon") +model PlanAddon { + ...ResourceTimestamps; + + /** + * Set of key-value pairs managed by the system. Cannot be modified by user. + */ + @visibility(Lifecycle.Read) + @summary("Annotations") + annotations?: Annotations; + + /** + * Additional metadata for the resource. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Metadata") + metadata?: Metadata; + + /** + * Add-on object. + */ + @summary("Addon") + @visibility(Lifecycle.Read) + addon: Addon; + + /** + * The key of the plan phase from the add-on becomes available for purchase. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("The plan phase from the add-on becomes purchasable") + fromPlanPhase: string; + + /** + * The maximum number of times the add-on can be purchased for the plan. + * It is not applicable for add-ons with single instance type. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Max quantity of the add-on") + maxQuantity?: integer; + + /** + * List of validation errors. + */ + @visibility(Lifecycle.Read) + @summary("Validation errors") + validationErrors: ValidationError[] | null; +} + +/** + * Order by options for plan add-on assignments. + */ +@friendlyName("PlanAddonOrderBy") +enum PlanAddonOrderBy { + id: "id", + key: "key", + version: "version", + createdAt: "created_at", + updatedAt: "updated_at", +} + +/** + * A plan add-on assignment create request. + */ +@friendlyName("PlanAddonCreate") +@withVisibility(Lifecycle.Create) +model PlanAddonCreate { + ...OmitProperties, "addon">; + + /** + * The add-on unique identifier in ULID format. + */ + @summary("Add-on unique identifier") + @visibility(Lifecycle.Create) + addonId: ULID; +} diff --git a/api/spec/packages/legacy/src/productcatalog/prices.tsp b/api/spec/packages/legacy/src/productcatalog/prices.tsp new file mode 100644 index 0000000000000000000000000000000000000000..06047913b63d24b29042c157de75628009b3a4b8 --- /dev/null +++ b/api/spec/packages/legacy/src/productcatalog/prices.tsp @@ -0,0 +1,305 @@ +namespace OpenMeter; + +/** + * The type of the price. + */ +@friendlyName("PriceType") +enum PriceType { + flat: "flat", + unit: "unit", + tiered: "tiered", + dynamic: "dynamic", + package: "package", +} + +/** + * Price. + * One of: flat, unit, or tiered. + */ +@friendlyName("Price") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union Price { + @summary("Flat price") + flat: FlatPrice, + + @summary("Unit price") + unit: UnitPrice, + + @summary("Tiered price") + tiered: TieredPrice, + + @summary("Dynamic price") + dynamic: DynamicPrice, + + @summary("Package price") + package: PackagePrice, +} + +/** + * The payment term of a flat price. + * One of: in_advance or in_arrears. + */ +@friendlyName("PricePaymentTerm") +union PricePaymentTerm { + /** + * If in_advance, the rate card will be invoiced in the previous billing cycle. + */ + inAdvance: "in_advance", + + /** + * If in_arrears, the rate card will be invoiced in the current billing cycle. + */ + inArrears: "in_arrears", + + // NOTE(chrisgacsal): prepaid might be implemented in future releases + // /** + // * If prepaid, entitlements will be granted only after invoice is paid + // */ + // prepaid: "prepaid", +} + +/** + * Flat price. + */ +@friendlyName("FlatPrice") +model FlatPrice { + /** + * The type of the price. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + type: PriceType.flat; + + /** + * The amount of the flat price. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + amount: Money; +} + +/** + * Flat price with payment term. + */ +@friendlyName("FlatPriceWithPaymentTerm") +model FlatPriceWithPaymentTerm { + ...FlatPrice; + + /** + * The payment term of the flat price. + * Defaults to in advance. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + paymentTerm?: PricePaymentTerm = PricePaymentTerm.inAdvance; +} + +/** + * Unit price. + */ +@friendlyName("UnitPrice") +model UnitPrice { + /** + * The type of the price. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + type: PriceType.unit; + + /** + * The amount of the unit price. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + amount: Money; +} + +/** + * The mode of the tiered price. + */ +@friendlyName("TieredPriceMode") +enum TieredPriceMode { + volume: "volume", + graduated: "graduated", +} + +/** + * Tiered price. + */ +@friendlyName("TieredPrice") +model TieredPrice { + /** + * The type of the price. + * + * One of: flat, unit, or tiered. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + type: PriceType.tiered; + + /** + * Defines if the tiering mode is volume-based or graduated: + * - In `volume`-based tiering, the maximum quantity within a period determines the per unit price. + * - In `graduated` tiering, pricing can change as the quantity grows. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Mode") + mode: TieredPriceMode; + + /** + * The tiers of the tiered price. + * At least one price component is required in each tier. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Tiers") + @minItems(1) + tiers: PriceTier[]; +} + +/** + * A price tier. + * At least one price component is required in each tier. + */ +@friendlyName("PriceTier") +model PriceTier { + /** + * Up to and including to this quantity will be contained in the tier. + * If null, the tier is open-ended. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Up to quantity") + upToAmount?: Numeric; + + /** + * The flat price component of the tier. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Flat price component") + flatPrice: FlatPrice | null; + + /** + * The unit price component of the tier. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Unit price component") + unitPrice: UnitPrice | null; +} + +/** + * Dynamic price. + * + * The underlying meter's value is considered the base price in the + * customer's currency. + * + * The rate specifies the markup over the price. + */ +@friendlyName("DynamicPrice") +model DynamicPrice { + /** + * The type of the price. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + type: PriceType.dynamic; + + /** + * The multiplier to apply to the base price to get the dynamic price. + * + * Examples: + * - 0.0: the price is zero + * - 0.5: the price is 50% of the base price + * - 1.0: the price is the same as the base price + * - 1.5: the price is 150% of the base price + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("The multiplier to apply to the base price to get the dynamic price") + multiplier?: Numeric = "1"; +} + +/** + * Package price. + * + * The item is sold in packages. Each package contains quantityPerPackage items, the price of the + * package is set in amount. + * + * The total price of the usage will be enough packages that can accomodate all the usage. + * + * Examples (given a package size of 20, and an amount of $10): + * - if the quantity is 98, the price will be 5*$10=$50. + * - if the quantity is zero, the price will be 0*$10=$0, as even the first package is not purchased. + * - if the quantity is 20, the price will be 1*$10=$10, as the usage fits into the first package. + * - if the quantity is 20.1, the price will be 2*$10=$20, as the additional 0.1 usage (compared to the + * previous example) requires a new package. + */ +@friendlyName("PackagePrice") +model PackagePrice { + /** + * The type of the price. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + type: PriceType.package; + + /** + * The price of one package. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Amount") + amount: Money; + + /** + * The quantity per package. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Quantity per package") + quantityPerPackage: Numeric; +} + +/** + * Spending commitments. + * The customer is committed to spend at least the minimum amount and at most the maximum amount. + */ +@friendlyName("SpendCommitments") +model SpendCommitments { + /** + * The customer is committed to spend at least the amount. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Minimum amount") + minimumAmount?: Money; + + /** + * The customer is limited to spend at most the amount. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Maximum amount") + maximumAmount?: Money; +} + +/** + * Unit price with spend commitments. + */ +@friendlyName("UnitPriceWithCommitments") +model UnitPriceWithCommitments { + ...UnitPrice; + ...SpendCommitments; +} + +/** + * Tiered price with spend commitments. + */ +@friendlyName("TieredPriceWithCommitments") +model TieredPriceWithCommitments { + ...TieredPrice; + ...SpendCommitments; +} + +/** + * Dynamic price with spend commitments. + */ +@friendlyName("DynamicPriceWithCommitments") +model DynamicPriceWithCommitments { + ...DynamicPrice; + ...SpendCommitments; +} + +/** + * Package price with spend commitments. + */ +@friendlyName("PackagePriceWithCommitments") +model PackagePriceWithCommitments { + ...PackagePrice; + ...SpendCommitments; +} diff --git a/api/spec/packages/legacy/src/productcatalog/prorating.tsp b/api/spec/packages/legacy/src/productcatalog/prorating.tsp new file mode 100644 index 0000000000000000000000000000000000000000..6c4ed09389e5a46f10fdc4c168fdef5c6e951215 --- /dev/null +++ b/api/spec/packages/legacy/src/productcatalog/prorating.tsp @@ -0,0 +1,30 @@ +namespace OpenMeter; + +/** + * Pro-rating mode options for handling billing period changes. + */ +@friendlyName("ProRatingMode") +union ProRatingMode { + /** + * Calculate pro-rated charges based on time remaining in billing period. + */ + proratePrices: "prorate_prices", +} + +/** + * Configuration for pro-rating behavior. + */ +@friendlyName("ProRatingConfig") +model ProRatingConfig { + /** + * Whether pro-rating is enabled for this plan. + */ + @summary("Enable pro-rating") + enabled: boolean = true; + + /** + * How to handle pro-rating for billing period changes. + */ + @summary("Pro-rating mode") + mode: ProRatingMode = ProRatingMode.proratePrices; +} diff --git a/api/spec/packages/legacy/src/productcatalog/ratecards.tsp b/api/spec/packages/legacy/src/productcatalog/ratecards.tsp new file mode 100644 index 0000000000000000000000000000000000000000..c0abe34b4e7852823e54c84d65b177d7f9e8caf1 --- /dev/null +++ b/api/spec/packages/legacy/src/productcatalog/ratecards.tsp @@ -0,0 +1,219 @@ +namespace OpenMeter; + +/** + * The type of the rate card. + */ +@friendlyName("RateCardType") +enum RateCardType { + flatFee: "flat_fee", + usageBased: "usage_based", +} + +/** + * Common fields of the rate card. + */ +@friendlyName("RateCardBase") +model RateCardBase { + /** + * The type of the RateCard. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("RateCard type") + type: T; + + /** + * A semi-unique identifier for the resource. + */ + @visibility(Lifecycle.Read, Lifecycle.Create) + @summary("Key") + key: Key; + + /** + * Human-readable name for the resource. Between 1 and 256 characters. + */ + @summary("Display name") + @minLength(1) + @maxLength(256) + name: string; + + /** + * Optional description of the resource. Maximum 1024 characters. + */ + @maxLength(1024) + @summary("Description") + description?: string; + + /** + * Additional metadata for the resource. + */ + @summary("Metadata") + metadata?: Metadata | null; + + /** + * The feature the customer is entitled to use. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Feature key") + featureKey?: Key; + + /** + * The entitlement of the rate card. + * Only available when featureKey is set. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + entitlementTemplate?: RateCardEntitlement; + + /** + * The tax config of the rate card. + * When undefined, the tax config of the feature or the default tax config of the plan is used. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Tax config") + taxConfig?: TaxConfig; +} + +/** + * A rate card defines the pricing and entitlement of a feature or service. + */ +@friendlyName("RateCard") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union RateCard { + flat_fee: RateCardFlatFee, + usage_based: RateCardUsageBased, +} + +/** + * A flat fee rate card defines a one-time purchase or a recurring fee. + */ +@friendlyName("RateCardFlatFee") +model RateCardFlatFee { + ...RateCardBase; + + /** + * The billing cadence of the rate card. + * When null it means it is a one time fee. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Billing cadence") + @encode(DurationKnownEncoding.ISO8601) + billingCadence: duration | null; + + /** + * The price of the rate card. + * When null, the feature or service is free. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Price") + @example(#{ type: PriceType.flat, amount: "100", paymentTerm: "in_arrears" }) + price: FlatPriceWithPaymentTerm | null; + + /** + * The discount of the rate card. For flat fee rate cards only percentage discounts are supported. + * Only available when price is set. + */ + @summary("Discounts") + discounts?: Discounts; +} + +/** + * The price of the usage based rate card. + */ +@friendlyName("RateCardUsageBasedPrice") +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +union RateCardUsageBasedPrice { + flat: FlatPriceWithPaymentTerm, + unit: UnitPriceWithCommitments, + tiered: TieredPriceWithCommitments, + dynamic: DynamicPriceWithCommitments, + package: PackagePriceWithCommitments, +} + +/** + * A usage-based rate card defines a price based on usage. + */ +@friendlyName("RateCardUsageBased") +model RateCardUsageBased { + ...RateCardBase; + + /** + * The billing cadence of the rate card. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Billing cadence") + @encode(DurationKnownEncoding.ISO8601) + billingCadence: duration; + + /** + * The price of the rate card. + * When null, the feature or service is free. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + price: RateCardUsageBasedPrice | null; + + /** + * The discounts of the rate card. + * + * Flat fee rate cards only support percentage discounts. + */ + @summary("Discounts") + discounts?: Discounts; +} + +/** + * Entitlement templates are used to define the entitlements of a plan. + * Features are omitted from the entitlement template, as they are defined in the rate card. + */ +@discriminated(#{ envelope: "none", discriminatorPropertyName: "type" }) +@friendlyName("RateCardEntitlement") +union RateCardEntitlement { + metered: RateCardMeteredEntitlement, + static: RateCardStaticEntitlement, + boolean: RateCardBooleanEntitlement, +} + +/** + * The entitlement template with a metered entitlement. + */ +@friendlyName("RateCardMeteredEntitlement") +model RateCardMeteredEntitlement { + ...OmitProperties< + EntitlementMeteredCreateInputs, + + | "featureKey" + | "featureId" + | "usagePeriod" + | "measureUsageFrom" + | "isUnlimited" + >; + + /** + * The interval of the metered entitlement. + * Defaults to the billing cadence of the rate card. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Usage Period") + @encode(DurationKnownEncoding.ISO8601) + usagePeriod?: duration; +} + +/** + * Entitlement template of a static entitlement. + */ +@friendlyName("RateCardStaticEntitlement") +model RateCardStaticEntitlement { + ...OmitProperties< + EntitlementStaticCreateInputs, + "featureKey" | "featureId" | "usagePeriod" + >; +} + +/** + * Entitlement template of a boolean entitlement. + */ +@friendlyName("RateCardBooleanEntitlement") +model RateCardBooleanEntitlement { + ...OmitProperties< + EntitlementBooleanCreateInputs, + "featureKey" | "featureId" | "usagePeriod" + >; +} diff --git a/api/spec/packages/legacy/src/productcatalog/routes.tsp b/api/spec/packages/legacy/src/productcatalog/routes.tsp new file mode 100644 index 0000000000000000000000000000000000000000..73a94cfe15711d984f8182be390556aed4b11da1 --- /dev/null +++ b/api/spec/packages/legacy/src/productcatalog/routes.tsp @@ -0,0 +1,703 @@ +import "../rest.tsp"; +import "./subscriptionaddon.tsp"; +import "./errors.tsp"; + +namespace OpenMeter; + +using TypeSpec.Http; +using TypeSpec.OpenAPI; + +@route("/api/v1/features") +@tag("Product Catalog") +@friendlyName("Features") +interface FeaturesEndpoints { + /** + * List features. + */ + @get + @operationId("listFeatures") + @summary("List features") + list( + /** + * Filter by meterSlug + */ + @query(#{ explode: true }) + meterSlug?: string[], + + /** + * Include archived features in response. + */ + @query + includeArchived?: boolean = false, + + ...QueryPagination, + ...QueryLimitOffset, + ...QueryOrdering, + ): + | { + @statusCode _: 200; + @body body: ListFeaturesResult; + } + | CommonErrors; + + /** + * Features are either metered or static. A feature is metered if meterSlug is provided at creation. + * For metered features you can pass additional filters that will be applied when calculating feature usage, based on the meter's groupBy fields. + * Meters with SUM, COUNT, UNIQUE_COUNT and LATEST aggregations are supported for features. + */ + @post + @operationId("createFeature") + @summary("Create feature") + create(@body feature: FeatureCreateInputs): + | { + @statusCode _: 201; + @body body: Feature; + } + | CommonErrors; + + /** + * Get a feature by ID. + */ + @get + @operationId("getFeature") + @summary("Get feature") + get(@path featureId: string): Feature | NotFoundError | CommonErrors; + + /** + * Archive a feature by ID. + * + * Once a feature is archived it cannot be unarchived. If a feature is archived, new entitlements cannot be created for it, but archiving the feature does not affect existing entitlements. + * This means, if you want to create a new feature with the same key, and then create entitlements for it, the previous entitlements have to be deleted first on a per subject basis. + */ + @delete + @operationId("deleteFeature") + @summary("Delete feature") + delete(@path featureId: string): + | { + @statusCode _: 204; + } + | NotFoundError + | CommonErrors; +} + +@route("/api/v1/plans") +@tag("Product Catalog") +@friendlyName("Plans") +interface PlansEndpoints { + /** + * List all plans. + */ + @list + @operationId("listPlans") + @summary("List plans") + list( + /** + * Include deleted plans in response. + * + * Usage: `?includeDeleted=true` + */ + @query + @example(true) + includeDeleted?: boolean = false, + + /** + * Filter by plan.id attribute + */ + @query(#{ explode: true }) + id?: ULID[], + + /** + * Filter by plan.key attribute + */ + @query(#{ explode: true }) + key?: Key[], + + /** + * Filter by plan.key and plan.version attributes + */ + @query(#{ explode: true, style: "deepObject" }) + keyVersion?: Record, + + /** + * Only return plans with the given status. + * + * Usage: + * - `?status=active`: return only the currently active plan + * - `?status=draft`: return only the draft plan + * - `?status=archived`: return only the archived plans + */ + @query(#{ explode: true }) + status?: PlanStatus[], + + /** + * Filter by plan.currency attribute + */ + @query(#{ explode: true }) + currency?: CurrencyCode[], + + ...QueryPagination, + ...QueryOrdering, + ): PaginatedResponse | CommonErrors; + + /** + * Create a new plan. + */ + @post + @operationId("createPlan") + @summary("Create a plan") + create(@body request: TypeSpec.Rest.Resource.ResourceCreateModel): + | { + @statusCode _: 201; + @body body: Plan; + } + | CommonErrors; + + /** + * Update plan by id. + */ + @put + @route("/{planId}") + @operationId("updatePlan") + @summary("Update a plan") + update( + @path planId: ULID, + @body body: TypeSpec.Rest.Resource.ResourceReplaceModel, + ): Plan | NotFoundError | CommonErrors; + + /** + * Get a plan by id or key. The latest published version is returned if latter is used. + */ + @get + @route("/{planId}") + @operationId("getPlan") + @summary("Get plan") + get( + @extension("x-go-type", "string") + @path + planId: ULIDOrKey, + + /** + * Include latest version of the Plan instead of the version in active state. + * + * Usage: `?includeLatest=true` + */ + @query + @example(true) + includeLatest?: boolean = false, + ): Plan | NotFoundError | CommonErrors; + + /** + * Soft delete plan by plan.id. + * + * Once a plan is deleted it cannot be undeleted. + */ + @delete + @route("/{planId}") + @operationId("deletePlan") + @summary("Delete plan") + delete(@path planId: ULID): + | { + @statusCode _: 204; + } + | NotFoundError + | CommonErrors; + + /** + * Publish a plan version. + */ + @post + @route("/{planId}/publish") + @operationId("publishPlan") + @summary("Publish plan") + publish(@path planId: ULID): Plan | NotFoundError | CommonErrors; + + /** + * Archive a plan version. + */ + @post + @route("/{planId}/archive") + @operationId("archivePlan") + @summary("Archive plan version") + archive(@path planId: ULID): Plan | NotFoundError | CommonErrors; + + /** + * Create a new draft version from plan. + * It returns error if there is already a plan in draft or planId does not reference the latest published version. + */ + #deprecated "Use createPlan instead" + @post + @route("/{planIdOrKey}/next") + @operationId("nextPlan") + @summary("New draft plan") + next( + @extension("x-go-type", "string") + @path + planIdOrKey: ULIDOrKey, + ): + | { + @statusCode _: 201; + @body body: Plan; + } + | NotFoundError + | CommonErrors; +} + +@route("/api/v1/plans/{planId}/addons") +@tag("Product Catalog") +@friendlyName("PlanAddons") +interface PlanAddonsEndpoints { + /** + * List all available add-ons for plan. + */ + @get + @operationId("listPlanAddons") + @summary("List all available add-ons for plan") + list( + @path planId: ULIDOrKey, + + /** + * Include deleted plan add-on assignments. + * + * Usage: `?includeDeleted=true` + */ + @query + @example(true) + includeDeleted?: boolean = false, + + /** + * Filter by addon.id attribute. + */ + @query(#{ explode: true }) + id?: ULID[], + + /** + * Filter by addon.key attribute. + */ + @query(#{ explode: true }) + key?: Key[], + + /** + * Filter by addon.key and addon.version attributes. + */ + @query(#{ explode: true, style: "deepObject" }) + keyVersion?: Record, + + ...QueryPagination, + ...QueryOrdering, + ): PaginatedResponse | NotFoundError | CommonErrors; + + /** + * Create new add-on assignment for plan. + */ + @post + @operationId("createPlanAddon") + @summary("Create new add-on assignment for plan") + create(@path planId: ULID, @body body: PlanAddonCreate): + | { + @statusCode _: 201; + @body body: PlanAddon; + } + | ConflictError + | NotFoundError + | CommonErrors; + + /** + * Update add-on assignment for plan. + */ + @put + @route("/{planAddonId}") + @operationId("updatePlanAddon") + @summary("Update add-on assignment for plan") + update( + @path planId: ULID, + @path planAddonId: ULID, + @body body: TypeSpec.Rest.Resource.ResourceReplaceModel, + ): PlanAddon | NotFoundError | CommonErrors; + + /** + * Get add-on assignment for plan by id. + */ + @get + @route("/{planAddonId}") + @operationId("getPlanAddon") + @summary("Get add-on assignment for plan") + get(@path planId: ULIDOrKey, @path planAddonId: ULIDOrKey): + | PlanAddon + | NotFoundError + | CommonErrors; + + /** + * Delete add-on assignment for plan. + * + * Once a plan is deleted it cannot be undeleted. + */ + @delete + @route("/{planAddonId}") + @operationId("deletePlanAddon") + @summary("Delete add-on assignment for plan") + delete(@path planId: ULID, @path planAddonId: ULID): + | { + @statusCode _: 204; + } + | NotFoundError + | CommonErrors; +} + +@route("/api/v1/addons") +@tag("Product Catalog") +@friendlyName("Addons") +interface AddonsEndpoints { + /** + * List all add-ons. + */ + @list + @operationId("listAddons") + @summary("List add-ons") + list( + /** + * Include deleted add-ons in response. + * + * Usage: `?includeDeleted=true` + */ + @query + @example(true) + includeDeleted?: boolean = false, + + /** + * Filter by addon.id attribute + */ + @query(#{ explode: true }) + id?: ULID[], + + /** + * Filter by addon.key attribute + */ + @query(#{ explode: true }) + key?: Key[], + + /** + * Filter by addon.key and addon.version attributes + */ + @query(#{ explode: true, style: "deepObject" }) + keyVersion?: Record, + + /** + * Only return add-ons with the given status. + * + * Usage: + * - `?status=active`: return only the currently active add-ons + * - `?status=draft`: return only the draft add-ons + * - `?status=archived`: return only the archived add-ons + */ + @query(#{ explode: true }) + status?: AddonStatus[], + + /** + * Filter by addon.currency attribute + */ + @query(#{ explode: true }) + currency?: CurrencyCode[], + + ...QueryPagination, + ...QueryOrdering, + ): PaginatedResponse | CommonErrors; + + /** + * Create a new add-on. + */ + @post + @operationId("createAddon") + @summary("Create an add-on") + create(@body request: TypeSpec.Rest.Resource.ResourceCreateModel): + | { + @statusCode _: 201; + @body body: Addon; + } + | CommonErrors; + + /** + * Update add-on by id. + */ + @put + @route("/{addonId}") + @operationId("updateAddon") + @summary("Update add-on") + update( + @path addonId: ULID, + @body request: TypeSpec.Rest.Resource.ResourceReplaceModel, + ): Addon | NotFoundError | CommonErrors; + + /** + * Get add-on by id or key. The latest published version is returned if latter is used. + */ + @get + @route("/{addonId}") + @operationId("getAddon") + @summary("Get add-on") + get( + @extension("x-go-type", "string") + @path + addonId: ULIDOrKey, + + /** + * Include latest version of the add-on instead of the version in active state. + * + * Usage: `?includeLatest=true` + */ + @query + @example(true) + includeLatest?: boolean = false, + ): Addon | NotFoundError | CommonErrors; + + /** + * Soft delete add-on by id. + * + * Once a add-on is deleted it cannot be undeleted. + */ + @delete + @route("/{addonId}") + @operationId("deleteAddon") + @summary("Delete add-on") + delete(@path addonId: ULID): + | { + @statusCode _: 204; + } + | NotFoundError + | CommonErrors; + + /** + * Publish a add-on version. + */ + @post + @route("/{addonId}/publish") + @operationId("publishAddon") + @summary("Publish add-on") + publish(@path addonId: ULID): Addon | NotFoundError | CommonErrors; + + /** + * Archive a add-on version. + */ + @post + @route("/{addonId}/archive") + @operationId("archiveAddon") + @summary("Archive add-on version") + archive(@path addonId: ULID): Addon | NotFoundError | CommonErrors; +} + +@route("/api/v1/subscriptions") +@tag("Subscriptions") +@friendlyName("Subscriptions") +interface SubscriptionsEndpoints { + @get + @sharedRoute + @operationId("getSubscription") + @summary("Get subscription") + getExpanded( + @path subscriptionId: ULID, + + /** + * The time at which the subscription should be queried. If not provided the current time is used. + */ + @query(#{ explode: true }) at?: DateTime, + ): SubscriptionExpanded | NotFoundError | CommonErrors; + + @post + @operationId("createSubscription") + @summary("Create subscription") + create(@body body: SubscriptionCreate): + | { + @statusCode _: 201; + @body body: Subscription; + } + | CommonSubscriptionErrors; + + /** + * Batch processing commands for manipulating running subscriptions. + * The key format is `/phases/{phaseKey}` or `/phases/{phaseKey}/items/{itemKey}`. + */ + @patch + @operationId("editSubscription") + @summary("Edit subscription") + @route("/{subscriptionId}") + @parameterVisibility(Lifecycle.Create) + edit( + @path subscriptionId: ULID, + + @body + body: SubscriptionEdit, + ): Subscription | NotFoundError | CommonSubscriptionErrors; + + /** + * Closes a running subscription and starts a new one according to the specification. + * Can be used for upgrades, downgrades, and plan changes. + */ + @post + @operationId("changeSubscription") + @summary("Change subscription") + @route("/{subscriptionId}/change") + change( + @path subscriptionId: ULID, + + @body + body: SubscriptionChange, + ): SubscriptionChangeResponseBody | NotFoundError | CommonSubscriptionErrors; + + /** + * Migrates the subscripiton to the provided version of the current plan. + * If possible, the migration will be done immediately. + * If not, the migration will be scheduled to the end of the current billing period. + */ + @post + @operationId("migrateSubscription") + @summary("Migrate subscription") + @route("/{subscriptionId}/migrate") + migrate( + @path subscriptionId: ULID, + @body body: { + /** + * Timing configuration for the migration, when the migration should take effect. + * If not supported by the subscription, 400 will be returned. + */ + timing?: SubscriptionTiming = SubscriptionTimingEnum.Immediate; + + /** + * The version of the plan to migrate to. + * If not provided, the subscription will migrate to the latest version of the current plan. + */ + @minValue(1) + targetVersion?: integer; + + /** + * The key of the phase to start the subscription in. + * If not provided, the subscription will start in the first phase of the plan. + */ + @minLength(1) + startingPhase?: string; + + /** + * The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used. + */ + billingAnchor?: DateTime; + }, + ): SubscriptionChangeResponseBody | NotFoundError | CommonSubscriptionErrors; + + /** + * Restores a canceled subscription. + * Any subscription scheduled to start later will be deleted and this subscription will be continued indefinitely. + */ + #deprecated "API will be removed by 2025-10-06" + @post + @operationId("restoreSubscription") + @summary("Restore subscription") + @route("/{subscriptionId}/restore") + restore(@path subscriptionId: ULID): + | Subscription + | NotFoundError + | CommonErrors; + + /** + * Cancels the subscription. + * Will result in a scheduling conflict if there are other subscriptions scheduled to start after the cancellation time. + */ + @post + @operationId("cancelSubscription") + @summary("Cancel subscription") + @route("/{subscriptionId}/cancel") + cancel( + @path subscriptionId: ULID, + @body body: { + /** + * If not provided the subscription is canceled immediately. + */ + timing?: SubscriptionTiming; + }, + ): Subscription | NotFoundError | CommonSubscriptionErrors; + + /** + * Cancels the scheduled cancelation. + */ + @post + @operationId("unscheduleCancelation") + @summary("Unschedule cancelation") + @route("/{subscriptionId}/unschedule-cancelation") + unscheduleCancelation(@path subscriptionId: ULID): + | Subscription + | NotFoundError + | CommonSubscriptionErrors; + + /** + * Deletes a subscription. Only scheduled subscriptions can be deleted. + */ + @delete + @operationId("deleteSubscription") + @summary("Delete subscription") + @route("/{subscriptionId}") + delete(@path subscriptionId: ULID): + | { + @statusCode _: 204; + } + | NotFoundError + | CommonSubscriptionErrors; +} + +@route("/api/v1/subscriptions/{subscriptionId}/addons") +@tag("Subscriptions") +@friendlyName("SubscriptionAddons") +interface SubscriptionAddonsEndpoints { + /** + * Create a new subscription addon, either providing the key or the id of the addon. + */ + @post + @operationId("createSubscriptionAddon") + @summary("Create subscription addon") + create( + @path subscriptionId: ULID, + + @body + request: SubscriptionAddonCreate, + ): + | { + @statusCode _: 201; + @body body: SubscriptionAddon; + } + | ConflictError + | NotFoundError + | CommonErrors; + + /** + * List all addons of a subscription. In the returned list will match to a set unique by addonId. + */ + @get + @operationId("listSubscriptionAddons") + @summary("List subscription addons") + list( + @path subscriptionId: ULID, // Should we implement pagination? This should never be a large list. + ): SubscriptionAddon[] | NotFoundError | CommonErrors; + + /** + * Get a subscription addon by id. + */ + @get + @route("/{subscriptionAddonId}") + @operationId("getSubscriptionAddon") + @summary("Get subscription addon") + get(@path subscriptionId: ULID, @path subscriptionAddonId: ULID): + | SubscriptionAddon + | NotFoundError + | CommonErrors; + + /** + * Updates a subscription addon (allows changing the quantity: purchasing more instances or cancelling the current instances) + */ + @patch + @route("/{subscriptionAddonId}") + @operationId("updateSubscriptionAddon") + @summary("Update subscription addon") + update( + @path subscriptionId: ULID, + @path subscriptionAddonId: ULID, + + @body + body: TypeSpec.Rest.Resource.ResourceCreateOrUpdateModel, + ): SubscriptionAddon | NotFoundError | CommonErrors; +} diff --git a/api/spec/packages/legacy/src/productcatalog/subscription.tsp b/api/spec/packages/legacy/src/productcatalog/subscription.tsp new file mode 100644 index 0000000000000000000000000000000000000000..b9c00000c33dd90eb1a638de90caa75f40fb8d36 --- /dev/null +++ b/api/spec/packages/legacy/src/productcatalog/subscription.tsp @@ -0,0 +1,638 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/openapi3"; + +import "../types.tsp"; +import "../errors.tsp"; +import "./prices.tsp"; +import "./ratecards.tsp"; +import "./discounts.tsp"; +import "../entitlements/main.tsp"; + +using TypeSpec.OpenAPI; + +namespace OpenMeter; + +/** + * Expanded subscription + */ +@friendlyName("SubscriptionExpanded") +model SubscriptionExpanded { + ...OmitProperties; + + /** + * Alignment details enriched with the current billing period. + */ + alignment?: SubscriptionAlignment; + + /** + * The phases of the subscription. + */ + phases: SubscriptionPhaseExpanded[]; +} + +/** + * Subscription status. + */ +@friendlyName("SubscriptionStatus") +enum SubscriptionStatus { + Active: "active", + Inactive: "inactive", + Canceled: "canceled", + Scheduled: "scheduled", +} + +/** + * Alignment details enriched with the current billing period. + */ +@friendlyName("SubscriptionAlignment") +model SubscriptionAlignment { + ...Alignment; + + /** + * The current billing period. Only has value if the subscription is aligned and active. + */ + currentAlignedBillingPeriod?: Period; +} + +/** + * Subscription is an exact subscription instance. + */ +@friendlyName("Subscription") +model Subscription { + ...global.Resource; + ...global.CadencedResource; + + /** + * Set of key-value pairs managed by the system. Cannot be modified by user. + */ + @visibility(Lifecycle.Read) + @summary("Annotations") + annotations?: Annotations; + + /** + * Alignment configuration for the plan. + */ + alignment?: Alignment; + + /** + * The status of the subscription. + */ + @visibility(Lifecycle.Read) + status: SubscriptionStatus; + + /** + * The customer ID of the subscription. + */ + customerId: ULID; + + /** + * The plan of the subscription. + */ + plan?: PlanReference; + + /** + * The currency code of the subscription. + * Will be revised once we add multi currency support. + */ + @summary("Currency") + currency: CurrencyCode = "USD"; + + /** + * The billing cadence for the subscriptions. + * Defines how often customers are billed using ISO8601 duration format. + * Examples: "P1M" (monthly), "P3M" (quarterly), "P1Y" (annually). + */ + @visibility(Lifecycle.Read) + @summary("Billing cadence") + @encode(DurationKnownEncoding.ISO8601) + @example(duration.fromISO("P1M")) + billingCadence: duration; + + /** + * The pro-rating configuration for the subscriptions. + */ + @visibility(Lifecycle.Read) + @summary("Pro-rating configuration") + proRatingConfig?: ProRatingConfig = #{ + enabled: true, + mode: ProRatingMode.proratePrices, + }; + + /** + * The normalizedbilling anchor of the subscription. + */ + @visibility(Lifecycle.Read) + @summary("Billing anchor") + billingAnchor: DateTime; + + /** + * The settlement mode of the subscription. + * - credit_then_invoice: credits from the previous billing period are applied first, then the remaining balance is invoiced. + * - credit_only: only credits from the previous billing period are generated and applied. No invoices are generated for the subscription. + * This is the default and most common settlement mode. + */ + @visibility(Lifecycle.Read) + @summary("Settlement mode") + settlementMode: SettlementMode = SettlementMode.CreditThenInvoice; +} + +/** + * Expanded subscription phase + */ +@friendlyName("SubscriptionPhaseExpanded") +model SubscriptionPhaseExpanded { + ...SubscriptionPhase; + + /** + * The items of the phase. The structure is flattened to better conform to the Plan API. + * The timelines are flattened according to the following rules: + * - for the current phase, the `items` contains only the active item for each key + * - for past phases, the `items` contains only the last item for each key + * - for future phases, the `items` contains only the first version of the item for each key + */ + items: SubscriptionItem[]; + + /** + * Includes all versions of the items on each key, including all edits, scheduled changes, etc... + */ + itemTimelines: Record; +} + +/** + * Subscription phase, analogous to plan phases. + */ +@friendlyName("SubscriptionPhase") +model SubscriptionPhase { + ...global.Resource; + ...Keyed; + + // TODO: lets try this with visibility + ...OmitProperties< + SubscriptionPhaseCreate, + "startAfter" | "duration" | "key" | "name" | "description" + >; + + /** + * The time from which the phase is active. + */ + activeFrom: DateTime; + + /** + * The until which the Phase is active. + */ + activeTo?: DateTime; +} + +/** + * Subscription phase create input. + */ +@friendlyName("SubscriptionPhaseCreate") +model SubscriptionPhaseCreate { + /** + * Interval after the subscription starts to transition to the phase. + * When null, the phase starts immediately after the subscription starts. + */ + @summary("Start after") + @encode(DurationKnownEncoding.ISO8601) + @example(duration.fromISO("P1Y")) + startAfter: duration | null; + + /** + * The intended duration of the new phase. + * Duration is required when the phase will not be the last phase. + */ + @summary("Duration") + @encode(DurationKnownEncoding.ISO8601) + @example(duration.fromISO("P1M")) + duration?: duration; + + /** + * The discounts on the plan. + */ + @summary("Discounts") + discounts?: Discounts; + + /** + * A locally unique identifier for the phase. + */ + key: Key; + + /** + * The name of the phase. + */ + name: string; + + /** + * The description of the phase. + */ + description?: string; +} + +/** + * The actual contents of the Subscription, what the user gets, what they pay, etc... + */ +@friendlyName("SubscriptionItem") +model SubscriptionItem { + ...global.Resource; + ...global.CadencedResource; + + /** + * The identifier of the RateCard. + * SubscriptionItem/RateCard can be identified, it has a reference: + * + * 1. If a Feature is associated with the SubscriptionItem, it is identified by the Feature + * 1.1 It can be an ID reference, for an exact version of the Feature (Features can change across versions) + * 1.2 It can be a Key reference, which always refers to the latest (active or inactive) version of a Feature + * + * 2. If a Feature is not associated with the SubscriptionItem, it is referenced by the Price + * + * We say "referenced by the Price" regardless of how a price itself is referenced, it colloquially makes sense to say "paying the same price for the same thing". In practice this should be derived from what's printed on the invoice line-item. + */ + key: Key; + + /** + * The feature's key (if present). + */ + featureKey?: Key; + + /** + * The billing cadence of the rate card. + * When null, the rate card is a one-time purchase. + */ + @summary("Billing cadence") + @encode(DurationKnownEncoding.ISO8601) + billingCadence: duration | null; + + /** + * The price of the rate card. + * When null, the feature or service is free. + */ + @summary("Price") + @example(#{ type: PriceType.flat, amount: "100", paymentTerm: "in_arrears" }) + price: RateCardUsageBasedPrice | null; + + /** + * The discounts applied to the rate card. + */ + @summary("Discounts") + discounts?: Discounts; + + /** + * Describes what access is gained via the SubscriptionItem + */ + included?: SubscriptionItemIncluded; + + /** + * The tax config of the Subscription Item. + * When undefined, the tax config of the feature or the default tax config of the plan is used. + */ + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @summary("Tax config") + taxConfig?: TaxConfig; +} + +/** + * Included contents like Entitlement, or the Feature. + */ +@friendlyName("SubscriptionItemIncluded") +model SubscriptionItemIncluded { + /** + * The feature the customer is entitled to use. + */ + feature: Feature; + + /** + * The entitlement of the Subscription Item. + */ + entitlement?: Entitlement; +} + +/** + * Subscription edit input. + */ +@friendlyName("SubscriptionEdit") +model SubscriptionEdit { + /** + * Batch processing commands for manipulating running subscriptions. + * The key format is `/phases/{phaseKey}` or `/phases/{phaseKey}/items/{itemKey}`. + */ + @maxItems(100) + customizations: SubscriptionEditOperation[]; + + /** + * Whether the billing period should be restarted. + */ + // restartBillingPeriod?: boolean; + /** + * Timing configuration to allow for the changes to take effect at different times. + */ + timing?: SubscriptionTiming; +} + +/** + * Response body for subscription change. + */ +@friendlyName("SubscriptionChangeResponseBody") +model SubscriptionChangeResponseBody { + /** + * The current subscription before the change. + */ + @summary("Current subscription") + current: Subscription; + + /** + * The new state of the subscription after the change. + */ + @summary("The subscription it will be changed to") + next: SubscriptionExpanded; +} + +/** + * Create a subscription. + */ +@friendlyName("SubscriptionCreate") +@oneOf +union SubscriptionCreate { + PlanSubscriptionCreate, + CustomSubscriptionCreate, +} + +/** + * Change a subscription. + */ +@friendlyName("SubscriptionChange") +@oneOf +union SubscriptionChange { + PlanSubscriptionChange, + CustomSubscriptionChange, +} + +/** + * Create a custom subscription. + */ +@summary("Create custom") +@friendlyName("CustomSubscriptionCreate") +model CustomSubscriptionCreate { + ...OmitProperties; + + /** + * Timing configuration for the change, when the change should take effect. + * The default is immediate. + */ + timing?: SubscriptionTiming = SubscriptionTimingEnum.Immediate; + + /** + * The ID of the customer. Provide either the key or ID. Has presedence over the key. + */ + customerId?: ULID; + + /** + * The key of the customer. Provide either the key or ID. + */ + customerKey?: ExternalKey; + + /** + * The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the subscription start time will be used. + */ + billingAnchor?: DateTime; +} + +/** + * Change a custom subscription. + */ +@friendlyName("CustomSubscriptionChange") +model CustomSubscriptionChange { + /** + * Timing configuration for the change, when the change should take effect. + * For changing a subscription, the accepted values depend on the subscription configuration. + */ + timing: SubscriptionTiming; + + /** + * The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used. + */ + billingAnchor?: DateTime; + + /** + * The custom plan description which defines the Subscription. + */ + customPlan: CustomPlanInput; +} + +/** + * Plan input for custom subscription creation (without key and version). + */ +@friendlyName("CustomPlanInput") +model CustomPlanInput + extends OmitProperties< + TypeSpec.Rest.Resource.ResourceCreateModel, + "key" | "version" + > {} + +/** + * Create subscription based on plan. + */ +@friendlyName("PlanSubscriptionCreate") +@summary("Create from plan") +model PlanSubscriptionCreate { + ...OmitProperties; + + /** + * Timing configuration for the change, when the change should take effect. + * The default is immediate. + */ + timing?: SubscriptionTiming = SubscriptionTimingEnum.Immediate; + + /** + * The ID of the customer. Provide either the key or ID. Has presedence over the key. + */ + customerId?: ULID; + + /** + * The key of the customer. Provide either the key or ID. + */ + customerKey?: ExternalKey; + + /** + * The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the subscription start time will be used. + */ + billingAnchor?: DateTime; +} + +/** + * Change subscription based on plan. + */ +@friendlyName("PlanSubscriptionChange") +model PlanSubscriptionChange { + /** + * Timing configuration for the change, when the change should take effect. + * For changing a subscription, the accepted values depend on the subscription configuration. + */ + timing: SubscriptionTiming; + + /** + * What alignment settings the subscription should have. + */ + alignment?: Alignment; + + /** + * Arbitrary metadata associated with the subscription. + */ + metadata?: global.Metadata; + + /** + * The plan reference to change to. + */ + plan: PlanReferenceInput; + + /** + * The key of the phase to start the subscription in. + * If not provided, the subscription will start in the first phase of the plan. + */ + @minLength(1) + startingPhase?: string; + + /** + * The name of the Subscription. If not provided the plan name is used. + */ + name?: string; + + /** + * Description for the Subscription. + */ + description?: string; + + /** + * The billing anchor of the subscription. The provided date will be normalized according to the billing cadence to the nearest recurrence before start time. If not provided, the previous subscription billing anchor will be used. + */ + billingAnchor?: DateTime; + + /** + * The settlement mode of the subscription. + */ + settlementMode?: SettlementMode; +} + +/** + * Subscription edit timing defined when the changes should take effect. + * If the provided configuration is not supported by the subscription, an error will be returned. + */ +@oneOf +@friendlyName("SubscriptionTiming") +union SubscriptionTiming { + Enum: SubscriptionTimingEnum, + Custom: DateTime, +} + +/** + * Subscription edit timing. + * When immediate, the requested changes take effect immediately. + * When nextBillingCycle, the requested changes take effect at the next billing cycle. + */ +@friendlyName("SubscriptionTimingEnum") +enum SubscriptionTimingEnum { + Immediate: "immediate", + NextBillingCycle: "next_billing_cycle", +} + +/** + * The operation to be performed on the subscription. + */ +@discriminated(#{ envelope: "none", discriminatorPropertyName: "op" }) +@friendlyName("SubscriptionEditOperation") +union SubscriptionEditOperation { + add_item: EditSubscriptionAddItem, + remove_item: EditSubscriptionRemoveItem, + add_phase: EditSubscriptionAddPhase, + remove_phase: EditSubscriptionRemovePhase, + stretch_phase: EditSubscriptionStretchPhase, + unschedule_edit: EditSubscriptionUnscheduleEdit, +} + +/** + * Enum listing the different operation types. + */ +@friendlyName("EditOp") +enum EditOp { + AddItem: "add_item", + RemoveItem: "remove_item", + UnscheduleEdit: "unschedule_edit", + AddPhase: "add_phase", + RemovePhase: "remove_phase", + StretchPhase: "stretch_phase", +} + +/** + * Unschedules any edits from the current phase. + */ +@friendlyName("EditSubscriptionUnscheduleEdit") +model EditSubscriptionUnscheduleEdit { + `op`: EditOp.UnscheduleEdit; +} + +/** + * Add a new item to a phase. + */ +@friendlyName("EditSubscriptionAddItem") +model EditSubscriptionAddItem { + `op`: EditOp.AddItem; + phaseKey: string; + rateCard: RateCard; +} + +/** + * Remove an item from a phase. + */ +@friendlyName("EditSubscriptionRemoveItem") +model EditSubscriptionRemoveItem { + `op`: EditOp.RemoveItem; + phaseKey: string; + itemKey: string; +} + +/** + * Add a new phase + */ +@friendlyName("EditSubscriptionAddPhase") +model EditSubscriptionAddPhase { + `op`: EditOp.AddPhase; + phase: SubscriptionPhaseCreate; +} + +/** + * Remove a phase + */ +@friendlyName("EditSubscriptionRemovePhase") +model EditSubscriptionRemovePhase { + `op`: EditOp.RemovePhase; + phaseKey: string; + shift: RemovePhaseShifting; +} + +/** + * Stretch a phase + */ +@friendlyName("EditSubscriptionStretchPhase") +model EditSubscriptionStretchPhase { + `op`: EditOp.StretchPhase; + phaseKey: string; + extendBy: duration; +} + +/** + * The direction of the phase shift when a phase is removed. + */ +@friendlyName("RemovePhaseShifting") +enum RemovePhaseShifting { + /** + * Shifts all subsequent phases to start sooner by the deleted phase's length + */ + Next: "next", + + /** + * Extends the previous phase to end later by the deleted phase's length + */ + Prev: "prev", +} diff --git a/api/spec/packages/legacy/src/productcatalog/subscriptionaddon.tsp b/api/spec/packages/legacy/src/productcatalog/subscriptionaddon.tsp new file mode 100644 index 0000000000000000000000000000000000000000..f1e61ace5bb90b3216a63549a978be336881f8de --- /dev/null +++ b/api/spec/packages/legacy/src/productcatalog/subscriptionaddon.tsp @@ -0,0 +1,179 @@ +import "@typespec/http"; +import "../types.tsp"; +import "./ratecards.tsp"; + +namespace OpenMeter; + +/** + * A subscription add-on, represents concrete instances of an add-on for a given subscription. + */ +@friendlyName("SubscriptionAddon") +model SubscriptionAddon { + ...Resource; + + /** + * The cadence start of the resource. + */ + @visibility(Lifecycle.Read) + activeFrom: DateTime; + + /** + * The cadence end of the resource. + */ + @visibility(Lifecycle.Read) + activeTo?: DateTime; + + /** + * Partially populated add-on properties. + */ + @summary("Addon") + @visibility(Lifecycle.Read, Lifecycle.Create) + addon: { + /** + * The ID of the add-on. + */ + @summary("ID") + @visibility(Lifecycle.Read, Lifecycle.Create) + id: ULID; + + /** + * A semi-unique identifier for the resource. + */ + @visibility(Lifecycle.Read) + @summary("Key") + key: Key; + + /** + * The version of the Add-on which templates this instance. + */ + @summary("Version") + @minValue(1) + @visibility(Lifecycle.Read) + version: integer = 1; + + /** + * The instance type of the add-on. + */ + @visibility(Lifecycle.Read) + @summary("InstanceType") + instanceType: AddonInstanceType; + }; + + /** + * For which point in time the quantity was resolved to. + */ + @summary("QuantityAt") + @visibility(Lifecycle.Read) + @example(DateTime.fromISO("2025-01-05T00:00:00Z")) + quantityAt: DateTime; + + /** + * The quantity of the add-on. Always 1 for single instance add-ons. + */ + @summary("Quantity") + @visibility(Lifecycle.Read, Lifecycle.Create, Lifecycle.Update) + @example(1) + @minValue(0) + quantity: integer; + + /** + * The timing of the operation. After the create or update, a new entry will be created in the timeline. + */ + @summary("Timing") + @visibility(Lifecycle.Create, Lifecycle.Update) + timing: SubscriptionTiming; + + /** + * The timeline of the add-on. The returned periods are sorted and continuous. + */ + @visibility(Lifecycle.Read) + @summary("Timeline") + @example(#[ + #{ + quantity: 1, + activeFrom: DateTime.fromISO("2025-01-01T00:00:00Z"), + activeTo: DateTime.fromISO("2025-01-02T00:00:00Z"), + }, + #{ + quantity: 0, + activeFrom: DateTime.fromISO("2025-01-02T00:00:00Z"), + activeTo: DateTime.fromISO("2025-01-03T00:00:00Z"), + }, + #{ quantity: 1, activeFrom: DateTime.fromISO("2025-01-03T00:00:00Z") } + ]) + timeline: SubscriptionAddonTimelineSegment[]; + + /** + * The ID of the subscription. + */ + @summary("SubscriptionID") + @visibility(Lifecycle.Read) + subscriptionId: ULID; + + /** + * The rate cards of the add-on. + */ + @visibility(Lifecycle.Read) + @summary("Rate cards") + rateCards: SubscriptionAddonRateCard[]; +} + +/** + * A subscription add-on create body. + */ +@friendlyName("SubscriptionAddonCreate") +@withVisibility(Lifecycle.Create) +model SubscriptionAddonCreate { + ...OmitProperties< + DefaultKeyVisibility, + "addon" + >; + + /** + * The add-on to create. + */ + @summary("Addon") + @visibility(Lifecycle.Create) + addon: { + /** + * The ID of the add-on. + */ + id: ULID; + }; +} + +/** + * A rate card for a subscription add-on. + */ +@friendlyName("SubscriptionAddonRateCard") +model SubscriptionAddonRateCard { + /** + * The rate card. + */ + @summary("Rate card") + rateCard: RateCard; + + /** + * The IDs of the subscription items that this rate card belongs to. + */ + @summary("Affected subscription item IDs") + @visibility(Lifecycle.Read) + affectedSubscriptionItemIds: ULID[]; +} + +/** + * A subscription add-on event. + */ +@friendlyName("SubscriptionAddonTimelineSegment") +model SubscriptionAddonTimelineSegment { + ...global.CadencedResource; + + /** + * The quantity of the add-on for the given period. + */ + @summary("Quantity") + @visibility(Lifecycle.Read) + @example(1) + @minValue(0) + quantity: integer; +} diff --git a/api/spec/packages/legacy/src/productcatalog/tax.tsp b/api/spec/packages/legacy/src/productcatalog/tax.tsp new file mode 100644 index 0000000000000000000000000000000000000000..76a9ee7a0ffee555c5ccf662e5deee8a859f2978 --- /dev/null +++ b/api/spec/packages/legacy/src/productcatalog/tax.tsp @@ -0,0 +1,92 @@ +namespace OpenMeter; + +/** + * Set of provider specific tax configs. + */ +@friendlyName("TaxConfig") +model TaxConfig { + /** + * Tax behavior. + * + * If not specified the billing profile is used to determine the tax behavior. + * If not specified in the billing profile, the provider's default behavior is used. + */ + @summary("Tax behavior") + behavior?: TaxBehavior; + + /** + * Stripe tax config. + * + * @deprecated Use `taxCodeId` instead. When both `stripe.code` and `taxCodeId` are provided, + * `taxCodeId` takes precedence and `stripe.code` is ignored. + */ + #deprecated "Use taxCodeId instead" + @summary("Stripe tax config") + stripe?: StripeTaxConfig; + + /** + * Custom invoicing tax config. + * + * @deprecated Use `taxCodeId` instead. + */ + #deprecated "Use taxCodeId instead" + @summary("Custom invoicing tax config") + customInvoicing?: CustomInvoicingTaxConfig; + + /** + * Tax code reference. + * + * When both `taxCodeId` and `stripe.code` are provided, `taxCodeId` takes precedence: + * the referenced tax code entity is used and `stripe.code` is ignored. + */ + @summary("Tax code ID") + taxCodeId?: ULID; +} + +/** + * The tax config for Stripe. + */ +@friendlyName("StripeTaxConfig") +model StripeTaxConfig { + /** + * Product tax code. + * + * See: https://docs.stripe.com/tax/tax-codes + */ + @summary("Tax code") + @pattern("^txcd_\\d{8}$") + @example("txcd_10000000") + code: string; +} + +/** + * Tax behavior. + * + * This enum is used to specify whether tax is included in the price or excluded from the price. + */ +@friendlyName("TaxBehavior") +enum TaxBehavior { + /** + * Tax is included in the price. + */ + inclusive: "inclusive", + + /** + * Tax is excluded from the price. + */ + exclusive: "exclusive", +} + +/** + * Custom invoicing tax config. + */ +@friendlyName("CustomInvoicingTaxConfig") +model CustomInvoicingTaxConfig { + /** + * Tax code. + * + * The tax code should be interpreted by the custom invoicing provider. + */ + @summary("Tax code") + code: string; +} diff --git a/api/spec/packages/legacy/src/query.tsp b/api/spec/packages/legacy/src/query.tsp new file mode 100644 index 0000000000000000000000000000000000000000..14c2590123911a336ce9f89d06e80542e46bcbd9 --- /dev/null +++ b/api/spec/packages/legacy/src/query.tsp @@ -0,0 +1,167 @@ +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/openapi3"; + +using TypeSpec.Http; + +namespace OpenMeter; + +/** + * Pagination query params + */ +@friendlyName("Pagination") +model QueryPagination { + /** + * Page index. + * + * Default is 1. + */ + @query + @minValue(1) + @example(1) + @pageIndex + page?: integer = 1; + + /** + * The maximum number of items per page. + * + * Default is 100. + */ + @query + @minValue(1) + @maxValue(1000) + @example(100) + @pageSize + pageSize?: integer = 100; +} + +/** + * Limit and offset query params + */ +@friendlyName("LimitOffset") +model QueryLimitOffset { + /** + * Number of items to skip. + * + * Default is 0. + */ + @query + @minValue(0) + @example(0) + offset?: integer = 0; + + /** + * Number of items to return. + * + * Default is 100. + */ + @query + @minValue(1) + @maxValue(1000) + @example(100) + limit?: integer = 100; +} + +/** + * Ordering query params + */ +@friendlyName("{name}Ordering", T) +model QueryOrdering { + /** + * The order direction. + */ + @query + @example(SortOrder.ASC) + order?: SortOrder = SortOrder.ASC; + + /** + * The order by field. + * + * @TODO Default values cannot be passed as generics in typespec, + * even though the docs say so: + * https://typespec.io/docs/language-basics/templates + */ + @query + orderBy?: T; +} + +/** + * The order direction. + */ +@friendlyName("SortOrder") +enum SortOrder { + #suppress "@openmeter/api-spec-legacy/casing" "Use existing values" + ASC: "ASC", + #suppress "@openmeter/api-spec-legacy/casing" "Use existing values" + DESC: "DESC", +} + +/** + * Paginated response + */ +@friendlyName("{name}PaginatedResponse", T) +model PaginatedResponse { + /** + * The total number of items. + */ + @example(500) + totalCount: integer; + + /** + * The page index. + */ + @example(1) + page: integer; + + /** + * The maximum number of items per page. + */ + @example(100) + pageSize: integer; + + /** + * The items in the current page. + */ + @pageItems + items: T[]; +} + +/** + * Paginated cursor query parameters. + */ +@friendlyName("CursorPagination") +model QueryCursorPagination { + /** + * The cursor after which to start the pagination. + */ + @query + @continuationToken + cursor?: string; + + /** + * The limit of the pagination. + */ + @query + @minValue(1) + @maxValue(100) + limit?: integer = 100; +} + +/** + * A response for cursor pagination. + */ +@friendlyName("{name}CursorPaginatedResponse", T) +model CursorPaginatedResponse { + /** + * The items in the response. + */ + @pageItems + @maxItems(100) + items: T[]; + + /** + * The cursor of the last item in the list. + */ + @continuationToken + nextCursor?: string; +}