// 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 * as qs from './internal/qs'; import { VERSION } from './version'; import * as Errors from './core/error'; import * as Uploads from './core/uploads'; import * as API from './resources/index'; import { APIPromise } from './core/api-promise'; import { ActivateSubscriptionCheckoutSessionClientSelectSchema, AddPaymentMethodCheckoutSessionClientSelectSchema, CheckoutSessionCreateParams, CheckoutSessionCreateResponse, CheckoutSessionListParams, CheckoutSessionListResponse, CheckoutSessionRetrieveResponse, CheckoutSessions, ProductCheckoutSessionClientSelectSchema, PurchaseCheckoutSessionClientSelectSchema, } from './resources/checkout-sessions'; import { CustomerClientSelectSchema, CustomerCreateParams, CustomerCreateResponse, CustomerListParams, CustomerListResponse, CustomerRetrieveBillingResponse, CustomerRetrieveResponse, CustomerUpdateParams, CustomerUpdateResponse, Customers, NonRenewingSubscriptionDetails, StandardSubscriptionDetails, ToggleSubscriptionItemFeatureRecord, UsageCreditGrantSubscriptionItemFeatureRecord, } from './resources/customers'; import { DefaultDiscountClientSelectSchema, DiscountCreateParams, DiscountCreateResponse, DiscountListParams, DiscountListResponse, DiscountRetrieveResponse, DiscountUpdateParams, DiscountUpdateResponse, Discounts, ForeverDiscountClientSelectSchema, NumberOfPaymentsDiscountClientSelectSchema, } from './resources/discounts'; import { InvoiceLineItemListParams, InvoiceLineItemListResponse, InvoiceLineItemRetrieveResponse, InvoiceLineItems, } from './resources/invoice-line-items'; import { InvoiceListParams, InvoiceListResponse, InvoiceRetrieveResponse, Invoices, } from './resources/invoices'; import { PaymentMethodListParams, PaymentMethodListResponse, PaymentMethodRetrieveResponse, PaymentMethods, } from './resources/payment-methods'; import { PaymentClientSelectSchema, PaymentListParams, PaymentListResponse, PaymentRefundParams, PaymentRefundResponse, PaymentRetrieveResponse, Payments, } from './resources/payments'; import { PriceCreateParams, PriceCreateResponse, PriceListParams, PriceListResponse, PriceUpdateParams, PriceUpdateResponse, Prices, SinglePaymentPriceClientSelectSchema, SubscriptionPriceClientSelectSchema, UsagePriceClientSelectSchema, } from './resources/prices'; import { PricingModelClientSelectSchema, PricingModelCloneParams, PricingModelCloneResponse, PricingModelCreateParams, PricingModelCreateResponse, PricingModelListParams, PricingModelListResponse, PricingModelRetrieveDefaultResponse, PricingModelRetrieveResponse, PricingModelUpdateParams, PricingModelUpdateResponse, PricingModels, } from './resources/pricing-models'; import { ProductClientSelectSchema, ProductCreateParams, ProductCreateResponse, ProductListParams, ProductListResponse, ProductRetrieveResponse, ProductUpdateParams, ProductUpdateResponse, Products, } from './resources/products'; import { ResourceClaimClaimParams, ResourceClaimClaimResponse, ResourceClaimListUsagesParams, ResourceClaimListUsagesResponse, ResourceClaimReleaseParams, ResourceClaimReleaseResponse, ResourceClaimRetrieveUsageParams, ResourceClaimRetrieveUsageResponse, ResourceClaims, } from './resources/resource-claims'; import { ResourceCreateParams, ResourceCreateResponse, ResourceListParams, ResourceListResponse, ResourceRetrieveResponse, ResourceUpdateParams, ResourceUpdateResponse, Resources, } from './resources/resources'; import { SubscriptionAdjustParams, SubscriptionAdjustResponse, SubscriptionCancelParams, SubscriptionCancelResponse, SubscriptionCreateParams, SubscriptionCreateResponse, SubscriptionListParams, SubscriptionListResponse, SubscriptionRetrieveResponse, SubscriptionUncancelResponse, Subscriptions, } from './resources/subscriptions'; import { UsageEventCreateParams, UsageEventCreateResponse, UsageEventRetrieveResponse, UsageEvents, } from './resources/usage-events'; import { UsageMeterCreateParams, UsageMeterCreateResponse, UsageMeterListParams, UsageMeterListResponse, UsageMeterRetrieveResponse, UsageMeterUpdateParams, UsageMeterUpdateResponse, UsageMeters, } from './resources/usage-meters'; 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'; export interface ClientOptions { /** * API key for accessing the Flowglad API */ apiKey?: string | undefined; /** * Override the default base URL for the API, e.g., "https://api.example.com/v2/" * * Defaults to process.env['FLOWGLAD_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 | undefined; /** * Set the log level. * * Defaults to process.env['FLOWGLAD_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 Flowglad API. */ export class Flowglad { apiKey: string; baseURL: string; maxRetries: number; timeout: number; logger: Logger; logLevel: LogLevel | undefined; fetchOptions: MergedRequestInit | undefined; private fetch: Fetch; #encoder: Opts.RequestEncoder; protected idempotencyHeader?: string; private _options: ClientOptions; /** * API Client for interfacing with the Flowglad API. * * @param {string | undefined} [opts.apiKey=process.env['FLOWGLAD_SECRET_KEY'] ?? undefined] * @param {string} [opts.baseURL=process.env['FLOWGLAD_BASE_URL'] ?? https://app.flowglad.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} opts.defaultQuery - Default query parameters to include with every request to the API. */ constructor({ baseURL = readEnv('FLOWGLAD_BASE_URL'), apiKey = readEnv('FLOWGLAD_SECRET_KEY'), ...opts }: ClientOptions = {}) { if (apiKey === undefined) { throw new Errors.FlowgladError( "The FLOWGLAD_SECRET_KEY environment variable is missing or empty; either provide it, or instantiate the Flowglad client with an apiKey option, like new Flowglad({ apiKey: 'My API Key' }).", ); } const options: ClientOptions = { apiKey, ...opts, baseURL: baseURL || `https://app.flowglad.com/`, }; this.baseURL = options.baseURL!; this.timeout = options.timeout ?? Flowglad.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('FLOWGLAD_LOG'), "process.env['FLOWGLAD_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.apiKey = apiKey; } /** * Create a new client instance re-using the same options given to the current client with optional overriding. */ withOptions(options: Partial): this { const client = new (this.constructor as any as new (props: ClientOptions) => typeof this)({ ...this._options, baseURL: this.baseURL, maxRetries: this.maxRetries, timeout: this.timeout, logger: this.logger, logLevel: this.logLevel, fetch: this.fetch, fetchOptions: this.fetchOptions, apiKey: this.apiKey, ...options, }); return client; } /** * Check whether the base URL is set to its default. */ #baseURLOverridden(): boolean { return this.baseURL !== 'https://app.flowglad.com/'; } protected defaultQuery(): Record | undefined { return this._options.defaultQuery; } protected validateHeaders({ values, nulls }: NullableHeaders) { return; } protected async authHeaders(opts: FinalRequestOptions): Promise { return buildHeaders([{ Authorization: this.apiKey }]); } protected stringifyQuery(query: Record): string { return qs.stringify(query, { arrayFormat: 'comma' }); } 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 | 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); } return url.toString(); } /** * Used as a callback for mutating the given `FinalRequestOptions` object. */ protected async prepareOptions(options: FinalRequestOptions): Promise {} /** * 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 {} get(path: string, opts?: PromiseOrValue): APIPromise { return this.methodRequest('get', path, opts); } post(path: string, opts?: PromiseOrValue): APIPromise { return this.methodRequest('post', path, opts); } patch(path: string, opts?: PromiseOrValue): APIPromise { return this.methodRequest('patch', path, opts); } put(path: string, opts?: PromiseOrValue): APIPromise { return this.methodRequest('put', path, opts); } delete(path: string, opts?: PromiseOrValue): APIPromise { return this.methodRequest('delete', path, opts); } private methodRequest( method: HTTPMethod, path: string, opts?: PromiseOrValue, ): APIPromise { return this.request( Promise.resolve(opts).then((opts) => { return { method, path, ...opts }; }), ); } request( options: PromiseOrValue, remainingRetries: number | null = null, ): APIPromise { return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined)); } private async makeRequest( optionsInput: PromiseOrValue, retriesRemaining: number | null, retryOfRequestLogID: string | undefined, ): Promise { 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 }; } async fetchWithTimeout( url: RequestInfo, init: RequestInit | undefined, ms: number, controller: AbortController, ): Promise { 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 { // 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 { 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, 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 { 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) }; } else { return this.#encoder({ body, headers }); } } static Flowglad = this; static DEFAULT_TIMEOUT = 60000; // 1 minute static FlowgladError = Errors.FlowgladError; 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; invoices: API.Invoices = new API.Invoices(this); invoiceLineItems: API.InvoiceLineItems = new API.InvoiceLineItems(this); pricingModels: API.PricingModels = new API.PricingModels(this); checkoutSessions: API.CheckoutSessions = new API.CheckoutSessions(this); products: API.Products = new API.Products(this); prices: API.Prices = new API.Prices(this); discounts: API.Discounts = new API.Discounts(this); customers: API.Customers = new API.Customers(this); payments: API.Payments = new API.Payments(this); paymentMethods: API.PaymentMethods = new API.PaymentMethods(this); subscriptions: API.Subscriptions = new API.Subscriptions(this); usageEvents: API.UsageEvents = new API.UsageEvents(this); usageMeters: API.UsageMeters = new API.UsageMeters(this); resources: API.Resources = new API.Resources(this); resourceClaims: API.ResourceClaims = new API.ResourceClaims(this); } Flowglad.Invoices = Invoices; Flowglad.InvoiceLineItems = InvoiceLineItems; Flowglad.PricingModels = PricingModels; Flowglad.CheckoutSessions = CheckoutSessions; Flowglad.Products = Products; Flowglad.Prices = Prices; Flowglad.Discounts = Discounts; Flowglad.Customers = Customers; Flowglad.Payments = Payments; Flowglad.PaymentMethods = PaymentMethods; Flowglad.Subscriptions = Subscriptions; Flowglad.UsageEvents = UsageEvents; Flowglad.UsageMeters = UsageMeters; Flowglad.Resources = Resources; Flowglad.ResourceClaims = ResourceClaims; export declare namespace Flowglad { export type RequestOptions = Opts.RequestOptions; export { Invoices as Invoices, type InvoiceRetrieveResponse as InvoiceRetrieveResponse, type InvoiceListResponse as InvoiceListResponse, type InvoiceListParams as InvoiceListParams, }; export { InvoiceLineItems as InvoiceLineItems, type InvoiceLineItemRetrieveResponse as InvoiceLineItemRetrieveResponse, type InvoiceLineItemListResponse as InvoiceLineItemListResponse, type InvoiceLineItemListParams as InvoiceLineItemListParams, }; export { PricingModels as PricingModels, type PricingModelClientSelectSchema as PricingModelClientSelectSchema, type PricingModelCreateResponse as PricingModelCreateResponse, type PricingModelRetrieveResponse as PricingModelRetrieveResponse, type PricingModelUpdateResponse as PricingModelUpdateResponse, type PricingModelListResponse as PricingModelListResponse, type PricingModelCloneResponse as PricingModelCloneResponse, type PricingModelRetrieveDefaultResponse as PricingModelRetrieveDefaultResponse, type PricingModelCreateParams as PricingModelCreateParams, type PricingModelUpdateParams as PricingModelUpdateParams, type PricingModelListParams as PricingModelListParams, type PricingModelCloneParams as PricingModelCloneParams, }; export { CheckoutSessions as CheckoutSessions, type ActivateSubscriptionCheckoutSessionClientSelectSchema as ActivateSubscriptionCheckoutSessionClientSelectSchema, type AddPaymentMethodCheckoutSessionClientSelectSchema as AddPaymentMethodCheckoutSessionClientSelectSchema, type ProductCheckoutSessionClientSelectSchema as ProductCheckoutSessionClientSelectSchema, type PurchaseCheckoutSessionClientSelectSchema as PurchaseCheckoutSessionClientSelectSchema, type CheckoutSessionCreateResponse as CheckoutSessionCreateResponse, type CheckoutSessionRetrieveResponse as CheckoutSessionRetrieveResponse, type CheckoutSessionListResponse as CheckoutSessionListResponse, type CheckoutSessionCreateParams as CheckoutSessionCreateParams, type CheckoutSessionListParams as CheckoutSessionListParams, }; export { Products as Products, type ProductClientSelectSchema as ProductClientSelectSchema, type ProductCreateResponse as ProductCreateResponse, type ProductRetrieveResponse as ProductRetrieveResponse, type ProductUpdateResponse as ProductUpdateResponse, type ProductListResponse as ProductListResponse, type ProductCreateParams as ProductCreateParams, type ProductUpdateParams as ProductUpdateParams, type ProductListParams as ProductListParams, }; export { Prices as Prices, type SinglePaymentPriceClientSelectSchema as SinglePaymentPriceClientSelectSchema, type SubscriptionPriceClientSelectSchema as SubscriptionPriceClientSelectSchema, type UsagePriceClientSelectSchema as UsagePriceClientSelectSchema, type PriceCreateResponse as PriceCreateResponse, type PriceUpdateResponse as PriceUpdateResponse, type PriceListResponse as PriceListResponse, type PriceCreateParams as PriceCreateParams, type PriceUpdateParams as PriceUpdateParams, type PriceListParams as PriceListParams, }; export { Discounts as Discounts, type DefaultDiscountClientSelectSchema as DefaultDiscountClientSelectSchema, type ForeverDiscountClientSelectSchema as ForeverDiscountClientSelectSchema, type NumberOfPaymentsDiscountClientSelectSchema as NumberOfPaymentsDiscountClientSelectSchema, type DiscountCreateResponse as DiscountCreateResponse, type DiscountRetrieveResponse as DiscountRetrieveResponse, type DiscountUpdateResponse as DiscountUpdateResponse, type DiscountListResponse as DiscountListResponse, type DiscountCreateParams as DiscountCreateParams, type DiscountUpdateParams as DiscountUpdateParams, type DiscountListParams as DiscountListParams, }; export { Customers as Customers, type CustomerClientSelectSchema as CustomerClientSelectSchema, type NonRenewingSubscriptionDetails as NonRenewingSubscriptionDetails, type StandardSubscriptionDetails as StandardSubscriptionDetails, type ToggleSubscriptionItemFeatureRecord as ToggleSubscriptionItemFeatureRecord, type UsageCreditGrantSubscriptionItemFeatureRecord as UsageCreditGrantSubscriptionItemFeatureRecord, type CustomerCreateResponse as CustomerCreateResponse, type CustomerRetrieveResponse as CustomerRetrieveResponse, type CustomerUpdateResponse as CustomerUpdateResponse, type CustomerListResponse as CustomerListResponse, type CustomerRetrieveBillingResponse as CustomerRetrieveBillingResponse, type CustomerCreateParams as CustomerCreateParams, type CustomerUpdateParams as CustomerUpdateParams, type CustomerListParams as CustomerListParams, }; export { Payments as Payments, type PaymentClientSelectSchema as PaymentClientSelectSchema, type PaymentRetrieveResponse as PaymentRetrieveResponse, type PaymentListResponse as PaymentListResponse, type PaymentRefundResponse as PaymentRefundResponse, type PaymentListParams as PaymentListParams, type PaymentRefundParams as PaymentRefundParams, }; export { PaymentMethods as PaymentMethods, type PaymentMethodRetrieveResponse as PaymentMethodRetrieveResponse, type PaymentMethodListResponse as PaymentMethodListResponse, type PaymentMethodListParams as PaymentMethodListParams, }; export { Subscriptions as Subscriptions, type SubscriptionCreateResponse as SubscriptionCreateResponse, type SubscriptionRetrieveResponse as SubscriptionRetrieveResponse, type SubscriptionListResponse as SubscriptionListResponse, type SubscriptionAdjustResponse as SubscriptionAdjustResponse, type SubscriptionCancelResponse as SubscriptionCancelResponse, type SubscriptionUncancelResponse as SubscriptionUncancelResponse, type SubscriptionCreateParams as SubscriptionCreateParams, type SubscriptionListParams as SubscriptionListParams, type SubscriptionAdjustParams as SubscriptionAdjustParams, type SubscriptionCancelParams as SubscriptionCancelParams, }; export { UsageEvents as UsageEvents, type UsageEventCreateResponse as UsageEventCreateResponse, type UsageEventRetrieveResponse as UsageEventRetrieveResponse, type UsageEventCreateParams as UsageEventCreateParams, }; export { UsageMeters as UsageMeters, type UsageMeterCreateResponse as UsageMeterCreateResponse, type UsageMeterRetrieveResponse as UsageMeterRetrieveResponse, type UsageMeterUpdateResponse as UsageMeterUpdateResponse, type UsageMeterListResponse as UsageMeterListResponse, type UsageMeterCreateParams as UsageMeterCreateParams, type UsageMeterUpdateParams as UsageMeterUpdateParams, type UsageMeterListParams as UsageMeterListParams, }; export { Resources as Resources, type ResourceCreateResponse as ResourceCreateResponse, type ResourceRetrieveResponse as ResourceRetrieveResponse, type ResourceUpdateResponse as ResourceUpdateResponse, type ResourceListResponse as ResourceListResponse, type ResourceCreateParams as ResourceCreateParams, type ResourceUpdateParams as ResourceUpdateParams, type ResourceListParams as ResourceListParams, }; export { ResourceClaims as ResourceClaims, type ResourceClaimClaimResponse as ResourceClaimClaimResponse, type ResourceClaimListUsagesResponse as ResourceClaimListUsagesResponse, type ResourceClaimReleaseResponse as ResourceClaimReleaseResponse, type ResourceClaimRetrieveUsageResponse as ResourceClaimRetrieveUsageResponse, type ResourceClaimClaimParams as ResourceClaimClaimParams, type ResourceClaimListUsagesParams as ResourceClaimListUsagesParams, type ResourceClaimReleaseParams as ResourceClaimReleaseParams, type ResourceClaimRetrieveUsageParams as ResourceClaimRetrieveUsageParams, }; export type BillingAddress = API.BillingAddress; export type NonRenewingSubscriptionRecord = API.NonRenewingSubscriptionRecord; export type PaymentMethodClientSelectSchema = API.PaymentMethodClientSelectSchema; export type PricingModelDetailsRecord = API.PricingModelDetailsRecord; export type PurchaseInvoiceClientSelectSchema = API.PurchaseInvoiceClientSelectSchema; export type StandaloneInvoiceClientSelectSchema = API.StandaloneInvoiceClientSelectSchema; export type StandardSubscriptionRecord = API.StandardSubscriptionRecord; export type StaticInvoiceLineItemClientSelectSchema = API.StaticInvoiceLineItemClientSelectSchema; export type SubscriptionInvoiceClientSelectSchema = API.SubscriptionInvoiceClientSelectSchema; export type ToggleFeatureClientSelectSchema = API.ToggleFeatureClientSelectSchema; export type UsageCreditGrantFeatureClientSelectSchema = API.UsageCreditGrantFeatureClientSelectSchema; export type UsageInvoiceLineItemClientSelectSchema = API.UsageInvoiceLineItemClientSelectSchema; export type UsageMeterClientSelectSchema = API.UsageMeterClientSelectSchema; }