import {z} from 'zod' export type OnlineUserListCreateData = {includeBackgroundSessions?: boolean | undefined, selectedConversationId?: (string | null) | undefined, hasFocus?: boolean | undefined, isTyping?: boolean | undefined, userIds?: Array | undefined}; export type CreateApiV1AppIdPresencesArgs = {appId: string, body: OnlineUserListCreateData}; export type CreateApiV1AppIdPresencesOptions = {baseUrl?: string | undefined, JWTAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const session = z.array(z.object({custom: z.record(z.string(), z.string()).optional(), selectedConversationId: z.string().optional(), isTyping: z.boolean().optional(), hasFocus: z.boolean().optional(), sessionId: z.string().optional()})); export const onlineUserList = z.object({data: z.record(z.string(), z.object({status: z.string().optional(), backgroundSessions: session.optional(), widgets: session.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 }; /** * List online users * * POST /v1/{appId}/presences * * Also accepts auth: ApiKeyAuth */ export const createApiV1AppIdPresences = async (args: CreateApiV1AppIdPresencesArgs, options?: CreateApiV1AppIdPresencesOptions) => { const {baseUrl = "https://api.talkjs.com", fetch: fetchFn = fetch, JWTAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (JWTAuth !== undefined) headers.set('authorization', `Bearer ${JWTAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/${encodeURIComponent(String(args.appId))}/presences${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(onlineUserList, await res.json()) };