diff --git a/contract/openapi.json b/contract/openapi.json index c5b8260..7961b6d 100644 --- a/contract/openapi.json +++ b/contract/openapi.json @@ -2,8 +2,8 @@ "openapi": "3.1.0", "info": { "title": "Wego API", - "description": "Wego's travel API: places, flights, hotels and fares. Please see https://docs.wego.com for more details.", - "version": "0.19.1" + "description": "Wego's travel API: places, flights, hotels and fares. Please see https://agents.wego.com for more details.", + "version": "0.19.5" }, "tags": [ { @@ -57,8 +57,8 @@ "description": "OAuth2 authorization-code flow (PKCE supported) against the Wego auth server.", "flows": { "authorizationCode": { - "authorizationUrl": "https://auth.wego.com/user-auth/v2/users/oauth/authorize", - "tokenUrl": "https://auth.wego.com/user-auth/v2/users/oauth/token", + "authorizationUrl": "https://auth.example.invalid/user-auth/v2/users/oauth/authorize", + "tokenUrl": "https://auth.example.invalid/user-auth/v2/users/oauth/token", "x-scalar-client-id": "251815b9647317f4895122fd4924b7d44541d8fcc27be528435e3ad9bbf7e1ee", "x-usePkce": "SHA-256", "scopes": { @@ -582,7 +582,7 @@ "operationId": "getPlaces", "tags": ["Places"], "summary": "Resolve travel locations", - "description": "Resolves a free-text location query to canonical Wego places (cities, airports, states, districts, hotels) with codes and coordinates, for use in later flight and hotel searches. When metadata.hasAmbiguity is true, clarify with the user before proceeding.", + "description": "Resolves a free-text location query to canonical Wego places (cities, airports, states, districts, hotels) with codes and coordinates, for use in later flight and hotel searches. A numeric query also matches a city code. When metadata.hasAmbiguity is true, clarify with the user before proceeding.", "responses": { "200": { "description": "Matching places plus pagination/ambiguity metadata.", @@ -5006,9 +5006,8 @@ "properties": { "cityCode": { "type": "string", - "pattern": "^[A-Z]{3}$", "example": "DXB", - "description": "City code to search. One destination only, see oneOf." + "description": "City code to search: a 3-letter code, or the numeric code some cities carry (Makkah is 8283). One destination only, see oneOf." }, "hotelId": { "type": "integer", diff --git a/integration/flights.test.ts b/integration/flights.test.ts index f120e0f..5c516d5 100644 --- a/integration/flights.test.ts +++ b/integration/flights.test.ts @@ -12,7 +12,7 @@ import { describe, expect, it } from "bun:test"; import { type Answer, problem } from "./harness/fake"; -import { answer, readFixture, route } from "./harness/fixtures"; +import { answer, placesKnowing, readFixture, route } from "./harness/fixtures"; import { useScenario } from "./harness/scenario"; import { json, signIn, writeSettings } from "./harness/wego"; @@ -1003,10 +1003,13 @@ describe("flights booking-link", () => { describe("flights share", () => { const leg = ["flights", "share", "SIN", "BKK", "2099-09-15"]; + const SHARE_PLACES = placesKnowing({ SIN: "city", BKK: "city" }); it("maps positionals and every flag to the query and prints the durable URL", async () => { signIn(s.home); - const fake = s.fake({ routes: [route("flights-search-link")] }); + const fake = s.fake({ + routes: [route("flights-search-link"), ...SHARE_PLACES], + }); const result = await s.run([ ...leg, "--return", @@ -1052,7 +1055,9 @@ describe("flights share", () => { it("inherits the stored currency, locale and site, over the account market", async () => { signIn(s.home, { accessToken: "access-1", market: "AE" }); writeSettings(s.home, { currency: "SAR", locale: "ar", site: "SA" }); - const fake = s.fake({ routes: [route("flights-search-link")] }); + const fake = s.fake({ + routes: [route("flights-search-link"), ...SHARE_PLACES], + }); expect((await s.run(leg)).code).toBe(0); expect(query(fake.requests("getFlightSearchLink")[0])).toMatchObject({ currency: "SAR", @@ -1064,7 +1069,9 @@ describe("flights share", () => { it("an explicit flag beats the stored setting", async () => { signIn(s.home); writeSettings(s.home, { currency: "SAR", site: "SA" }); - const fake = s.fake({ routes: [route("flights-search-link")] }); + const fake = s.fake({ + routes: [route("flights-search-link"), ...SHARE_PLACES], + }); expect( (await s.run([...leg, "--currency", "USD", "--site", "SG"])).code, ).toBe(0); @@ -1077,7 +1084,9 @@ describe("flights share", () => { for (const cabin of ["economy", "premium_economy", "business", "first"]) { it(`accepts the published cabin ${cabin}`, async () => { signIn(s.home); - const fake = s.fake({ routes: [route("flights-search-link")] }); + const fake = s.fake({ + routes: [route("flights-search-link"), ...SHARE_PLACES], + }); expect((await s.run([...leg, "--cabin", cabin])).code).toBe(0); expect(fake.requests("getFlightSearchLink")[0]?.query.get("cabin")).toBe( cabin, @@ -1123,6 +1132,94 @@ describe("flights share", () => { expect(fake.seen).toEqual([]); }); + it("refuses a code that resolves to no city or airport: exit 6, no link built", async () => { + signIn(s.home); + const fake = s.fake({ + routes: [route("flights-search-link"), ...SHARE_PLACES], + }); + const result = await s.run([ + "flights", + "share", + "ZZZ", + "BKK", + "2099-09-15", + ]); + + expect(result.code).toBe(6); + expect(result.out).toBe(""); + expect(result.err).toContain( + 'the from code "ZZZ" resolves to no city or airport', + ); + expect(result.err).toContain("wego places "); + expect(result.err).not.toMatch(/retry/i); + expect(fake.requests("getFlightSearchLink")).toHaveLength(0); + expect( + fake + .requests("getPlaces") + .map((r) => r.query.get("query")) + .sort(), + ).toEqual(["BKK", "ZZZ"]); + }); + + it("names both codes when neither resolves", async () => { + signIn(s.home); + s.fake({ routes: [route("flights-search-link"), ...SHARE_PLACES] }); + const result = await s.run([ + "flights", + "share", + "ZZZ", + "QQQ", + "2099-09-15", + ]); + + expect(result.code).toBe(6); + expect(result.err).toContain( + 'the from code "ZZZ" and the to code "QQQ" resolve to no city or airport', + ); + }); + + it("accepts an airport code Places reports", async () => { + signIn(s.home); + const fake = s.fake({ + routes: [ + route("flights-search-link"), + ...placesKnowing({ LHR: "airport", BKK: "city" }), + ], + }); + const result = await s.run([ + "flights", + "share", + "LHR", + "BKK", + "2099-09-15", + ]); + + expect(result.code).toBe(0); + expect(fake.requests("getFlightSearchLink")).toHaveLength(1); + }); + + it("--from-city refuses a code that is only an airport", async () => { + signIn(s.home); + const fake = s.fake({ + routes: [ + route("flights-search-link"), + ...placesKnowing({ LHR: "airport", BKK: "city" }), + ], + }); + const result = await s.run([ + "flights", + "share", + "LHR", + "BKK", + "2099-09-15", + "--from-city", + ]); + + expect(result.code).toBe(6); + expect(result.err).toContain('the from code "LHR" resolves to no city.'); + expect(fake.requests("getFlightSearchLink")).toHaveLength(0); + }); + it("--help prints its usage on stdout with exit 0", async () => { const result = await s.run(["flights", "share", "--help"]); expect(result.code).toBe(0); diff --git a/integration/harness/fixtures.ts b/integration/harness/fixtures.ts index 07b61ca..0751110 100644 --- a/integration/harness/fixtures.ts +++ b/integration/harness/fixtures.ts @@ -10,7 +10,7 @@ import { readdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; -import type { Answer, Route } from "./fake"; +import type { Answer, Route, Seen } from "./fake"; export const FIXTURES_DIR = fileURLToPath( new URL("../fixtures/", import.meta.url), @@ -59,3 +59,29 @@ export function route( answers: answers.map((a) => (typeof a === "string" ? answer(a) : a)), }; } + +/** + * `getPlaces` routes that know exactly `known` (code to place type). A query + * for any other code finds nothing, which is how the API answers an unknown one. + */ +export function placesKnowing(known: Record): Route[] { + const page = (results: unknown[]) => + answer("places", () => ({ + results, + metadata: { + resultCount: results.length, + totalCandidates: results.length, + hasMore: false, + hasAmbiguity: false, + }, + })); + const op = readFixture("places").op; + return [ + ...Object.entries(known).map(([code, type], i) => ({ + op, + answers: [page([{ id: i + 1, code, name: code, type, cityCode: code }])], + when: (seen: Seen) => seen.query.get("query") === code, + })), + { op, answers: [page([])] }, + ]; +} diff --git a/integration/hotels.test.ts b/integration/hotels.test.ts index 0e6de2c..33b3224 100644 --- a/integration/hotels.test.ts +++ b/integration/hotels.test.ts @@ -12,7 +12,7 @@ import { describe, expect, it } from "bun:test"; import { type Answer, problem } from "./harness/fake"; -import { answer, readFixture, route } from "./harness/fixtures"; +import { answer, placesKnowing, readFixture, route } from "./harness/fixtures"; import { useScenario } from "./harness/scenario"; import { type CliResult, json, signIn, writeSettings } from "./harness/wego"; @@ -440,6 +440,57 @@ describe("hotels usage errors: exit 2, no request", () => { }); describe("hotels search", () => { + it("sends an all-digit location that Places lists as a city as cityCode", async () => { + signIn(s.home); + const fake = s.fake({ + routes: [ + ...placesKnowing({ "8283": "city" }), + route("hotels-search-create"), + route("hotels-search-results"), + ], + }); + const result = await s.run(["hotels", "search", "8283", ...DATES]); + + expect(result.code).toBe(0); + expect(fake.requests("getPlaces")[0]?.query.get("query")).toBe("8283"); + expect(createBody(fake)).toMatchObject({ cityCode: "8283" }); + expect(createBody(fake)).not.toHaveProperty("hotelId"); + }); + + it("keeps an all-digit location that Places lists as no city a hotelId", async () => { + signIn(s.home); + const fake = s.fake({ + routes: [ + ...placesKnowing({}), + route("hotels-search-create"), + route("hotels-search-results"), + ], + }); + const result = await s.run(["hotels", "search", "999999999", ...DATES]); + + expect(result.code).toBe(0); + expect(fake.requests("getPlaces")).toHaveLength(1); + expect(createBody(fake)).toMatchObject({ hotelId: 999999999 }); + expect(createBody(fake)).not.toHaveProperty("cityCode"); + }); + + it("looks up an all-digit location by the digits as typed, so 008283 stays a hotelId", async () => { + signIn(s.home); + const fake = s.fake({ + routes: [ + ...placesKnowing({ "8283": "city" }), + route("hotels-search-create"), + route("hotels-search-results"), + ], + }); + const result = await s.run(["hotels", "search", "008283", ...DATES]); + + expect(result.code).toBe(0); + expect(fake.requests("getPlaces")[0]?.query.get("query")).toBe("008283"); + expect(createBody(fake)).toMatchObject({ hotelId: 8283 }); + expect(createBody(fake)).not.toHaveProperty("cityCode"); + }); + it("creates the search, prints the settled first page, and hints at a currency setting", async () => { signIn(s.home); const fake = s.fake({ @@ -1244,10 +1295,68 @@ describe("hotels booking-link", () => { describe("hotels share", () => { const SHARE = ["hotels", "share", "BKK", ...DATES]; + const SHARE_PLACES = placesKnowing({ BKK: "city" }); + + it("refuses a city code that resolves to no city: exit 6, no link built", async () => { + signIn(s.home); + const fake = s.fake({ + routes: [route("hotels-search-link"), ...SHARE_PLACES], + }); + const result = await s.run(["hotels", "share", "ZZZ", ...DATES]); + + expect(result.code).toBe(6); + expect(result.out).toBe(""); + expect(result.err).toContain('the city code "ZZZ" resolves to no city'); + expect(result.err).not.toMatch(/retry/i); + expect(fake.requests("getHotelSearchLink")).toHaveLength(0); + expect(fake.requests("getPlaces")[0]?.query.getAll("types")).toEqual([ + "city", + ]); + }); + + it("accepts a city that Places reports by cityCode alone", async () => { + signIn(s.home); + const fake = s.fake({ + routes: [ + route("hotels-search-link"), + { + op: "getPlaces", + answers: [ + answer("places", (b: { results: unknown[] }) => ({ + ...b, + results: [ + { id: 9, name: "Bangkok", type: "city", cityCode: "BKK" }, + ], + })), + ], + }, + ], + }); + const result = await s.run(SHARE); + + expect(result.code).toBe(0); + expect(fake.requests("getHotelSearchLink")).toHaveLength(1); + }); + + it("refuses an airport code, which no hotel link can carry", async () => { + signIn(s.home); + const fake = s.fake({ + routes: [ + route("hotels-search-link"), + ...placesKnowing({ LHR: "airport" }), + ], + }); + const result = await s.run(["hotels", "share", "LHR", ...DATES]); + + expect(result.code).toBe(6); + expect(fake.requests("getHotelSearchLink")).toHaveLength(0); + }); it("forwards the city, dates and occupancy, and prints the durable link", async () => { signIn(s.home); - const fake = s.fake({ routes: [route("hotels-search-link")] }); + const fake = s.fake({ + routes: [route("hotels-search-link"), ...SHARE_PLACES], + }); const result = await s.run([...SHARE, "--adults", "2"]); expect(result.code).toBe(0); @@ -1265,7 +1374,9 @@ describe("hotels share", () => { it("sends --rooms, the same occupancy vocabulary as hotels search", async () => { signIn(s.home); - const fake = s.fake({ routes: [route("hotels-search-link")] }); + const fake = s.fake({ + routes: [route("hotels-search-link"), ...SHARE_PLACES], + }); const result = await s.run([...SHARE, "--adults", "4", "--rooms", "2"]); expect(result.code).toBe(0); expect(query(fake, "getHotelSearchLink")).toMatchObject({ @@ -1276,7 +1387,9 @@ describe("hotels share", () => { it("packs --children-ages into a CSV the API parses", async () => { signIn(s.home); - const fake = s.fake({ routes: [route("hotels-search-link")] }); + const fake = s.fake({ + routes: [route("hotels-search-link"), ...SHARE_PLACES], + }); const result = await s.run([ ...SHARE, "--children", @@ -1294,7 +1407,9 @@ describe("hotels share", () => { it("inherits the stored currency, locale and site, which the link hands on", async () => { signIn(s.home); writeSettings(s.home, { currency: "SAR", locale: "ar", site: "SA" }); - const fake = s.fake({ routes: [route("hotels-search-link")] }); + const fake = s.fake({ + routes: [route("hotels-search-link"), ...SHARE_PLACES], + }); const result = await s.run(SHARE); expect(result.code).toBe(0); expect(query(fake, "getHotelSearchLink")).toMatchObject({ @@ -1307,7 +1422,9 @@ describe("hotels share", () => { it("an explicit --site beats the stored one", async () => { signIn(s.home); writeSettings(s.home, { site: "SA" }); - const fake = s.fake({ routes: [route("hotels-search-link")] }); + const fake = s.fake({ + routes: [route("hotels-search-link"), ...SHARE_PLACES], + }); const result = await s.run([...SHARE, "--site", "AE"]); expect(result.code).toBe(0); expect(query(fake, "getHotelSearchLink").siteCode).toBe("AE"); diff --git a/src/commands.ts b/src/commands.ts index bd9f2bc..0294f47 100644 --- a/src/commands.ts +++ b/src/commands.ts @@ -1071,6 +1071,8 @@ export interface FlightsDeps extends AuthedCommandDeps { fetchFareOptions: typeof fetchFareOptions; fetchBookingLink: typeof fetchBookingLink; fetchSearchLink: typeof fetchSearchLink; + /** Resolves `flights share` codes before a durable link is built. */ + fetchPlaces: typeof fetchPlaces; /** Delay between `flights results --wait` re-reads (injected for tests). */ sleep: (ms: number) => Promise; } @@ -1390,14 +1392,102 @@ async function flightsShare( // built from a settings-priced funnel must not hand off in USD, and a durable // link hands the wrong currency to everyone it is shared with, not just once. const withPrefs = applyPreferences(params, settings); - const result = await withAccessToken(config, deps, (accessToken, market) => - deps.fetchSearchLink(config.apiBaseUrl, accessToken, { - ...withPrefs, - siteCode: resolveCliSite(params.siteCode, settings.site, market).siteCode, - }), + const result = await withAccessToken( + config, + deps, + async ( + accessToken, + market, + ): Promise>>> => { + const unresolved = await unresolvedShareCodes( + deps.fetchPlaces, + config.apiBaseUrl, + accessToken, + [ + { + name: "from", + code: params.from, + types: endpointTypes(params.fromCity), + }, + { name: "to", code: params.to, types: endpointTypes(params.toCity) }, + ], + ); + if (unresolved.length > 0) return { unresolved }; + return { + link: await deps.fetchSearchLink(config.apiBaseUrl, accessToken, { + ...withPrefs, + siteCode: resolveCliSite(params.siteCode, settings.site, market) + .siteCode, + }), + }; + }, ); if (!result.ok) return result.code; - return printJson(result.value, deps); + if ("unresolved" in result.value) { + deps.error(unresolvedShareMessage(result.value.unresolved)); + return EXIT.PERMANENT; + } + return printJson(result.value.link, deps); +} + +/** A share either names the codes it refused, or carries the built link. */ +type SharePlan = { unresolved: ShareCode[] } | { link: T }; + +interface ShareCode { + /** How the message names the code: `from`, `to`, `city`. */ + name: string; + code: string; + /** The place types the code may resolve to. */ + types: string[]; +} + +/** `--from-city` / `--to-city` read the code as a city, so an airport cannot match. */ +function endpointTypes(asCity: boolean | undefined): string[] { + return asCity ? ["city"] : ["city", "airport"]; +} + +/** + * The codes Places cannot resolve to an exact match of their `types`. A durable + * link is built from the codes alone and no search ever checks them, so an + * unknown code would hand out a dead link. + */ +async function unresolvedShareCodes( + lookup: typeof fetchPlaces, + apiBaseUrl: string, + accessToken: string, + codes: ShareCode[], +): Promise { + const found = await Promise.all( + codes.map(async ({ code, types }) => { + const wanted = code.trim().toUpperCase(); + const { results } = await lookup(apiBaseUrl, accessToken, { + query: wanted, + types, + }); + return results.some((place) => { + if (!types.includes(place.type)) return false; + // A city row may carry its code only as `cityCode`, as the API reads it. + const placeCode = + place.type === "city" ? (place.code ?? place.cityCode) : place.code; + return ( + typeof placeCode === "string" && placeCode.toUpperCase() === wanted + ); + }); + }), + ); + return codes.filter((_, i) => !found[i]); +} + +function unresolvedShareMessage(codes: ShareCode[]): string { + const wants = new Set(codes.map(({ types }) => types.join(" or "))); + const named = codes.map(({ name, code }) => `the ${name} code "${code}"`); + const what = + wants.size === 1 + ? `${named.join(" and ")} ${codes.length > 1 ? "resolve" : "resolves"} to no ${[...wants][0]}` + : codes + .map((c, i) => `${named[i]} resolves to no ${c.types.join(" or ")}`) + .join(" and "); + return `No link was built: ${what}. Find one with \`${PROG} places \` and pass the code it reports.`; } const FARES_FLAGS = new Set(["--currency", "--locale"]); @@ -1983,12 +2073,15 @@ export interface HotelsDeps extends AuthedCommandDeps { fetchHotelBookingLink: typeof fetchHotelBookingLink; fetchHotelSearchLink: typeof fetchHotelSearchLink; fetchHotelReviews: typeof fetchHotelReviews; + /** Resolves the `hotels share` city before a durable link is built. */ + fetchPlaces: typeof fetchPlaces; /** Injected so tests drive the settle without real timers. */ sleep: (ms: number) => Promise; } /** Resolve the positional location arg by shape: 3-letter city code, all-digit - * hotelId, or a `lat,lng` pair. */ + * hotelId, or a `lat,lng` pair. `hotelsSearch` then sends an all-digit city + * code as `cityCode` (`withNumericCity`). */ function locationFields(location: string): Partial { if (/^[A-Z]{3}$/.test(location)) return { cityCode: location }; if (/^\d+$/.test(location)) return { hotelId: Number(location) }; @@ -2104,7 +2197,10 @@ const SEARCH_FLAGS = new Set([ "--locale", ]); -function parseSearchArgs(args: string[]): HotelsSearchBody { +function parseSearchArgs(args: string[]): { + body: HotelsSearchBody; + location: string; +} { const { positional, single } = tokenizeFlagSets( args, HOTELS_SEARCH_USAGE, @@ -2125,7 +2221,59 @@ function parseSearchArgs(args: string[]): HotelsSearchBody { const radius = single.get("--radius"); if (radius) body.radius = parseIntArg(radius, "--radius"); applyOccupancyFlags(body, single); - return body; + return { body, location }; +} + +/** + * The city code an all-digit location names, when the top place Places returns + * is the city with exactly that code. Makkah has no airport and is `8283`. + * Any other answer leaves the location a hotelId. + */ +export async function numericCityCode( + lookup: typeof fetchPlaces, + apiBaseUrl: string, + accessToken: string, + code: string, +): Promise { + const { results } = await lookup(apiBaseUrl, accessToken, { + query: code, + types: ["city"], + }); + const top = results[0]; + if (top?.type !== "city") return undefined; + return (top.code ?? top.cityCode) === code ? code : undefined; +} + +/** Send an all-digit location that Places knows as a city code as `cityCode`. + * The lookup uses the digits as typed, so `008283` is no match for `8283`. + * A failed lookup other than a 401 keeps the hotelId, so a Places outage + * never stops a hotel search. */ +async function withNumericCity( + config: CliConfig, + body: HotelsSearchBody, + location: string, + deps: HotelsDeps, +): Promise< + { ok: true; value: HotelsSearchBody } | { ok: false; code: number } +> { + const { hotelId, ...rest } = body; + if (hotelId === undefined) return { ok: true, value: body }; + const city = await withAccessToken(config, deps, (accessToken) => + numericCityCode( + deps.fetchPlaces, + config.apiBaseUrl, + accessToken, + location, + ).catch((err: unknown) => { + if (err instanceof UnauthorizedError) throw err; + return undefined; + }), + ); + if (!city.ok) return city; + return { + ok: true, + value: city.value ? { ...rest, cityCode: city.value } : body, + }; } async function hotelsSearch( @@ -2137,13 +2285,21 @@ async function hotelsSearch( deps.log(HOTELS_SEARCH_USAGE); return 0; } - let body: HotelsSearchBody; + let parsed: ReturnType; try { - body = parseSearchArgs(args); + parsed = parseSearchArgs(args); } catch (err) { deps.error(errorMessage(err)); return EXIT.USAGE; } + const located = await withNumericCity( + config, + parsed.body, + parsed.location, + deps, + ); + if (!located.ok) return located.code; + const body = located.value; // ①+③ through the shared engine: create, block-to-settled on candidate-count // convergence, stamp `settled` (issue #1084). The `HOTELS` vertical owns the // per-vertical pieces (site resolution, the occupancy echo, the empty-page @@ -2286,14 +2442,35 @@ async function hotelsShare( const settings = await deps.loadSettings(); // A durable link hands its currency to everyone it reaches, so it inherits the stored preferences like `flights share`. const withPrefs = applyPreferences(query, settings); - const result = await withAccessToken(config, deps, (accessToken, market) => - deps.fetchHotelSearchLink(config.apiBaseUrl, accessToken, { - ...withPrefs, - siteCode: resolveCliSite(query.siteCode, settings.site, market).siteCode, - }), + const result = await withAccessToken( + config, + deps, + async ( + accessToken, + market, + ): Promise>>> => { + const unresolved = await unresolvedShareCodes( + deps.fetchPlaces, + config.apiBaseUrl, + accessToken, + [{ name: "city", code: query.cityCode ?? "", types: ["city"] }], + ); + if (unresolved.length > 0) return { unresolved }; + return { + link: await deps.fetchHotelSearchLink(config.apiBaseUrl, accessToken, { + ...withPrefs, + siteCode: resolveCliSite(query.siteCode, settings.site, market) + .siteCode, + }), + }; + }, ); if (!result.ok) return result.code; - return printJson(result.value, deps); + if ("unresolved" in result.value) { + deps.error(unresolvedShareMessage(result.value.unresolved)); + return EXIT.PERMANENT; + } + return printJson(result.value.link, deps); } /** Enum/bound guards for the hotels `results`/`details` flags, mirroring diff --git a/src/hotels.test.ts b/src/hotels.test.ts index 9a81381..ec4a613 100644 --- a/src/hotels.test.ts +++ b/src/hotels.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "bun:test"; -import { parseRoomsArgs, settleRates } from "./commands"; +import { numericCityCode, parseRoomsArgs, settleRates } from "./commands"; import { HOTELS } from "./verticals"; /** @@ -191,3 +191,36 @@ describe("HOTELS empty-page note", () => { ).toBeUndefined(); }); }); + +describe("numericCityCode", () => { + const places = (results: unknown[]) => + (async () => ({ results, metadata: {} })) as unknown as Parameters< + typeof numericCityCode + >[0]; + + it("answers the code when the top place is that exact city", async () => { + const lookup = places([{ type: "city", code: "8283", name: "Makkah" }]); + expect(await numericCityCode(lookup, "https://api", "t", "8283")).toBe( + "8283", + ); + }); + + it("reads a city that carries its code only as cityCode", async () => { + const lookup = places([{ type: "city", cityCode: "8283", name: "Makkah" }]); + expect(await numericCityCode(lookup, "https://api", "t", "8283")).toBe( + "8283", + ); + }); + + it("answers nothing when the top place is another code or no city", async () => { + for (const results of [ + [], + [{ type: "city", code: "9999", name: "Elsewhere" }], + [{ type: "hotel", code: "8283", name: "Hotel 8283" }], + ]) { + expect( + await numericCityCode(places(results), "https://api", "t", "8283"), + ).toBeUndefined(); + } + }); +}); diff --git a/src/index.ts b/src/index.ts index d63d3f7..105f69b 100755 --- a/src/index.ts +++ b/src/index.ts @@ -521,6 +521,7 @@ export function buildRealDeps(): RunDeps { fetchFareOptions, fetchBookingLink, fetchSearchLink, + fetchPlaces, sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)), }), hotels: (config, args) => @@ -534,6 +535,7 @@ export function buildRealDeps(): RunDeps { fetchHotelReviews, fetchHotelBookingLink, fetchHotelSearchLink, + fetchPlaces, sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)), }), feedback: (config, args) =>