import {z} from 'zod' export type GetApiApiV1TriggerUsageArgs = {from?: string | undefined, to?: string | undefined, period?: ('24h' | '7d' | '30d') | undefined}; export type GetApiApiV1TriggerUsageOptions = {baseUrl?: string | undefined, oauth2?: string | undefined, fetch?: typeof fetch | undefined}; export const triggersTriggerUsageBucket = z.enum(["TRIGGER_USAGE_BUCKET_DAY", "TRIGGER_USAGE_BUCKET_HOUR"]); export const triggersTriggerUsageDay = z.object({date: z.string().optional(), units: z.string().optional()}); export const triggersTriggerUsageHour = z.object({start: z.string().optional(), units: z.string().optional()}); export const triggersGetTriggerUsageResponse = z.object({bucket: triggersTriggerUsageBucket.optional(), current_hour: z.string().optional(), days: z.array(triggersTriggerUsageDay).optional(), from: z.string().optional(), hours: z.array(triggersTriggerUsageHour).optional(), period: z.string().optional(), to: z.string().optional(), today: z.string().optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Get metered trigger usage * * GET /api/v1/trigger-usage */ export const getApiApiV1TriggerUsage = async (args: GetApiApiV1TriggerUsageArgs, options?: GetApiApiV1TriggerUsageOptions) => { const {baseUrl = "https://$SCALEKIT_ENVIRONMENT_URL", fetch: fetchFn = fetch, oauth2} = 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)) if (args.period != null) query.append("period", String(args.period)) if (oauth2 !== undefined) headers.set('authorization', `Bearer ${oauth2}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/trigger-usage${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(triggersGetTriggerUsageResponse, await res.json()) };