import {z} from 'zod' export type GetApiV2UsageSummaryArgs = {from?: string | undefined, to?: string | undefined, usageTermsIds?: Array | undefined, accountIds?: Array | undefined, pricingRuleKeys?: (Array<'apiChecks' | 'multistepChecks' | 'browserChecks' | 'playwrightCheckSuites' | 'uptimeMonitors' | 'aiInvocations' | 'statusPages' | 'statusPageAdditionalServices' | 'statusPageAdditionalSubscribers' | 'additionalSms' | 'additionalPhoneAlerts'>) | undefined, 'x-checkly-account'?: string | undefined}; export type GetApiV2UsageSummaryOptions = {baseUrl?: string | undefined, Bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const usageV2PricingRule = z.union([z.object({method: z.literal("per_unit"), quantity: z.number().gt(0), unit: z.string().min(1), credits: z.number().gte(0), rates: z.array(z.object({when: z.string().min(1), credits: z.number().gte(0)})).optional(), included: z.object({quantity: z.number().gte(0), period: z.string().min(1).optional()}).optional()}), z.object({method: z.literal("per_period"), period: z.literal("day"), price: z.object({annualCredits: z.number().gte(0)})}), z.object({method: z.literal("capacity_blocks_per_period"), period: z.literal("day"), unit: z.string().min(1), included: z.object({quantity: z.number().gte(0)}), block: z.object({quantity: z.number().gt(0), annualCredits: z.number().gte(0)})})]); export const usageV2Calculation = z.union([z.object({rateCondition: z.string().nullable(), measuredQuantity: z.number().gte(0), includedQuantity: z.number().gte(0).nullable(), billableQuantity: z.number().gte(0).nullable(), creditsUsed: z.number().gte(0).nullable()}), z.object({billableResourceDays: z.number().gte(0), appliedDailyCredits: z.number().gte(0), proration: z.object({daysPerYear: z.literal(365)}), creditsUsed: z.number().gte(0).nullable()}), z.object({scope: z.literal("statusPage"), measuredQuantity: z.number().gte(0), includedQuantity: z.number().gte(0), billableBlockDays: z.number().gte(0), appliedDailyCreditsPerBlock: z.number().gte(0), proration: z.object({daysPerYear: z.literal(365)}), creditsUsed: z.number().gte(0).nullable()})]); export const usageV2Breakdown = z.object({usageTermsId: z.string(), pricingRuleKey: z.enum(["apiChecks", "multistepChecks", "browserChecks", "playwrightCheckSuites", "uptimeMonitors", "aiInvocations", "statusPages", "statusPageAdditionalServices", "statusPageAdditionalSubscribers", "additionalSms", "additionalPhoneAlerts"]), accountId: z.string().optional(), period: z.object({from: z.string(), to: z.string()}), pricingRule: usageV2PricingRule, calculations: z.array(usageV2Calculation), creditsUsed: z.number().gte(0).nullable()}); export const usageV2SummaryResponse = z.object({period: z.object({from: z.string(), to: z.string()}), usageTermsIds: z.array(z.string()), totals: z.object({creditsUsed: z.number().gte(0).nullable()}), breakdown: z.array(usageV2Breakdown), coverage: z.object({gaps: z.array(z.object({from: z.string(), to: z.string()}))})}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Get usage summary * * GET /v2/usage/summary */ export const getApiV2UsageSummary = async (args: GetApiV2UsageSummaryArgs, options?: GetApiV2UsageSummaryOptions) => { const {baseUrl = "https://api.checklyhq.com", fetch: fetchFn = fetch, Bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.from != null) query.append("from", String(args.from)) if (args.to != null) query.append("to", String(args.to)) for (const item of args.usageTermsIds ?? []) query.append("usageTermsIds", String(item)) for (const item of args.accountIds ?? []) query.append("accountIds", String(item)) for (const item of args.pricingRuleKeys ?? []) query.append("pricingRuleKeys", String(item)) if (args['x-checkly-account'] != null) headers.set("x-checkly-account", String(args['x-checkly-account'])) if (Bearer !== undefined) headers.set('authorization', `Bearer ${Bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/usage/summary${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(usageV2SummaryResponse, await res.json()) };