import {z} from 'zod' export type GetApiRoutesArgs = {pageToken?: string | undefined, maxPageSize?: number | undefined, filter?: ({startsGte?: string | undefined, startsLte?: string | undefined}) | undefined}; export type GetApiRoutesOptions = {baseUrl?: string | undefined, BasicAuth?: {username: string, password: string} | undefined, fetch?: typeof fetch | undefined}; export const routeIdSchema = z.string(); export const driverIdSchema = z.string(); export const planIdSchema = z.string(); export const routeSchema = z.object({id: routeIdSchema, title: z.string(), stopCount: z.number(), driver: driverIdSchema.nullable(), state: z.object({completed: z.boolean(), completedAt: z.number().nullable(), distributed: z.boolean(), distributedAt: z.number().nullable(), notifiedRecipients: z.boolean(), notifiedRecipientsAt: z.number().nullable(), started: z.boolean(), startedAt: z.number().nullable()}).nullable(), plan: planIdSchema.nullable()}); export const getApiRoutesResponse = z.object({routes: z.array(routeSchema), nextPageToken: z.string().nullable()}); 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 Routes * * GET /routes */ export const getApiRoutes = async (args: GetApiRoutesArgs, options?: GetApiRoutesOptions) => { const {baseUrl = "https://api.spoke.com/public/v1", fetch: fetchFn = fetch, BasicAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.pageToken != null) query.append("pageToken", String(args.pageToken)) if (args.maxPageSize != null) query.append("maxPageSize", String(args.maxPageSize)) if (args.filter != null) query.append("filter", JSON.stringify(args.filter)) if (BasicAuth !== undefined) headers.set('authorization', `Basic ${btoa(`${BasicAuth.username}:${BasicAuth.password}`)}`) const url = `${baseUrl.replace(/\/+$/, '')}/routes${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(getApiRoutesResponse, await res.json()) };