import {z} from 'zod' export type GetApiOptimizationJsonArgs = {coordinates: unknown, destination?: ('any' | 'last') | undefined, geometries?: ('polyline' | 'polyline6' | 'geojson') | undefined, key: unknown, mode?: ('car' | 'truck') | undefined, roundtrip?: boolean | undefined, source?: ('any' | 'first') | undefined, with_geometry?: boolean | undefined, approaches?: ('unrestricted' | 'curb') | undefined}; export type GetApiOptimizationJsonOptions = {baseUrl?: string | undefined, apiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiOptimizationJsonResponse = z.object({code: z.string().optional(), trips: z.array(z.object({distance: z.number().optional(), duration: z.number().optional(), geojson: z.object({geometry: z.string().optional(), properties: z.string().optional(), type: z.enum(["Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", "FeatureCollection", "Link"]).optional()}).optional(), geometry: z.string().optional(), legs: z.array(z.object({distance: z.number().optional(), duration: z.number().optional(), steps: z.array(z.object({distance: z.number().optional(), duration: z.number().optional(), geojson: z.object({geometry: z.string().optional(), properties: z.string().optional(), type: z.enum(["Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection", "Feature", "FeatureCollection", "Link"]).optional()}).optional(), geometry: z.string().optional()})).optional(), summary: z.string().optional()})).optional()})).optional(), waypoints: z.array(z.object({location: z.object({latitude: z.number().optional(), longitude: z.number().optional()}).optional(), name: z.string().optional(), trips_index: z.number().int().optional(), waypoint_index: z.number().int().optional()})).optional(), location: z.object({latitude: z.number().optional(), longitude: z.number().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 }; /** * Optimization * * GET /optimization/json */ export const getApiOptimizationJson = async (args: GetApiOptimizationJsonArgs, options?: GetApiOptimizationJsonOptions) => { const {baseUrl = "https://api.nextbillion.io", fetch: fetchFn = fetch, apiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.coordinates != null) query.append("coordinates", String(args.coordinates)) if (args.destination != null) query.append("destination", String(args.destination)) if (args.geometries != null) query.append("geometries", String(args.geometries)) if (args.key != null) query.append("key", String(args.key)) if (args.mode != null) query.append("mode", String(args.mode)) if (args.roundtrip != null) query.append("roundtrip", String(args.roundtrip)) if (args.source != null) query.append("source", String(args.source)) if (args.with_geometry != null) query.append("with_geometry", String(args.with_geometry)) if (args.approaches != null) query.append("approaches", String(args.approaches)) if (apiKey !== undefined) query.set("key", apiKey) const url = `${baseUrl.replace(/\/+$/, '')}/optimization/json${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(getApiOptimizationJsonResponse, await res.json()) };