import {z} from 'zod' export type ScimSearchRequest = {schemas?: Array | undefined, filter?: string | undefined, attributes?: Array | undefined, excludedAttributes?: Array | undefined, sortBy?: string | undefined, sortOrder?: ('ascending' | 'descending') | undefined, startIndex?: number | undefined, count?: number | undefined}; export type CreateApiScimV2GroupsSearchArgs = {body: ScimSearchRequest}; export type CreateApiScimV2GroupsSearchOptions = {baseUrl?: string | undefined, Authorization?: string | undefined, fetch?: typeof fetch | undefined}; export const scimListResponse = z.object({schemas: z.array(z.string()).optional(), totalResults: z.number().int().optional(), startIndex: z.number().int().optional(), itemsPerPage: z.number().int().optional(), Resources: z.array(z.object({})).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 }; /** * Search SCIM groups * * POST /scim/v2/Groups/.search */ export const createApiScimV2GroupsSearch = async (args: CreateApiScimV2GroupsSearchArgs, options?: CreateApiScimV2GroupsSearchOptions) => { const {baseUrl = "https://public-api.ringover.com/v2", fetch: fetchFn = fetch, Authorization} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/scim+json") headers.set('accept', "application/scim+json") if (Authorization !== undefined) headers.set("Authorization", Authorization) const url = `${baseUrl.replace(/\/+$/, '')}/scim/v2/Groups/.search${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(scimListResponse, await res.json()) };