import {z} from 'zod' export type GetApiV1WhoamiOptions = {baseUrl?: string | undefined, DashboardUserOrServiceAccountContextAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const whoamiUserPrincipal = z.object({principal_type: z.literal("user").optional(), id: z.string(), email: z.string().nullable().optional(), first_name: z.string().nullable().optional(), last_name: z.string().nullable().optional()}); export const whoamiServiceAccountPrincipal = z.object({principal_type: z.literal("service_account").optional(), service_account_id: z.string(), name: z.string().nullable().optional()}); export const whoamiOrganization = z.object({id: z.string(), name: z.string(), org_tier: z.string().nullable().optional(), internal: z.boolean().optional(), kind: z.string().optional()}); export const userIdentityWorkspace = z.object({id: z.string(), name: z.string()}); export const whoamiResponse = z.object({principal: z.discriminatedUnion("principal_type", [whoamiUserPrincipal, whoamiServiceAccountPrincipal]), organization: whoamiOrganization.nullable().optional(), workspace: userIdentityWorkspace.nullable().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 }; /** * Whoami * * GET /v1/whoami * * Also accepts auth: BearerUserContextAuth */ export const getApiV1Whoami = async (options?: GetApiV1WhoamiOptions) => { const {baseUrl = "https://api.mistral.ai", fetch: fetchFn = fetch, DashboardUserOrServiceAccountContextAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (DashboardUserOrServiceAccountContextAuth !== undefined) headers.set("x-api-key", DashboardUserOrServiceAccountContextAuth) const url = `${baseUrl.replace(/\/+$/, '')}/v1/whoami${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(whoamiResponse, await res.json()) };