Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

32.3 KB
Raw Blame
/**
 * Tests for the search-page transport (`src/search/tfs.ts`).
 *
 * Everything here is offline.
 *
 * The `tfs` goldens were produced by running the Python reference
 * implementation this module ports — see the header on `TFS_GOLDENS`
 * below for the exact command. A mismatch means the TypeScript encoder
 * has drifted from the Python one, and therefore from what Google
 * accepts.
 */

import { describe, expect, test } from "bun:test";
import { Airline } from "../../src/models/airline.ts";
import { Airport } from "../../src/models/airport.ts";
import {
  Alliance,
  type FlightLeg,
  type FlightResult,
  FlightSegment,
  type LayoverRestrictions,
  MaxStops,
  type PassengerInfo,
  type PriceLimit,
  SeatType,
  type TimeRestrictions,
  TripType,
} from "../../src/models/google-flights/base.ts";
import { FlightSearchFilters } from "../../src/models/google-flights/flights.ts";
import { Client } from "../../src/search/client.ts";
import { SearchUnsupportedError } from "../../src/search/exceptions.ts";
import { setSearchLogger } from "../../src/search/logging.ts";
import { buildTfsToken, passengerCodes as passengerCodesFromInfo } from "../../src/search/proto.ts";
import {
  _setPageRetrySleep,
  applyClientSideFilters,
  buildTfs,
  extractPayload,
  fetchPayload,
  PAGE_FETCH_ATTEMPTS,
  pageUrl,
  unsupportedFilters,
} from "../../src/search/tfs.ts";

// ---------------------------------------------------------------------------
// Golden `tfs` values
// ---------------------------------------------------------------------------

/**
 * Expected `tfs` values, generated by running the Python implementation.
 *
 * Regenerate with (from the repository root):
 *
 * ```
 * uv run --python 3.13 python fli-js/scripts/dump_tfs_goldens.py
 * ```
 *
 * The travel dates are deliberately far out (2030): `FlightSegment`
 * rejects a past date, and unlike the Python suite this one has no
 * clock-pinning fixture, so a golden built on a near date would start
 * failing the day it passed. The `tfs` bytes do not depend on "today" —
 * only on the dates in the filters — so a 2030 date pins the encoder
 * exactly as a 2026 one would.
 */
const TFS_GOLDENS: Record<string, string> = {
  alliance_exclude_oneworld:
    "CBwQAhooEgoyMDMwLTA5LTE1OghPTkVXT1JMRGoHCAESA0pGS3IHCAESA0xBWEABSAFwAZgBAg",
  alliance_exclude_skyteam:
    "CBwQAhonEgoyMDMwLTA5LTE1OgdTS1lURUFNagcIARIDSkZLcgcIARIDTEFYQAFIAXABmAEC",
  alliance_exclude_star_alliance:
    "CBwQAhotEgoyMDMwLTA5LTE1Og1TVEFSX0FMTElBTkNFagcIARIDSkZLcgcIARIDTEFYQAFIAXABmAEC",
  alliance_include_oneworld:
    "CBwQAhooEgoyMDMwLTA5LTE1MghPTkVXT1JMRGoHCAESA0pGS3IHCAESA0xBWEABSAFwAZgBAg",
  alliance_include_skyteam:
    "CBwQAhonEgoyMDMwLTA5LTE1MgdTS1lURUFNagcIARIDSkZLcgcIARIDTEFYQAFIAXABmAEC",
  alliance_include_star_alliance:
    "CBwQAhotEgoyMDMwLTA5LTE1Mg1TVEFSX0FMTElBTkNFagcIARIDSkZLcgcIARIDTEFYQAFIAXABmAEC",
  alliance_include_two_exclude_one:
    "CBwQAhpAEgoyMDMwLTA5LTE1MghPTkVXT1JMRDINU1RBUl9BTExJQU5DRToHU0tZVEVBTWoHCAESA0pGS3IHCAESA0xBWEABSAFwAZgBAg",
  cabin_business: "CBwQAhoeEgoyMDMwLTA5LTE1agcIARIDSkZLcgcIARIDTEFYQAFIA3ABmAEC",
  cabin_economy: "CBwQAhoeEgoyMDMwLTA5LTE1agcIARIDSkZLcgcIARIDTEFYQAFIAXABmAEC",
  cabin_first: "CBwQAhoeEgoyMDMwLTA5LTE1agcIARIDSkZLcgcIARIDTEFYQAFIBHABmAEC",
  cabin_premium_economy: "CBwQAhoeEgoyMDMwLTA5LTE1agcIARIDSkZLcgcIARIDTEFYQAFIAnABmAEC",
  kitchen_sink_round_trip:
    "CBwQAhpIEgoyMDMwLTA5LTE1KAEyCE9ORVdPUkxEagcIARIDSkZLagcIARIDRVdScgcIARIDTEhScgcIARIDTEdXegNEVUKIATyQAfABGkgSCjIwMzAtMDktMTkoATIIT05FV09STERqBwgBEgNMSFJqBwgBEgNMR1dyBwgBEgNKRktyBwgBEgNFV1J6A0RVQogBPJAB8AFAAUABQAJAA0gDcAGYAQE",
  layover_airport_and_min:
    "CBwQAhomEgoyMDMwLTA5LTE1agcIARIDSkZLcgcIARIDTEFYegNPUkSIAXhAAUgBcAGYAQI",
  layover_full:
    "CBwQAhovEgoyMDMwLTA5LTE1agcIARIDSkZLcgcIARIDTEFYegNPUkR6A0RGV4gBWpAB2ARAAUgBcAGYAQI",
  layover_max_only: "CBwQAhoiEgoyMDMwLTA5LTE1agcIARIDSkZLcgcIARIDTEFYkAGsAkABSAFwAZgBAg",
  multi_airport:
    "CBwQAho5EgoyMDMwLTEwLTE1agcIARIDQk9NagcIARIDREVMagcIARIDQU1EcgcIARIDT1JEcgcIARIDRFRXQAFIAXABmAEC",
  one_way_jfk_lax: "CBwQAhoeEgoyMDMwLTA5LTE1agcIARIDSkZLcgcIARIDTEFYQAFIAXABmAEC",
  pax_adult_child: "CBwQAhoeEgoyMDMwLTA5LTE1agcIARIDSkZLcgcIARIDTEFYQAFAAkgBcAGYAQI",
  pax_adult_lap_infant: "CBwQAhoeEgoyMDMwLTA5LTE1agcIARIDSkZLcgcIARIDTEFYQAFAA0gBcAGYAQI",
  pax_adult_seat_infant: "CBwQAhoeEgoyMDMwLTA5LTE1agcIARIDSkZLcgcIARIDTEFYQAFABEgBcAGYAQI",
  pax_family_mix: "CBwQAhoeEgoyMDMwLTA5LTE1agcIARIDSkZLcgcIARIDTEFYQAFAAUACQANABEgBcAGYAQI",
  pax_full_house:
    "CBwQAhoeEgoyMDMwLTA5LTE1agcIARIDSkZLcgcIARIDTEFYQAFAAUABQAFAAkACQANABEAESAFwAZgBAg",
  pax_single_adult: "CBwQAhoeEgoyMDMwLTA5LTE1agcIARIDSkZLcgcIARIDTEFYQAFIAXABmAEC",
  pax_two_adults: "CBwQAhoeEgoyMDMwLTA5LTE1agcIARIDSkZLcgcIARIDTEFYQAFAAUgBcAGYAQI",
  pax_two_adults_two_lap_infants:
    "CBwQAhoeEgoyMDMwLTA5LTE1agcIARIDSkZLcgcIARIDTEFYQAFAAUADQANIAXABmAEC",
  round_trip_jfk_lax:
    "CBwQAhoeEgoyMDMwLTA5LTE1agcIARIDSkZLcgcIARIDTEFYGh4SCjIwMzAtMDktMTlqBwgBEgNMQVhyBwgBEgNKRktAAUgBcAGYAQE",
  round_trip_selected_connecting_outbound:
    "CBwQAhpgEgoyMDMwLTA5LTE1Ih8KA0pGSxIKMjAzMC0wOS0xNRoDT1JEKgJBQTIDMTAwIh8KA09SRBIKMjAzMC0wOS0xNRoDTEhSKgJBQTIDMjAwagcIARIDSkZLcgcIARIDTEhSGh4SCjIwMzAtMDktMTlqBwgBEgNMSFJyBwgBEgNKRktAAUgBcAGYAQE",
  round_trip_selected_outbound:
    "CBwQAho_EgoyMDMwLTA5LTE1Ih8KA0pGSxIKMjAzMC0wOS0xNRoDTEhSKgJCQTIDMTc4agcIARIDSkZLcgcIARIDTEhSGh4SCjIwMzAtMDktMTlqBwgBEgNMSFJyBwgBEgNKRktAAUgBcAGYAQE",
  stops_any: "CBwQAhoeEgoyMDMwLTA5LTE1agcIARIDSkZLcgcIARIDTEFYQAFIAXABmAEC",
  stops_non_stop: "CBwQAhogEgoyMDMwLTA5LTE1KABqBwgBEgNKRktyBwgBEgNMQVhAAUgBcAGYAQI",
  stops_one_stop_or_fewer: "CBwQAhogEgoyMDMwLTA5LTE1KAFqBwgBEgNKRktyBwgBEgNMQVhAAUgBcAGYAQI",
  stops_two_or_fewer_stops: "CBwQAhogEgoyMDMwLTA5LTE1KAJqBwgBEgNKRktyBwgBEgNMQVhAAUgBcAGYAQI",
  sweep_one_way_date_override: "CBwQAhoeEgoyMDMwLTExLTAyagcIARIDSkZLcgcIARIDTEFYQAFIAXABmAEC",
  sweep_round_trip_date_override:
    "CBwQAhoeEgoyMDMwLTExLTAyagcIARIDSkZLcgcIARIDTEFYGh4SCjIwMzAtMTEtMDlqBwgBEgNMQVhyBwgBEgNKRktAAUgBcAGYAQE",
};

const OUT = "2030-09-15";
const RET = "2030-09-19";
const MULTI = "2030-10-15";

// ---------------------------------------------------------------------------
// Builders mirroring the Python test helpers
// ---------------------------------------------------------------------------

interface FilterOverrides {
  trip_type?: TripType;
  passenger_info?: Partial<PassengerInfo>;
  stops?: MaxStops;
  seat_type?: SeatType;
  airlines?: Airline[] | null;
  airlines_exclude?: Airline[] | null;
  max_duration?: number | null;
  price_limit?: PriceLimit | null;
  alliances?: Alliance[] | null;
  alliances_exclude?: Alliance[] | null;
  layover_restrictions?: LayoverRestrictions | null;
  time_restrictions?: TimeRestrictions | null;
}

function pax(counts: Partial<PassengerInfo> = {}): PassengerInfo {
  return {
    adults: counts.adults ?? 1,
    children: counts.children ?? 0,
    infants_in_seat: counts.infants_in_seat ?? 0,
    infants_on_lap: counts.infants_on_lap ?? 0,
  };
}

function filters(
  segments: Array<[string[], string[], string]>,
  overrides: FilterOverrides = {},
): FlightSearchFilters {
  return new FlightSearchFilters({
    trip_type: overrides.trip_type ?? TripType.ONE_WAY,
    passenger_info: pax(overrides.passenger_info),
    flight_segments: segments.map(([o, d, date]) => {
      const s = new FlightSegment({
        departure_airport: [o.map((x) => [x as Airport, 0])],
        arrival_airport: [d.map((x) => [x as Airport, 0])],
        travel_date: date,
        time_restrictions: overrides.time_restrictions ?? null,
      });
      return s;
    }),
    stops: overrides.stops ?? MaxStops.ANY,
    seat_type: overrides.seat_type ?? SeatType.ECONOMY,
    airlines: overrides.airlines ?? null,
    airlines_exclude: overrides.airlines_exclude ?? null,
    max_duration: overrides.max_duration ?? null,
    price_limit: overrides.price_limit ?? null,
    alliances: overrides.alliances ?? null,
    alliances_exclude: overrides.alliances_exclude ?? null,
    layover_restrictions: overrides.layover_restrictions ?? null,
  });
}

function leg(over: Partial<FlightLeg> = {}): FlightLeg {
  return {
    airline: Airline.AA,
    flight_number: "171",
    departure_airport: Airport.JFK,
    arrival_airport: Airport.LAX,
    departure_datetime: new Date(2030, 8, 15, 9, 0),
    arrival_datetime: new Date(2030, 8, 15, 12, 0),
    duration: 180,
    ...over,
  };
}

function flight(
  over: { airline?: Airline; price?: number | null; duration?: number; hour?: number } = {},
): FlightResult {
  const hour = over.hour ?? 9;
  const duration = over.duration ?? 180;
  return {
    legs: [
      leg({
        airline: over.airline ?? Airline.AA,
        departure_datetime: new Date(2030, 8, 15, hour, 0),
        arrival_datetime: new Date(2030, 8, 15, hour + 3, 0),
        duration,
      }),
    ],
    price: over.price === undefined ? 300 : over.price,
    currency: "USD",
    duration,
    stops: 0,
  };
}

function decode(tfs: string): Uint8Array {
  const padded = tfs + "=".repeat((4 - (tfs.length % 4)) % 4);
  return new Uint8Array(Buffer.from(padded.replace(/-/g, "+").replace(/_/g, "/"), "base64"));
}

/** Read the repeated field 8 (passenger kinds) out of a `tfs` token. */
function passengerCodes(tfs: string): number[] {
  const raw = decode(tfs);
  const codes: number[] = [];
  let offset = 0;
  const readVarint = (): number => {
    let value = 0;
    let shift = 0;
    while (true) {
      const byte = raw[offset] as number;
      offset++;
      value += (byte & 0x7f) * 2 ** shift;
      if ((byte & 0x80) === 0) return value;
      shift += 7;
    }
  };
  while (offset < raw.length) {
    const tag = readVarint();
    const field = tag >> 3;
    const wire = tag & 0x7;
    if (wire === 0) {
      const value = readVarint();
      if (field === 8) codes.push(value);
    } else if (wire === 2) {
      // `offset += readVarint()` would read `offset` before the call
      // mutates it, and skip from the wrong place.
      const length = readVarint();
      offset += length;
    } else {
      throw new Error(`unexpected wire type ${wire} at offset ${offset}`);
    }
  }
  return codes;
}

// ---------------------------------------------------------------------------
// Token parity with the Python implementation
// ---------------------------------------------------------------------------

describe("buildTfs golden parity with Python", () => {
  const cases: Array<[string, () => string]> = [
    ["one_way_jfk_lax", () => buildTfs(filters([[["JFK"], ["LAX"], OUT]]))],
    [
      "round_trip_jfk_lax",
      () =>
        buildTfs(
          filters(
            [
              [["JFK"], ["LAX"], OUT],
              [["LAX"], ["JFK"], RET],
            ],
            { trip_type: TripType.ROUND_TRIP },
          ),
        ),
    ],
    [
      "round_trip_selected_outbound",
      () => {
        const spec = filters(
          [
            [["JFK"], ["LHR"], OUT],
            [["LHR"], ["JFK"], RET],
          ],
          { trip_type: TripType.ROUND_TRIP },
        );
        (spec.flight_segments[0] as FlightSegment).selected_flight = {
          legs: [
            leg({
              airline: Airline.BA,
              flight_number: "178",
              departure_airport: Airport.JFK,
              arrival_airport: Airport.LHR,
              departure_datetime: new Date(2030, 8, 15, 20, 30),
              arrival_datetime: new Date(2030, 8, 16, 8, 30),
              duration: 420,
            }),
          ],
          price: 295,
          currency: "USD",
          duration: 420,
          stops: 0,
        };
        return buildTfs(spec);
      },
    ],
    [
      "round_trip_selected_connecting_outbound",
      () => {
        const spec = filters(
          [
            [["JFK"], ["LHR"], OUT],
            [["LHR"], ["JFK"], RET],
          ],
          { trip_type: TripType.ROUND_TRIP },
        );
        (spec.flight_segments[0] as FlightSegment).selected_flight = {
          legs: [
            leg({
              airline: Airline.AA,
              flight_number: "100",
              departure_airport: Airport.JFK,
              arrival_airport: Airport.ORD,
              departure_datetime: new Date(2030, 8, 15, 7, 0),
              arrival_datetime: new Date(2030, 8, 15, 9, 0),
              duration: 150,
            }),
            leg({
              airline: Airline.AA,
              flight_number: "200",
              departure_airport: Airport.ORD,
              arrival_airport: Airport.LHR,
              departure_datetime: new Date(2030, 8, 15, 17, 0),
              arrival_datetime: new Date(2030, 8, 16, 7, 0),
              duration: 480,
            }),
          ],
          price: 420,
          currency: "USD",
          duration: 900,
          stops: 1,
        };
        return buildTfs(spec);
      },
    ],
    ["multi_airport", () => buildTfs(filters([[["BOM", "DEL", "AMD"], ["ORD", "DTW"], MULTI]]))],
    ["cabin_economy", () => buildTfs(filters([[["JFK"], ["LAX"], OUT]]))],
    [
      "cabin_premium_economy",
      () => buildTfs(filters([[["JFK"], ["LAX"], OUT]], { seat_type: SeatType.PREMIUM_ECONOMY })),
    ],
    [
      "cabin_business",
      () => buildTfs(filters([[["JFK"], ["LAX"], OUT]], { seat_type: SeatType.BUSINESS })),
    ],
    [
      "cabin_first",
      () => buildTfs(filters([[["JFK"], ["LAX"], OUT]], { seat_type: SeatType.FIRST })),
    ],
    ["stops_any", () => buildTfs(filters([[["JFK"], ["LAX"], OUT]], { stops: MaxStops.ANY }))],
    [
      "stops_non_stop",
      () => buildTfs(filters([[["JFK"], ["LAX"], OUT]], { stops: MaxStops.NON_STOP })),
    ],
    [
      "stops_one_stop_or_fewer",
      () => buildTfs(filters([[["JFK"], ["LAX"], OUT]], { stops: MaxStops.ONE_STOP_OR_FEWER })),
    ],
    [
      "stops_two_or_fewer_stops",
      () => buildTfs(filters([[["JFK"], ["LAX"], OUT]], { stops: MaxStops.TWO_OR_FEWER_STOPS })),
    ],
    [
      "pax_single_adult",
      () => buildTfs(filters([[["JFK"], ["LAX"], OUT]], { passenger_info: { adults: 1 } })),
    ],
    [
      "pax_two_adults",
      () => buildTfs(filters([[["JFK"], ["LAX"], OUT]], { passenger_info: { adults: 2 } })),
    ],
    [
      "pax_adult_child",
      () =>
        buildTfs(
          filters([[["JFK"], ["LAX"], OUT]], { passenger_info: { adults: 1, children: 1 } }),
        ),
    ],
    [
      "pax_adult_lap_infant",
      () =>
        buildTfs(
          filters([[["JFK"], ["LAX"], OUT]], { passenger_info: { adults: 1, infants_on_lap: 1 } }),
        ),
    ],
    [
      "pax_adult_seat_infant",
      () =>
        buildTfs(
          filters([[["JFK"], ["LAX"], OUT]], { passenger_info: { adults: 1, infants_in_seat: 1 } }),
        ),
    ],
    [
      "pax_family_mix",
      () =>
        buildTfs(
          filters([[["JFK"], ["LAX"], OUT]], {
            passenger_info: { adults: 2, children: 1, infants_in_seat: 1, infants_on_lap: 1 },
          }),
        ),
    ],
    [
      "pax_full_house",
      () =>
        buildTfs(
          filters([[["JFK"], ["LAX"], OUT]], {
            passenger_info: { adults: 4, children: 2, infants_in_seat: 2, infants_on_lap: 1 },
          }),
        ),
    ],
    [
      "pax_two_adults_two_lap_infants",
      () =>
        buildTfs(
          filters([[["JFK"], ["LAX"], OUT]], { passenger_info: { adults: 2, infants_on_lap: 2 } }),
        ),
    ],
    [
      "alliance_include_oneworld",
      () => buildTfs(filters([[["JFK"], ["LAX"], OUT]], { alliances: [Alliance.ONEWORLD] })),
    ],
    [
      "alliance_include_skyteam",
      () => buildTfs(filters([[["JFK"], ["LAX"], OUT]], { alliances: [Alliance.SKYTEAM] })),
    ],
    [
      "alliance_include_star_alliance",
      () => buildTfs(filters([[["JFK"], ["LAX"], OUT]], { alliances: [Alliance.STAR_ALLIANCE] })),
    ],
    [
      "alliance_exclude_oneworld",
      () =>
        buildTfs(filters([[["JFK"], ["LAX"], OUT]], { alliances_exclude: [Alliance.ONEWORLD] })),
    ],
    [
      "alliance_exclude_skyteam",
      () => buildTfs(filters([[["JFK"], ["LAX"], OUT]], { alliances_exclude: [Alliance.SKYTEAM] })),
    ],
    [
      "alliance_exclude_star_alliance",
      () =>
        buildTfs(
          filters([[["JFK"], ["LAX"], OUT]], { alliances_exclude: [Alliance.STAR_ALLIANCE] }),
        ),
    ],
    [
      "alliance_include_two_exclude_one",
      () =>
        buildTfs(
          filters([[["JFK"], ["LAX"], OUT]], {
            alliances: [Alliance.ONEWORLD, Alliance.STAR_ALLIANCE],
            alliances_exclude: [Alliance.SKYTEAM],
          }),
        ),
    ],
    [
      "layover_airport_and_min",
      () =>
        buildTfs(
          filters([[["JFK"], ["LAX"], OUT]], {
            layover_restrictions: { airports: [Airport.ORD], min_duration: 120 },
          }),
        ),
    ],
    [
      "layover_max_only",
      () =>
        buildTfs(
          filters([[["JFK"], ["LAX"], OUT]], { layover_restrictions: { max_duration: 300 } }),
        ),
    ],
    [
      "layover_full",
      () =>
        buildTfs(
          filters([[["JFK"], ["LAX"], OUT]], {
            layover_restrictions: {
              airports: [Airport.ORD, Airport.DFW],
              min_duration: 90,
              max_duration: 600,
            },
          }),
        ),
    ],
    [
      "kitchen_sink_round_trip",
      () =>
        buildTfs(
          filters(
            [
              [["JFK", "EWR"], ["LHR", "LGW"], OUT],
              [["LHR", "LGW"], ["JFK", "EWR"], RET],
            ],
            {
              trip_type: TripType.ROUND_TRIP,
              stops: MaxStops.ONE_STOP_OR_FEWER,
              seat_type: SeatType.BUSINESS,
              passenger_info: { adults: 2, children: 1, infants_on_lap: 1 },
              alliances: [Alliance.ONEWORLD],
              layover_restrictions: {
                airports: [Airport.DUB],
                min_duration: 60,
                max_duration: 240,
              },
            },
          ),
        ),
    ],
    [
      "sweep_one_way_date_override",
      () => buildTfs(filters([[["JFK"], ["LAX"], OUT]]), { travelDates: ["2030-11-02"] }),
    ],
    [
      "sweep_round_trip_date_override",
      () =>
        buildTfs(
          filters(
            [
              [["JFK"], ["LAX"], OUT],
              [["LAX"], ["JFK"], RET],
            ],
            { trip_type: TripType.ROUND_TRIP },
          ),
          { travelDates: ["2030-11-02", "2030-11-09"] },
        ),
    ],
  ];

  for (const [name, build] of cases) {
    test(`${name} is byte-identical to Python`, () => {
      const golden = TFS_GOLDENS[name];
      expect(golden).toBeDefined();
      expect(build()).toBe(golden as string);
    });
  }

  test("every golden is covered by a case", () => {
    expect(new Set(cases.map(([name]) => name))).toEqual(new Set(Object.keys(TFS_GOLDENS)));
  });
});

describe("buildTfs structure", () => {
  test("MaxStops.ANY omits the ceiling — writing 0 would mean non-stop", () => {
    expect(buildTfs(filters([[["JFK"], ["LAX"], OUT]]))).not.toBe(TFS_GOLDENS.stops_non_stop);
  });

  test("every airport in a multi-airport segment reaches the request", () => {
    const raw = Buffer.from(
      decode(buildTfs(filters([[["BOM", "DEL", "AMD"], ["ORD", "DTW"], MULTI]]))),
    );
    for (const code of ["BOM", "DEL", "AMD", "ORD", "DTW"]) {
      expect(raw.includes(code)).toBe(true);
    }
  });

  test("field 19 says one-way (2) or round trip (1)", () => {
    const oneWay = decode(buildTfs(filters([[["JFK"], ["LAX"], OUT]])));
    const roundTrip = decode(
      buildTfs(
        filters(
          [
            [["JFK"], ["LAX"], OUT],
            [["LAX"], ["JFK"], RET],
          ],
          { trip_type: TripType.ROUND_TRIP },
        ),
      ),
    );
    expect(Array.from(oneWay.slice(-3))).toEqual([0x98, 0x01, 0x02]);
    expect(Array.from(roundTrip.slice(-3))).toEqual([0x98, 0x01, 0x01]);
  });

  test("multi-city is refused with a typed error", () => {
    const spec = filters(
      [
        [["MNL"], ["DXB"], "2030-10-12"],
        [["DXB"], ["FCO"], "2030-10-16"],
        [["FCO"], ["MNL"], "2030-10-25"],
      ],
      { trip_type: TripType.MULTI_CITY },
    );
    expect(() => buildTfs(spec)).toThrow(SearchUnsupportedError);
    expect(() => buildTfs(spec)).toThrow(/Multi-city/);
  });
});

describe("passenger wire codes", () => {
  // These codes are money: on an international route a lap infant prices
  // at ~10% of the adult fare while an infant in its own seat prices like
  // a child, at ~100%. Swapping the two produces a plausible,
  // non-erroring search that quotes the wrong fare.
  const kinds: Array<[keyof PassengerInfo, number]> = [
    ["adults", 1],
    ["children", 2],
    ["infants_on_lap", 3],
    ["infants_in_seat", 4],
  ];

  for (const [field, code] of kinds) {
    test(`${field} encodes as ${code}`, () => {
      const counts: Partial<PassengerInfo> = { adults: 1 };
      counts[field] = (counts[field] ?? 0) + 1;
      expect(
        passengerCodes(
          buildTfs(
            filters([[["JFK"], ["LAX"], OUT]], {
              passenger_info: counts,
            }),
          ),
        ),
      ).toEqual([1, code]);
    });
  }

  test("a lap infant is 3 and a seat infant is 4, not the other way round", () => {
    const lap = filters([[["JFK"], ["LAX"], OUT]], {
      passenger_info: { adults: 1, infants_on_lap: 1 },
    });
    const seat = filters([[["JFK"], ["LAX"], OUT]], {
      passenger_info: { adults: 1, infants_in_seat: 1 },
    });
    expect(passengerCodes(buildTfs(lap))).toEqual([1, 3]);
    expect(passengerCodes(buildTfs(seat))).toEqual([1, 4]);
  });

  test("one field-8 entry per traveller, in field order", () => {
    const spec = filters([[["JFK"], ["LAX"], OUT]], {
      passenger_info: { adults: 2, children: 1, infants_in_seat: 1, infants_on_lap: 1 },
    });
    expect(passengerCodes(buildTfs(spec))).toEqual([1, 1, 2, 3, 4]);
  });

  test("an all-zero mix still books one adult", () => {
    const spec = filters([[["JFK"], ["LAX"], OUT]], {
      passenger_info: { adults: 0, children: 0, infants_in_seat: 0, infants_on_lap: 0 },
    });
    expect(passengerCodes(buildTfs(spec))).toEqual([1]);
  });
});

describe("passenger codes parity with buildTfsToken", () => {
  // Drift guard: buildTfs (search token) and buildTfsToken (booking-URL
  // token) must encode the identical field-8 sequence for the same
  // PassengerInfo — both are built from proto.ts's passengerCodes helper.
  test("family mix matches between the search token and the booking token", () => {
    const info = pax({ adults: 2, children: 1, infants_on_lap: 1 });
    const spec = filters([[["JFK"], ["LAX"], OUT]], { passenger_info: info });
    const searchCodes = passengerCodes(buildTfs(spec));

    const bookingToken = buildTfsToken(
      [[{ origin: "JFK", depDate: OUT, dest: "LAX", airline: "AA", flightNumber: "171" }]],
      { passengers: passengerCodesFromInfo(info) },
    );
    const bookingCodes = passengerCodes(bookingToken);

    expect(searchCodes).toEqual([1, 1, 2, 3]);
    expect(bookingCodes).toEqual([1, 1, 2, 3]);
    expect(searchCodes).toEqual(bookingCodes);
  });
});

describe("pageUrl", () => {
  test("includes locale and currency", () => {
    const url = pageUrl("TFS", "EUR", "de", "DE");
    expect(url).toContain("tfs=TFS");
    expect(url).toContain("curr=EUR");
    expect(url).toContain("hl=de");
    expect(url).toContain("gl=DE");
  });

  test("defaults when locale omitted", () => {
    const url = pageUrl("TFS");
    expect(url).toContain("hl=en");
    expect(url).toContain("gl=US");
    expect(url).not.toContain("curr=");
  });
});

describe("extractPayload", () => {
  test("reads the ds:1 blob past the other AF_initDataCallback blocks", () => {
    const html =
      "<script>AF_initDataCallback({key: 'ds:0', hash: '1', " +
      'data:["other"], sideChannel: {}});</script>' +
      "<script>AF_initDataCallback({key: 'ds:1', hash: '2', " +
      'data:[1,2,[["row"]]], sideChannel: {}});</script>';
    expect(extractPayload(html)).toEqual([1, 2, [["row"]]]);
  });

  test("returns null without a ds:1 block", () => {
    const html =
      "<script>AF_initDataCallback({key: 'ds:4', hash: '2', data:[], sideChannel: {}});</script>";
    expect(extractPayload(html)).toBeNull();
  });

  test("returns null on an unparseable blob, with one concise warning", () => {
    const html =
      "<script>AF_initDataCallback({key: 'ds:1', hash: '2', data:[oops, sideChannel: {}});</script>";
    const warnings: string[] = [];
    setSearchLogger({
      warn: (m) => warnings.push(m),
      debug: () => {},
    });
    try {
      expect(extractPayload(html)).toBeNull();
    } finally {
      setSearchLogger(null);
    }
    // Exactly one line, and no stack trace on a per-page code path.
    expect(warnings).toHaveLength(1);
    expect(warnings[0]).toContain("ds:1 blob is not valid JSON");
    expect(warnings[0]).not.toContain("    at ");
  });
});

describe("fetchPayload retry", () => {
  const restoreSleep = () => _setPageRetrySleep(null);

  function pageWith(payload: unknown): string {
    return `<script>AF_initDataCallback({key: 'ds:1', hash: '1', data:${JSON.stringify(payload)}, sideChannel: {}});</script>`;
  }

  test("a page missing ds:1 once then present takes exactly 2 fetches", async () => {
    const slept: number[] = [];
    _setPageRetrySleep(async (ms) => {
      slept.push(ms);
    });
    try {
      let calls = 0;
      const client = new Client({
        retries: 1,
        fetchImpl: (async () => {
          calls++;
          return new Response(calls === 1 ? "<html>no payload</html>" : pageWith([1, 2]), {
            status: 200,
          });
        }) as unknown as typeof fetch,
      });
      expect(await fetchPayload(client, "https://example.com")).toEqual([1, 2]);
      expect(calls).toBe(2);
      expect(slept).toEqual([500]);
    } finally {
      restoreSleep();
    }
  });

  test("a page missing ds:1 every time gives up after exactly 3 fetches", async () => {
    const slept: number[] = [];
    _setPageRetrySleep(async (ms) => {
      slept.push(ms);
    });
    try {
      let calls = 0;
      const client = new Client({
        retries: 1,
        fetchImpl: (async () => {
          calls++;
          return new Response("<html>no payload</html>", { status: 200 });
        }) as unknown as typeof fetch,
      });
      expect(await fetchPayload(client, "https://example.com")).toBeNull();
      expect(calls).toBe(PAGE_FETCH_ATTEMPTS);
      expect(calls).toBe(3);
      // Backs off between attempts only, never after the last one.
      expect(slept).toEqual([500, 1500]);
    } finally {
      restoreSleep();
    }
  });

  test("a good page on the first try costs exactly one fetch and no sleep", async () => {
    const slept: number[] = [];
    _setPageRetrySleep(async (ms) => {
      slept.push(ms);
    });
    try {
      let calls = 0;
      const client = new Client({
        retries: 1,
        fetchImpl: (async () => {
          calls++;
          return new Response(pageWith(["ok"]), { status: 200 });
        }) as unknown as typeof fetch,
      });
      expect(await fetchPayload(client, "https://example.com")).toEqual(["ok"]);
      expect(calls).toBe(1);
      expect(slept).toEqual([]);
    } finally {
      restoreSleep();
    }
  });

  test("an HTTP error propagates on the first attempt — no page-level retry", async () => {
    let calls = 0;
    const client = new Client({
      retries: 1,
      fetchImpl: (async () => {
        calls++;
        return new Response("nope", { status: 503 });
      }) as unknown as typeof fetch,
    });
    await expect(fetchPayload(client, "https://example.com")).rejects.toThrow(/HTTP 503/);
    expect(calls).toBe(1);
  });
});

describe("applyClientSideFilters", () => {
  test("airline include keeps only matching carriers", () => {
    const kept = applyClientSideFilters(
      [flight({ airline: Airline.AA }), flight({ airline: Airline.DL })],
      filters([[["JFK"], ["LAX"], OUT]], { airlines: [Airline.AA] }),
    );
    expect(kept.map((f) => f.legs[0]?.airline)).toEqual([Airline.AA]);
  });

  test("airline exclude drops matching carriers", () => {
    const kept = applyClientSideFilters(
      [flight({ airline: Airline.AA }), flight({ airline: Airline.DL })],
      filters([[["JFK"], ["LAX"], OUT]], { airlines_exclude: [Airline.AA] }),
    );
    expect(kept.map((f) => f.legs[0]?.airline)).toEqual([Airline.DL]);
  });

  test("price cap drops expensive flights", () => {
    const kept = applyClientSideFilters(
      [flight({ price: 100 }), flight({ price: 900 })],
      filters([[["JFK"], ["LAX"], OUT]], { price_limit: { max_price: 500, currency: null } }),
    );
    expect(kept.map((f) => f.price)).toEqual([100]);
  });

  test("max duration drops long flights", () => {
    const kept = applyClientSideFilters(
      [flight({ duration: 120 }), flight({ duration: 600 })],
      filters([[["JFK"], ["LAX"], OUT]], { max_duration: 300 }),
    );
    expect(kept.map((f) => f.duration)).toEqual([120]);
  });

  test("departure window drops flights outside it", () => {
    const kept = applyClientSideFilters(
      [flight({ hour: 6 }), flight({ hour: 20 })],
      filters([[["JFK"], ["LAX"], OUT]], {
        time_restrictions: { earliest_departure: 8, latest_departure: 22 },
      }),
    );
    expect(kept.map((f) => f.legs[0]?.departure_datetime.getHours())).toEqual([20]);
  });

  test("the window follows the segment still being chosen", () => {
    // During round-trip expansion the outbound is pinned and the rows
    // coming back are return options. Filtering them against segment
    // zero's window drops valid returns and keeps invalid ones.
    const spec = new FlightSearchFilters({
      trip_type: TripType.ROUND_TRIP,
      passenger_info: pax(),
      flight_segments: [
        new FlightSegment({
          departure_airport: [[[Airport.JFK, 0]]],
          arrival_airport: [[[Airport.LAX, 0]]],
          travel_date: OUT,
          time_restrictions: { earliest_departure: 5, latest_departure: 9 },
          selected_flight: flight({ hour: 6 }),
        }),
        new FlightSegment({
          departure_airport: [[[Airport.LAX, 0]]],
          arrival_airport: [[[Airport.JFK, 0]]],
          travel_date: RET,
          time_restrictions: { earliest_departure: 18, latest_departure: 23 },
        }),
      ],
    });
    const kept = applyClientSideFilters([flight({ hour: 6 }), flight({ hour: 20 })], spec);
    expect(kept.map((f) => f.legs[0]?.departure_datetime.getHours())).toEqual([20]);
  });

  test("with nothing pinned, segment zero's window applies", () => {
    const spec = new FlightSearchFilters({
      trip_type: TripType.ROUND_TRIP,
      passenger_info: pax(),
      flight_segments: [
        new FlightSegment({
          departure_airport: [[[Airport.JFK, 0]]],
          arrival_airport: [[[Airport.LAX, 0]]],
          travel_date: OUT,
          time_restrictions: { earliest_departure: 5, latest_departure: 9 },
        }),
        new FlightSegment({
          departure_airport: [[[Airport.LAX, 0]]],
          arrival_airport: [[[Airport.JFK, 0]]],
          travel_date: RET,
          time_restrictions: { earliest_departure: 18, latest_departure: 23 },
        }),
      ],
    });
    const kept = applyClientSideFilters([flight({ hour: 6 }), flight({ hour: 20 })], spec);
    expect(kept.map((f) => f.legs[0]?.departure_datetime.getHours())).toEqual([6]);
  });

  test("a legless row cannot satisfy a window, and does not crash the search", () => {
    const legless = { ...flight(), legs: [] };
    const spec = filters([[["JFK"], ["LAX"], OUT]], {
      time_restrictions: { earliest_departure: 0, latest_departure: 23 },
    });
    expect(applyClientSideFilters([legless], spec)).toEqual([]);
  });

  test("no filters keeps everything", () => {
    const all = [flight({ airline: Airline.AA }), flight({ airline: Airline.DL })];
    expect(applyClientSideFilters(all, filters([[["JFK"], ["LAX"], OUT]]))).toEqual(all);
  });
});

describe("unsupportedFilters", () => {
  test("reports nothing for a plain search", () => {
    expect(unsupportedFilters(filters([[["JFK"], ["LAX"], OUT]]))).toEqual([]);
  });

  test("names the filters the page cannot honour", () => {
    const spec = filters([[["JFK"], ["LAX"], OUT]]);
    spec.exclude_basic_economy = true;
    spec.emissions = 1;
    spec.bags = { checked_bags: 1, carry_on: true };
    expect(unsupportedFilters(spec).sort()).toEqual(["bags", "emissions", "exclude_basic_economy"]);
  });

  test("alliances and layovers ride in the request, so are not unsupported", () => {
    const spec = filters([[["JFK"], ["LAX"], OUT]], {
      alliances: [Alliance.SKYTEAM],
      layover_restrictions: { min_duration: 90 },
    });
    expect(unsupportedFilters(spec)).toEqual([]);
  });
});