import {z} from 'zod' export type TokensUsageRawData = {type: 'tokens-usage-raw-data', schema: {dateFrom: string, dateTo: string, format?: ('json' | 'csv') | undefined, projectIds?: Array | undefined, promptIds?: Array | undefined, userIds?: Array | undefined, languageIds?: Array | undefined}}; export type AiReportBase = {dateFrom: string, dateTo: string, format?: ('json' | 'csv') | undefined, projectIds?: Array | undefined, promptIds?: Array | undefined, userIds?: Array | undefined}; export type CostsByUsers = {type: 'costs-by-users', schema: AiReportBase}; export type CreateApiAiReportsArgs = {body: TokensUsageRawData | CostsByUsers}; export type CreateApiAiReportsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const aiReportGenerate = z.object({identifier: z.string().optional(), status: z.string().optional(), progress: z.number().int().optional(), attributes: z.object({format: z.string().optional(), reportType: z.string().optional(), schema: z.object({}).optional()}).optional(), createdAt: z.string().optional(), updatedAt: z.string().optional(), startedAt: z.string().optional(), finishedAt: z.string().optional(), eta: z.string().optional()}); export const aiReportResource = z.object({data: aiReportGenerate}); 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 }; /** * Generate AI Report * * POST /ai/reports */ export const createApiAiReports = async (args: CreateApiAiReportsArgs, options?: CreateApiAiReportsOptions) => { const {baseUrl = "https://api.crowdin.com/api/v2", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/ai/reports${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(aiReportResource, await res.json()) };