import {z} from 'zod' export type GetApiMatrixClientV3SyncArgs = {filter?: string | undefined, since?: string | undefined, full_state?: boolean | undefined, set_presence?: ('offline' | 'online' | 'unavailable') | undefined, timeout?: number | undefined, use_state_after?: boolean | undefined}; export type GetApiMatrixClientV3SyncOptions = {baseUrl?: string | undefined, accessTokenQuery?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiMatrixClientV3SyncResponse = z.object({account_data: z.object({events: z.array(z.object({content: z.object({}), type: z.string()})).optional()}).optional(), device_lists: z.object({}).optional(), device_one_time_keys_count: z.record(z.string(), z.number().int()).optional(), next_batch: z.string(), presence: z.object({events: z.array(z.object({content: z.object({}), type: z.string()})).optional()}).optional(), rooms: z.object({invite: z.object({}).optional(), join: z.object({}).optional(), knock: z.object({}).optional(), leave: z.object({}).optional()}).optional(), to_device: 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 }; /** * Synchronise the client's state and receive new messages. * * GET /_matrix/client/v3/sync * * Also accepts auth: accessTokenBearer */ export const getApiMatrixClientV3Sync = async (args: GetApiMatrixClientV3SyncArgs, options?: GetApiMatrixClientV3SyncOptions) => { const {baseUrl = "https://matrix.org", fetch: fetchFn = fetch, accessTokenQuery} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.filter != null) query.append("filter", String(args.filter)) if (args.since != null) query.append("since", String(args.since)) if (args.full_state != null) query.append("full_state", String(args.full_state)) if (args.set_presence != null) query.append("set_presence", String(args.set_presence)) if (args.timeout != null) query.append("timeout", String(args.timeout)) if (args.use_state_after != null) query.append("use_state_after", String(args.use_state_after)) if (accessTokenQuery !== undefined) query.set("access_token", accessTokenQuery) const url = `${baseUrl.replace(/\/+$/, '')}/_matrix/client/v3/sync${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(getApiMatrixClientV3SyncResponse, await res.json()) };