This is page 6 of 8. Use http://codebase.md/dodopayments/dodopayments-node?page={x} to view the full context.
# Directory Structure
```
├── .devcontainer
│ └── devcontainer.json
├── .github
│ └── workflows
│ ├── ci.yml
│ ├── docker-mcp.yml
│ ├── publish-npm.yml
│ └── release-doctor.yml
├── .gitignore
├── .prettierignore
├── .prettierrc.json
├── .release-please-manifest.json
├── .stats.yml
├── api.md
├── bin
│ ├── check-release-environment
│ ├── cli
│ ├── docker-tags
│ ├── migration-config.json
│ └── publish-npm
├── Brewfile
├── CHANGELOG.md
├── CONTRIBUTING.md
├── eslint.config.mjs
├── examples
│ └── .keep
├── jest.config.ts
├── LICENSE
├── MIGRATION.md
├── package.json
├── packages
│ └── mcp-server
│ ├── .dockerignore
│ ├── build
│ ├── cloudflare-worker
│ │ ├── .gitignore
│ │ ├── biome.json
│ │ ├── package.json
│ │ ├── README.md
│ │ ├── src
│ │ │ ├── app.ts
│ │ │ ├── index.ts
│ │ │ └── utils.ts
│ │ ├── static
│ │ │ └── home.md
│ │ ├── tsconfig.json
│ │ ├── worker-configuration.d.ts
│ │ └── wrangler.jsonc
│ ├── Dockerfile
│ ├── jest.config.ts
│ ├── manifest.json
│ ├── package.json
│ ├── README.md
│ ├── scripts
│ │ ├── copy-bundle-files.cjs
│ │ └── postprocess-dist-package-json.cjs
│ ├── src
│ │ ├── code-tool-paths.cts
│ │ ├── code-tool-types.ts
│ │ ├── code-tool-worker.ts
│ │ ├── code-tool.ts
│ │ ├── compat.ts
│ │ ├── docs-search-tool.ts
│ │ ├── dynamic-tools.ts
│ │ ├── filtering.ts
│ │ ├── headers.ts
│ │ ├── http.ts
│ │ ├── index.ts
│ │ ├── options.ts
│ │ ├── server.ts
│ │ ├── stdio.ts
│ │ ├── tools
│ │ │ ├── addons
│ │ │ │ ├── create-addons.ts
│ │ │ │ ├── list-addons.ts
│ │ │ │ ├── retrieve-addons.ts
│ │ │ │ ├── update-addons.ts
│ │ │ │ └── update-images-addons.ts
│ │ │ ├── brands
│ │ │ │ ├── create-brands.ts
│ │ │ │ ├── list-brands.ts
│ │ │ │ ├── retrieve-brands.ts
│ │ │ │ ├── update-brands.ts
│ │ │ │ └── update-images-brands.ts
│ │ │ ├── checkout-sessions
│ │ │ │ ├── create-checkout-sessions.ts
│ │ │ │ └── retrieve-checkout-sessions.ts
│ │ │ ├── customers
│ │ │ │ ├── create-customers.ts
│ │ │ │ ├── customer-portal
│ │ │ │ │ └── create-customers-customer-portal.ts
│ │ │ │ ├── list-customers.ts
│ │ │ │ ├── retrieve-customers.ts
│ │ │ │ ├── update-customers.ts
│ │ │ │ └── wallets
│ │ │ │ ├── ledger-entries
│ │ │ │ │ ├── create-wallets-customers-ledger-entries.ts
│ │ │ │ │ └── list-wallets-customers-ledger-entries.ts
│ │ │ │ └── list-customers-wallets.ts
│ │ │ ├── discounts
│ │ │ │ ├── create-discounts.ts
│ │ │ │ ├── delete-discounts.ts
│ │ │ │ ├── list-discounts.ts
│ │ │ │ ├── retrieve-discounts.ts
│ │ │ │ └── update-discounts.ts
│ │ │ ├── disputes
│ │ │ │ ├── list-disputes.ts
│ │ │ │ └── retrieve-disputes.ts
│ │ │ ├── index.ts
│ │ │ ├── invoices
│ │ │ │ └── payments
│ │ │ │ ├── retrieve-invoices-payments.ts
│ │ │ │ └── retrieve-refund-invoices-payments.ts
│ │ │ ├── license-key-instances
│ │ │ │ ├── list-license-key-instances.ts
│ │ │ │ ├── retrieve-license-key-instances.ts
│ │ │ │ └── update-license-key-instances.ts
│ │ │ ├── license-keys
│ │ │ │ ├── list-license-keys.ts
│ │ │ │ ├── retrieve-license-keys.ts
│ │ │ │ └── update-license-keys.ts
│ │ │ ├── licenses
│ │ │ │ ├── activate-licenses.ts
│ │ │ │ ├── deactivate-licenses.ts
│ │ │ │ └── validate-licenses.ts
│ │ │ ├── meters
│ │ │ │ ├── archive-meters.ts
│ │ │ │ ├── create-meters.ts
│ │ │ │ ├── list-meters.ts
│ │ │ │ ├── retrieve-meters.ts
│ │ │ │ └── unarchive-meters.ts
│ │ │ ├── misc
│ │ │ │ └── list-supported-countries-misc.ts
│ │ │ ├── payments
│ │ │ │ ├── create-payments.ts
│ │ │ │ ├── list-payments.ts
│ │ │ │ ├── retrieve-line-items-payments.ts
│ │ │ │ └── retrieve-payments.ts
│ │ │ ├── payouts
│ │ │ │ └── list-payouts.ts
│ │ │ ├── products
│ │ │ │ ├── archive-products.ts
│ │ │ │ ├── create-products.ts
│ │ │ │ ├── images
│ │ │ │ │ └── update-products-images.ts
│ │ │ │ ├── list-products.ts
│ │ │ │ ├── retrieve-products.ts
│ │ │ │ ├── unarchive-products.ts
│ │ │ │ ├── update-files-products.ts
│ │ │ │ └── update-products.ts
│ │ │ ├── refunds
│ │ │ │ ├── create-refunds.ts
│ │ │ │ ├── list-refunds.ts
│ │ │ │ └── retrieve-refunds.ts
│ │ │ ├── subscriptions
│ │ │ │ ├── change-plan-subscriptions.ts
│ │ │ │ ├── charge-subscriptions.ts
│ │ │ │ ├── create-subscriptions.ts
│ │ │ │ ├── list-subscriptions.ts
│ │ │ │ ├── retrieve-subscriptions.ts
│ │ │ │ ├── retrieve-usage-history-subscriptions.ts
│ │ │ │ └── update-subscriptions.ts
│ │ │ ├── types.ts
│ │ │ ├── usage-events
│ │ │ │ ├── ingest-usage-events.ts
│ │ │ │ ├── list-usage-events.ts
│ │ │ │ └── retrieve-usage-events.ts
│ │ │ └── webhooks
│ │ │ ├── create-webhooks.ts
│ │ │ ├── delete-webhooks.ts
│ │ │ ├── headers
│ │ │ │ ├── retrieve-webhooks-headers.ts
│ │ │ │ └── update-webhooks-headers.ts
│ │ │ ├── list-webhooks.ts
│ │ │ ├── retrieve-secret-webhooks.ts
│ │ │ ├── retrieve-webhooks.ts
│ │ │ └── update-webhooks.ts
│ │ └── tools.ts
│ ├── tests
│ │ ├── compat.test.ts
│ │ ├── dynamic-tools.test.ts
│ │ ├── options.test.ts
│ │ └── tools.test.ts
│ ├── tsc-multi.json
│ ├── tsconfig.build.json
│ ├── tsconfig.dist-src.json
│ ├── tsconfig.json
│ └── yarn.lock
├── README.md
├── release-please-config.json
├── scripts
│ ├── bootstrap
│ ├── build
│ ├── build-all
│ ├── fast-format
│ ├── format
│ ├── lint
│ ├── mock
│ ├── publish-packages.ts
│ ├── test
│ └── utils
│ ├── attw-report.cjs
│ ├── check-is-in-git-install.sh
│ ├── check-version.cjs
│ ├── fix-index-exports.cjs
│ ├── git-swap.sh
│ ├── make-dist-package-json.cjs
│ ├── postprocess-files.cjs
│ └── upload-artifact.sh
├── SECURITY.md
├── src
│ ├── api-promise.ts
│ ├── client.ts
│ ├── core
│ │ ├── api-promise.ts
│ │ ├── error.ts
│ │ ├── pagination.ts
│ │ ├── README.md
│ │ ├── resource.ts
│ │ └── uploads.ts
│ ├── error.ts
│ ├── index.ts
│ ├── internal
│ │ ├── builtin-types.ts
│ │ ├── detect-platform.ts
│ │ ├── errors.ts
│ │ ├── headers.ts
│ │ ├── parse.ts
│ │ ├── README.md
│ │ ├── request-options.ts
│ │ ├── shim-types.ts
│ │ ├── shims.ts
│ │ ├── to-file.ts
│ │ ├── types.ts
│ │ ├── uploads.ts
│ │ ├── utils
│ │ │ ├── base64.ts
│ │ │ ├── bytes.ts
│ │ │ ├── env.ts
│ │ │ ├── log.ts
│ │ │ ├── path.ts
│ │ │ ├── sleep.ts
│ │ │ ├── uuid.ts
│ │ │ └── values.ts
│ │ └── utils.ts
│ ├── lib
│ │ └── .keep
│ ├── pagination.ts
│ ├── resource.ts
│ ├── resources
│ │ ├── addons.ts
│ │ ├── brands.ts
│ │ ├── checkout-sessions.ts
│ │ ├── customers
│ │ │ ├── customer-portal.ts
│ │ │ ├── customers.ts
│ │ │ ├── index.ts
│ │ │ ├── wallets
│ │ │ │ ├── index.ts
│ │ │ │ ├── ledger-entries.ts
│ │ │ │ └── wallets.ts
│ │ │ └── wallets.ts
│ │ ├── customers.ts
│ │ ├── discounts.ts
│ │ ├── disputes.ts
│ │ ├── index.ts
│ │ ├── invoices
│ │ │ ├── index.ts
│ │ │ ├── invoices.ts
│ │ │ └── payments.ts
│ │ ├── invoices.ts
│ │ ├── license-key-instances.ts
│ │ ├── license-keys.ts
│ │ ├── licenses.ts
│ │ ├── meters.ts
│ │ ├── misc.ts
│ │ ├── payments.ts
│ │ ├── payouts.ts
│ │ ├── products
│ │ │ ├── images.ts
│ │ │ ├── index.ts
│ │ │ └── products.ts
│ │ ├── products.ts
│ │ ├── refunds.ts
│ │ ├── subscriptions.ts
│ │ ├── usage-events.ts
│ │ ├── webhook-events.ts
│ │ ├── webhooks
│ │ │ ├── headers.ts
│ │ │ ├── index.ts
│ │ │ └── webhooks.ts
│ │ └── webhooks.ts
│ ├── resources.ts
│ ├── uploads.ts
│ └── version.ts
├── tests
│ ├── api-resources
│ │ ├── addons.test.ts
│ │ ├── brands.test.ts
│ │ ├── checkout-sessions.test.ts
│ │ ├── customers
│ │ │ ├── customer-portal.test.ts
│ │ │ ├── customers.test.ts
│ │ │ └── wallets
│ │ │ ├── ledger-entries.test.ts
│ │ │ └── wallets.test.ts
│ │ ├── discounts.test.ts
│ │ ├── disputes.test.ts
│ │ ├── license-key-instances.test.ts
│ │ ├── license-keys.test.ts
│ │ ├── licenses.test.ts
│ │ ├── meters.test.ts
│ │ ├── misc.test.ts
│ │ ├── payments.test.ts
│ │ ├── payouts.test.ts
│ │ ├── products
│ │ │ ├── images.test.ts
│ │ │ └── products.test.ts
│ │ ├── refunds.test.ts
│ │ ├── subscriptions.test.ts
│ │ ├── usage-events.test.ts
│ │ └── webhooks
│ │ ├── headers.test.ts
│ │ └── webhooks.test.ts
│ ├── base64.test.ts
│ ├── buildHeaders.test.ts
│ ├── form.test.ts
│ ├── index.test.ts
│ ├── path.test.ts
│ ├── stringifyQuery.test.ts
│ └── uploads.test.ts
├── tsc-multi.json
├── tsconfig.build.json
├── tsconfig.deno.json
├── tsconfig.dist-src.json
├── tsconfig.json
└── yarn.lock
```
# Files
--------------------------------------------------------------------------------
/api.md:
--------------------------------------------------------------------------------
```markdown
# CheckoutSessions
Types:
- <code><a href="./src/resources/checkout-sessions.ts">CheckoutSessionRequest</a></code>
- <code><a href="./src/resources/checkout-sessions.ts">CheckoutSessionResponse</a></code>
- <code><a href="./src/resources/checkout-sessions.ts">CheckoutSessionStatus</a></code>
Methods:
- <code title="post /checkouts">client.checkoutSessions.<a href="./src/resources/checkout-sessions.ts">create</a>({ ...params }) -> CheckoutSessionResponse</code>
- <code title="get /checkouts/{id}">client.checkoutSessions.<a href="./src/resources/checkout-sessions.ts">retrieve</a>(id) -> CheckoutSessionStatus</code>
# Payments
Types:
- <code><a href="./src/resources/payments.ts">AttachExistingCustomer</a></code>
- <code><a href="./src/resources/payments.ts">BillingAddress</a></code>
- <code><a href="./src/resources/payments.ts">CreateNewCustomer</a></code>
- <code><a href="./src/resources/payments.ts">CustomerLimitedDetails</a></code>
- <code><a href="./src/resources/payments.ts">CustomerRequest</a></code>
- <code><a href="./src/resources/payments.ts">IntentStatus</a></code>
- <code><a href="./src/resources/payments.ts">NewCustomer</a></code>
- <code><a href="./src/resources/payments.ts">OneTimeProductCartItem</a></code>
- <code><a href="./src/resources/payments.ts">Payment</a></code>
- <code><a href="./src/resources/payments.ts">PaymentMethodTypes</a></code>
- <code><a href="./src/resources/payments.ts">PaymentCreateResponse</a></code>
- <code><a href="./src/resources/payments.ts">PaymentListResponse</a></code>
- <code><a href="./src/resources/payments.ts">PaymentRetrieveLineItemsResponse</a></code>
Methods:
- <code title="post /payments">client.payments.<a href="./src/resources/payments.ts">create</a>({ ...params }) -> PaymentCreateResponse</code>
- <code title="get /payments/{payment_id}">client.payments.<a href="./src/resources/payments.ts">retrieve</a>(paymentID) -> Payment</code>
- <code title="get /payments">client.payments.<a href="./src/resources/payments.ts">list</a>({ ...params }) -> PaymentListResponsesDefaultPageNumberPagination</code>
- <code title="get /payments/{payment_id}/line-items">client.payments.<a href="./src/resources/payments.ts">retrieveLineItems</a>(paymentID) -> PaymentRetrieveLineItemsResponse</code>
# Subscriptions
Types:
- <code><a href="./src/resources/subscriptions.ts">AddonCartResponseItem</a></code>
- <code><a href="./src/resources/subscriptions.ts">AttachAddon</a></code>
- <code><a href="./src/resources/subscriptions.ts">OnDemandSubscription</a></code>
- <code><a href="./src/resources/subscriptions.ts">Subscription</a></code>
- <code><a href="./src/resources/subscriptions.ts">SubscriptionStatus</a></code>
- <code><a href="./src/resources/subscriptions.ts">TimeInterval</a></code>
- <code><a href="./src/resources/subscriptions.ts">SubscriptionCreateResponse</a></code>
- <code><a href="./src/resources/subscriptions.ts">SubscriptionListResponse</a></code>
- <code><a href="./src/resources/subscriptions.ts">SubscriptionChargeResponse</a></code>
- <code><a href="./src/resources/subscriptions.ts">SubscriptionRetrieveUsageHistoryResponse</a></code>
Methods:
- <code title="post /subscriptions">client.subscriptions.<a href="./src/resources/subscriptions.ts">create</a>({ ...params }) -> SubscriptionCreateResponse</code>
- <code title="get /subscriptions/{subscription_id}">client.subscriptions.<a href="./src/resources/subscriptions.ts">retrieve</a>(subscriptionID) -> Subscription</code>
- <code title="patch /subscriptions/{subscription_id}">client.subscriptions.<a href="./src/resources/subscriptions.ts">update</a>(subscriptionID, { ...params }) -> Subscription</code>
- <code title="get /subscriptions">client.subscriptions.<a href="./src/resources/subscriptions.ts">list</a>({ ...params }) -> SubscriptionListResponsesDefaultPageNumberPagination</code>
- <code title="post /subscriptions/{subscription_id}/change-plan">client.subscriptions.<a href="./src/resources/subscriptions.ts">changePlan</a>(subscriptionID, { ...params }) -> void</code>
- <code title="post /subscriptions/{subscription_id}/charge">client.subscriptions.<a href="./src/resources/subscriptions.ts">charge</a>(subscriptionID, { ...params }) -> SubscriptionChargeResponse</code>
- <code title="get /subscriptions/{subscription_id}/usage-history">client.subscriptions.<a href="./src/resources/subscriptions.ts">retrieveUsageHistory</a>(subscriptionID, { ...params }) -> SubscriptionRetrieveUsageHistoryResponsesDefaultPageNumberPagination</code>
# Invoices
## Payments
Methods:
- <code title="get /invoices/payments/{payment_id}">client.invoices.payments.<a href="./src/resources/invoices/payments.ts">retrieve</a>(paymentID) -> Response</code>
- <code title="get /invoices/refunds/{refund_id}">client.invoices.payments.<a href="./src/resources/invoices/payments.ts">retrieveRefund</a>(refundID) -> Response</code>
# Licenses
Types:
- <code><a href="./src/resources/licenses.ts">LicenseActivateResponse</a></code>
- <code><a href="./src/resources/licenses.ts">LicenseValidateResponse</a></code>
Methods:
- <code title="post /licenses/activate">client.licenses.<a href="./src/resources/licenses.ts">activate</a>({ ...params }) -> LicenseActivateResponse</code>
- <code title="post /licenses/deactivate">client.licenses.<a href="./src/resources/licenses.ts">deactivate</a>({ ...params }) -> void</code>
- <code title="post /licenses/validate">client.licenses.<a href="./src/resources/licenses.ts">validate</a>({ ...params }) -> LicenseValidateResponse</code>
# LicenseKeys
Types:
- <code><a href="./src/resources/license-keys.ts">LicenseKey</a></code>
- <code><a href="./src/resources/license-keys.ts">LicenseKeyStatus</a></code>
Methods:
- <code title="get /license_keys/{id}">client.licenseKeys.<a href="./src/resources/license-keys.ts">retrieve</a>(id) -> LicenseKey</code>
- <code title="patch /license_keys/{id}">client.licenseKeys.<a href="./src/resources/license-keys.ts">update</a>(id, { ...params }) -> LicenseKey</code>
- <code title="get /license_keys">client.licenseKeys.<a href="./src/resources/license-keys.ts">list</a>({ ...params }) -> LicenseKeysDefaultPageNumberPagination</code>
# LicenseKeyInstances
Types:
- <code><a href="./src/resources/license-key-instances.ts">LicenseKeyInstance</a></code>
Methods:
- <code title="get /license_key_instances/{id}">client.licenseKeyInstances.<a href="./src/resources/license-key-instances.ts">retrieve</a>(id) -> LicenseKeyInstance</code>
- <code title="patch /license_key_instances/{id}">client.licenseKeyInstances.<a href="./src/resources/license-key-instances.ts">update</a>(id, { ...params }) -> LicenseKeyInstance</code>
- <code title="get /license_key_instances">client.licenseKeyInstances.<a href="./src/resources/license-key-instances.ts">list</a>({ ...params }) -> LicenseKeyInstancesDefaultPageNumberPagination</code>
# Customers
Types:
- <code><a href="./src/resources/customers/customers.ts">Customer</a></code>
- <code><a href="./src/resources/customers/customers.ts">CustomerPortalSession</a></code>
Methods:
- <code title="post /customers">client.customers.<a href="./src/resources/customers/customers.ts">create</a>({ ...params }) -> Customer</code>
- <code title="get /customers/{customer_id}">client.customers.<a href="./src/resources/customers/customers.ts">retrieve</a>(customerID) -> Customer</code>
- <code title="patch /customers/{customer_id}">client.customers.<a href="./src/resources/customers/customers.ts">update</a>(customerID, { ...params }) -> Customer</code>
- <code title="get /customers">client.customers.<a href="./src/resources/customers/customers.ts">list</a>({ ...params }) -> CustomersDefaultPageNumberPagination</code>
## CustomerPortal
Methods:
- <code title="post /customers/{customer_id}/customer-portal/session">client.customers.customerPortal.<a href="./src/resources/customers/customer-portal.ts">create</a>(customerID, { ...params }) -> CustomerPortalSession</code>
## Wallets
Types:
- <code><a href="./src/resources/customers/wallets/wallets.ts">CustomerWallet</a></code>
- <code><a href="./src/resources/customers/wallets/wallets.ts">WalletListResponse</a></code>
Methods:
- <code title="get /customers/{customer_id}/wallets">client.customers.wallets.<a href="./src/resources/customers/wallets/wallets.ts">list</a>(customerID) -> WalletListResponse</code>
### LedgerEntries
Types:
- <code><a href="./src/resources/customers/wallets/ledger-entries.ts">CustomerWalletTransaction</a></code>
Methods:
- <code title="post /customers/{customer_id}/wallets/ledger-entries">client.customers.wallets.ledgerEntries.<a href="./src/resources/customers/wallets/ledger-entries.ts">create</a>(customerID, { ...params }) -> CustomerWallet</code>
- <code title="get /customers/{customer_id}/wallets/ledger-entries">client.customers.wallets.ledgerEntries.<a href="./src/resources/customers/wallets/ledger-entries.ts">list</a>(customerID, { ...params }) -> CustomerWalletTransactionsDefaultPageNumberPagination</code>
# Refunds
Types:
- <code><a href="./src/resources/refunds.ts">Refund</a></code>
- <code><a href="./src/resources/refunds.ts">RefundStatus</a></code>
- <code><a href="./src/resources/refunds.ts">RefundListResponse</a></code>
Methods:
- <code title="post /refunds">client.refunds.<a href="./src/resources/refunds.ts">create</a>({ ...params }) -> Refund</code>
- <code title="get /refunds/{refund_id}">client.refunds.<a href="./src/resources/refunds.ts">retrieve</a>(refundID) -> Refund</code>
- <code title="get /refunds">client.refunds.<a href="./src/resources/refunds.ts">list</a>({ ...params }) -> RefundListResponsesDefaultPageNumberPagination</code>
# Disputes
Types:
- <code><a href="./src/resources/disputes.ts">Dispute</a></code>
- <code><a href="./src/resources/disputes.ts">DisputeStage</a></code>
- <code><a href="./src/resources/disputes.ts">DisputeStatus</a></code>
- <code><a href="./src/resources/disputes.ts">GetDispute</a></code>
- <code><a href="./src/resources/disputes.ts">DisputeListResponse</a></code>
Methods:
- <code title="get /disputes/{dispute_id}">client.disputes.<a href="./src/resources/disputes.ts">retrieve</a>(disputeID) -> GetDispute</code>
- <code title="get /disputes">client.disputes.<a href="./src/resources/disputes.ts">list</a>({ ...params }) -> DisputeListResponsesDefaultPageNumberPagination</code>
# Payouts
Types:
- <code><a href="./src/resources/payouts.ts">PayoutListResponse</a></code>
Methods:
- <code title="get /payouts">client.payouts.<a href="./src/resources/payouts.ts">list</a>({ ...params }) -> PayoutListResponsesDefaultPageNumberPagination</code>
# Products
Types:
- <code><a href="./src/resources/products/products.ts">AddMeterToPrice</a></code>
- <code><a href="./src/resources/products/products.ts">LicenseKeyDuration</a></code>
- <code><a href="./src/resources/products/products.ts">Price</a></code>
- <code><a href="./src/resources/products/products.ts">Product</a></code>
- <code><a href="./src/resources/products/products.ts">ProductListResponse</a></code>
- <code><a href="./src/resources/products/products.ts">ProductUpdateFilesResponse</a></code>
Methods:
- <code title="post /products">client.products.<a href="./src/resources/products/products.ts">create</a>({ ...params }) -> Product</code>
- <code title="get /products/{id}">client.products.<a href="./src/resources/products/products.ts">retrieve</a>(id) -> Product</code>
- <code title="patch /products/{id}">client.products.<a href="./src/resources/products/products.ts">update</a>(id, { ...params }) -> void</code>
- <code title="get /products">client.products.<a href="./src/resources/products/products.ts">list</a>({ ...params }) -> ProductListResponsesDefaultPageNumberPagination</code>
- <code title="delete /products/{id}">client.products.<a href="./src/resources/products/products.ts">archive</a>(id) -> void</code>
- <code title="post /products/{id}/unarchive">client.products.<a href="./src/resources/products/products.ts">unarchive</a>(id) -> void</code>
- <code title="put /products/{id}/files">client.products.<a href="./src/resources/products/products.ts">updateFiles</a>(id, { ...params }) -> ProductUpdateFilesResponse</code>
## Images
Types:
- <code><a href="./src/resources/products/images.ts">ImageUpdateResponse</a></code>
Methods:
- <code title="put /products/{id}/images">client.products.images.<a href="./src/resources/products/images.ts">update</a>(id, { ...params }) -> ImageUpdateResponse</code>
# Misc
Types:
- <code><a href="./src/resources/misc.ts">CountryCode</a></code>
- <code><a href="./src/resources/misc.ts">Currency</a></code>
- <code><a href="./src/resources/misc.ts">TaxCategory</a></code>
- <code><a href="./src/resources/misc.ts">MiscListSupportedCountriesResponse</a></code>
Methods:
- <code title="get /checkout/supported_countries">client.misc.<a href="./src/resources/misc.ts">listSupportedCountries</a>() -> MiscListSupportedCountriesResponse</code>
# Discounts
Types:
- <code><a href="./src/resources/discounts.ts">Discount</a></code>
- <code><a href="./src/resources/discounts.ts">DiscountType</a></code>
Methods:
- <code title="post /discounts">client.discounts.<a href="./src/resources/discounts.ts">create</a>({ ...params }) -> Discount</code>
- <code title="get /discounts/{discount_id}">client.discounts.<a href="./src/resources/discounts.ts">retrieve</a>(discountID) -> Discount</code>
- <code title="patch /discounts/{discount_id}">client.discounts.<a href="./src/resources/discounts.ts">update</a>(discountID, { ...params }) -> Discount</code>
- <code title="get /discounts">client.discounts.<a href="./src/resources/discounts.ts">list</a>({ ...params }) -> DiscountsDefaultPageNumberPagination</code>
- <code title="delete /discounts/{discount_id}">client.discounts.<a href="./src/resources/discounts.ts">delete</a>(discountID) -> void</code>
# Addons
Types:
- <code><a href="./src/resources/addons.ts">AddonResponse</a></code>
- <code><a href="./src/resources/addons.ts">AddonUpdateImagesResponse</a></code>
Methods:
- <code title="post /addons">client.addons.<a href="./src/resources/addons.ts">create</a>({ ...params }) -> AddonResponse</code>
- <code title="get /addons/{id}">client.addons.<a href="./src/resources/addons.ts">retrieve</a>(id) -> AddonResponse</code>
- <code title="patch /addons/{id}">client.addons.<a href="./src/resources/addons.ts">update</a>(id, { ...params }) -> AddonResponse</code>
- <code title="get /addons">client.addons.<a href="./src/resources/addons.ts">list</a>({ ...params }) -> AddonResponsesDefaultPageNumberPagination</code>
- <code title="put /addons/{id}/images">client.addons.<a href="./src/resources/addons.ts">updateImages</a>(id) -> AddonUpdateImagesResponse</code>
# Brands
Types:
- <code><a href="./src/resources/brands.ts">Brand</a></code>
- <code><a href="./src/resources/brands.ts">BrandListResponse</a></code>
- <code><a href="./src/resources/brands.ts">BrandUpdateImagesResponse</a></code>
Methods:
- <code title="post /brands">client.brands.<a href="./src/resources/brands.ts">create</a>({ ...params }) -> Brand</code>
- <code title="get /brands/{id}">client.brands.<a href="./src/resources/brands.ts">retrieve</a>(id) -> Brand</code>
- <code title="patch /brands/{id}">client.brands.<a href="./src/resources/brands.ts">update</a>(id, { ...params }) -> Brand</code>
- <code title="get /brands">client.brands.<a href="./src/resources/brands.ts">list</a>() -> BrandListResponse</code>
- <code title="put /brands/{id}/images">client.brands.<a href="./src/resources/brands.ts">updateImages</a>(id) -> BrandUpdateImagesResponse</code>
# Webhooks
Types:
- <code><a href="./src/resources/webhooks/webhooks.ts">WebhookDetails</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">WebhookRetrieveSecretResponse</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">DisputeAcceptedWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">DisputeCancelledWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">DisputeChallengedWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">DisputeExpiredWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">DisputeLostWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">DisputeOpenedWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">DisputeWonWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">LicenseKeyCreatedWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">PaymentCancelledWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">PaymentFailedWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">PaymentProcessingWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">PaymentSucceededWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">RefundFailedWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">RefundSucceededWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">SubscriptionActiveWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">SubscriptionCancelledWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">SubscriptionExpiredWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">SubscriptionFailedWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">SubscriptionOnHoldWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">SubscriptionPlanChangedWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">SubscriptionRenewedWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">DisputeAcceptedWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">DisputeCancelledWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">DisputeChallengedWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">DisputeExpiredWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">DisputeLostWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">DisputeOpenedWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">DisputeWonWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">LicenseKeyCreatedWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">PaymentCancelledWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">PaymentFailedWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">PaymentProcessingWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">PaymentSucceededWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">RefundFailedWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">RefundSucceededWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">SubscriptionActiveWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">SubscriptionCancelledWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">SubscriptionExpiredWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">SubscriptionFailedWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">SubscriptionOnHoldWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">SubscriptionPlanChangedWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">SubscriptionRenewedWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">UnsafeUnwrapWebhookEvent</a></code>
- <code><a href="./src/resources/webhooks/webhooks.ts">UnwrapWebhookEvent</a></code>
Methods:
- <code title="post /webhooks">client.webhooks.<a href="./src/resources/webhooks/webhooks.ts">create</a>({ ...params }) -> WebhookDetails</code>
- <code title="get /webhooks/{webhook_id}">client.webhooks.<a href="./src/resources/webhooks/webhooks.ts">retrieve</a>(webhookID) -> WebhookDetails</code>
- <code title="patch /webhooks/{webhook_id}">client.webhooks.<a href="./src/resources/webhooks/webhooks.ts">update</a>(webhookID, { ...params }) -> WebhookDetails</code>
- <code title="get /webhooks">client.webhooks.<a href="./src/resources/webhooks/webhooks.ts">list</a>({ ...params }) -> WebhookDetailsCursorPagePagination</code>
- <code title="delete /webhooks/{webhook_id}">client.webhooks.<a href="./src/resources/webhooks/webhooks.ts">delete</a>(webhookID) -> void</code>
- <code title="get /webhooks/{webhook_id}/secret">client.webhooks.<a href="./src/resources/webhooks/webhooks.ts">retrieveSecret</a>(webhookID) -> WebhookRetrieveSecretResponse</code>
- <code>client.webhooks.<a href="./src/resources/webhooks/webhooks.ts">unsafeUnwrap</a>(body) -> void</code>
- <code>client.webhooks.<a href="./src/resources/webhooks/webhooks.ts">unwrap</a>(body) -> void</code>
## Headers
Types:
- <code><a href="./src/resources/webhooks/headers.ts">HeaderRetrieveResponse</a></code>
Methods:
- <code title="get /webhooks/{webhook_id}/headers">client.webhooks.headers.<a href="./src/resources/webhooks/headers.ts">retrieve</a>(webhookID) -> HeaderRetrieveResponse</code>
- <code title="patch /webhooks/{webhook_id}/headers">client.webhooks.headers.<a href="./src/resources/webhooks/headers.ts">update</a>(webhookID, { ...params }) -> void</code>
# WebhookEvents
Types:
- <code><a href="./src/resources/webhook-events.ts">WebhookEventType</a></code>
- <code><a href="./src/resources/webhook-events.ts">WebhookPayload</a></code>
# UsageEvents
Types:
- <code><a href="./src/resources/usage-events.ts">Event</a></code>
- <code><a href="./src/resources/usage-events.ts">EventInput</a></code>
- <code><a href="./src/resources/usage-events.ts">UsageEventIngestResponse</a></code>
Methods:
- <code title="get /events/{event_id}">client.usageEvents.<a href="./src/resources/usage-events.ts">retrieve</a>(eventID) -> Event</code>
- <code title="get /events">client.usageEvents.<a href="./src/resources/usage-events.ts">list</a>({ ...params }) -> EventsDefaultPageNumberPagination</code>
- <code title="post /events/ingest">client.usageEvents.<a href="./src/resources/usage-events.ts">ingest</a>({ ...params }) -> UsageEventIngestResponse</code>
# Meters
Types:
- <code><a href="./src/resources/meters.ts">Meter</a></code>
- <code><a href="./src/resources/meters.ts">MeterAggregation</a></code>
- <code><a href="./src/resources/meters.ts">MeterFilter</a></code>
Methods:
- <code title="post /meters">client.meters.<a href="./src/resources/meters.ts">create</a>({ ...params }) -> Meter</code>
- <code title="get /meters/{id}">client.meters.<a href="./src/resources/meters.ts">retrieve</a>(id) -> Meter</code>
- <code title="get /meters">client.meters.<a href="./src/resources/meters.ts">list</a>({ ...params }) -> MetersDefaultPageNumberPagination</code>
- <code title="delete /meters/{id}">client.meters.<a href="./src/resources/meters.ts">archive</a>(id) -> void</code>
- <code title="post /meters/{id}/unarchive">client.meters.<a href="./src/resources/meters.ts">unarchive</a>(id) -> void</code>
```
--------------------------------------------------------------------------------
/tests/index.test.ts:
--------------------------------------------------------------------------------
```typescript
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIPromise } from 'dodopayments/core/api-promise';
import util from 'node:util';
import DodoPayments from 'dodopayments';
import { APIUserAbortError } from 'dodopayments';
const defaultFetch = fetch;
describe('instantiate client', () => {
const env = process.env;
beforeEach(() => {
jest.resetModules();
process.env = { ...env };
});
afterEach(() => {
process.env = env;
});
describe('defaultHeaders', () => {
const client = new DodoPayments({
baseURL: 'http://localhost:5000/',
defaultHeaders: { 'X-My-Default-Header': '2' },
bearerToken: 'My Bearer Token',
});
test('they are used in the request', async () => {
const { req } = await client.buildRequest({ path: '/foo', method: 'post' });
expect(req.headers.get('x-my-default-header')).toEqual('2');
});
test('can ignore `undefined` and leave the default', async () => {
const { req } = await client.buildRequest({
path: '/foo',
method: 'post',
headers: { 'X-My-Default-Header': undefined },
});
expect(req.headers.get('x-my-default-header')).toEqual('2');
});
test('can be removed with `null`', async () => {
const { req } = await client.buildRequest({
path: '/foo',
method: 'post',
headers: { 'X-My-Default-Header': null },
});
expect(req.headers.has('x-my-default-header')).toBe(false);
});
});
describe('logging', () => {
const env = process.env;
beforeEach(() => {
process.env = { ...env };
process.env['DODO_PAYMENTS_LOG'] = undefined;
});
afterEach(() => {
process.env = env;
});
const forceAPIResponseForClient = async (client: DodoPayments) => {
await new APIPromise(
client,
Promise.resolve({
response: new Response(),
controller: new AbortController(),
requestLogID: 'log_000000',
retryOfRequestLogID: undefined,
startTime: Date.now(),
options: {
method: 'get',
path: '/',
},
}),
);
};
test('debug logs when log level is debug', async () => {
const debugMock = jest.fn();
const logger = {
debug: debugMock,
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
};
const client = new DodoPayments({ logger: logger, logLevel: 'debug', bearerToken: 'My Bearer Token' });
await forceAPIResponseForClient(client);
expect(debugMock).toHaveBeenCalled();
});
test('default logLevel is warn', async () => {
const client = new DodoPayments({ bearerToken: 'My Bearer Token' });
expect(client.logLevel).toBe('warn');
});
test('debug logs are skipped when log level is info', async () => {
const debugMock = jest.fn();
const logger = {
debug: debugMock,
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
};
const client = new DodoPayments({ logger: logger, logLevel: 'info', bearerToken: 'My Bearer Token' });
await forceAPIResponseForClient(client);
expect(debugMock).not.toHaveBeenCalled();
});
test('debug logs happen with debug env var', async () => {
const debugMock = jest.fn();
const logger = {
debug: debugMock,
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
};
process.env['DODO_PAYMENTS_LOG'] = 'debug';
const client = new DodoPayments({ logger: logger, bearerToken: 'My Bearer Token' });
expect(client.logLevel).toBe('debug');
await forceAPIResponseForClient(client);
expect(debugMock).toHaveBeenCalled();
});
test('warn when env var level is invalid', async () => {
const warnMock = jest.fn();
const logger = {
debug: jest.fn(),
info: jest.fn(),
warn: warnMock,
error: jest.fn(),
};
process.env['DODO_PAYMENTS_LOG'] = 'not a log level';
const client = new DodoPayments({ logger: logger, bearerToken: 'My Bearer Token' });
expect(client.logLevel).toBe('warn');
expect(warnMock).toHaveBeenCalledWith(
'process.env[\'DODO_PAYMENTS_LOG\'] was set to "not a log level", expected one of ["off","error","warn","info","debug"]',
);
});
test('client log level overrides env var', async () => {
const debugMock = jest.fn();
const logger = {
debug: debugMock,
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
};
process.env['DODO_PAYMENTS_LOG'] = 'debug';
const client = new DodoPayments({ logger: logger, logLevel: 'off', bearerToken: 'My Bearer Token' });
await forceAPIResponseForClient(client);
expect(debugMock).not.toHaveBeenCalled();
});
test('no warning logged for invalid env var level + valid client level', async () => {
const warnMock = jest.fn();
const logger = {
debug: jest.fn(),
info: jest.fn(),
warn: warnMock,
error: jest.fn(),
};
process.env['DODO_PAYMENTS_LOG'] = 'not a log level';
const client = new DodoPayments({ logger: logger, logLevel: 'debug', bearerToken: 'My Bearer Token' });
expect(client.logLevel).toBe('debug');
expect(warnMock).not.toHaveBeenCalled();
});
});
describe('defaultQuery', () => {
test('with null query params given', () => {
const client = new DodoPayments({
baseURL: 'http://localhost:5000/',
defaultQuery: { apiVersion: 'foo' },
bearerToken: 'My Bearer Token',
});
expect(client.buildURL('/foo', null)).toEqual('http://localhost:5000/foo?apiVersion=foo');
});
test('multiple default query params', () => {
const client = new DodoPayments({
baseURL: 'http://localhost:5000/',
defaultQuery: { apiVersion: 'foo', hello: 'world' },
bearerToken: 'My Bearer Token',
});
expect(client.buildURL('/foo', null)).toEqual('http://localhost:5000/foo?apiVersion=foo&hello=world');
});
test('overriding with `undefined`', () => {
const client = new DodoPayments({
baseURL: 'http://localhost:5000/',
defaultQuery: { hello: 'world' },
bearerToken: 'My Bearer Token',
});
expect(client.buildURL('/foo', { hello: undefined })).toEqual('http://localhost:5000/foo');
});
});
test('custom fetch', async () => {
const client = new DodoPayments({
baseURL: 'http://localhost:5000/',
bearerToken: 'My Bearer Token',
fetch: (url) => {
return Promise.resolve(
new Response(JSON.stringify({ url, custom: true }), {
headers: { 'Content-Type': 'application/json' },
}),
);
},
});
const response = await client.get('/foo');
expect(response).toEqual({ url: 'http://localhost:5000/foo', custom: true });
});
test('explicit global fetch', async () => {
// make sure the global fetch type is assignable to our Fetch type
const client = new DodoPayments({
baseURL: 'http://localhost:5000/',
bearerToken: 'My Bearer Token',
fetch: defaultFetch,
});
});
test('custom signal', async () => {
const client = new DodoPayments({
baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010',
bearerToken: 'My Bearer Token',
fetch: (...args) => {
return new Promise((resolve, reject) =>
setTimeout(
() =>
defaultFetch(...args)
.then(resolve)
.catch(reject),
300,
),
);
},
});
const controller = new AbortController();
setTimeout(() => controller.abort(), 200);
const spy = jest.spyOn(client, 'request');
await expect(client.get('/foo', { signal: controller.signal })).rejects.toThrowError(APIUserAbortError);
expect(spy).toHaveBeenCalledTimes(1);
});
test('normalized method', async () => {
let capturedRequest: RequestInit | undefined;
const testFetch = async (url: string | URL | Request, init: RequestInit = {}): Promise<Response> => {
capturedRequest = init;
return new Response(JSON.stringify({}), { headers: { 'Content-Type': 'application/json' } });
};
const client = new DodoPayments({
baseURL: 'http://localhost:5000/',
bearerToken: 'My Bearer Token',
fetch: testFetch,
});
await client.patch('/foo');
expect(capturedRequest?.method).toEqual('PATCH');
});
describe('baseUrl', () => {
test('trailing slash', () => {
const client = new DodoPayments({
baseURL: 'http://localhost:5000/custom/path/',
bearerToken: 'My Bearer Token',
});
expect(client.buildURL('/foo', null)).toEqual('http://localhost:5000/custom/path/foo');
});
test('no trailing slash', () => {
const client = new DodoPayments({
baseURL: 'http://localhost:5000/custom/path',
bearerToken: 'My Bearer Token',
});
expect(client.buildURL('/foo', null)).toEqual('http://localhost:5000/custom/path/foo');
});
afterEach(() => {
process.env['DODO_PAYMENTS_BASE_URL'] = undefined;
});
test('explicit option', () => {
const client = new DodoPayments({ baseURL: 'https://example.com', bearerToken: 'My Bearer Token' });
expect(client.baseURL).toEqual('https://example.com');
});
test('env variable', () => {
process.env['DODO_PAYMENTS_BASE_URL'] = 'https://example.com/from_env';
const client = new DodoPayments({ bearerToken: 'My Bearer Token' });
expect(client.baseURL).toEqual('https://example.com/from_env');
});
test('empty env variable', () => {
process.env['DODO_PAYMENTS_BASE_URL'] = ''; // empty
const client = new DodoPayments({ bearerToken: 'My Bearer Token' });
expect(client.baseURL).toEqual('https://live.dodopayments.com');
});
test('blank env variable', () => {
process.env['DODO_PAYMENTS_BASE_URL'] = ' '; // blank
const client = new DodoPayments({ bearerToken: 'My Bearer Token' });
expect(client.baseURL).toEqual('https://live.dodopayments.com');
});
test('env variable with environment', () => {
process.env['DODO_PAYMENTS_BASE_URL'] = 'https://example.com/from_env';
expect(
() => new DodoPayments({ bearerToken: 'My Bearer Token', environment: 'live_mode' }),
).toThrowErrorMatchingInlineSnapshot(
`"Ambiguous URL; The \`baseURL\` option (or DODO_PAYMENTS_BASE_URL env var) and the \`environment\` option are given. If you want to use the environment you must pass baseURL: null"`,
);
const client = new DodoPayments({
bearerToken: 'My Bearer Token',
baseURL: null,
environment: 'live_mode',
});
expect(client.baseURL).toEqual('https://live.dodopayments.com');
});
test('in request options', () => {
const client = new DodoPayments({ bearerToken: 'My Bearer Token' });
expect(client.buildURL('/foo', null, 'http://localhost:5000/option')).toEqual(
'http://localhost:5000/option/foo',
);
});
test('in request options overridden by client options', () => {
const client = new DodoPayments({
bearerToken: 'My Bearer Token',
baseURL: 'http://localhost:5000/client',
});
expect(client.buildURL('/foo', null, 'http://localhost:5000/option')).toEqual(
'http://localhost:5000/client/foo',
);
});
test('in request options overridden by env variable', () => {
process.env['DODO_PAYMENTS_BASE_URL'] = 'http://localhost:5000/env';
const client = new DodoPayments({ bearerToken: 'My Bearer Token' });
expect(client.buildURL('/foo', null, 'http://localhost:5000/option')).toEqual(
'http://localhost:5000/env/foo',
);
});
});
test('maxRetries option is correctly set', () => {
const client = new DodoPayments({ maxRetries: 4, bearerToken: 'My Bearer Token' });
expect(client.maxRetries).toEqual(4);
// default
const client2 = new DodoPayments({ bearerToken: 'My Bearer Token' });
expect(client2.maxRetries).toEqual(2);
});
describe('withOptions', () => {
test('creates a new client with overridden options', async () => {
const client = new DodoPayments({
baseURL: 'http://localhost:5000/',
maxRetries: 3,
bearerToken: 'My Bearer Token',
});
const newClient = client.withOptions({
maxRetries: 5,
baseURL: 'http://localhost:5001/',
});
// Verify the new client has updated options
expect(newClient.maxRetries).toEqual(5);
expect(newClient.baseURL).toEqual('http://localhost:5001/');
// Verify the original client is unchanged
expect(client.maxRetries).toEqual(3);
expect(client.baseURL).toEqual('http://localhost:5000/');
// Verify it's a different instance
expect(newClient).not.toBe(client);
expect(newClient.constructor).toBe(client.constructor);
});
test('inherits options from the parent client', async () => {
const client = new DodoPayments({
baseURL: 'http://localhost:5000/',
defaultHeaders: { 'X-Test-Header': 'test-value' },
defaultQuery: { 'test-param': 'test-value' },
bearerToken: 'My Bearer Token',
});
const newClient = client.withOptions({
baseURL: 'http://localhost:5001/',
});
// Test inherited options remain the same
expect(newClient.buildURL('/foo', null)).toEqual('http://localhost:5001/foo?test-param=test-value');
const { req } = await newClient.buildRequest({ path: '/foo', method: 'get' });
expect(req.headers.get('x-test-header')).toEqual('test-value');
});
test('respects runtime property changes when creating new client', () => {
const client = new DodoPayments({
baseURL: 'http://localhost:5000/',
timeout: 1000,
bearerToken: 'My Bearer Token',
});
// Modify the client properties directly after creation
client.baseURL = 'http://localhost:6000/';
client.timeout = 2000;
// Create a new client with withOptions
const newClient = client.withOptions({
maxRetries: 10,
});
// Verify the new client uses the updated properties, not the original ones
expect(newClient.baseURL).toEqual('http://localhost:6000/');
expect(newClient.timeout).toEqual(2000);
expect(newClient.maxRetries).toEqual(10);
// Original client should still have its modified properties
expect(client.baseURL).toEqual('http://localhost:6000/');
expect(client.timeout).toEqual(2000);
expect(client.maxRetries).not.toEqual(10);
// Verify URL building uses the updated baseURL
expect(newClient.buildURL('/bar', null)).toEqual('http://localhost:6000/bar');
});
});
test('with environment variable arguments', () => {
// set options via env var
process.env['DODO_PAYMENTS_API_KEY'] = 'My Bearer Token';
const client = new DodoPayments();
expect(client.bearerToken).toBe('My Bearer Token');
});
test('with overridden environment variable arguments', () => {
// set options via env var
process.env['DODO_PAYMENTS_API_KEY'] = 'another My Bearer Token';
const client = new DodoPayments({ bearerToken: 'My Bearer Token' });
expect(client.bearerToken).toBe('My Bearer Token');
});
});
describe('request building', () => {
const client = new DodoPayments({ bearerToken: 'My Bearer Token' });
describe('custom headers', () => {
test('handles undefined', async () => {
const { req } = await client.buildRequest({
path: '/foo',
method: 'post',
body: { value: 'hello' },
headers: { 'X-Foo': 'baz', 'x-foo': 'bar', 'x-Foo': undefined, 'x-baz': 'bam', 'X-Baz': null },
});
expect(req.headers.get('x-foo')).toEqual('bar');
expect(req.headers.get('x-Foo')).toEqual('bar');
expect(req.headers.get('X-Foo')).toEqual('bar');
expect(req.headers.get('x-baz')).toEqual(null);
});
});
});
describe('default encoder', () => {
const client = new DodoPayments({ bearerToken: 'My Bearer Token' });
class Serializable {
toJSON() {
return { $type: 'Serializable' };
}
}
class Collection<T> {
#things: T[];
constructor(things: T[]) {
this.#things = Array.from(things);
}
toJSON() {
return Array.from(this.#things);
}
[Symbol.iterator]() {
return this.#things[Symbol.iterator];
}
}
for (const jsonValue of [{}, [], { __proto__: null }, new Serializable(), new Collection(['item'])]) {
test(`serializes ${util.inspect(jsonValue)} as json`, async () => {
const { req } = await client.buildRequest({
path: '/foo',
method: 'post',
body: jsonValue,
});
expect(req.headers).toBeInstanceOf(Headers);
expect(req.headers.get('content-type')).toEqual('application/json');
expect(req.body).toBe(JSON.stringify(jsonValue));
});
}
const encoder = new TextEncoder();
const asyncIterable = (async function* () {
yield encoder.encode('a\n');
yield encoder.encode('b\n');
yield encoder.encode('c\n');
})();
for (const streamValue of [
[encoder.encode('a\nb\nc\n')][Symbol.iterator](),
new Response('a\nb\nc\n').body,
asyncIterable,
]) {
test(`converts ${util.inspect(streamValue)} to ReadableStream`, async () => {
const { req } = await client.buildRequest({
path: '/foo',
method: 'post',
body: streamValue,
});
expect(req.headers).toBeInstanceOf(Headers);
expect(req.headers.get('content-type')).toEqual(null);
expect(req.body).toBeInstanceOf(ReadableStream);
expect(await new Response(req.body).text()).toBe('a\nb\nc\n');
});
}
test(`can set content-type for ReadableStream`, async () => {
const { req } = await client.buildRequest({
path: '/foo',
method: 'post',
body: new Response('a\nb\nc\n').body,
headers: { 'Content-Type': 'text/plain' },
});
expect(req.headers).toBeInstanceOf(Headers);
expect(req.headers.get('content-type')).toEqual('text/plain');
expect(req.body).toBeInstanceOf(ReadableStream);
expect(await new Response(req.body).text()).toBe('a\nb\nc\n');
});
});
describe('retries', () => {
test('retry on timeout', async () => {
let count = 0;
const testFetch = async (
url: string | URL | Request,
{ signal }: RequestInit = {},
): Promise<Response> => {
if (count++ === 0) {
return new Promise(
(resolve, reject) => signal?.addEventListener('abort', () => reject(new Error('timed out'))),
);
}
return new Response(JSON.stringify({ a: 1 }), { headers: { 'Content-Type': 'application/json' } });
};
const client = new DodoPayments({ bearerToken: 'My Bearer Token', timeout: 10, fetch: testFetch });
expect(await client.request({ path: '/foo', method: 'get' })).toEqual({ a: 1 });
expect(count).toEqual(2);
expect(
await client
.request({ path: '/foo', method: 'get' })
.asResponse()
.then((r) => r.text()),
).toEqual(JSON.stringify({ a: 1 }));
expect(count).toEqual(3);
});
test('retry count header', async () => {
let count = 0;
let capturedRequest: RequestInit | undefined;
const testFetch = async (url: string | URL | Request, init: RequestInit = {}): Promise<Response> => {
count++;
if (count <= 2) {
return new Response(undefined, {
status: 429,
headers: {
'Retry-After': '0.1',
},
});
}
capturedRequest = init;
return new Response(JSON.stringify({ a: 1 }), { headers: { 'Content-Type': 'application/json' } });
};
const client = new DodoPayments({ bearerToken: 'My Bearer Token', fetch: testFetch, maxRetries: 4 });
expect(await client.request({ path: '/foo', method: 'get' })).toEqual({ a: 1 });
expect((capturedRequest!.headers as Headers).get('x-stainless-retry-count')).toEqual('2');
expect(count).toEqual(3);
});
test('omit retry count header', async () => {
let count = 0;
let capturedRequest: RequestInit | undefined;
const testFetch = async (url: string | URL | Request, init: RequestInit = {}): Promise<Response> => {
count++;
if (count <= 2) {
return new Response(undefined, {
status: 429,
headers: {
'Retry-After': '0.1',
},
});
}
capturedRequest = init;
return new Response(JSON.stringify({ a: 1 }), { headers: { 'Content-Type': 'application/json' } });
};
const client = new DodoPayments({ bearerToken: 'My Bearer Token', fetch: testFetch, maxRetries: 4 });
expect(
await client.request({
path: '/foo',
method: 'get',
headers: { 'X-Stainless-Retry-Count': null },
}),
).toEqual({ a: 1 });
expect((capturedRequest!.headers as Headers).has('x-stainless-retry-count')).toBe(false);
});
test('omit retry count header by default', async () => {
let count = 0;
let capturedRequest: RequestInit | undefined;
const testFetch = async (url: string | URL | Request, init: RequestInit = {}): Promise<Response> => {
count++;
if (count <= 2) {
return new Response(undefined, {
status: 429,
headers: {
'Retry-After': '0.1',
},
});
}
capturedRequest = init;
return new Response(JSON.stringify({ a: 1 }), { headers: { 'Content-Type': 'application/json' } });
};
const client = new DodoPayments({
bearerToken: 'My Bearer Token',
fetch: testFetch,
maxRetries: 4,
defaultHeaders: { 'X-Stainless-Retry-Count': null },
});
expect(
await client.request({
path: '/foo',
method: 'get',
}),
).toEqual({ a: 1 });
expect(capturedRequest!.headers as Headers).not.toHaveProperty('x-stainless-retry-count');
});
test('overwrite retry count header', async () => {
let count = 0;
let capturedRequest: RequestInit | undefined;
const testFetch = async (url: string | URL | Request, init: RequestInit = {}): Promise<Response> => {
count++;
if (count <= 2) {
return new Response(undefined, {
status: 429,
headers: {
'Retry-After': '0.1',
},
});
}
capturedRequest = init;
return new Response(JSON.stringify({ a: 1 }), { headers: { 'Content-Type': 'application/json' } });
};
const client = new DodoPayments({ bearerToken: 'My Bearer Token', fetch: testFetch, maxRetries: 4 });
expect(
await client.request({
path: '/foo',
method: 'get',
headers: { 'X-Stainless-Retry-Count': '42' },
}),
).toEqual({ a: 1 });
expect((capturedRequest!.headers as Headers).get('x-stainless-retry-count')).toEqual('42');
});
test('retry on 429 with retry-after', async () => {
let count = 0;
const testFetch = async (
url: string | URL | Request,
{ signal }: RequestInit = {},
): Promise<Response> => {
if (count++ === 0) {
return new Response(undefined, {
status: 429,
headers: {
'Retry-After': '0.1',
},
});
}
return new Response(JSON.stringify({ a: 1 }), { headers: { 'Content-Type': 'application/json' } });
};
const client = new DodoPayments({ bearerToken: 'My Bearer Token', fetch: testFetch });
expect(await client.request({ path: '/foo', method: 'get' })).toEqual({ a: 1 });
expect(count).toEqual(2);
expect(
await client
.request({ path: '/foo', method: 'get' })
.asResponse()
.then((r) => r.text()),
).toEqual(JSON.stringify({ a: 1 }));
expect(count).toEqual(3);
});
test('retry on 429 with retry-after-ms', async () => {
let count = 0;
const testFetch = async (
url: string | URL | Request,
{ signal }: RequestInit = {},
): Promise<Response> => {
if (count++ === 0) {
return new Response(undefined, {
status: 429,
headers: {
'Retry-After-Ms': '10',
},
});
}
return new Response(JSON.stringify({ a: 1 }), { headers: { 'Content-Type': 'application/json' } });
};
const client = new DodoPayments({ bearerToken: 'My Bearer Token', fetch: testFetch });
expect(await client.request({ path: '/foo', method: 'get' })).toEqual({ a: 1 });
expect(count).toEqual(2);
expect(
await client
.request({ path: '/foo', method: 'get' })
.asResponse()
.then((r) => r.text()),
).toEqual(JSON.stringify({ a: 1 }));
expect(count).toEqual(3);
});
});
```
--------------------------------------------------------------------------------
/packages/mcp-server/tests/compat.test.ts:
--------------------------------------------------------------------------------
```typescript
import {
truncateToolNames,
removeTopLevelUnions,
removeAnyOf,
inlineRefs,
applyCompatibilityTransformations,
removeFormats,
findUsedDefs,
} from '../src/compat';
import { Tool } from '@modelcontextprotocol/sdk/types.js';
import { JSONSchema } from '../src/compat';
import { Endpoint } from '../src/tools';
describe('truncateToolNames', () => {
it('should return original names when maxLength is 0 or negative', () => {
const names = ['tool1', 'tool2', 'tool3'];
expect(truncateToolNames(names, 0)).toEqual(new Map());
expect(truncateToolNames(names, -1)).toEqual(new Map());
});
it('should return original names when all names are shorter than maxLength', () => {
const names = ['tool1', 'tool2', 'tool3'];
expect(truncateToolNames(names, 10)).toEqual(new Map());
});
it('should truncate names longer than maxLength', () => {
const names = ['very-long-tool-name', 'another-long-tool-name', 'short'];
expect(truncateToolNames(names, 10)).toEqual(
new Map([
['very-long-tool-name', 'very-long-'],
['another-long-tool-name', 'another-lo'],
]),
);
});
it('should handle duplicate truncated names by appending numbers', () => {
const names = ['tool-name-a', 'tool-name-b', 'tool-name-c'];
expect(truncateToolNames(names, 8)).toEqual(
new Map([
['tool-name-a', 'tool-na1'],
['tool-name-b', 'tool-na2'],
['tool-name-c', 'tool-na3'],
]),
);
});
});
describe('removeTopLevelUnions', () => {
const createTestTool = (overrides = {}): Tool => ({
name: 'test-tool',
description: 'Test tool',
inputSchema: {
type: 'object',
properties: {},
},
...overrides,
});
it('should return the original tool if it has no anyOf at the top level', () => {
const tool = createTestTool({
inputSchema: {
type: 'object',
properties: {
foo: { type: 'string' },
},
},
});
expect(removeTopLevelUnions(tool)).toEqual([tool]);
});
it('should split a tool with top-level anyOf into multiple tools', () => {
const tool = createTestTool({
name: 'union-tool',
description: 'A tool with unions',
inputSchema: {
type: 'object',
properties: {
common: { type: 'string' },
},
anyOf: [
{
title: 'first variant',
description: 'Its the first variant',
properties: {
variant1: { type: 'string' },
},
required: ['variant1'],
},
{
title: 'second variant',
properties: {
variant2: { type: 'number' },
},
required: ['variant2'],
},
],
},
});
const result = removeTopLevelUnions(tool);
expect(result).toEqual([
{
name: 'union-tool_first_variant',
description: 'Its the first variant',
inputSchema: {
type: 'object',
title: 'first variant',
description: 'Its the first variant',
properties: {
common: { type: 'string' },
variant1: { type: 'string' },
},
required: ['variant1'],
},
},
{
name: 'union-tool_second_variant',
description: 'A tool with unions',
inputSchema: {
type: 'object',
title: 'second variant',
description: 'A tool with unions',
properties: {
common: { type: 'string' },
variant2: { type: 'number' },
},
required: ['variant2'],
},
},
]);
});
it('should handle $defs and only include those used by the variant', () => {
const tool = createTestTool({
name: 'defs-tool',
description: 'A tool with $defs',
inputSchema: {
type: 'object',
properties: {
common: { type: 'string' },
},
$defs: {
def1: { type: 'string', format: 'email' },
def2: { type: 'number', minimum: 0 },
unused: { type: 'boolean' },
},
anyOf: [
{
properties: {
email: { $ref: '#/$defs/def1' },
},
},
{
properties: {
count: { $ref: '#/$defs/def2' },
},
},
],
},
});
const result = removeTopLevelUnions(tool);
expect(result).toEqual([
{
name: 'defs-tool_variant1',
description: 'A tool with $defs',
inputSchema: {
type: 'object',
description: 'A tool with $defs',
properties: {
common: { type: 'string' },
email: { $ref: '#/$defs/def1' },
},
$defs: {
def1: { type: 'string', format: 'email' },
},
},
},
{
name: 'defs-tool_variant2',
description: 'A tool with $defs',
inputSchema: {
type: 'object',
description: 'A tool with $defs',
properties: {
common: { type: 'string' },
count: { $ref: '#/$defs/def2' },
},
$defs: {
def2: { type: 'number', minimum: 0 },
},
},
},
]);
});
});
describe('removeAnyOf', () => {
it('should return original schema if it has no anyOf', () => {
const schema = {
type: 'object',
properties: {
foo: { type: 'string' },
bar: { type: 'number' },
},
};
expect(removeAnyOf(schema)).toEqual(schema);
});
it('should remove anyOf field and use the first variant', () => {
const schema = {
type: 'object',
properties: {
common: { type: 'string' },
},
anyOf: [
{
properties: {
variant1: { type: 'string' },
},
required: ['variant1'],
},
{
properties: {
variant2: { type: 'number' },
},
required: ['variant2'],
},
],
};
const expected = {
type: 'object',
properties: {
common: { type: 'string' },
variant1: { type: 'string' },
},
required: ['variant1'],
};
expect(removeAnyOf(schema)).toEqual(expected);
});
it('should recursively remove anyOf fields from nested properties', () => {
const schema = {
type: 'object',
properties: {
foo: { type: 'string' },
nested: {
type: 'object',
properties: {
bar: { type: 'number' },
},
anyOf: [
{
properties: {
option1: { type: 'boolean' },
},
},
{
properties: {
option2: { type: 'array' },
},
},
],
},
},
};
const expected = {
type: 'object',
properties: {
foo: { type: 'string' },
nested: {
type: 'object',
properties: {
bar: { type: 'number' },
option1: { type: 'boolean' },
},
},
},
};
expect(removeAnyOf(schema)).toEqual(expected);
});
it('should handle arrays', () => {
const schema = {
type: 'object',
properties: {
items: {
type: 'array',
items: {
anyOf: [{ type: 'string' }, { type: 'number' }],
},
},
},
};
const expected = {
type: 'object',
properties: {
items: {
type: 'array',
items: {
type: 'string',
},
},
},
};
expect(removeAnyOf(schema)).toEqual(expected);
});
});
describe('findUsedDefs', () => {
it('should handle circular references without stack overflow', () => {
const defs = {
person: {
type: 'object',
properties: {
name: { type: 'string' },
friend: { $ref: '#/$defs/person' }, // Circular reference
},
},
};
const schema = {
type: 'object',
properties: {
user: { $ref: '#/$defs/person' },
},
};
// This should not throw a stack overflow error
expect(() => {
const result = findUsedDefs(schema, defs);
expect(result).toHaveProperty('person');
}).not.toThrow();
});
it('should handle indirect circular references without stack overflow', () => {
const defs = {
node: {
type: 'object',
properties: {
value: { type: 'string' },
child: { $ref: '#/$defs/childNode' },
},
},
childNode: {
type: 'object',
properties: {
value: { type: 'string' },
parent: { $ref: '#/$defs/node' }, // Indirect circular reference
},
},
};
const schema = {
type: 'object',
properties: {
root: { $ref: '#/$defs/node' },
},
};
// This should not throw a stack overflow error
expect(() => {
const result = findUsedDefs(schema, defs);
expect(result).toHaveProperty('node');
expect(result).toHaveProperty('childNode');
}).not.toThrow();
});
it('should find all used definitions in non-circular schemas', () => {
const defs = {
user: {
type: 'object',
properties: {
name: { type: 'string' },
address: { $ref: '#/$defs/address' },
},
},
address: {
type: 'object',
properties: {
street: { type: 'string' },
city: { type: 'string' },
},
},
unused: {
type: 'object',
properties: {
data: { type: 'string' },
},
},
};
const schema = {
type: 'object',
properties: {
person: { $ref: '#/$defs/user' },
},
};
const result = findUsedDefs(schema, defs);
expect(result).toHaveProperty('user');
expect(result).toHaveProperty('address');
expect(result).not.toHaveProperty('unused');
});
});
describe('inlineRefs', () => {
it('should return the original schema if it does not contain $refs', () => {
const schema: JSONSchema = {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'number' },
},
};
expect(inlineRefs(schema)).toEqual(schema);
});
it('should inline simple $refs', () => {
const schema: JSONSchema = {
type: 'object',
properties: {
user: { $ref: '#/$defs/user' },
},
$defs: {
user: {
type: 'object',
properties: {
name: { type: 'string' },
email: { type: 'string' },
},
},
},
};
const expected: JSONSchema = {
type: 'object',
properties: {
user: {
type: 'object',
properties: {
name: { type: 'string' },
email: { type: 'string' },
},
},
},
};
expect(inlineRefs(schema)).toEqual(expected);
});
it('should inline nested $refs', () => {
const schema: JSONSchema = {
type: 'object',
properties: {
order: { $ref: '#/$defs/order' },
},
$defs: {
order: {
type: 'object',
properties: {
id: { type: 'string' },
items: { type: 'array', items: { $ref: '#/$defs/item' } },
},
},
item: {
type: 'object',
properties: {
product: { type: 'string' },
quantity: { type: 'integer' },
},
},
},
};
const expected: JSONSchema = {
type: 'object',
properties: {
order: {
type: 'object',
properties: {
id: { type: 'string' },
items: {
type: 'array',
items: {
type: 'object',
properties: {
product: { type: 'string' },
quantity: { type: 'integer' },
},
},
},
},
},
},
};
expect(inlineRefs(schema)).toEqual(expected);
});
it('should handle circular references by removing the circular part', () => {
const schema: JSONSchema = {
type: 'object',
properties: {
person: { $ref: '#/$defs/person' },
},
$defs: {
person: {
type: 'object',
properties: {
name: { type: 'string' },
friend: { $ref: '#/$defs/person' }, // Circular reference
},
},
},
};
const expected: JSONSchema = {
type: 'object',
properties: {
person: {
type: 'object',
properties: {
name: { type: 'string' },
// friend property is removed to break the circular reference
},
},
},
};
expect(inlineRefs(schema)).toEqual(expected);
});
it('should handle indirect circular references', () => {
const schema: JSONSchema = {
type: 'object',
properties: {
node: { $ref: '#/$defs/node' },
},
$defs: {
node: {
type: 'object',
properties: {
value: { type: 'string' },
child: { $ref: '#/$defs/childNode' },
},
},
childNode: {
type: 'object',
properties: {
value: { type: 'string' },
parent: { $ref: '#/$defs/node' }, // Circular reference through childNode
},
},
},
};
const expected: JSONSchema = {
type: 'object',
properties: {
node: {
type: 'object',
properties: {
value: { type: 'string' },
child: {
type: 'object',
properties: {
value: { type: 'string' },
// parent property is removed to break the circular reference
},
},
},
},
},
};
expect(inlineRefs(schema)).toEqual(expected);
});
it('should preserve other properties when inlining references', () => {
const schema: JSONSchema = {
type: 'object',
properties: {
address: { $ref: '#/$defs/address', description: 'User address' },
},
$defs: {
address: {
type: 'object',
properties: {
street: { type: 'string' },
city: { type: 'string' },
},
required: ['street'],
},
},
};
const expected: JSONSchema = {
type: 'object',
properties: {
address: {
type: 'object',
description: 'User address',
properties: {
street: { type: 'string' },
city: { type: 'string' },
},
required: ['street'],
},
},
};
expect(inlineRefs(schema)).toEqual(expected);
});
});
describe('removeFormats', () => {
it('should return original schema if formats capability is true', () => {
const schema = {
type: 'object',
properties: {
date: { type: 'string', description: 'A date field', format: 'date' },
email: { type: 'string', description: 'An email field', format: 'email' },
},
};
expect(removeFormats(schema, true)).toEqual(schema);
});
it('should move format to description when formats capability is false', () => {
const schema = {
type: 'object',
properties: {
date: { type: 'string', description: 'A date field', format: 'date' },
email: { type: 'string', description: 'An email field', format: 'email' },
},
};
const expected = {
type: 'object',
properties: {
date: { type: 'string', description: 'A date field (format: "date")' },
email: { type: 'string', description: 'An email field (format: "email")' },
},
};
expect(removeFormats(schema, false)).toEqual(expected);
});
it('should handle properties without description', () => {
const schema = {
type: 'object',
properties: {
date: { type: 'string', format: 'date' },
},
};
const expected = {
type: 'object',
properties: {
date: { type: 'string', description: '(format: "date")' },
},
};
expect(removeFormats(schema, false)).toEqual(expected);
});
it('should handle nested properties', () => {
const schema = {
type: 'object',
properties: {
user: {
type: 'object',
properties: {
created_at: { type: 'string', description: 'Creation date', format: 'date-time' },
},
},
},
};
const expected = {
type: 'object',
properties: {
user: {
type: 'object',
properties: {
created_at: { type: 'string', description: 'Creation date (format: "date-time")' },
},
},
},
};
expect(removeFormats(schema, false)).toEqual(expected);
});
it('should handle arrays of objects', () => {
const schema = {
type: 'object',
properties: {
dates: {
type: 'array',
items: {
type: 'object',
properties: {
start: { type: 'string', description: 'Start date', format: 'date' },
end: { type: 'string', description: 'End date', format: 'date' },
},
},
},
},
};
const expected = {
type: 'object',
properties: {
dates: {
type: 'array',
items: {
type: 'object',
properties: {
start: { type: 'string', description: 'Start date (format: "date")' },
end: { type: 'string', description: 'End date (format: "date")' },
},
},
},
},
};
expect(removeFormats(schema, false)).toEqual(expected);
});
it('should handle schemas with $defs', () => {
const schema = {
type: 'object',
properties: {
date: { type: 'string', description: 'A date field', format: 'date' },
},
$defs: {
timestamp: {
type: 'string',
description: 'A timestamp field',
format: 'date-time',
},
},
};
const expected = {
type: 'object',
properties: {
date: { type: 'string', description: 'A date field (format: "date")' },
},
$defs: {
timestamp: {
type: 'string',
description: 'A timestamp field (format: "date-time")',
},
},
};
expect(removeFormats(schema, false)).toEqual(expected);
});
});
describe('applyCompatibilityTransformations', () => {
const createTestTool = (name: string, overrides = {}): Tool => ({
name,
description: 'Test tool',
inputSchema: {
type: 'object',
properties: {},
},
...overrides,
});
const createTestEndpoint = (tool: Tool): Endpoint => ({
tool,
handler: jest.fn(),
metadata: {
resource: 'test',
operation: 'read' as const,
tags: [],
},
});
it('should not modify endpoints when all capabilities are enabled', () => {
const tool = createTestTool('test-tool');
const endpoints = [createTestEndpoint(tool)];
const capabilities = {
topLevelUnions: true,
validJson: true,
refs: true,
unions: true,
formats: true,
toolNameLength: undefined,
};
const transformed = applyCompatibilityTransformations(endpoints, capabilities);
expect(transformed).toEqual(endpoints);
});
it('should split tools with top-level unions when topLevelUnions is disabled', () => {
const tool = createTestTool('union-tool', {
inputSchema: {
type: 'object',
properties: {
common: { type: 'string' },
},
anyOf: [
{
title: 'first variant',
properties: {
variant1: { type: 'string' },
},
},
{
title: 'second variant',
properties: {
variant2: { type: 'number' },
},
},
],
},
});
const endpoints = [createTestEndpoint(tool)];
const capabilities = {
topLevelUnions: false,
validJson: true,
refs: true,
unions: true,
formats: true,
toolNameLength: undefined,
};
const transformed = applyCompatibilityTransformations(endpoints, capabilities);
expect(transformed.length).toBe(2);
expect(transformed[0]!.tool.name).toBe('union-tool_first_variant');
expect(transformed[1]!.tool.name).toBe('union-tool_second_variant');
});
it('should handle variants without titles in removeTopLevelUnions', () => {
const tool = createTestTool('union-tool', {
inputSchema: {
type: 'object',
properties: {
common: { type: 'string' },
},
anyOf: [
{
properties: {
variant1: { type: 'string' },
},
},
{
properties: {
variant2: { type: 'number' },
},
},
],
},
});
const endpoints = [createTestEndpoint(tool)];
const capabilities = {
topLevelUnions: false,
validJson: true,
refs: true,
unions: true,
formats: true,
toolNameLength: undefined,
};
const transformed = applyCompatibilityTransformations(endpoints, capabilities);
expect(transformed.length).toBe(2);
expect(transformed[0]!.tool.name).toBe('union-tool_variant1');
expect(transformed[1]!.tool.name).toBe('union-tool_variant2');
});
it('should truncate tool names when toolNameLength is set', () => {
const tools = [
createTestTool('very-long-tool-name-that-exceeds-limit'),
createTestTool('another-long-tool-name-to-truncate'),
createTestTool('short-name'),
];
const endpoints = tools.map(createTestEndpoint);
const capabilities = {
topLevelUnions: true,
validJson: true,
refs: true,
unions: true,
formats: true,
toolNameLength: 20,
};
const transformed = applyCompatibilityTransformations(endpoints, capabilities);
expect(transformed[0]!.tool.name).toBe('very-long-tool-name-');
expect(transformed[1]!.tool.name).toBe('another-long-tool-na');
expect(transformed[2]!.tool.name).toBe('short-name');
});
it('should inline refs when refs capability is disabled', () => {
const tool = createTestTool('ref-tool', {
inputSchema: {
type: 'object',
properties: {
user: { $ref: '#/$defs/user' },
},
$defs: {
user: {
type: 'object',
properties: {
name: { type: 'string' },
email: { type: 'string' },
},
},
},
},
});
const endpoints = [createTestEndpoint(tool)];
const capabilities = {
topLevelUnions: true,
validJson: true,
refs: false,
unions: true,
formats: true,
toolNameLength: undefined,
};
const transformed = applyCompatibilityTransformations(endpoints, capabilities);
const schema = transformed[0]!.tool.inputSchema as JSONSchema;
expect(schema.$defs).toBeUndefined();
if (schema.properties) {
expect(schema.properties['user']).toEqual({
type: 'object',
properties: {
name: { type: 'string' },
email: { type: 'string' },
},
});
}
});
it('should preserve external refs when inlining', () => {
const tool = createTestTool('ref-tool', {
inputSchema: {
type: 'object',
properties: {
internal: { $ref: '#/$defs/internal' },
external: { $ref: 'https://example.com/schemas/external.json' },
},
$defs: {
internal: {
type: 'object',
properties: {
name: { type: 'string' },
},
},
},
},
});
const endpoints = [createTestEndpoint(tool)];
const capabilities = {
topLevelUnions: true,
validJson: true,
refs: false,
unions: true,
formats: true,
toolNameLength: undefined,
};
const transformed = applyCompatibilityTransformations(endpoints, capabilities);
const schema = transformed[0]!.tool.inputSchema as JSONSchema;
if (schema.properties) {
expect(schema.properties['internal']).toEqual({
type: 'object',
properties: {
name: { type: 'string' },
},
});
expect(schema.properties['external']).toEqual({
$ref: 'https://example.com/schemas/external.json',
});
}
});
it('should remove anyOf fields when unions capability is disabled', () => {
const tool = createTestTool('union-tool', {
inputSchema: {
type: 'object',
properties: {
field: {
anyOf: [{ type: 'string' }, { type: 'number' }],
},
},
},
});
const endpoints = [createTestEndpoint(tool)];
const capabilities = {
topLevelUnions: true,
validJson: true,
refs: true,
unions: false,
formats: true,
toolNameLength: undefined,
};
const transformed = applyCompatibilityTransformations(endpoints, capabilities);
const schema = transformed[0]!.tool.inputSchema as JSONSchema;
if (schema.properties && schema.properties['field']) {
const field = schema.properties['field'];
expect(field.anyOf).toBeUndefined();
expect(field.type).toBe('string');
}
});
it('should correctly combine topLevelUnions and toolNameLength transformations', () => {
const tool = createTestTool('very-long-union-tool-name', {
inputSchema: {
type: 'object',
properties: {
common: { type: 'string' },
},
anyOf: [
{
title: 'first variant',
properties: {
variant1: { type: 'string' },
},
},
{
title: 'second variant',
properties: {
variant2: { type: 'number' },
},
},
],
},
});
const endpoints = [createTestEndpoint(tool)];
const capabilities = {
topLevelUnions: false,
validJson: true,
refs: true,
unions: true,
formats: true,
toolNameLength: 20,
};
const transformed = applyCompatibilityTransformations(endpoints, capabilities);
expect(transformed.length).toBe(2);
// Both names should be truncated because they exceed 20 characters
expect(transformed[0]!.tool.name).toBe('very-long-union-too1');
expect(transformed[1]!.tool.name).toBe('very-long-union-too2');
});
it('should correctly combine refs and unions transformations', () => {
const tool = createTestTool('complex-tool', {
inputSchema: {
type: 'object',
properties: {
user: { $ref: '#/$defs/user' },
},
$defs: {
user: {
type: 'object',
properties: {
preference: {
anyOf: [{ type: 'string' }, { type: 'number' }],
},
},
},
},
},
});
const endpoints = [createTestEndpoint(tool)];
const capabilities = {
topLevelUnions: true,
validJson: true,
refs: false,
unions: false,
formats: true,
toolNameLength: undefined,
};
const transformed = applyCompatibilityTransformations(endpoints, capabilities);
const schema = transformed[0]!.tool.inputSchema as JSONSchema;
// Refs should be inlined
expect(schema.$defs).toBeUndefined();
// Safely access nested properties
if (schema.properties && schema.properties['user']) {
const user = schema.properties['user'];
// User should be inlined
expect(user.type).toBe('object');
// AnyOf in the inlined user.preference should be removed
if (user.properties && user.properties['preference']) {
const preference = user.properties['preference'];
expect(preference.anyOf).toBeUndefined();
expect(preference.type).toBe('string');
}
}
});
it('should handle formats capability being false', () => {
const tool = createTestTool('format-tool', {
inputSchema: {
type: 'object',
properties: {
date: { type: 'string', description: 'A date', format: 'date' },
},
},
});
const endpoints = [createTestEndpoint(tool)];
const capabilities = {
topLevelUnions: true,
validJson: true,
refs: true,
unions: true,
formats: false,
toolNameLength: undefined,
};
const transformed = applyCompatibilityTransformations(endpoints, capabilities);
const schema = transformed[0]!.tool.inputSchema as JSONSchema;
if (schema.properties && schema.properties['date']) {
const dateField = schema.properties['date'];
expect(dateField['format']).toBeUndefined();
expect(dateField['description']).toBe('A date (format: "date")');
}
});
});
```
--------------------------------------------------------------------------------
/src/resources/webhooks/webhooks.ts:
--------------------------------------------------------------------------------
```typescript
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { APIResource } from '../../core/resource';
import * as DisputesAPI from '../disputes';
import * as LicenseKeysAPI from '../license-keys';
import * as PaymentsAPI from '../payments';
import * as RefundsAPI from '../refunds';
import * as SubscriptionsAPI from '../subscriptions';
import * as WebhookEventsAPI from '../webhook-events';
import * as HeadersAPI from './headers';
import { HeaderRetrieveResponse, HeaderUpdateParams, Headers } from './headers';
import { Webhook } from 'standardwebhooks';
import { APIPromise } from '../../core/api-promise';
import { CursorPagePagination, type CursorPagePaginationParams, PagePromise } from '../../core/pagination';
import { buildHeaders } from '../../internal/headers';
import { RequestOptions } from '../../internal/request-options';
import { path } from '../../internal/utils/path';
export class Webhooks extends APIResource {
headers: HeadersAPI.Headers = new HeadersAPI.Headers(this._client);
/**
* Create a new webhook
*/
create(body: WebhookCreateParams, options?: RequestOptions): APIPromise<WebhookDetails> {
return this._client.post('/webhooks', { body, ...options });
}
/**
* Get a webhook by id
*/
retrieve(webhookID: string, options?: RequestOptions): APIPromise<WebhookDetails> {
return this._client.get(path`/webhooks/${webhookID}`, options);
}
/**
* Patch a webhook by id
*/
update(webhookID: string, body: WebhookUpdateParams, options?: RequestOptions): APIPromise<WebhookDetails> {
return this._client.patch(path`/webhooks/${webhookID}`, { body, ...options });
}
/**
* List all webhooks
*/
list(
query: WebhookListParams | null | undefined = {},
options?: RequestOptions,
): PagePromise<WebhookDetailsCursorPagePagination, WebhookDetails> {
return this._client.getAPIList('/webhooks', CursorPagePagination<WebhookDetails>, { query, ...options });
}
/**
* Delete a webhook by id
*/
delete(webhookID: string, options?: RequestOptions): APIPromise<void> {
return this._client.delete(path`/webhooks/${webhookID}`, {
...options,
headers: buildHeaders([{ Accept: '*/*' }, options?.headers]),
});
}
/**
* Get webhook secret by id
*/
retrieveSecret(webhookID: string, options?: RequestOptions): APIPromise<WebhookRetrieveSecretResponse> {
return this._client.get(path`/webhooks/${webhookID}/secret`, options);
}
unsafeUnwrap(body: string): UnsafeUnwrapWebhookEvent {
return JSON.parse(body) as UnsafeUnwrapWebhookEvent;
}
unwrap(
body: string,
{ headers, key }: { headers: Record<string, string>; key?: string },
): UnwrapWebhookEvent {
if (headers !== undefined) {
const keyStr: string | null = key === undefined ? this._client.webhookKey : key;
if (keyStr === null) throw new Error('Webhook key must not be null in order to unwrap');
const wh = new Webhook(keyStr);
wh.verify(body, headers);
}
return JSON.parse(body) as UnwrapWebhookEvent;
}
}
export type WebhookDetailsCursorPagePagination = CursorPagePagination<WebhookDetails>;
export interface WebhookDetails {
/**
* The webhook's ID.
*/
id: string;
/**
* Created at timestamp
*/
created_at: string;
/**
* An example webhook name.
*/
description: string;
/**
* Metadata of the webhook
*/
metadata: { [key: string]: string };
/**
* Updated at timestamp
*/
updated_at: string;
/**
* Url endpoint of the webhook
*/
url: string;
/**
* Status of the webhook.
*
* If true, events are not sent
*/
disabled?: boolean | null;
/**
* Filter events to the webhook.
*
* Webhook event will only be sent for events in the list.
*/
filter_types?: Array<string> | null;
/**
* Configured rate limit
*/
rate_limit?: number | null;
}
export interface WebhookRetrieveSecretResponse {
secret: string;
}
export interface DisputeAcceptedWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: DisputeAcceptedWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'dispute.accepted';
}
export namespace DisputeAcceptedWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends DisputesAPI.Dispute {
/**
* The type of payload in the data field
*/
payload_type?: 'Dispute';
}
}
export interface DisputeCancelledWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: DisputeCancelledWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'dispute.cancelled';
}
export namespace DisputeCancelledWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends DisputesAPI.Dispute {
/**
* The type of payload in the data field
*/
payload_type?: 'Dispute';
}
}
export interface DisputeChallengedWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: DisputeChallengedWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'dispute.challenged';
}
export namespace DisputeChallengedWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends DisputesAPI.Dispute {
/**
* The type of payload in the data field
*/
payload_type?: 'Dispute';
}
}
export interface DisputeExpiredWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: DisputeExpiredWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'dispute.expired';
}
export namespace DisputeExpiredWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends DisputesAPI.Dispute {
/**
* The type of payload in the data field
*/
payload_type?: 'Dispute';
}
}
export interface DisputeLostWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: DisputeLostWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'dispute.lost';
}
export namespace DisputeLostWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends DisputesAPI.Dispute {
/**
* The type of payload in the data field
*/
payload_type?: 'Dispute';
}
}
export interface DisputeOpenedWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: DisputeOpenedWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'dispute.opened';
}
export namespace DisputeOpenedWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends DisputesAPI.Dispute {
/**
* The type of payload in the data field
*/
payload_type?: 'Dispute';
}
}
export interface DisputeWonWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: DisputeWonWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'dispute.won';
}
export namespace DisputeWonWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends DisputesAPI.Dispute {
/**
* The type of payload in the data field
*/
payload_type?: 'Dispute';
}
}
export interface LicenseKeyCreatedWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: LicenseKeyCreatedWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'license_key.created';
}
export namespace LicenseKeyCreatedWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends LicenseKeysAPI.LicenseKey {
/**
* The type of payload in the data field
*/
payload_type?: 'LicenseKey';
}
}
export interface PaymentCancelledWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: PaymentCancelledWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'payment.cancelled';
}
export namespace PaymentCancelledWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends PaymentsAPI.Payment {
/**
* The type of payload in the data field
*/
payload_type?: 'Payment';
}
}
export interface PaymentFailedWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: PaymentFailedWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'payment.failed';
}
export namespace PaymentFailedWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends PaymentsAPI.Payment {
/**
* The type of payload in the data field
*/
payload_type?: 'Payment';
}
}
export interface PaymentProcessingWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: PaymentProcessingWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'payment.processing';
}
export namespace PaymentProcessingWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends PaymentsAPI.Payment {
/**
* The type of payload in the data field
*/
payload_type?: 'Payment';
}
}
export interface PaymentSucceededWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: PaymentSucceededWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'payment.succeeded';
}
export namespace PaymentSucceededWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends PaymentsAPI.Payment {
/**
* The type of payload in the data field
*/
payload_type?: 'Payment';
}
}
export interface RefundFailedWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: RefundFailedWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'refund.failed';
}
export namespace RefundFailedWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends RefundsAPI.Refund {
/**
* The type of payload in the data field
*/
payload_type?: 'Refund';
}
}
export interface RefundSucceededWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: RefundSucceededWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'refund.succeeded';
}
export namespace RefundSucceededWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends RefundsAPI.Refund {
/**
* The type of payload in the data field
*/
payload_type?: 'Refund';
}
}
export interface SubscriptionActiveWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: SubscriptionActiveWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'subscription.active';
}
export namespace SubscriptionActiveWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends SubscriptionsAPI.Subscription {
/**
* The type of payload in the data field
*/
payload_type?: 'Subscription';
}
}
export interface SubscriptionCancelledWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: SubscriptionCancelledWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'subscription.cancelled';
}
export namespace SubscriptionCancelledWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends SubscriptionsAPI.Subscription {
/**
* The type of payload in the data field
*/
payload_type?: 'Subscription';
}
}
export interface SubscriptionExpiredWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: SubscriptionExpiredWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'subscription.expired';
}
export namespace SubscriptionExpiredWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends SubscriptionsAPI.Subscription {
/**
* The type of payload in the data field
*/
payload_type?: 'Subscription';
}
}
export interface SubscriptionFailedWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: SubscriptionFailedWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'subscription.failed';
}
export namespace SubscriptionFailedWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends SubscriptionsAPI.Subscription {
/**
* The type of payload in the data field
*/
payload_type?: 'Subscription';
}
}
export interface SubscriptionOnHoldWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: SubscriptionOnHoldWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'subscription.on_hold';
}
export namespace SubscriptionOnHoldWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends SubscriptionsAPI.Subscription {
/**
* The type of payload in the data field
*/
payload_type?: 'Subscription';
}
}
export interface SubscriptionPlanChangedWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: SubscriptionPlanChangedWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'subscription.plan_changed';
}
export namespace SubscriptionPlanChangedWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends SubscriptionsAPI.Subscription {
/**
* The type of payload in the data field
*/
payload_type?: 'Subscription';
}
}
export interface SubscriptionRenewedWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: SubscriptionRenewedWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'subscription.renewed';
}
export namespace SubscriptionRenewedWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends SubscriptionsAPI.Subscription {
/**
* The type of payload in the data field
*/
payload_type?: 'Subscription';
}
}
export interface DisputeAcceptedWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: DisputeAcceptedWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'dispute.accepted';
}
export namespace DisputeAcceptedWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends DisputesAPI.Dispute {
/**
* The type of payload in the data field
*/
payload_type?: 'Dispute';
}
}
export interface DisputeCancelledWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: DisputeCancelledWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'dispute.cancelled';
}
export namespace DisputeCancelledWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends DisputesAPI.Dispute {
/**
* The type of payload in the data field
*/
payload_type?: 'Dispute';
}
}
export interface DisputeChallengedWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: DisputeChallengedWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'dispute.challenged';
}
export namespace DisputeChallengedWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends DisputesAPI.Dispute {
/**
* The type of payload in the data field
*/
payload_type?: 'Dispute';
}
}
export interface DisputeExpiredWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: DisputeExpiredWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'dispute.expired';
}
export namespace DisputeExpiredWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends DisputesAPI.Dispute {
/**
* The type of payload in the data field
*/
payload_type?: 'Dispute';
}
}
export interface DisputeLostWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: DisputeLostWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'dispute.lost';
}
export namespace DisputeLostWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends DisputesAPI.Dispute {
/**
* The type of payload in the data field
*/
payload_type?: 'Dispute';
}
}
export interface DisputeOpenedWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: DisputeOpenedWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'dispute.opened';
}
export namespace DisputeOpenedWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends DisputesAPI.Dispute {
/**
* The type of payload in the data field
*/
payload_type?: 'Dispute';
}
}
export interface DisputeWonWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: DisputeWonWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'dispute.won';
}
export namespace DisputeWonWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends DisputesAPI.Dispute {
/**
* The type of payload in the data field
*/
payload_type?: 'Dispute';
}
}
export interface LicenseKeyCreatedWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: LicenseKeyCreatedWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'license_key.created';
}
export namespace LicenseKeyCreatedWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends LicenseKeysAPI.LicenseKey {
/**
* The type of payload in the data field
*/
payload_type?: 'LicenseKey';
}
}
export interface PaymentCancelledWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: PaymentCancelledWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'payment.cancelled';
}
export namespace PaymentCancelledWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends PaymentsAPI.Payment {
/**
* The type of payload in the data field
*/
payload_type?: 'Payment';
}
}
export interface PaymentFailedWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: PaymentFailedWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'payment.failed';
}
export namespace PaymentFailedWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends PaymentsAPI.Payment {
/**
* The type of payload in the data field
*/
payload_type?: 'Payment';
}
}
export interface PaymentProcessingWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: PaymentProcessingWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'payment.processing';
}
export namespace PaymentProcessingWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends PaymentsAPI.Payment {
/**
* The type of payload in the data field
*/
payload_type?: 'Payment';
}
}
export interface PaymentSucceededWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: PaymentSucceededWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'payment.succeeded';
}
export namespace PaymentSucceededWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends PaymentsAPI.Payment {
/**
* The type of payload in the data field
*/
payload_type?: 'Payment';
}
}
export interface RefundFailedWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: RefundFailedWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'refund.failed';
}
export namespace RefundFailedWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends RefundsAPI.Refund {
/**
* The type of payload in the data field
*/
payload_type?: 'Refund';
}
}
export interface RefundSucceededWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: RefundSucceededWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'refund.succeeded';
}
export namespace RefundSucceededWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends RefundsAPI.Refund {
/**
* The type of payload in the data field
*/
payload_type?: 'Refund';
}
}
export interface SubscriptionActiveWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: SubscriptionActiveWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'subscription.active';
}
export namespace SubscriptionActiveWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends SubscriptionsAPI.Subscription {
/**
* The type of payload in the data field
*/
payload_type?: 'Subscription';
}
}
export interface SubscriptionCancelledWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: SubscriptionCancelledWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'subscription.cancelled';
}
export namespace SubscriptionCancelledWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends SubscriptionsAPI.Subscription {
/**
* The type of payload in the data field
*/
payload_type?: 'Subscription';
}
}
export interface SubscriptionExpiredWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: SubscriptionExpiredWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'subscription.expired';
}
export namespace SubscriptionExpiredWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends SubscriptionsAPI.Subscription {
/**
* The type of payload in the data field
*/
payload_type?: 'Subscription';
}
}
export interface SubscriptionFailedWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: SubscriptionFailedWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'subscription.failed';
}
export namespace SubscriptionFailedWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends SubscriptionsAPI.Subscription {
/**
* The type of payload in the data field
*/
payload_type?: 'Subscription';
}
}
export interface SubscriptionOnHoldWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: SubscriptionOnHoldWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'subscription.on_hold';
}
export namespace SubscriptionOnHoldWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends SubscriptionsAPI.Subscription {
/**
* The type of payload in the data field
*/
payload_type?: 'Subscription';
}
}
export interface SubscriptionPlanChangedWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: SubscriptionPlanChangedWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'subscription.plan_changed';
}
export namespace SubscriptionPlanChangedWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends SubscriptionsAPI.Subscription {
/**
* The type of payload in the data field
*/
payload_type?: 'Subscription';
}
}
export interface SubscriptionRenewedWebhookEvent {
/**
* The business identifier
*/
business_id: string;
/**
* Event-specific data
*/
data: SubscriptionRenewedWebhookEvent.Data;
/**
* The timestamp of when the event occurred
*/
timestamp: string;
/**
* The event type
*/
type: 'subscription.renewed';
}
export namespace SubscriptionRenewedWebhookEvent {
/**
* Event-specific data
*/
export interface Data extends SubscriptionsAPI.Subscription {
/**
* The type of payload in the data field
*/
payload_type?: 'Subscription';
}
}
export type UnsafeUnwrapWebhookEvent =
| DisputeAcceptedWebhookEvent
| DisputeCancelledWebhookEvent
| DisputeChallengedWebhookEvent
| DisputeExpiredWebhookEvent
| DisputeLostWebhookEvent
| DisputeOpenedWebhookEvent
| DisputeWonWebhookEvent
| LicenseKeyCreatedWebhookEvent
| PaymentCancelledWebhookEvent
| PaymentFailedWebhookEvent
| PaymentProcessingWebhookEvent
| PaymentSucceededWebhookEvent
| RefundFailedWebhookEvent
| RefundSucceededWebhookEvent
| SubscriptionActiveWebhookEvent
| SubscriptionCancelledWebhookEvent
| SubscriptionExpiredWebhookEvent
| SubscriptionFailedWebhookEvent
| SubscriptionOnHoldWebhookEvent
| SubscriptionPlanChangedWebhookEvent
| SubscriptionRenewedWebhookEvent;
export type UnwrapWebhookEvent =
| DisputeAcceptedWebhookEvent
| DisputeCancelledWebhookEvent
| DisputeChallengedWebhookEvent
| DisputeExpiredWebhookEvent
| DisputeLostWebhookEvent
| DisputeOpenedWebhookEvent
| DisputeWonWebhookEvent
| LicenseKeyCreatedWebhookEvent
| PaymentCancelledWebhookEvent
| PaymentFailedWebhookEvent
| PaymentProcessingWebhookEvent
| PaymentSucceededWebhookEvent
| RefundFailedWebhookEvent
| RefundSucceededWebhookEvent
| SubscriptionActiveWebhookEvent
| SubscriptionCancelledWebhookEvent
| SubscriptionExpiredWebhookEvent
| SubscriptionFailedWebhookEvent
| SubscriptionOnHoldWebhookEvent
| SubscriptionPlanChangedWebhookEvent
| SubscriptionRenewedWebhookEvent;
export interface WebhookCreateParams {
/**
* Url of the webhook
*/
url: string;
description?: string | null;
/**
* Create the webhook in a disabled state.
*
* Default is false
*/
disabled?: boolean | null;
/**
* Filter events to the webhook.
*
* Webhook event will only be sent for events in the list.
*/
filter_types?: Array<WebhookEventsAPI.WebhookEventType>;
/**
* Custom headers to be passed
*/
headers?: { [key: string]: string } | null;
/**
* The request's idempotency key
*/
idempotency_key?: string | null;
/**
* Metadata to be passed to the webhook Defaut is {}
*/
metadata?: { [key: string]: string } | null;
rate_limit?: number | null;
}
export interface WebhookUpdateParams {
/**
* Description of the webhook
*/
description?: string | null;
/**
* To Disable the endpoint, set it to true.
*/
disabled?: boolean | null;
/**
* Filter events to the endpoint.
*
* Webhook event will only be sent for events in the list.
*/
filter_types?: Array<WebhookEventsAPI.WebhookEventType> | null;
/**
* Metadata
*/
metadata?: { [key: string]: string } | null;
/**
* Rate limit
*/
rate_limit?: number | null;
/**
* Url endpoint
*/
url?: string | null;
}
export interface WebhookListParams extends CursorPagePaginationParams {}
Webhooks.Headers = Headers;
export declare namespace Webhooks {
export {
type WebhookDetails as WebhookDetails,
type WebhookRetrieveSecretResponse as WebhookRetrieveSecretResponse,
type DisputeAcceptedWebhookEvent as DisputeAcceptedWebhookEvent,
type DisputeCancelledWebhookEvent as DisputeCancelledWebhookEvent,
type DisputeChallengedWebhookEvent as DisputeChallengedWebhookEvent,
type DisputeExpiredWebhookEvent as DisputeExpiredWebhookEvent,
type DisputeLostWebhookEvent as DisputeLostWebhookEvent,
type DisputeOpenedWebhookEvent as DisputeOpenedWebhookEvent,
type DisputeWonWebhookEvent as DisputeWonWebhookEvent,
type LicenseKeyCreatedWebhookEvent as LicenseKeyCreatedWebhookEvent,
type PaymentCancelledWebhookEvent as PaymentCancelledWebhookEvent,
type PaymentFailedWebhookEvent as PaymentFailedWebhookEvent,
type PaymentProcessingWebhookEvent as PaymentProcessingWebhookEvent,
type PaymentSucceededWebhookEvent as PaymentSucceededWebhookEvent,
type RefundFailedWebhookEvent as RefundFailedWebhookEvent,
type RefundSucceededWebhookEvent as RefundSucceededWebhookEvent,
type SubscriptionActiveWebhookEvent as SubscriptionActiveWebhookEvent,
type SubscriptionCancelledWebhookEvent as SubscriptionCancelledWebhookEvent,
type SubscriptionExpiredWebhookEvent as SubscriptionExpiredWebhookEvent,
type SubscriptionFailedWebhookEvent as SubscriptionFailedWebhookEvent,
type SubscriptionOnHoldWebhookEvent as SubscriptionOnHoldWebhookEvent,
type SubscriptionPlanChangedWebhookEvent as SubscriptionPlanChangedWebhookEvent,
type SubscriptionRenewedWebhookEvent as SubscriptionRenewedWebhookEvent,
type UnsafeUnwrapWebhookEvent as UnsafeUnwrapWebhookEvent,
type UnwrapWebhookEvent as UnwrapWebhookEvent,
type WebhookDetailsCursorPagePagination as WebhookDetailsCursorPagePagination,
type WebhookCreateParams as WebhookCreateParams,
type WebhookUpdateParams as WebhookUpdateParams,
type WebhookListParams as WebhookListParams,
};
export {
Headers as Headers,
type HeaderRetrieveResponse as HeaderRetrieveResponse,
type HeaderUpdateParams as HeaderUpdateParams,
};
}
```
--------------------------------------------------------------------------------
/src/client.ts:
--------------------------------------------------------------------------------
```typescript
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import type { RequestInit, RequestInfo, BodyInit } from './internal/builtin-types';
import type { HTTPMethod, PromiseOrValue, MergedRequestInit, FinalizedRequestInit } from './internal/types';
import { uuid4 } from './internal/utils/uuid';
import { validatePositiveInteger, isAbsoluteURL, safeJSON } from './internal/utils/values';
import { sleep } from './internal/utils/sleep';
export type { Logger, LogLevel } from './internal/utils/log';
import { castToError, isAbortError } from './internal/errors';
import type { APIResponseProps } from './internal/parse';
import { getPlatformHeaders } from './internal/detect-platform';
import * as Shims from './internal/shims';
import * as Opts from './internal/request-options';
import { VERSION } from './version';
import * as Errors from './core/error';
import * as Pagination from './core/pagination';
import {
AbstractPage,
type CursorPagePaginationParams,
CursorPagePaginationResponse,
type DefaultPageNumberPaginationParams,
DefaultPageNumberPaginationResponse,
} from './core/pagination';
import * as Uploads from './core/uploads';
import * as API from './resources/index';
import { APIPromise } from './core/api-promise';
import {
AddonCreateParams,
AddonListParams,
AddonResponse,
AddonResponsesDefaultPageNumberPagination,
AddonUpdateImagesResponse,
AddonUpdateParams,
Addons,
} from './resources/addons';
import {
Brand,
BrandCreateParams,
BrandListResponse,
BrandUpdateImagesResponse,
BrandUpdateParams,
Brands,
} from './resources/brands';
import {
CheckoutSessionCreateParams,
CheckoutSessionRequest,
CheckoutSessionResponse,
CheckoutSessionStatus,
CheckoutSessions,
} from './resources/checkout-sessions';
import {
Discount,
DiscountCreateParams,
DiscountListParams,
DiscountType,
DiscountUpdateParams,
Discounts,
DiscountsDefaultPageNumberPagination,
} from './resources/discounts';
import {
Dispute,
DisputeListParams,
DisputeListResponse,
DisputeListResponsesDefaultPageNumberPagination,
DisputeStage,
DisputeStatus,
Disputes,
GetDispute,
} from './resources/disputes';
import {
LicenseKeyInstance,
LicenseKeyInstanceListParams,
LicenseKeyInstanceUpdateParams,
LicenseKeyInstances,
LicenseKeyInstancesDefaultPageNumberPagination,
} from './resources/license-key-instances';
import {
LicenseKey,
LicenseKeyListParams,
LicenseKeyStatus,
LicenseKeyUpdateParams,
LicenseKeys,
LicenseKeysDefaultPageNumberPagination,
} from './resources/license-keys';
import {
LicenseActivateParams,
LicenseActivateResponse,
LicenseDeactivateParams,
LicenseValidateParams,
LicenseValidateResponse,
Licenses,
} from './resources/licenses';
import {
Meter,
MeterAggregation,
MeterCreateParams,
MeterFilter,
MeterListParams,
Meters,
MetersDefaultPageNumberPagination,
} from './resources/meters';
import {
CountryCode,
Currency,
Misc,
MiscListSupportedCountriesResponse,
TaxCategory,
} from './resources/misc';
import {
AttachExistingCustomer,
BillingAddress,
CreateNewCustomer,
CustomerLimitedDetails,
CustomerRequest,
IntentStatus,
NewCustomer,
OneTimeProductCartItem,
Payment,
PaymentCreateParams,
PaymentCreateResponse,
PaymentListParams,
PaymentListResponse,
PaymentListResponsesDefaultPageNumberPagination,
PaymentMethodTypes,
PaymentRetrieveLineItemsResponse,
Payments,
} from './resources/payments';
import {
PayoutListParams,
PayoutListResponse,
PayoutListResponsesDefaultPageNumberPagination,
Payouts,
} from './resources/payouts';
import {
Refund,
RefundCreateParams,
RefundListParams,
RefundListResponse,
RefundListResponsesDefaultPageNumberPagination,
RefundStatus,
Refunds,
} from './resources/refunds';
import {
AddonCartResponseItem,
AttachAddon,
OnDemandSubscription,
Subscription,
SubscriptionChangePlanParams,
SubscriptionChargeParams,
SubscriptionChargeResponse,
SubscriptionCreateParams,
SubscriptionCreateResponse,
SubscriptionListParams,
SubscriptionListResponse,
SubscriptionListResponsesDefaultPageNumberPagination,
SubscriptionRetrieveUsageHistoryParams,
SubscriptionRetrieveUsageHistoryResponse,
SubscriptionRetrieveUsageHistoryResponsesDefaultPageNumberPagination,
SubscriptionStatus,
SubscriptionUpdateParams,
Subscriptions,
TimeInterval,
} from './resources/subscriptions';
import {
Event,
EventInput,
EventsDefaultPageNumberPagination,
UsageEventIngestParams,
UsageEventIngestResponse,
UsageEventListParams,
UsageEvents,
} from './resources/usage-events';
import { WebhookEventType, WebhookEvents, WebhookPayload } from './resources/webhook-events';
import {
Customer,
CustomerCreateParams,
CustomerListParams,
CustomerPortalSession,
CustomerUpdateParams,
Customers,
CustomersDefaultPageNumberPagination,
} from './resources/customers/customers';
import { Invoices } from './resources/invoices/invoices';
import {
AddMeterToPrice,
LicenseKeyDuration,
Price,
Product,
ProductCreateParams,
ProductListParams,
ProductListResponse,
ProductListResponsesDefaultPageNumberPagination,
ProductUpdateFilesParams,
ProductUpdateFilesResponse,
ProductUpdateParams,
Products,
} from './resources/products/products';
import {
DisputeAcceptedWebhookEvent,
DisputeCancelledWebhookEvent,
DisputeChallengedWebhookEvent,
DisputeExpiredWebhookEvent,
DisputeLostWebhookEvent,
DisputeOpenedWebhookEvent,
DisputeWonWebhookEvent,
LicenseKeyCreatedWebhookEvent,
PaymentCancelledWebhookEvent,
PaymentFailedWebhookEvent,
PaymentProcessingWebhookEvent,
PaymentSucceededWebhookEvent,
RefundFailedWebhookEvent,
RefundSucceededWebhookEvent,
SubscriptionActiveWebhookEvent,
SubscriptionCancelledWebhookEvent,
SubscriptionExpiredWebhookEvent,
SubscriptionFailedWebhookEvent,
SubscriptionOnHoldWebhookEvent,
SubscriptionPlanChangedWebhookEvent,
SubscriptionRenewedWebhookEvent,
UnsafeUnwrapWebhookEvent,
UnwrapWebhookEvent,
WebhookCreateParams,
WebhookDetails,
WebhookDetailsCursorPagePagination,
WebhookListParams,
WebhookRetrieveSecretResponse,
WebhookUpdateParams,
Webhooks,
} from './resources/webhooks/webhooks';
import { type Fetch } from './internal/builtin-types';
import { HeadersLike, NullableHeaders, buildHeaders } from './internal/headers';
import { FinalRequestOptions, RequestOptions } from './internal/request-options';
import { readEnv } from './internal/utils/env';
import {
type LogLevel,
type Logger,
formatRequestDetails,
loggerFor,
parseLogLevel,
} from './internal/utils/log';
import { isEmptyObj } from './internal/utils/values';
const environments = {
live_mode: 'https://live.dodopayments.com',
test_mode: 'https://test.dodopayments.com',
};
type Environment = keyof typeof environments;
export interface ClientOptions {
/**
* Bearer Token for API authentication
*/
bearerToken?: string | undefined;
/**
* Defaults to process.env['DODO_PAYMENTS_WEBHOOK_KEY'].
*/
webhookKey?: string | null | undefined;
/**
* Specifies the environment to use for the API.
*
* Each environment maps to a different base URL:
* - `live_mode` corresponds to `https://live.dodopayments.com`
* - `test_mode` corresponds to `https://test.dodopayments.com`
*/
environment?: Environment | undefined;
/**
* Override the default base URL for the API, e.g., "https://api.example.com/v2/"
*
* Defaults to process.env['DODO_PAYMENTS_BASE_URL'].
*/
baseURL?: string | null | undefined;
/**
* The maximum amount of time (in milliseconds) that the client should wait for a response
* from the server before timing out a single request.
*
* Note that request timeouts are retried by default, so in a worst-case scenario you may wait
* much longer than this timeout before the promise succeeds or fails.
*
* @unit milliseconds
*/
timeout?: number | undefined;
/**
* Additional `RequestInit` options to be passed to `fetch` calls.
* Properties will be overridden by per-request `fetchOptions`.
*/
fetchOptions?: MergedRequestInit | undefined;
/**
* Specify a custom `fetch` function implementation.
*
* If not provided, we expect that `fetch` is defined globally.
*/
fetch?: Fetch | undefined;
/**
* The maximum number of times that the client will retry a request in case of a
* temporary failure, like a network error or a 5XX error from the server.
*
* @default 2
*/
maxRetries?: number | undefined;
/**
* Default headers to include with every request to the API.
*
* These can be removed in individual requests by explicitly setting the
* header to `null` in request options.
*/
defaultHeaders?: HeadersLike | undefined;
/**
* Default query parameters to include with every request to the API.
*
* These can be removed in individual requests by explicitly setting the
* param to `undefined` in request options.
*/
defaultQuery?: Record<string, string | undefined> | undefined;
/**
* Set the log level.
*
* Defaults to process.env['DODO_PAYMENTS_LOG'] or 'warn' if it isn't set.
*/
logLevel?: LogLevel | undefined;
/**
* Set the logger.
*
* Defaults to globalThis.console.
*/
logger?: Logger | undefined;
}
/**
* API Client for interfacing with the Dodo Payments API.
*/
export class DodoPayments {
bearerToken: string;
webhookKey: string | null;
baseURL: string;
maxRetries: number;
timeout: number;
logger: Logger | undefined;
logLevel: LogLevel | undefined;
fetchOptions: MergedRequestInit | undefined;
private fetch: Fetch;
#encoder: Opts.RequestEncoder;
protected idempotencyHeader?: string;
private _options: ClientOptions;
/**
* API Client for interfacing with the Dodo Payments API.
*
* @param {string | undefined} [opts.bearerToken=process.env['DODO_PAYMENTS_API_KEY'] ?? undefined]
* @param {string | null | undefined} [opts.webhookKey=process.env['DODO_PAYMENTS_WEBHOOK_KEY'] ?? null]
* @param {Environment} [opts.environment=live_mode] - Specifies the environment URL to use for the API.
* @param {string} [opts.baseURL=process.env['DODO_PAYMENTS_BASE_URL'] ?? https://live.dodopayments.com] - Override the default base URL for the API.
* @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
* @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
* @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
* @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
* @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
*/
constructor({
baseURL = readEnv('DODO_PAYMENTS_BASE_URL'),
bearerToken = readEnv('DODO_PAYMENTS_API_KEY'),
webhookKey = readEnv('DODO_PAYMENTS_WEBHOOK_KEY') ?? null,
...opts
}: ClientOptions = {}) {
if (bearerToken === undefined) {
throw new Errors.DodoPaymentsError(
"The DODO_PAYMENTS_API_KEY environment variable is missing or empty; either provide it, or instantiate the DodoPayments client with an bearerToken option, like new DodoPayments({ bearerToken: 'My Bearer Token' }).",
);
}
const options: ClientOptions = {
bearerToken,
webhookKey,
...opts,
baseURL,
environment: opts.environment ?? 'live_mode',
};
if (baseURL && opts.environment) {
throw new Errors.DodoPaymentsError(
'Ambiguous URL; The `baseURL` option (or DODO_PAYMENTS_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null',
);
}
this.baseURL = options.baseURL || environments[options.environment || 'live_mode'];
this.timeout = options.timeout ?? DodoPayments.DEFAULT_TIMEOUT /* 1 minute */;
this.logger = options.logger ?? console;
const defaultLogLevel = 'warn';
// Set default logLevel early so that we can log a warning in parseLogLevel.
this.logLevel = defaultLogLevel;
this.logLevel =
parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
parseLogLevel(readEnv('DODO_PAYMENTS_LOG'), "process.env['DODO_PAYMENTS_LOG']", this) ??
defaultLogLevel;
this.fetchOptions = options.fetchOptions;
this.maxRetries = options.maxRetries ?? 2;
this.fetch = options.fetch ?? Shims.getDefaultFetch();
this.#encoder = Opts.FallbackEncoder;
this._options = options;
this.bearerToken = bearerToken;
this.webhookKey = webhookKey;
}
/**
* Create a new client instance re-using the same options given to the current client with optional overriding.
*/
withOptions(options: Partial<ClientOptions>): this {
const client = new (this.constructor as any as new (props: ClientOptions) => typeof this)({
...this._options,
environment: options.environment ? options.environment : undefined,
baseURL: options.environment ? undefined : this.baseURL,
maxRetries: this.maxRetries,
timeout: this.timeout,
logger: this.logger,
logLevel: this.logLevel,
fetch: this.fetch,
fetchOptions: this.fetchOptions,
bearerToken: this.bearerToken,
webhookKey: this.webhookKey,
...options,
});
return client;
}
/**
* Check whether the base URL is set to its default.
*/
#baseURLOverridden(): boolean {
return this.baseURL !== environments[this._options.environment || 'live_mode'];
}
protected defaultQuery(): Record<string, string | undefined> | undefined {
return this._options.defaultQuery;
}
protected validateHeaders({ values, nulls }: NullableHeaders) {
return;
}
protected async authHeaders(opts: FinalRequestOptions): Promise<NullableHeaders | undefined> {
return buildHeaders([{ Authorization: `Bearer ${this.bearerToken}` }]);
}
/**
* Basic re-implementation of `qs.stringify` for primitive types.
*/
protected stringifyQuery(query: Record<string, unknown>): string {
return Object.entries(query)
.filter(([_, value]) => typeof value !== 'undefined')
.map(([key, value]) => {
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
}
if (value === null) {
return `${encodeURIComponent(key)}=`;
}
throw new Errors.DodoPaymentsError(
`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`,
);
})
.join('&');
}
private getUserAgent(): string {
return `${this.constructor.name}/JS ${VERSION}`;
}
protected defaultIdempotencyKey(): string {
return `stainless-node-retry-${uuid4()}`;
}
protected makeStatusError(
status: number,
error: Object,
message: string | undefined,
headers: Headers,
): Errors.APIError {
return Errors.APIError.generate(status, error, message, headers);
}
buildURL(
path: string,
query: Record<string, unknown> | null | undefined,
defaultBaseURL?: string | undefined,
): string {
const baseURL = (!this.#baseURLOverridden() && defaultBaseURL) || this.baseURL;
const url =
isAbsoluteURL(path) ?
new URL(path)
: new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
const defaultQuery = this.defaultQuery();
if (!isEmptyObj(defaultQuery)) {
query = { ...defaultQuery, ...query };
}
if (typeof query === 'object' && query && !Array.isArray(query)) {
url.search = this.stringifyQuery(query as Record<string, unknown>);
}
return url.toString();
}
/**
* Used as a callback for mutating the given `FinalRequestOptions` object.
*/
protected async prepareOptions(options: FinalRequestOptions): Promise<void> {}
/**
* Used as a callback for mutating the given `RequestInit` object.
*
* This is useful for cases where you want to add certain headers based off of
* the request properties, e.g. `method` or `url`.
*/
protected async prepareRequest(
request: RequestInit,
{ url, options }: { url: string; options: FinalRequestOptions },
): Promise<void> {}
get<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {
return this.methodRequest('get', path, opts);
}
post<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {
return this.methodRequest('post', path, opts);
}
patch<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {
return this.methodRequest('patch', path, opts);
}
put<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {
return this.methodRequest('put', path, opts);
}
delete<Rsp>(path: string, opts?: PromiseOrValue<RequestOptions>): APIPromise<Rsp> {
return this.methodRequest('delete', path, opts);
}
private methodRequest<Rsp>(
method: HTTPMethod,
path: string,
opts?: PromiseOrValue<RequestOptions>,
): APIPromise<Rsp> {
return this.request(
Promise.resolve(opts).then((opts) => {
return { method, path, ...opts };
}),
);
}
request<Rsp>(
options: PromiseOrValue<FinalRequestOptions>,
remainingRetries: number | null = null,
): APIPromise<Rsp> {
return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
}
private async makeRequest(
optionsInput: PromiseOrValue<FinalRequestOptions>,
retriesRemaining: number | null,
retryOfRequestLogID: string | undefined,
): Promise<APIResponseProps> {
const options = await optionsInput;
const maxRetries = options.maxRetries ?? this.maxRetries;
if (retriesRemaining == null) {
retriesRemaining = maxRetries;
}
await this.prepareOptions(options);
const { req, url, timeout } = await this.buildRequest(options, {
retryCount: maxRetries - retriesRemaining,
});
await this.prepareRequest(req, { url, options });
/** Not an API request ID, just for correlating local log entries. */
const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
const startTime = Date.now();
loggerFor(this).debug(
`[${requestLogID}] sending request`,
formatRequestDetails({
retryOfRequestLogID,
method: options.method,
url,
options,
headers: req.headers,
}),
);
if (options.signal?.aborted) {
throw new Errors.APIUserAbortError();
}
const controller = new AbortController();
const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
const headersTime = Date.now();
if (response instanceof globalThis.Error) {
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
if (options.signal?.aborted) {
throw new Errors.APIUserAbortError();
}
// detect native connection timeout errors
// deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
// undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
// others do not provide enough information to distinguish timeouts from other connection errors
const isTimeout =
isAbortError(response) ||
/timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
if (retriesRemaining) {
loggerFor(this).info(
`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`,
);
loggerFor(this).debug(
`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`,
formatRequestDetails({
retryOfRequestLogID,
url,
durationMs: headersTime - startTime,
message: response.message,
}),
);
return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
}
loggerFor(this).info(
`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`,
);
loggerFor(this).debug(
`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`,
formatRequestDetails({
retryOfRequestLogID,
url,
durationMs: headersTime - startTime,
message: response.message,
}),
);
if (isTimeout) {
throw new Errors.APIConnectionTimeoutError();
}
throw new Errors.APIConnectionError({ cause: response });
}
const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${
response.ok ? 'succeeded' : 'failed'
} with status ${response.status} in ${headersTime - startTime}ms`;
if (!response.ok) {
const shouldRetry = await this.shouldRetry(response);
if (retriesRemaining && shouldRetry) {
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
// We don't need the body of this response.
await Shims.CancelReadableStream(response.body);
loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
loggerFor(this).debug(
`[${requestLogID}] response error (${retryMessage})`,
formatRequestDetails({
retryOfRequestLogID,
url: response.url,
status: response.status,
headers: response.headers,
durationMs: headersTime - startTime,
}),
);
return this.retryRequest(
options,
retriesRemaining,
retryOfRequestLogID ?? requestLogID,
response.headers,
);
}
const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
const errText = await response.text().catch((err: any) => castToError(err).message);
const errJSON = safeJSON(errText);
const errMessage = errJSON ? undefined : errText;
loggerFor(this).debug(
`[${requestLogID}] response error (${retryMessage})`,
formatRequestDetails({
retryOfRequestLogID,
url: response.url,
status: response.status,
headers: response.headers,
message: errMessage,
durationMs: Date.now() - startTime,
}),
);
const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
throw err;
}
loggerFor(this).info(responseInfo);
loggerFor(this).debug(
`[${requestLogID}] response start`,
formatRequestDetails({
retryOfRequestLogID,
url: response.url,
status: response.status,
headers: response.headers,
durationMs: headersTime - startTime,
}),
);
return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
}
getAPIList<Item, PageClass extends Pagination.AbstractPage<Item> = Pagination.AbstractPage<Item>>(
path: string,
Page: new (...args: any[]) => PageClass,
opts?: RequestOptions,
): Pagination.PagePromise<PageClass, Item> {
return this.requestAPIList(Page, { method: 'get', path, ...opts });
}
requestAPIList<
Item = unknown,
PageClass extends Pagination.AbstractPage<Item> = Pagination.AbstractPage<Item>,
>(
Page: new (...args: ConstructorParameters<typeof Pagination.AbstractPage>) => PageClass,
options: FinalRequestOptions,
): Pagination.PagePromise<PageClass, Item> {
const request = this.makeRequest(options, null, undefined);
return new Pagination.PagePromise<PageClass, Item>(this as any as DodoPayments, request, Page);
}
async fetchWithTimeout(
url: RequestInfo,
init: RequestInit | undefined,
ms: number,
controller: AbortController,
): Promise<Response> {
const { signal, method, ...options } = init || {};
if (signal) signal.addEventListener('abort', () => controller.abort());
const timeout = setTimeout(() => controller.abort(), ms);
const isReadableBody =
((globalThis as any).ReadableStream && options.body instanceof (globalThis as any).ReadableStream) ||
(typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
const fetchOptions: RequestInit = {
signal: controller.signal as any,
...(isReadableBody ? { duplex: 'half' } : {}),
method: 'GET',
...options,
};
if (method) {
// Custom methods like 'patch' need to be uppercased
// See https://github.com/nodejs/undici/issues/2294
fetchOptions.method = method.toUpperCase();
}
try {
// use undefined this binding; fetch errors if bound to something else in browser/cloudflare
return await this.fetch.call(undefined, url, fetchOptions);
} finally {
clearTimeout(timeout);
}
}
private async shouldRetry(response: Response): Promise<boolean> {
// Note this is not a standard header.
const shouldRetryHeader = response.headers.get('x-should-retry');
// If the server explicitly says whether or not to retry, obey.
if (shouldRetryHeader === 'true') return true;
if (shouldRetryHeader === 'false') return false;
// Retry on request timeouts.
if (response.status === 408) return true;
// Retry on lock timeouts.
if (response.status === 409) return true;
// Retry on rate limits.
if (response.status === 429) return true;
// Retry internal errors.
if (response.status >= 500) return true;
return false;
}
private async retryRequest(
options: FinalRequestOptions,
retriesRemaining: number,
requestLogID: string,
responseHeaders?: Headers | undefined,
): Promise<APIResponseProps> {
let timeoutMillis: number | undefined;
// Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
if (retryAfterMillisHeader) {
const timeoutMs = parseFloat(retryAfterMillisHeader);
if (!Number.isNaN(timeoutMs)) {
timeoutMillis = timeoutMs;
}
}
// About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
const retryAfterHeader = responseHeaders?.get('retry-after');
if (retryAfterHeader && !timeoutMillis) {
const timeoutSeconds = parseFloat(retryAfterHeader);
if (!Number.isNaN(timeoutSeconds)) {
timeoutMillis = timeoutSeconds * 1000;
} else {
timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
}
}
// If the API asks us to wait a certain amount of time (and it's a reasonable amount),
// just do what it says, but otherwise calculate a default
if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
const maxRetries = options.maxRetries ?? this.maxRetries;
timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
}
await sleep(timeoutMillis);
return this.makeRequest(options, retriesRemaining - 1, requestLogID);
}
private calculateDefaultRetryTimeoutMillis(retriesRemaining: number, maxRetries: number): number {
const initialRetryDelay = 0.5;
const maxRetryDelay = 8.0;
const numRetries = maxRetries - retriesRemaining;
// Apply exponential backoff, but not more than the max.
const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
// Apply some jitter, take up to at most 25 percent of the retry time.
const jitter = 1 - Math.random() * 0.25;
return sleepSeconds * jitter * 1000;
}
async buildRequest(
inputOptions: FinalRequestOptions,
{ retryCount = 0 }: { retryCount?: number } = {},
): Promise<{ req: FinalizedRequestInit; url: string; timeout: number }> {
const options = { ...inputOptions };
const { method, path, query, defaultBaseURL } = options;
const url = this.buildURL(path!, query as Record<string, unknown>, defaultBaseURL);
if ('timeout' in options) validatePositiveInteger('timeout', options.timeout);
options.timeout = options.timeout ?? this.timeout;
const { bodyHeaders, body } = this.buildBody({ options });
const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
const req: FinalizedRequestInit = {
method,
headers: reqHeaders,
...(options.signal && { signal: options.signal }),
...((globalThis as any).ReadableStream &&
body instanceof (globalThis as any).ReadableStream && { duplex: 'half' }),
...(body && { body }),
...((this.fetchOptions as any) ?? {}),
...((options.fetchOptions as any) ?? {}),
};
return { req, url, timeout: options.timeout };
}
private async buildHeaders({
options,
method,
bodyHeaders,
retryCount,
}: {
options: FinalRequestOptions;
method: HTTPMethod;
bodyHeaders: HeadersLike;
retryCount: number;
}): Promise<Headers> {
let idempotencyHeaders: HeadersLike = {};
if (this.idempotencyHeader && method !== 'get') {
if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey();
idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
}
const headers = buildHeaders([
idempotencyHeaders,
{
Accept: 'application/json',
'User-Agent': this.getUserAgent(),
'X-Stainless-Retry-Count': String(retryCount),
...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
...getPlatformHeaders(),
},
await this.authHeaders(options),
this._options.defaultHeaders,
bodyHeaders,
options.headers,
]);
this.validateHeaders(headers);
return headers.values;
}
private buildBody({ options: { body, headers: rawHeaders } }: { options: FinalRequestOptions }): {
bodyHeaders: HeadersLike;
body: BodyInit | undefined;
} {
if (!body) {
return { bodyHeaders: undefined, body: undefined };
}
const headers = buildHeaders([rawHeaders]);
if (
// Pass raw type verbatim
ArrayBuffer.isView(body) ||
body instanceof ArrayBuffer ||
body instanceof DataView ||
(typeof body === 'string' &&
// Preserve legacy string encoding behavior for now
headers.values.has('content-type')) ||
// `Blob` is superset of `File`
((globalThis as any).Blob && body instanceof (globalThis as any).Blob) ||
// `FormData` -> `multipart/form-data`
body instanceof FormData ||
// `URLSearchParams` -> `application/x-www-form-urlencoded`
body instanceof URLSearchParams ||
// Send chunked stream (each chunk has own `length`)
((globalThis as any).ReadableStream && body instanceof (globalThis as any).ReadableStream)
) {
return { bodyHeaders: undefined, body: body as BodyInit };
} else if (
typeof body === 'object' &&
(Symbol.asyncIterator in body ||
(Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))
) {
return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body as AsyncIterable<Uint8Array>) };
} else {
return this.#encoder({ body, headers });
}
}
static DodoPayments = this;
static DEFAULT_TIMEOUT = 60000; // 1 minute
static DodoPaymentsError = Errors.DodoPaymentsError;
static APIError = Errors.APIError;
static APIConnectionError = Errors.APIConnectionError;
static APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
static APIUserAbortError = Errors.APIUserAbortError;
static NotFoundError = Errors.NotFoundError;
static ConflictError = Errors.ConflictError;
static RateLimitError = Errors.RateLimitError;
static BadRequestError = Errors.BadRequestError;
static AuthenticationError = Errors.AuthenticationError;
static InternalServerError = Errors.InternalServerError;
static PermissionDeniedError = Errors.PermissionDeniedError;
static UnprocessableEntityError = Errors.UnprocessableEntityError;
static toFile = Uploads.toFile;
checkoutSessions: API.CheckoutSessions = new API.CheckoutSessions(this);
payments: API.Payments = new API.Payments(this);
subscriptions: API.Subscriptions = new API.Subscriptions(this);
invoices: API.Invoices = new API.Invoices(this);
licenses: API.Licenses = new API.Licenses(this);
licenseKeys: API.LicenseKeys = new API.LicenseKeys(this);
licenseKeyInstances: API.LicenseKeyInstances = new API.LicenseKeyInstances(this);
customers: API.Customers = new API.Customers(this);
refunds: API.Refunds = new API.Refunds(this);
disputes: API.Disputes = new API.Disputes(this);
payouts: API.Payouts = new API.Payouts(this);
products: API.Products = new API.Products(this);
misc: API.Misc = new API.Misc(this);
discounts: API.Discounts = new API.Discounts(this);
addons: API.Addons = new API.Addons(this);
brands: API.Brands = new API.Brands(this);
webhooks: API.Webhooks = new API.Webhooks(this);
webhookEvents: API.WebhookEvents = new API.WebhookEvents(this);
usageEvents: API.UsageEvents = new API.UsageEvents(this);
meters: API.Meters = new API.Meters(this);
}
DodoPayments.CheckoutSessions = CheckoutSessions;
DodoPayments.Payments = Payments;
DodoPayments.Subscriptions = Subscriptions;
DodoPayments.Invoices = Invoices;
DodoPayments.Licenses = Licenses;
DodoPayments.LicenseKeys = LicenseKeys;
DodoPayments.LicenseKeyInstances = LicenseKeyInstances;
DodoPayments.Customers = Customers;
DodoPayments.Refunds = Refunds;
DodoPayments.Disputes = Disputes;
DodoPayments.Payouts = Payouts;
DodoPayments.Products = Products;
DodoPayments.Misc = Misc;
DodoPayments.Discounts = Discounts;
DodoPayments.Addons = Addons;
DodoPayments.Brands = Brands;
DodoPayments.Webhooks = Webhooks;
DodoPayments.WebhookEvents = WebhookEvents;
DodoPayments.UsageEvents = UsageEvents;
DodoPayments.Meters = Meters;
export declare namespace DodoPayments {
export type RequestOptions = Opts.RequestOptions;
export import DefaultPageNumberPagination = Pagination.DefaultPageNumberPagination;
export {
type DefaultPageNumberPaginationParams as DefaultPageNumberPaginationParams,
type DefaultPageNumberPaginationResponse as DefaultPageNumberPaginationResponse,
};
export import CursorPagePagination = Pagination.CursorPagePagination;
export {
type CursorPagePaginationParams as CursorPagePaginationParams,
type CursorPagePaginationResponse as CursorPagePaginationResponse,
};
export {
CheckoutSessions as CheckoutSessions,
type CheckoutSessionRequest as CheckoutSessionRequest,
type CheckoutSessionResponse as CheckoutSessionResponse,
type CheckoutSessionStatus as CheckoutSessionStatus,
type CheckoutSessionCreateParams as CheckoutSessionCreateParams,
};
export {
Payments as Payments,
type AttachExistingCustomer as AttachExistingCustomer,
type BillingAddress as BillingAddress,
type CreateNewCustomer as CreateNewCustomer,
type CustomerLimitedDetails as CustomerLimitedDetails,
type CustomerRequest as CustomerRequest,
type IntentStatus as IntentStatus,
type NewCustomer as NewCustomer,
type OneTimeProductCartItem as OneTimeProductCartItem,
type Payment as Payment,
type PaymentMethodTypes as PaymentMethodTypes,
type PaymentCreateResponse as PaymentCreateResponse,
type PaymentListResponse as PaymentListResponse,
type PaymentRetrieveLineItemsResponse as PaymentRetrieveLineItemsResponse,
type PaymentListResponsesDefaultPageNumberPagination as PaymentListResponsesDefaultPageNumberPagination,
type PaymentCreateParams as PaymentCreateParams,
type PaymentListParams as PaymentListParams,
};
export {
Subscriptions as Subscriptions,
type AddonCartResponseItem as AddonCartResponseItem,
type AttachAddon as AttachAddon,
type OnDemandSubscription as OnDemandSubscription,
type Subscription as Subscription,
type SubscriptionStatus as SubscriptionStatus,
type TimeInterval as TimeInterval,
type SubscriptionCreateResponse as SubscriptionCreateResponse,
type SubscriptionListResponse as SubscriptionListResponse,
type SubscriptionChargeResponse as SubscriptionChargeResponse,
type SubscriptionRetrieveUsageHistoryResponse as SubscriptionRetrieveUsageHistoryResponse,
type SubscriptionListResponsesDefaultPageNumberPagination as SubscriptionListResponsesDefaultPageNumberPagination,
type SubscriptionRetrieveUsageHistoryResponsesDefaultPageNumberPagination as SubscriptionRetrieveUsageHistoryResponsesDefaultPageNumberPagination,
type SubscriptionCreateParams as SubscriptionCreateParams,
type SubscriptionUpdateParams as SubscriptionUpdateParams,
type SubscriptionListParams as SubscriptionListParams,
type SubscriptionChangePlanParams as SubscriptionChangePlanParams,
type SubscriptionChargeParams as SubscriptionChargeParams,
type SubscriptionRetrieveUsageHistoryParams as SubscriptionRetrieveUsageHistoryParams,
};
export { Invoices as Invoices };
export {
Licenses as Licenses,
type LicenseActivateResponse as LicenseActivateResponse,
type LicenseValidateResponse as LicenseValidateResponse,
type LicenseActivateParams as LicenseActivateParams,
type LicenseDeactivateParams as LicenseDeactivateParams,
type LicenseValidateParams as LicenseValidateParams,
};
export {
LicenseKeys as LicenseKeys,
type LicenseKey as LicenseKey,
type LicenseKeyStatus as LicenseKeyStatus,
type LicenseKeysDefaultPageNumberPagination as LicenseKeysDefaultPageNumberPagination,
type LicenseKeyUpdateParams as LicenseKeyUpdateParams,
type LicenseKeyListParams as LicenseKeyListParams,
};
export {
LicenseKeyInstances as LicenseKeyInstances,
type LicenseKeyInstance as LicenseKeyInstance,
type LicenseKeyInstancesDefaultPageNumberPagination as LicenseKeyInstancesDefaultPageNumberPagination,
type LicenseKeyInstanceUpdateParams as LicenseKeyInstanceUpdateParams,
type LicenseKeyInstanceListParams as LicenseKeyInstanceListParams,
};
export {
Customers as Customers,
type Customer as Customer,
type CustomerPortalSession as CustomerPortalSession,
type CustomersDefaultPageNumberPagination as CustomersDefaultPageNumberPagination,
type CustomerCreateParams as CustomerCreateParams,
type CustomerUpdateParams as CustomerUpdateParams,
type CustomerListParams as CustomerListParams,
};
export {
Refunds as Refunds,
type Refund as Refund,
type RefundStatus as RefundStatus,
type RefundListResponse as RefundListResponse,
type RefundListResponsesDefaultPageNumberPagination as RefundListResponsesDefaultPageNumberPagination,
type RefundCreateParams as RefundCreateParams,
type RefundListParams as RefundListParams,
};
export {
Disputes as Disputes,
type Dispute as Dispute,
type DisputeStage as DisputeStage,
type DisputeStatus as DisputeStatus,
type GetDispute as GetDispute,
type DisputeListResponse as DisputeListResponse,
type DisputeListResponsesDefaultPageNumberPagination as DisputeListResponsesDefaultPageNumberPagination,
type DisputeListParams as DisputeListParams,
};
export {
Payouts as Payouts,
type PayoutListResponse as PayoutListResponse,
type PayoutListResponsesDefaultPageNumberPagination as PayoutListResponsesDefaultPageNumberPagination,
type PayoutListParams as PayoutListParams,
};
export {
Products as Products,
type AddMeterToPrice as AddMeterToPrice,
type LicenseKeyDuration as LicenseKeyDuration,
type Price as Price,
type Product as Product,
type ProductListResponse as ProductListResponse,
type ProductUpdateFilesResponse as ProductUpdateFilesResponse,
type ProductListResponsesDefaultPageNumberPagination as ProductListResponsesDefaultPageNumberPagination,
type ProductCreateParams as ProductCreateParams,
type ProductUpdateParams as ProductUpdateParams,
type ProductListParams as ProductListParams,
type ProductUpdateFilesParams as ProductUpdateFilesParams,
};
export {
Misc as Misc,
type CountryCode as CountryCode,
type Currency as Currency,
type TaxCategory as TaxCategory,
type MiscListSupportedCountriesResponse as MiscListSupportedCountriesResponse,
};
export {
Discounts as Discounts,
type Discount as Discount,
type DiscountType as DiscountType,
type DiscountsDefaultPageNumberPagination as DiscountsDefaultPageNumberPagination,
type DiscountCreateParams as DiscountCreateParams,
type DiscountUpdateParams as DiscountUpdateParams,
type DiscountListParams as DiscountListParams,
};
export {
Addons as Addons,
type AddonResponse as AddonResponse,
type AddonUpdateImagesResponse as AddonUpdateImagesResponse,
type AddonResponsesDefaultPageNumberPagination as AddonResponsesDefaultPageNumberPagination,
type AddonCreateParams as AddonCreateParams,
type AddonUpdateParams as AddonUpdateParams,
type AddonListParams as AddonListParams,
};
export {
Brands as Brands,
type Brand as Brand,
type BrandListResponse as BrandListResponse,
type BrandUpdateImagesResponse as BrandUpdateImagesResponse,
type BrandCreateParams as BrandCreateParams,
type BrandUpdateParams as BrandUpdateParams,
};
export {
Webhooks as Webhooks,
type WebhookDetails as WebhookDetails,
type WebhookRetrieveSecretResponse as WebhookRetrieveSecretResponse,
type DisputeAcceptedWebhookEvent as DisputeAcceptedWebhookEvent,
type DisputeCancelledWebhookEvent as DisputeCancelledWebhookEvent,
type DisputeChallengedWebhookEvent as DisputeChallengedWebhookEvent,
type DisputeExpiredWebhookEvent as DisputeExpiredWebhookEvent,
type DisputeLostWebhookEvent as DisputeLostWebhookEvent,
type DisputeOpenedWebhookEvent as DisputeOpenedWebhookEvent,
type DisputeWonWebhookEvent as DisputeWonWebhookEvent,
type LicenseKeyCreatedWebhookEvent as LicenseKeyCreatedWebhookEvent,
type PaymentCancelledWebhookEvent as PaymentCancelledWebhookEvent,
type PaymentFailedWebhookEvent as PaymentFailedWebhookEvent,
type PaymentProcessingWebhookEvent as PaymentProcessingWebhookEvent,
type PaymentSucceededWebhookEvent as PaymentSucceededWebhookEvent,
type RefundFailedWebhookEvent as RefundFailedWebhookEvent,
type RefundSucceededWebhookEvent as RefundSucceededWebhookEvent,
type SubscriptionActiveWebhookEvent as SubscriptionActiveWebhookEvent,
type SubscriptionCancelledWebhookEvent as SubscriptionCancelledWebhookEvent,
type SubscriptionExpiredWebhookEvent as SubscriptionExpiredWebhookEvent,
type SubscriptionFailedWebhookEvent as SubscriptionFailedWebhookEvent,
type SubscriptionOnHoldWebhookEvent as SubscriptionOnHoldWebhookEvent,
type SubscriptionPlanChangedWebhookEvent as SubscriptionPlanChangedWebhookEvent,
type SubscriptionRenewedWebhookEvent as SubscriptionRenewedWebhookEvent,
type UnsafeUnwrapWebhookEvent as UnsafeUnwrapWebhookEvent,
type UnwrapWebhookEvent as UnwrapWebhookEvent,
type WebhookDetailsCursorPagePagination as WebhookDetailsCursorPagePagination,
type WebhookCreateParams as WebhookCreateParams,
type WebhookUpdateParams as WebhookUpdateParams,
type WebhookListParams as WebhookListParams,
};
export {
WebhookEvents as WebhookEvents,
type WebhookEventType as WebhookEventType,
type WebhookPayload as WebhookPayload,
};
export {
UsageEvents as UsageEvents,
type Event as Event,
type EventInput as EventInput,
type UsageEventIngestResponse as UsageEventIngestResponse,
type EventsDefaultPageNumberPagination as EventsDefaultPageNumberPagination,
type UsageEventListParams as UsageEventListParams,
type UsageEventIngestParams as UsageEventIngestParams,
};
export {
Meters as Meters,
type Meter as Meter,
type MeterAggregation as MeterAggregation,
type MeterFilter as MeterFilter,
type MetersDefaultPageNumberPagination as MetersDefaultPageNumberPagination,
type MeterCreateParams as MeterCreateParams,
type MeterListParams as MeterListParams,
};
}
```