import {z} from 'zod' export type CreateApiApiUsersV2Args = {body: {data: {type: 'ppms/user', attributes: {password: string, email: string, role?: ('OWNER' | 'USER') | undefined, language?: unknown | undefined}}}}; export type CreateApiApiUsersV2Options = {baseUrl?: string | undefined, OAuth2ClientCredentials?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiApiUsersV2Response = z.object({data: z.object({id: z.string().optional(), type: z.literal("ppms/user").optional(), attributes: z.object({email: z.string().optional(), role: z.enum(["OWNER", "USER"]).optional(), organization: z.string().optional(), addedAt: z.string().optional(), language: z.string().optional()}).optional()}).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 }; /** * Create user * * POST /api/users/v2 */ export const createApiApiUsersV2 = async (args: CreateApiApiUsersV2Args, options?: CreateApiApiUsersV2Options) => { const {baseUrl = "https://example.piwik.pro", fetch: fetchFn = fetch, OAuth2ClientCredentials} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/vnd.api+json") headers.set('accept', "application/vnd.api+json") if (OAuth2ClientCredentials !== undefined) headers.set('authorization', `Bearer ${OAuth2ClientCredentials}`) const url = `${baseUrl.replace(/\/+$/, '')}/api/users/v2${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(createApiApiUsersV2Response, await res.json()) };