import {z} from 'zod' export type GetApiFlightsSearchArgs = {query?: string | undefined, max_pages?: number | undefined, cursor?: string | undefined}; export type GetApiFlightsSearchOptions = {baseUrl?: string | undefined, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const getApiFlightsSearchResponse = z.object({links: z.object({next: z.string()}).nullable(), num_pages: z.number().int().gte(1), flights: z.array(z.object({ident: z.string(), ident_icao: z.string().nullable().optional(), ident_iata: z.string().nullable().optional(), fa_flight_id: z.string(), origin: z.object({code: z.string().nullable(), code_icao: z.string().nullable().optional(), code_iata: z.string().nullable().optional(), code_lid: z.string().nullable().optional(), timezone: z.string().nullable().optional(), name: z.string().nullable().optional(), city: z.string().nullable().optional(), airport_info_url: z.string().nullable()}).nullable(), destination: z.object({code: z.string().nullable(), code_icao: z.string().nullable().optional(), code_iata: z.string().nullable().optional(), code_lid: z.string().nullable().optional(), timezone: z.string().nullable().optional(), name: z.string().nullable().optional(), city: z.string().nullable().optional(), airport_info_url: z.string().nullable()}).nullable(), waypoints: z.array(z.number()), first_position_time: z.string().nullable(), last_position: z.object({fa_flight_id: z.string().nullable(), altitude: z.number().int(), altitude_change: z.enum(["C", "D", "-"]), groundspeed: z.number().int(), heading: z.number().int().gte(0).lte(360).nullable(), latitude: z.number(), longitude: z.number(), timestamp: z.string(), update_type: z.enum(["P", "O", "Z", "A", "M", "D", "X", "S", "null"]).nullable()}).nullable(), bounding_box: z.array(z.number()).nullable(), ident_prefix: z.string().nullable(), aircraft_type: z.string().nullable(), actual_off: z.string().nullable(), actual_on: z.string().nullable(), foresight_predictions_available: z.boolean(), predicted_out: z.string().nullable(), predicted_off: z.string().nullable(), predicted_on: z.string().nullable(), predicted_in: z.string().nullable(), predicted_out_source: z.enum(["null", "Foresight", "Historical Average"]).nullable(), predicted_off_source: z.enum(["null", "Foresight", "Historical Average"]).nullable(), predicted_on_source: z.enum(["null", "Foresight", "Historical Average"]).nullable(), predicted_in_source: z.enum(["null", "Foresight", "Historical Average"]).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 }; /** * Search for flights * * GET /flights/search */ export const getApiFlightsSearch = async (args: GetApiFlightsSearchArgs, options?: GetApiFlightsSearchOptions) => { const {baseUrl = "https://aeroapi.flightaware.com/aeroapi", fetch: fetchFn = fetch, ApiKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json; charset=UTF-8") if (args.query != null) query.append("query", String(args.query)) if (args.max_pages != null) query.append("max_pages", String(args.max_pages)) if (args.cursor != null) query.append("cursor", String(args.cursor)) if (ApiKeyAuth !== undefined) headers.set("x-apikey", ApiKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/flights/search${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(getApiFlightsSearchResponse, await res.json()) };