import {z} from 'zod' export type GetApiApiV1SlackChannelsArgs = {search?: string | undefined, excludeArchived?: boolean | undefined, excludeDms?: boolean | undefined, excludeGroups?: boolean | undefined, forceRefresh?: boolean | undefined, includeChannelIds?: string | undefined}; export type GetApiApiV1SlackChannelsOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const slackChannel = z.object({name: z.string(), id: z.string()}); export const apiSlackChannelsResponse = z.object({results: z.array(slackChannel).optional(), status: z.literal("ok")}); 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 }; /** * Get Slack channels * * GET /api/v1/slack/channels */ export const getApiApiV1SlackChannels = async (args: GetApiApiV1SlackChannelsArgs, options: GetApiApiV1SlackChannelsOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.search != null) query.append("search", String(args.search)) if (args.excludeArchived != null) query.append("excludeArchived", String(args.excludeArchived)) if (args.excludeDms != null) query.append("excludeDms", String(args.excludeDms)) if (args.excludeGroups != null) query.append("excludeGroups", String(args.excludeGroups)) if (args.forceRefresh != null) query.append("forceRefresh", String(args.forceRefresh)) if (args.includeChannelIds != null) query.append("includeChannelIds", String(args.includeChannelIds)) const url = `${baseUrl.replace(/\/+$/, '')}/api/v1/slack/channels${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(apiSlackChannelsResponse, await res.json()) };