import {z} from 'zod' export type GetApiCalendarSummaryArgs = {around: string, consequence: 'allow' | 'first_to_arrive' | 'permit' | 'unlock', elevator_stop_id?: number | undefined, group_id?: number | undefined, lock_id?: number | undefined}; export type GetApiCalendarSummaryOptions = {baseUrl?: string | undefined, KisiLogin?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiCalendarSummaryResponse = z.object({events: z.array(z.object({starts_at: z.string(), ends_at: z.string()})).optional(), exceptions: z.array(z.object({starts_at: z.string(), ends_at: z.string()})).optional(), schedules_by_day: z.array(z.object({date: z.string(), schedule_ids: z.array(z.number().int())})).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 }; /** * Fetch summary of the events of a scheduleable's schedules * * GET /calendar/summary * * Also accepts auth: OAuth2 */ export const getApiCalendarSummary = async (args: GetApiCalendarSummaryArgs, options?: GetApiCalendarSummaryOptions) => { const {baseUrl = "https://api.kisi.io", fetch: fetchFn = fetch, KisiLogin} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.around != null) query.append("around", String(args.around)) if (args.consequence != null) query.append("consequence", String(args.consequence)) if (args.elevator_stop_id != null) query.append("elevator_stop_id", String(args.elevator_stop_id)) if (args.group_id != null) query.append("group_id", String(args.group_id)) if (args.lock_id != null) query.append("lock_id", String(args.lock_id)) if (KisiLogin !== undefined) headers.set("Authorization", KisiLogin) const url = `${baseUrl.replace(/\/+$/, '')}/calendar/summary${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(getApiCalendarSummaryResponse, await res.json()) };