diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 95c621e..f929a35 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,6 +38,13 @@ jobs: - name: Install dependencies run: npm ci + # Browser tests (tests/browser) run the in-page scroll/expand/session/navigation code + # against local fixtures in headless Chromium. Only the headless shell is needed. + # `npm exec --no` uses the locally installed Playwright and never fetches from the registry. + # Do not copy this step into release.yml's publish job (it holds id-token: write). + - name: Install Chromium (headless shell) for browser tests + run: npm exec --no -- playwright install --with-deps --only-shell chromium + - name: Type check run: npm run typecheck diff --git a/AGENTS.md b/AGENTS.md index 5128c34..8477718 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,13 +15,14 @@ npm run dev -- scrape '' [options] # Run CLI directly (single-quote URLs!) npm run dev -- auth # Authenticate with Google (opens browser) npm run dev -- auth status # Check if signed in npm run build # Build to dist/ via tsup (ESM, shebang) -npm test # Run all tests (vitest) +npm test # Run all tests (vitest) – needs Chromium (browser tests) +npm run test:browser # Only the headless-browser tests (tests/browser) npm run test:watch # Watch mode npx vitest run tests/parser.test.ts # Run a single test file npm run typecheck # Type check without emitting npm run check:pack # Assert the tarball contract (dist present, no src/tests) npm run test:package # Pack + install into a temp consumer, assert --version -npx playwright install chromium # Required once before first scrape +npx playwright install chromium # Required once before first scrape and before `npm test` # Release (see "Release and publishing" below) node scripts/release.mjs patch|minor|major # Prepare: stamp package.json + lock (the workflow opens the bump PR) @@ -104,8 +105,8 @@ CLI (src/index.ts) ─── commander routes to 4 commands: src/scraper/scrape-location.ts ── shared orchestrator, accepts ParsedUrl (used by both commands); delegates final payload construction to exported pure helper `assembleScrapeResult()` which reconciles `business.totalReviews` with `reviews.length` │ ├── browser.ts ── persistent Chromium context (~/.revcli/chrome-profile/), anti-detection, SIGINT cleanup -├── auth.ts ── isSignedIn(), hasLimitedView(), waitForUserAuth(), waitForSignIn(), waitForBrowserClose() – Google auth detection; decideSignedIn()/GOOGLE_AUTH_COOKIES make the cookie check authoritative -├── navigator.ts ── orchestrates state eviction → consent → locale → limited-view check → tab → sort; verifies loaded placeId against parsed.placeId +├── auth.ts ── getSessionState()/decideSessionState() (single source of truth for the Google session), hasLimitedView(), authRequiredError()/authRequiredMessage(), waitForUserAuth(), waitForSignIn(), waitForBrowserClose() +├── navigator.ts ── orchestrates state eviction → short-link redirect wait → consent → locale → tab (limited-view check before and after the review cards load) → sort; verifies loaded placeId against parsed.placeId ├── consent.ts ── Google consent handling, hl=en enforcement, g_ep/entry stripping ├── business-extractor.ts ── business name/rating/totalReviews/address extraction; page.evaluate() returns raw DOM strings only, parsing happens Node-side via parseReviewCount + parseRatingText; PII-scrubbed debug logging of candidate strings ├── scroller.ts ── mouse wheel scrolling, deduplication by review ID, exponential backoff stale-scroll detection, loading spinner awareness @@ -117,7 +118,8 @@ src/scraper/scrape-location.ts ── shared orchestrator, accepts ParsedUrl (u src/core/ ├── schema.ts ── Zod schemas + SortOrder/OutputFormat union types + SORT_ORDERS/OUTPUT_FORMATS constants ├── retry.ts ── withRetry() – exponential backoff, isUnrecoverable() detection (instanceof UnrecoverableError + substring fallback) -├── errors.ts ── UnrecoverableError typed class with `kind` discriminator – prefer over magic-substring Error for anything we throw +├── errors.ts ── UnrecoverableError typed class with a `kind: UnrecoverableKind` union, hasUnrecoverableKind() – prefer over magic-substring Error for anything we throw +├── fatal.ts ── reportFatalError() – the top-level handler index.ts installs; describeFatalError() decides what it prints (message without Playwright call log; stack at debug only); re-exports safeErrorMessage() └── rate-limiter.ts ── minimum delay between operations src/output/ @@ -138,10 +140,10 @@ URL input → `parseGoogleMapsInput()` validates → `scrapeLocation(parsed)` la ### Patterns to know - **Persistent browser profile**: `launchBrowser()` uses `chromium.launchPersistentContext()` with `~/.revcli/chrome-profile/`. Google auth cookies survive between CLI runs. The `PROFILE_DIR` constant is exported from `browser.ts`. `ensureProfileDir()` in `browser.ts` creates the directory with owner-only `0700` permissions – it is a **credential store** holding your Google session cookies, so it must never be shared, backed up, or committed. The profile's spoofed user-agent and `navigator.webdriver` masking are ToS-sensitive (see the anti-automation note in README's Legal notice); removing them would break unauthenticated scraping. -- **Authentication flow**: Google Maps shows a "limited view" (no Reviews tab) to unauthenticated EEA users. `revcli auth` opens a browser for manual sign-in and never short-circuits on an existing session – the window stays open (until the user closes it) so the profile can be switched to a different account. The scrape command also detects limited view inline and can prompt for auth in headed mode. -- **Cookie-authoritative sign-in detection**: `auth.ts` defines `GOOGLE_AUTH_COOKIES` (the definitive set of Google session cookies: SID/HSID/SSID/APISID/SAPISID/`__Secure-*PSID`). `decideSignedIn(cookieCheckSucceeded, hasAuthCookies, signInButtonVisible)` treats a successful cookie check as authoritative – when `cookieCheckSucceeded` is true, `hasAuthCookies` decides, and the DOM "Sign in" button is only a fallback when the cookie check failed. `hasGoogleAuthSession()` checks the cookie set directly; `waitForSignIn()` polls and throws a typed `UnrecoverableError` with kind `"AUTH_POLL"` on timeout, returning `SignInOutcome` (`"signed-in"` | `"browser-closed"`) otherwise – `waitForUserAuth()` treats a closed window as fatal for the scrape, while `revcli auth` reports it as a normal end. `waitForBrowserClose()` resolves once the window is gone, polling `pages()` as well as the `close` event because closing the last window on macOS leaves the process (and context) alive. +- **Authentication flow**: Google Maps shows a "limited view" to signed-out EEA users and to profiles whose saved session has expired: the Reviews tab is still there but only ~5 reviews load, a "You're seeing a limited view of Google Maps" banner appears, and Sort opens a "Sign-in to get the best of Google Maps" dialog. **The scrape decides from these limited-view signals (banner + Sort sign-in dialog), not from session state**, because non-EEA signed-out users get the full view – do not "simplify" this to a session check. `openReviewsTab()` checks the banner twice (after the tabs, and again after the review cards, since it can render late and `relevant` has no Sort click); `setSortOrder()` waits for the first *visible* of the sort menu or `SELECTORS.signInDialog`. Both throw `authRequiredError()` (`UnrecoverableError` kind `"AUTH_REQUIRED"`, never retried). `scrapeLocation()` delegates to the exported, fake-tested `navigateWithAuthFallback()`: headless rethrows at once; headed runs `waitForUserAuth()` and navigates again, **using the second navigation's business info**. A terminal `AUTH_REQUIRED` is reworded by a 5 s session probe: `authRequiredMessage()` gives the "run `revcli auth`" text for `expired`/`signed-out`/unknown and a "appears to be signed in" text for `signed-in`/`unconfirmed`, so `auth status` and the scrape cannot contradict each other silently. Session state is only used to word that error and to detect sign-in completion. `revcli auth` opens a browser for manual sign-in and never short-circuits on a real session – for `signed-in`/`unconfirmed` the window stays open until the user closes it (#24, account switching); for `expired` it says so and waits for a fresh sign-in, closing on detection. +- **Session state (single source of truth)**: `getSessionState(page, { timeoutMs, stableMs })` in `auth.ts` returns `SessionState` (`"signed-in" | "expired" | "signed-out" | "unconfirmed"`) and is used by `auth`, `auth status` and `waitForSignIn()`; there is no second "is signed in" check. It reads the `.google.com` cookies (`GOOGLE_AUTH_COOKIES`: SID/HSID/SSID/APISID/SAPISID/`__Secure-*PSID`/`__Secure-*PAPISID`) – no auth cookies is a fast `signed-out` – then waits (default 15 s) for an account marker: `SELECTORS.accountButton` (`a[href^="https://accounts.google.com/SignOutOptions"]`) vs `SELECTORS.signInLink` (`…/ServiceLogin`). Markers are matched by **href, never aria-label**: hrefs are language-independent, while labels are localized and the account label holds the user's name and email. Cookies prove a session *exists*, not that Google *accepts* it – a dead session keeps its cookies and shows "Sign in", which `decideSessionState()` (pure, exported) maps to `expired`. With auth cookies a "Sign in" link must stay the only marker for `stableMs` because Google can render it briefly on a valid session – `SESSION_SIGN_IN_STABLE_MS` (3 s, the default, for `auth` and `auth status`, which report once) and `POLL_SIGN_IN_STABLE_MS` (1.5 s, in `POLL_PROBE`, for the sign-in poll loop and the scrape's error wording, which simply ask again); the account link always wins; no stable marker in time → `unconfirmed` (trusted with a warning by `auth`/`auth status`; `waitForSignIn()` keeps polling). The marker read swallows every Playwright error and never logs error text, element HTML or labels (Playwright call logs print markup). `waitForSignIn()` takes an injectable `probe` (defaults to `getSessionState` with `POLL_PROBE`: 5 s marker wait, 1.5 s stability; `tests/browser/session.test.ts` also runs it with the real probe), returns `"signed-in"` only when the probe says so, throws `UnrecoverableError` kind `"AUTH_POLL"` on timeout, and returns `SignInOutcome` (`"signed-in"` | `"browser-closed"`) – `waitForUserAuth()` treats a closed window as fatal for the scrape, while `revcli auth` reports it as a normal end. `waitForBrowserClose()` resolves once the window is gone, polling `pages()` as well as the `close` event because closing the last window on macOS leaves the process (and context) alive. - **Default headed mode**: The browser shows by default so users can observe scraping. Use `--headless` to hide it. This is the opposite of most scrapers – it's intentional because auth requires a visible browser. -- **URL normalization**: `appendHlParam()` in `consent.ts` always forces `hl=en` and strips `g_ep`/`entry` tracking params that trigger Google's limited view. This runs before every navigation. +- **URL normalization**: `appendHlParam()` in `consent.ts` always forces `hl=en` and strips `g_ep`/`entry` tracking params that trigger Google's limited view. This runs before every navigation. After the page has landed (redirects, consent), `ensureEnglishLocale()` navigates again when the *parsed* query has `hl` other than exactly `en` (pure helper `englishLocaleTarget()`). Only for short-link input (`stripLimitedViewParams: parsed.isShortUrl`) it also navigates to strip `entry`/`g_ep`, because that is the one case where they could not be stripped before the load; on other links Google's own page script may add them back, and re-checking would cost a second page load on every scrape. - **Centralized selectors**: All Google Maps CSS class selectors live in `src/scraper/selectors.ts`. Google obfuscates these names and changes them periodically. When scraping breaks, check selectors first. See [docs/selector-maintenance.md](docs/selector-maintenance.md) for the full update procedure. - **Mouse wheel scrolling**: Google Maps' virtualized review list only lazy-loads from real scroll events. `page.mouse.wheel()` triggers it; `scrollTop` alone does not. - **Zod as source of truth**: Types are derived from Zod schemas via `z.infer<>`. The `parseReview()` function validates every review at the boundary before it enters the output. @@ -160,7 +162,14 @@ URL input → `parseGoogleMapsInput()` validates → `scrapeLocation(parsed)` la - **totalReviews reconciliation**: `assembleScrapeResult()` in `src/scraper/scrape-location.ts` is an exported pure helper called from `scrapeLocation()` to enforce the invariant `business.totalReviews === reviews.length` at the single seam where `businessInfo` (header-derived) and `reviews` (scraped) first coexist. The original Google-header value is preserved as `business.headerTotalReviews`. See issue #5. When `--max-reviews N` caps collection, `totalReviews === N` (not the header) and `headerTotalReviews` holds Google's larger number. - **Header parsing extracted for testability**: `src/scraper/parser.ts` exports `parseReviewCount(text)` and `src/scraper/business-extractor.ts` exports `parseRatingText(text)`. Both are pure functions called from the Node side after `page.evaluate()` returns raw DOM strings. This matches the repo's "extract pure logic out of Playwright-coupled code" convention (see `parseInputFile`, `extractPlaceIdFromUrl`, `calculateStaleDelay`). `parseReviewCount` assumes the `hl=en` locale – comma thousand separator, period is a decimal and not a thousands separator. Suffix forms (`1.6K reviews`) return null; reconciliation backfills via `reviews.length`. - **Business header debug logging**: `business-extractor.ts` emits PII-scrubbed debug-level logs of raw DOM candidate strings (tab text, aria-label badge, scoped `[role="main"]` body snippet) so selector staleness can be diagnosed from `--verbose` output without leaking reviewer names or review content. The scrub preserves digits, separators, K/M/B suffixes, and the letters of "reviews"; all other characters become `·`. -- **Playwright locator scoping for comma-lists**: Never flat-concatenate selector constants like `` `${SELECTORS.reviewCard} ${SELECTORS.expandButton}` `` – CSS parses the comma as a selector-list union, leaving the second alternative unscoped and matching page-wide. Use chained locators: `page.locator(SELECTORS.reviewCard).locator(SELECTORS.expandButton)`. Chaining scopes both alternatives to the parent's subtree. `expandAllReviews()` in `extractor.ts` is the reference implementation. `tests/extractor-selectors.test.ts` pins the regression shape. +- **Playwright locator scoping for comma-lists**: Never flat-concatenate selector constants like `` `${SELECTORS.reviewCard} ${SELECTORS.expandButton}` `` – CSS parses the comma as a selector-list union, leaving the second alternative unscoped and matching page-wide. Use chained locators (`page.locator(SELECTORS.reviewCard).locator(SELECTORS.expandButton)`) or, in-page, `card.querySelectorAll(SELECTORS.expandButton)` – both scope every alternative to the parent's subtree. `expandAllReviews()` in `extractor.ts` now scopes in-page this way. `tests/extractor-selectors.test.ts` pins the regression shape. +- **Visible-filtered waits and counts**: every "first of several markers" wait uses `a.or(b).filter({ visible: true }).first().waitFor({ state: "visible", timeout })`, and every presence check uses `loc.filter({ visible: true }).count() > 0` – never `isVisible()` on a multi-match locator, and never an unfiltered `.first()`, because a hidden earlier match (a template, a duplicate link) stalls the wait or answers wrongly. Used by `setSortOrder()` and the session-marker read. +- **In-page closures**: code passed to `page.evaluate`, `waitForFunction` or `locator.evaluate` runs in the browser. It may reference only its parameters and browser globals (pass Node constants as arguments – `SCROLL_STEP` read from Node scope crashed every scrape on the second scroll, issue #31), and must not declare named inner functions or `const f = () => …`: tsx/esbuild keepNames wraps those in `__name(...)`, which does not exist in the page. Anonymous inline callbacks (`.map((x) => …)`) are fine. Init scripts are passed as strings (`addInitScript({ content })`) so no transform can touch them. The vitest transform does **not** enable keepNames, so the browser tests catch Node-reference bugs but **not** `__name` bugs – that guard is a live `npm run dev` run that scrolls (e.g. `-m 30`). +- **Expand step**: Google removes a review's "More" button once clicked, so `expandAllReviews(page, skipIds)` uses mark-and-confirm, never positional `nth(i)`: one in-page scan (`scanExpandButtons`) stamps each *pending* button (rendered, not `aria-expanded="true"`) in cards not in `skipIds` with a Node-generated `data-revcli-expand` token (alphabet `[a-z0-9-]`, old stamps cleared first); each token is clicked and confirmed by `waitForFunction` (gone, disconnected, hidden, or `aria-expanded="true"` – this also covers owner-response buttons whichever way they react); up to 2 passes. The scroller passes its collected ids as `skipIds`, so a stuck button costs at most 2 clicks once. `ExpandResult` is for debug logs only: the truncation warning (`formatTruncationWarning()`) comes from the per-card `expandPending` flag that `extractReviews()` reads at extraction time, counted by `collectOnce()` for newly collected reviews and logged once at the end of `scrollAndCollectReviews()`. Every collect path (including the spinner retry) goes through `expandAndCollect()`. Still-truncated reviews are collected anyway (deferring risks losing the whole card from the virtualized list). See docs/selector-maintenance.md §5. +- **Short links redirect in page script**: `maps.app.goo.gl` links no longer redirect with an HTTP 3xx, so `page.goto(..., domcontentloaded)` can resolve while the page is still on the short-link host. `waitForShortLinkRedirect()` in `navigator.ts` waits for the destination before `handleConsent()`/`ensureEnglishLocale()` run. Without it `hl=en` is added to the short link and lost in the redirect, and a signed-out or non-English profile gets a localized page that no English selector or banner text matches (the host constant `SHORT_LINK_HOST` and the pure helper `isShortLinkUrl()` live in `src/utils/url.ts`, which also derives the short-URL input regex from the same constant; pinned by `tests/browser/navigation.test.ts`, which also asserts the final URL has `hl=en` and no `entry`/`g_ep`). +- **Non-place detection**: a link that lands on a search results page fails once with `UnrecoverableError` kind `"NOT_A_PLACE"` and `NOT_A_PLACE_MESSAGE` (which does not echo the URL – batch prints it). Detection is by path (`isSearchResultsUrl()`: `/maps/search…`), never by text (Google may serve that page in another language), and only after the `h1` wait (or the tab wait) times out, because CID and some redirect links pass through `/maps/search/` on their way to `/maps/place/`. Any other timeout is rethrown unchanged so real network flakiness is still retried. +- **Fatal error reporting**: `index.ts` runs `program.parseAsync().catch(reportFatalError)`; `reportFatalError()` in `fatal.ts` prints `describeFatalError(err).message` once via `logger.error`, sets exit code 1, adds "Run again with --verbose for details." only for unexpected errors (not `isUnrecoverable` ones or `ENOENT`), and logs the stack at debug level only. Playwright's "Call log:" section is cut from the message and the stack (it can print the account link's label). `withRetry()` logs its "unrecoverable error" line at debug, so the message appears exactly once; command handlers do not catch `UnrecoverableError` themselves. Any error message from browser code that reaches output or logs goes through `safeErrorMessage()` (call log cut) – batch's per-location failure line, the `withRetry` debug line and the sign-in poll debug line. It is defined in `errors.ts` (no imports, so `retry.ts` can use it without a cycle) and re-exported from `fatal.ts`. +- **Browser tests**: `tests/browser/*.test.ts` run the real in-page code (scroll, expand, session markers, navigation) in a fresh non-persistent headless Chromium (`chromium.launch`) against local HTML from `tests/browser/fixtures/maps-page.ts`. They must **never** import `launchBrowser` or `PROFILE_DIR` (the `~/.revcli` credential store); `tests/browser-import-guard.test.ts` scans every test file for such imports. Timing-sensitive fixture behaviour is event-driven where possible (e.g. `bannerOnReviewsTabClick` shows the banner only after revcli's first check). The harness registers `context.route("**/*", abort)` first and fixture routes after it, so nothing reaches the network even with fake cookies. Fixture behaviour is a plain ` +`; +} diff --git a/tests/browser/harness.ts b/tests/browser/harness.ts new file mode 100644 index 0000000..d800c5a --- /dev/null +++ b/tests/browser/harness.ts @@ -0,0 +1,62 @@ +/** + * Browser-test harness: a throwaway headless Chromium that only ever sees + * local fixture HTML. + * + * Rules (see AGENTS.md "Browser tests"): + * - Never import `launchBrowser` or `PROFILE_DIR` from src/scraper/browser.ts + * here or in any browser test. They open the persistent profile in + * ~/.revcli, which is a credential store holding a real Google session. + * - Every context blocks all network traffic first; fixture routes are added + * afterwards (Playwright runs the most recently registered matching route + * first), so nothing can reach Google even with fake cookies in the context. + */ +import { + chromium, + type Browser, + type BrowserContext, + type Page, +} from "playwright"; + +export async function launchTestBrowser(): Promise { + return chromium.launch({ headless: true }); +} + +/** A fresh, non-persistent context with every network request aborted. */ +export async function newFixtureContext(browser: Browser): Promise { + const context = await browser.newContext({ + viewport: { width: 1280, height: 800 }, + locale: "en-US", + }); + await context.route("**/*", (route) => route.abort()); + return context; +} + +/** A page whose content is the given fixture HTML (no URL, no network). */ +export async function newFixturePage( + context: BrowserContext, + html: string, +): Promise { + const page = await context.newPage(); + await page.setContent(html); + return page; +} + +export type RouteMatcher = string | RegExp | ((url: URL) => boolean); + +/** + * Serve fixture HTML for requests matching `url`. Registered after the + * abort-all route, so it takes precedence for its own URLs only. + * + * There is deliberately no redirect variant: Playwright does not route the + * follow-up request of a fulfilled 3xx, so such a navigation hangs. Fixtures + * that need a different final URL use `rewriteUrlTo` (history.replaceState). + */ +export async function routeFixture( + context: BrowserContext, + url: RouteMatcher, + html: string, +): Promise { + await context.route(url, (route) => + route.fulfill({ status: 200, contentType: "text/html", body: html }), + ); +} diff --git a/tests/browser/navigation.test.ts b/tests/browser/navigation.test.ts new file mode 100644 index 0000000..b56677e --- /dev/null +++ b/tests/browser/navigation.test.ts @@ -0,0 +1,208 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import type { Browser, BrowserContext } from "playwright"; +import { navigateToReviews, NOT_A_PLACE_MESSAGE, setSortOrder } from "../../src/scraper/navigator.js"; +import { parseGoogleMapsInput } from "../../src/utils/url.js"; +import { hasUnrecoverableKind, UnrecoverableError } from "../../src/core/errors.js"; +import { SORT_ORDERS } from "../../src/core/schema.js"; +import { buildMapsPage, type MapsFixtureOptions } from "./fixtures/maps-page.js"; +import { launchTestBrowser, newFixtureContext, newFixturePage, routeFixture } from "./harness.js"; + +vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 }); + +const PLACE_URL = "https://www.google.com/maps/place/Test/data=!1s0x1:0x2?hl=en"; +const isPlacePath = (u: URL) => u.hostname === "www.google.com" && u.pathname === "/maps/place/Test/data=!1s0x1:0x2"; +const CID_URL = "https://www.google.com/maps?cid=1234567890"; +const isCidLink = (u: URL) => u.hostname === "www.google.com" && u.pathname === "/maps" && u.searchParams.has("cid"); +const SEARCH_PATH = "/maps/search/foo/@1,2,3z?hl=en"; + +const PLACE: MapsFixtureOptions = { totalReviews: 10, batchSize: 10, withSortMenu: true }; + +let browser: Browser; +let context: BrowserContext; + +beforeAll(async () => { + browser = await launchTestBrowser(); +}); + +afterAll(async () => { + await browser?.close(); +}); + +beforeEach(async () => { + context = await newFixtureContext(browser); +}); + +afterEach(async () => { + await context?.close(); +}); + +async function rejection(p: Promise): Promise { + return p.then( + () => new Error("expected a rejection"), + (e: unknown) => e, + ); +} + +describe("navigateToReviews on a limited view (issue #31 finding 5)", () => { + it.each([...SORT_ORDERS])("fails with AUTH_REQUIRED for sort %s", async (sort) => { + await routeFixture(context, isPlacePath, buildMapsPage({ ...PLACE, limitedViewBanner: true })); + const page = await context.newPage(); + + const err = await rejection(navigateToReviews(page, parseGoogleMapsInput(PLACE_URL), sort)); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + }); + + it("catches a banner that appears only after the Reviews tab is clicked", async () => { + // The banner is inserted by the tab click, i.e. after the first check: + // only the second check (after the review cards) can see it. + await routeFixture( + context, + isPlacePath, + buildMapsPage({ ...PLACE, limitedViewBanner: true, bannerOnReviewsTabClick: true }), + ); + const page = await context.newPage(); + + const err = await rejection(navigateToReviews(page, parseGoogleMapsInput(PLACE_URL), "relevant")); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + }); + + it.each(["newest", "highest", "lowest"] as const)( + "fails with AUTH_REQUIRED when Sort opens the sign-in dialog, with no banner (sort %s)", + async (sort) => { + await routeFixture(context, isPlacePath, buildMapsPage({ ...PLACE, sortOpensSignInDialog: true })); + const page = await context.newPage(); + + const err = await rejection(navigateToReviews(page, parseGoogleMapsInput(PLACE_URL), sort)); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + }, + ); + + it("does not see the Sort sign-in dialog for sort relevant (no Sort click), so it resolves", async () => { + // Pins current behaviour: with no banner, "relevant" never clicks Sort, so + // the dialog signal cannot fire. The banner is the only signal for it. + await routeFixture(context, isPlacePath, buildMapsPage({ ...PLACE, sortOpensSignInDialog: true })); + const page = await context.newPage(); + + const business = await navigateToReviews(page, parseGoogleMapsInput(PLACE_URL), "relevant"); + + expect(business.name).toBe("Test Place"); + }); + + it("is not fooled by a review quoting the banner text", async () => { + await routeFixture(context, isPlacePath, buildMapsPage({ ...PLACE, reviewQuotingBanner: true })); + const page = await context.newPage(); + + const business = await navigateToReviews(page, parseGoogleMapsInput(PLACE_URL), "relevant"); + + expect(business.name).toBe("Test Place"); + }); +}); + +describe("navigateToReviews on a short link (issue #31)", () => { + it("waits for the script redirect before forcing hl=en", async () => { + // Google redirects maps.app.goo.gl links in page script. If hl=en is added + // to the short link itself it is lost, and a signed-out or non-English + // profile gets a localized page that no English selector matches. + // hl=en is already there, so only the short-link rule can cause the + // extra navigation that strips entry/g_ep. + const target = "https://www.google.com/maps/place/Test/data=!1s0x1:0x2?hl=en&entry=tts&g_ep=Egoy"; + await routeFixture( + context, + (u) => u.hostname === "maps.app.goo.gl", + ``, + ); + await routeFixture(context, isPlacePath, buildMapsPage(PLACE)); + const page = await context.newPage(); + + await navigateToReviews(page, parseGoogleMapsInput("https://maps.app.goo.gl/abcDEF123"), "relevant"); + + const finalUrl = new URL(page.url()); + expect(finalUrl.hostname).toBe("www.google.com"); + expect(finalUrl.searchParams.get("hl")).toBe("en"); + expect(finalUrl.searchParams.has("entry")).toBe(false); + expect(finalUrl.searchParams.has("g_ep")).toBe(false); + }); +}); + +describe("setSortOrder", () => { + it("fails fast with AUTH_REQUIRED when Sort opens the sign-in dialog", async () => { + const page = await newFixturePage(context, buildMapsPage({ ...PLACE, sortOpensSignInDialog: true })); + + const start = Date.now(); + const err = await rejection(setSortOrder(page, "newest")); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + expect(Date.now() - start).toBeLessThan(3000); + }); + + it("is not stalled by a hidden menu item earlier in the DOM", async () => { + const page = await newFixturePage( + context, + buildMapsPage({ ...PLACE, sortOpensSignInDialog: true, hiddenMenuTemplate: true }), + ); + + const start = Date.now(); + const err = await rejection(setSortOrder(page, "newest")); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + expect(Date.now() - start).toBeLessThan(3000); + }); + + it("carries on when the sort menu is visible alongside a sign-in dialog", async () => { + const page = await newFixturePage(context, buildMapsPage({ ...PLACE, signInDialogAtLoad: true })); + + await expect(setSortOrder(page, "newest")).resolves.toBeUndefined(); + }); + + it("still applies the sort through the real menu", async () => { + const page = await newFixturePage(context, buildMapsPage(PLACE)); + + await expect(setSortOrder(page, "newest")).resolves.toBeUndefined(); + }); + + it("still applies the sort with a hidden menu item earlier in the DOM", async () => { + const page = await newFixturePage(context, buildMapsPage({ ...PLACE, hiddenMenuTemplate: true })); + + await expect(setSortOrder(page, "lowest")).resolves.toBeUndefined(); + }); +}); + +// The link loads, then the page rewrites its URL to a search results path – as +// Google Maps does for a link that does not resolve to one place. +describe("navigateToReviews on a non-place link (issue #31 finding 6)", () => { + const searchPage = (h1: string | null) => + buildMapsPage({ totalReviews: 0, batchSize: 1, h1, tabs: [], rewriteUrlTo: SEARCH_PATH }); + + it("fails once with NOT_A_PLACE when the link lands on a search page without h1", async () => { + await routeFixture(context, isCidLink, searchPage(null)); + const page = await context.newPage(); + + const err = await rejection(navigateToReviews(page, parseGoogleMapsInput(CID_URL), "relevant")); + + expect(err).toBeInstanceOf(UnrecoverableError); + expect((err as UnrecoverableError).kind).toBe("NOT_A_PLACE"); + expect((err as UnrecoverableError).message).toBe(NOT_A_PLACE_MESSAGE); + }); + + it("fails with NOT_A_PLACE when the search page has an h1 but no tabs", async () => { + await routeFixture(context, isCidLink, searchPage("Results")); + const page = await context.newPage(); + + const err = await rejection(navigateToReviews(page, parseGoogleMapsInput(CID_URL), "relevant")); + + expect(hasUnrecoverableKind(err, "NOT_A_PLACE")).toBe(true); + }); + + it("rethrows a plain timeout when a place panel never loads on a non-search URL", async () => { + await routeFixture(context, isCidLink, buildMapsPage({ totalReviews: 0, batchSize: 1, h1: null })); + const page = await context.newPage(); + + const err = await rejection(navigateToReviews(page, parseGoogleMapsInput(CID_URL), "relevant")); + + expect(err).toBeInstanceOf(Error); + expect(err).not.toBeInstanceOf(UnrecoverableError); + }); +}); diff --git a/tests/browser/scroll.test.ts b/tests/browser/scroll.test.ts new file mode 100644 index 0000000..0b84a83 --- /dev/null +++ b/tests/browser/scroll.test.ts @@ -0,0 +1,53 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import type { Browser, BrowserContext } from "playwright"; +import { scrollAndCollectReviews } from "../../src/scraper/scroller.js"; +import { buildMapsPage } from "./fixtures/maps-page.js"; +import { launchTestBrowser, newFixtureContext, newFixturePage } from "./harness.js"; + +vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 }); + +let browser: Browser; +let context: BrowserContext; + +beforeAll(async () => { + browser = await launchTestBrowser(); +}); + +afterAll(async () => { + await browser?.close(); +}); + +beforeEach(async () => { + context = await newFixtureContext(browser); +}); + +afterEach(async () => { + await context?.close(); +}); + +describe("scrollAndCollectReviews (in-page scroll code, issue #31 finding 1)", () => { + it("collects exactly maxReviews across several scrolls", async () => { + const page = await newFixturePage( + context, + buildMapsPage({ totalReviews: 35, batchSize: 10 }), + ); + + const reviews = await scrollAndCollectReviews(page, { maxReviews: 30, delayMs: 1 }); + + expect(reviews).toHaveLength(30); + expect(new Set(reviews.map((r) => r.id)).size).toBe(30); + }); + + it("collects every review and stops when the list stops growing", async () => { + const page = await newFixturePage( + context, + buildMapsPage({ totalReviews: 12, batchSize: 5 }), + ); + + const reviews = await scrollAndCollectReviews(page, { delayMs: 1 }); + + expect(reviews.map((r) => r.id).sort()).toEqual( + Array.from({ length: 12 }, (_, i) => `r${i}`).sort(), + ); + }); +}); diff --git a/tests/browser/session.test.ts b/tests/browser/session.test.ts new file mode 100644 index 0000000..9877311 --- /dev/null +++ b/tests/browser/session.test.ts @@ -0,0 +1,210 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import type { Browser, BrowserContext } from "playwright"; +import { + getSessionState, + POLL_PROBE, + SESSION_SIGN_IN_STABLE_MS, + waitForSignIn, +} from "../../src/scraper/auth.js"; +import { hasUnrecoverableKind } from "../../src/core/errors.js"; +import { logger } from "../../src/utils/logger.js"; +import { buildMapsPage, type MapsFixtureOptions } from "./fixtures/maps-page.js"; +import { launchTestBrowser, newFixtureContext, newFixturePage, routeFixture } from "./harness.js"; + +vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 }); + +/** Made-up values: the context blocks all network, so these never reach Google. */ +const FAKE_AUTH_COOKIES = ["SID", "HSID", "SSID", "APISID", "SAPISID", "__Secure-1PSID", "__Secure-3PSID"]; +const PII = ["test.user@example.com", "Konto Google"]; + +let browser: Browser; +let context: BrowserContext; + +beforeAll(async () => { + browser = await launchTestBrowser(); +}); + +afterAll(async () => { + await browser?.close(); +}); + +beforeEach(async () => { + context = await newFixtureContext(browser); +}); + +afterEach(async () => { + await context?.close(); +}); + +async function addFakeAuthCookies(): Promise { + await context.addCookies( + FAKE_AUTH_COOKIES.map((name) => ({ + name, + value: `revcli-fake-${name}`, + domain: ".google.com", + path: "/", + secure: true, + })), + ); +} + +function page(opts: Partial) { + return newFixturePage(context, buildMapsPage({ totalReviews: 0, batchSize: 1, ...opts })); +} + +async function timed(fn: () => Promise): Promise<{ value: T; ms: number }> { + const start = Date.now(); + const value = await fn(); + return { value, ms: Date.now() - start }; +} + +describe("getSessionState (issue #31 findings 3–4)", () => { + it("reports a dead session (cookies + steady Sign in link) as expired", async () => { + await addFakeAuthCookies(); + const p = await page({ markerTimeline: [{ atMs: 0, marker: "sign-in" }] }); + + const { value, ms } = await timed(() => getSessionState(p)); + + expect(value).toBe("expired"); + expect(ms).toBeGreaterThanOrEqual(SESSION_SIGN_IN_STABLE_MS); + }); + + it("uses a longer stability window for the commands than for the poll loop", async () => { + // "Sign in" for 2 s, then the account link: longer than the poll loop's + // 1.5 s window, shorter than the commands' 3 s window. + await addFakeAuthCookies(); + const timeline = [ + { atMs: 0, marker: "sign-in" as const }, + { atMs: 2000, marker: "account" as const }, + ]; + + const forCommands = await page({ markerTimeline: timeline }); + expect(await getSessionState(forCommands)).toBe("signed-in"); + + const forPolling = await page({ markerTimeline: timeline }); + expect(await getSessionState(forPolling, POLL_PROBE)).toBe("expired"); + }); + + it("reports cookies + account link as signed-in", async () => { + await addFakeAuthCookies(); + const p = await page({ markerTimeline: [{ atMs: 0, marker: "account" }], markerLang: "en" }); + + expect(await getSessionState(p)).toBe("signed-in"); + }); + + it("reads the markers independently of the page language", async () => { + await addFakeAuthCookies(); + const account = await page({ markerTimeline: [{ atMs: 0, marker: "account" }], markerLang: "pl" }); + expect(await getSessionState(account)).toBe("signed-in"); + + const signIn = await page({ markerTimeline: [{ atMs: 0, marker: "sign-in" }], markerLang: "pl" }); + expect(await getSessionState(signIn)).toBe("expired"); + }); + + it("reports signed-out quickly when there are no auth cookies", async () => { + const p = await page({ markerTimeline: [{ atMs: 0, marker: "sign-in" }] }); + + const { value, ms } = await timed(() => getSessionState(p)); + + expect(value).toBe("signed-out"); + expect(ms).toBeLessThan(1000); + }); + + it("waits for a slow account marker, and is unconfirmed when none appears", async () => { + await addFakeAuthCookies(); + const slow = await page({ markerTimeline: [{ atMs: 1500, marker: "account" }] }); + expect(await getSessionState(slow)).toBe("signed-in"); + + const none = await page({}); + expect(await getSessionState(none, { timeoutMs: 500 })).toBe("unconfirmed"); + }); + + it("never reports a transient Sign in link on a valid session as expired", async () => { + await addFakeAuthCookies(); + const p = await page({ + markerTimeline: [ + { atMs: 0, marker: "sign-in" }, + { atMs: 800, marker: "account" }, + ], + }); + + expect(await getSessionState(p)).toBe("signed-in"); + }); + + it("ignores a hidden duplicate Sign in link earlier in the DOM", async () => { + await addFakeAuthCookies(); + const p = await page({ + hiddenDuplicateMarker: "sign-in", + markerTimeline: [{ atMs: 0, marker: "account" }], + }); + + const { value, ms } = await timed(() => getSessionState(p)); + + expect(value).toBe("signed-in"); + expect(ms).toBeLessThan(2000); + }); + + it("never logs the account label (name, email)", async () => { + const spies = (["debug", "info", "warn", "error"] as const).map((level) => + vi.spyOn(logger, level), + ); + try { + await addFakeAuthCookies(); + for (const markerLang of ["en", "pl"] as const) { + for (const marker of ["account", "sign-in"] as const) { + const p = await page({ markerTimeline: [{ atMs: 0, marker }], markerLang }); + await getSessionState(p, POLL_PROBE); + } + } + const unconfirmed = await page({ hiddenDuplicateMarker: "account" }); + await getSessionState(unconfirmed, { timeoutMs: 300 }); + + const logged = spies.flatMap((s) => s.mock.calls).map((args) => args.map(String).join(" ")); + expect(logged.length).toBeGreaterThan(0); + for (const line of logged) { + for (const secret of PII) expect(line).not.toContain(secret); + } + } finally { + for (const spy of spies) spy.mockRestore(); + } + }); +}); + +// The real session probe inside the sign-in poll loop (no injected `probe`). +// A cookie-only check would report "signed-in" for the dead session below. +describe("waitForSignIn with the real session probe", () => { + const MAPS_HOME = "https://www.google.com/maps?hl=en"; + const isMapsHome = (u: URL) => u.hostname === "www.google.com" && u.pathname === "/maps"; + + it("keeps waiting on a dead session (cookies + steady Sign in link) and times out", async () => { + await addFakeAuthCookies(); + await routeFixture( + context, + isMapsHome, + buildMapsPage({ totalReviews: 0, batchSize: 1, markerTimeline: [{ atMs: 0, marker: "sign-in" }] }), + ); + const p = await context.newPage(); + await p.goto(MAPS_HOME); + + const err = await waitForSignIn(context, p, { timeoutMs: 8000, pollIntervalMs: 50 }).catch( + (e: unknown) => e, + ); + + expect(hasUnrecoverableKind(err, "AUTH_POLL")).toBe(true); + }); + + it("returns signed-in once Google shows the account link", async () => { + await addFakeAuthCookies(); + await routeFixture( + context, + isMapsHome, + buildMapsPage({ totalReviews: 0, batchSize: 1, markerTimeline: [{ atMs: 0, marker: "account" }] }), + ); + const p = await context.newPage(); + await p.goto(MAPS_HOME); + + await expect(waitForSignIn(context, p, { timeoutMs: 8000, pollIntervalMs: 50 })).resolves.toBe( + "signed-in", + ); + }); +}); diff --git a/tests/consent.test.ts b/tests/consent.test.ts index e92b189..a3121c0 100644 --- a/tests/consent.test.ts +++ b/tests/consent.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from "vitest"; -import { appendHlParam } from "../src/scraper/consent.js"; +import { appendHlParam, englishLocaleTarget } from "../src/scraper/consent.js"; import { extractPlaceIdFromUrl } from "../src/utils/url.js"; describe("appendHlParam", () => { @@ -68,3 +68,56 @@ describe("appendHlParam", () => { expect(placeId).toBe("0x3e2ee3641f7016d7:0x8e3a8bcf52dad296"); }); }); + +describe("appendHlParam short-link detection", () => { + it("rewrites a normal Maps link that only mentions the short-link host in its query", () => { + const out = appendHlParam("https://www.google.com/maps/place/Test/@0,0,15z?ref=maps.app.goo.gl"); + expect(new URL(out).searchParams.get("hl")).toBe("en"); + }); +}); + +describe("englishLocaleTarget", () => { + const params = (url: string | null) => new URL(url ?? "about:blank").searchParams; + + it("returns null for an English URL without limited-view params", () => { + expect(englishLocaleTarget("https://www.google.com/maps/place/Test/@0,0,15z?hl=en")).toBeNull(); + }); + + it("forces hl=en when hl is missing or another language", () => { + for (const url of [ + "https://www.google.com/maps/place/Test/@0,0,15z", + "https://www.google.com/maps/place/Test/@0,0,15z?hl=pl", + "https://www.google.com/maps/place/Test/@0,0,15z?hl=en-GB", + ]) { + expect(params(englishLocaleTarget(url)).get("hl")).toBe("en"); + } + }); + + it("does not mistake hl=en inside another parameter's value for the locale", () => { + const url = "https://www.google.com/maps/place/Test/@0,0,15z?q=hl%3Den&hl=de"; + expect(params(englishLocaleTarget(url)).get("hl")).toBe("en"); + }); + + it("leaves an English URL alone when Google's script re-added entry/g_ep", () => { + // Without the option, tracking params must not cost a second page load. + expect( + englishLocaleTarget("https://www.google.com/maps/place/Test/@0,0,15z?hl=en&entry=ttu&g_ep=Egoy"), + ).toBeNull(); + }); + + it("strips entry and g_ep after a short-link redirect even when hl is already en", () => { + const target = englishLocaleTarget( + "https://www.google.com/maps/place/Test/@0,0,15z?hl=en&entry=tts&g_ep=Egoy", + { stripLimitedViewParams: true }, + ); + const p = params(target); + expect(p.get("hl")).toBe("en"); + expect(p.has("entry")).toBe(false); + expect(p.has("g_ep")).toBe(false); + }); + + it("returns null for a short link and for unparseable input", () => { + expect(englishLocaleTarget("https://maps.app.goo.gl/abc123")).toBeNull(); + expect(englishLocaleTarget("not a url")).toBeNull(); + }); +}); diff --git a/tests/extractor.test.ts b/tests/extractor.test.ts index 769c23e..c7f75cf 100644 --- a/tests/extractor.test.ts +++ b/tests/extractor.test.ts @@ -5,8 +5,23 @@ import { buildCardSelector, shouldFallbackLang, resolveOriginalLanguage, + formatTruncationWarning, } from "../src/scraper/extractor.js"; +describe("formatTruncationWarning", () => { + it("uses the singular noun for a single collected review", () => { + expect(formatTruncationWarning(1, 1)).toBe( + 'Could not expand the full text of 1 of 1 collected review – their text may be cut off (ends with "…").', + ); + }); + + it("uses the plural noun for several collected reviews", () => { + expect(formatTruncationWarning(3, 300)).toBe( + 'Could not expand the full text of 3 of 300 collected reviews – their text may be cut off (ends with "…").', + ); + }); +}); + describe("isShowingTranslation", () => { it("is true when aria-checked is 'true'", () => { expect(isShowingTranslation("true")).toBe(true); diff --git a/tests/fatal.test.ts b/tests/fatal.test.ts new file mode 100644 index 0000000..c19271c --- /dev/null +++ b/tests/fatal.test.ts @@ -0,0 +1,123 @@ +import { afterEach, describe, it, expect, vi } from "vitest"; +import { describeFatalError, reportFatalError, safeErrorMessage } from "../src/core/fatal.js"; +import { logger } from "../src/utils/logger.js"; +import { UnrecoverableError } from "../src/core/errors.js"; + +describe("describeFatalError", () => { + it("treats a typed UnrecoverableError as expected", () => { + const f = describeFatalError(new UnrecoverableError("AUTH_REQUIRED", "Run `revcli auth`.")); + expect(f).toMatchObject({ message: "Run `revcli auth`.", expected: true }); + }); + + it("treats an invalid-input error as expected", () => { + const f = describeFatalError(new Error('Invalid input: "foo". Provide a Google Maps URL or Place ID.')); + expect(f.expected).toBe(true); + expect(f.message).toBe('Invalid input: "foo". Provide a Google Maps URL or Place ID.'); + }); + + it("treats a missing file (ENOENT) as expected", () => { + const err = Object.assign(new Error("ENOENT: no such file or directory, open 'urls.txt'"), { + code: "ENOENT", + }); + expect(describeFatalError(err).expected).toBe(true); + }); + + it("treats a plain error as unexpected and keeps its stack for debug output", () => { + const f = describeFatalError(new Error("Something went wrong")); + expect(f.expected).toBe(false); + expect(f.message).toBe("Something went wrong"); + expect(f.stack).toContain("Something went wrong"); + }); + + it("stringifies a non-Error throwable", () => { + expect(describeFatalError("plain string")).toEqual({ + message: "plain string", + stack: null, + expected: false, + }); + }); + + it("cuts Playwright's call log, which can contain the account name and email", () => { + const err = new Error( + 'locator.click: Timeout 1000ms exceeded.\nCall log:\n - locator resolved to ', + ); + const f = describeFatalError(err); + expect(f.message).toBe("locator.click: Timeout 1000ms exceeded."); + expect(f.message).not.toContain("Call log"); + expect(f.message).not.toContain("example.com"); + expect(f.stack).not.toContain("example.com"); + }); +}); + +const CALL_LOG_ERROR = () => + new Error( + 'locator.click: Timeout 1000ms exceeded.\nCall log:\n - locator resolved to ', + ); + +describe("safeErrorMessage", () => { + it("cuts Playwright's call log", () => { + expect(safeErrorMessage(CALL_LOG_ERROR())).toBe("locator.click: Timeout 1000ms exceeded."); + }); + + it("keeps a message without a call log unchanged", () => { + expect(safeErrorMessage(new Error("boom\nsecond line"))).toBe("boom\nsecond line"); + }); + + it("stringifies a non-Error throwable", () => { + expect(safeErrorMessage("plain")).toBe("plain"); + expect(safeErrorMessage(42)).toBe("42"); + }); +}); + +describe("reportFatalError", () => { + const originalExitCode = process.exitCode; + + afterEach(() => { + process.exitCode = originalExitCode; + vi.restoreAllMocks(); + }); + + function spies() { + return { + error: vi.spyOn(logger, "error").mockImplementation(() => {}), + info: vi.spyOn(logger, "info").mockImplementation(() => {}), + debug: vi.spyOn(logger, "debug").mockImplementation(() => {}), + }; + } + + it("prints an expected error once, with no --verbose hint, stack at debug only", () => { + const s = spies(); + + reportFatalError(new UnrecoverableError("AUTH_REQUIRED", "Run `revcli auth`.")); + + expect(s.error).toHaveBeenCalledTimes(1); + expect(s.error).toHaveBeenCalledWith("Run `revcli auth`."); + expect(s.info).not.toHaveBeenCalled(); + expect(s.debug).toHaveBeenCalledTimes(1); + expect(String(s.debug.mock.calls[0][0])).toContain("UnrecoverableError"); + expect(process.exitCode).toBe(1); + }); + + it("adds the --verbose hint for an unexpected error and never prints the stack at error level", () => { + const s = spies(); + + reportFatalError(CALL_LOG_ERROR()); + + expect(s.error).toHaveBeenCalledTimes(1); + expect(s.error).toHaveBeenCalledWith("locator.click: Timeout 1000ms exceeded."); + expect(s.info).toHaveBeenCalledWith("Run again with --verbose for details."); + expect(String(s.error.mock.calls[0][0])).not.toContain(" at "); + expect(String(s.debug.mock.calls[0][0])).not.toContain("example.com"); + expect(process.exitCode).toBe(1); + }); + + it("reports a non-Error throwable without a stack", () => { + const s = spies(); + + reportFatalError("plain string"); + + expect(s.error).toHaveBeenCalledWith("plain string"); + expect(s.debug).not.toHaveBeenCalled(); + expect(process.exitCode).toBe(1); + }); +}); diff --git a/tests/retry.test.ts b/tests/retry.test.ts index c989f6f..d949e9b 100644 --- a/tests/retry.test.ts +++ b/tests/retry.test.ts @@ -1,5 +1,7 @@ import { describe, it, expect, vi } from "vitest"; import { withRetry } from "../src/core/retry.js"; +import { UnrecoverableError } from "../src/core/errors.js"; +import { logger } from "../src/utils/logger.js"; describe("withRetry", () => { it("returns result on first success", async () => { @@ -57,6 +59,29 @@ describe("withRetry", () => { expect(fn).toHaveBeenCalledTimes(1); }); + it("does not retry a typed AUTH_REQUIRED error", async () => { + const fn = vi + .fn() + .mockRejectedValue(new UnrecoverableError("AUTH_REQUIRED", "limited view")); + await expect( + withRetry(fn, "test", { maxRetries: 3, baseDelayMs: 10 }), + ).rejects.toThrow("limited view"); + expect(fn).toHaveBeenCalledTimes(1); + }); + + it("does not log an UnrecoverableError at error level (the caller prints it once)", async () => { + const errorSpy = vi.spyOn(logger, "error"); + try { + const fn = vi.fn().mockRejectedValue(new UnrecoverableError("NOT_A_PLACE", "search page")); + await expect( + withRetry(fn, "test", { maxRetries: 3, baseDelayMs: 10 }), + ).rejects.toThrow("search page"); + expect(errorSpy).not.toHaveBeenCalled(); + } finally { + errorSpy.mockRestore(); + } + }); + it("wraps non-Error throwables", async () => { const fn = vi.fn().mockRejectedValue("string error"); await expect( diff --git a/tests/scrape-location.test.ts b/tests/scrape-location.test.ts index db3a1ae..888fb44 100644 --- a/tests/scrape-location.test.ts +++ b/tests/scrape-location.test.ts @@ -1,5 +1,11 @@ -import { describe, it, expect } from "vitest"; -import { assembleScrapeResult } from "../src/scraper/scrape-location.js"; +import { describe, it, expect, vi } from "vitest"; +import { + assembleScrapeResult, + navigateWithAuthFallback, + type AuthFallbackDeps, +} from "../src/scraper/scrape-location.js"; +import { authRequiredError, type SessionState } from "../src/scraper/auth.js"; +import { hasUnrecoverableKind } from "../src/core/errors.js"; import type { Business, Review } from "../src/core/schema.js"; function makeReview(id: string): Review { @@ -155,3 +161,70 @@ describe("assembleScrapeResult", () => { expect(reviews[0].id).toBe(originalFirstId); }); }); + +describe("navigateWithAuthFallback", () => { + const M1_START = "Google Maps is showing a limited view: this browser profile is not signed in"; + const M1B_START = "Google Maps is showing a limited view even though this browser profile appears to be signed in"; + + function deps(overrides: Partial> = {}) { + const navigate = vi.fn<() => Promise<{ name: string }>>(); + const waitForAuth = vi.fn<() => Promise>().mockResolvedValue(undefined); + const sessionProbe = vi.fn<() => Promise>().mockResolvedValue("expired"); + return { headless: true, navigate, waitForAuth, sessionProbe, ...overrides }; + } + + it("fails headless at once with the sign-in wording", async () => { + const d = deps(); + d.navigate.mockRejectedValue(authRequiredError()); + + const err = await navigateWithAuthFallback(d).catch((e: unknown) => e); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + expect((err as Error).message.startsWith(M1_START)).toBe(true); + expect(d.waitForAuth).not.toHaveBeenCalled(); + expect(d.navigate).toHaveBeenCalledTimes(1); + }); + + it("headed: waits for sign-in and returns the second navigation's result", async () => { + const d = deps({ headless: false }); + d.navigate + .mockRejectedValueOnce(authRequiredError()) + .mockResolvedValueOnce({ name: "B" }); + + await expect(navigateWithAuthFallback(d)).resolves.toEqual({ name: "B" }); + expect(d.waitForAuth).toHaveBeenCalledTimes(1); + expect(d.sessionProbe).not.toHaveBeenCalled(); + }); + + it("headed: a limited view after sign-in on a signed-in profile gets the M1b wording", async () => { + const d = deps({ headless: false }); + d.navigate.mockRejectedValue(authRequiredError()); + d.sessionProbe.mockResolvedValue("signed-in"); + + const err = await navigateWithAuthFallback(d).catch((e: unknown) => e); + + expect(hasUnrecoverableKind(err, "AUTH_REQUIRED")).toBe(true); + expect((err as Error).message.startsWith(M1B_START)).toBe(true); + expect(d.navigate).toHaveBeenCalledTimes(2); + }); + + it("falls back to the sign-in wording when the session probe fails", async () => { + const d = deps(); + d.navigate.mockRejectedValue(authRequiredError()); + d.sessionProbe.mockRejectedValue(new Error("page closed")); + + const err = await navigateWithAuthFallback(d).catch((e: unknown) => e); + + expect((err as Error).message.startsWith(M1_START)).toBe(true); + }); + + it("rethrows any other error unchanged without probing or prompting", async () => { + const d = deps({ headless: false }); + const boom = new Error("boom"); + d.navigate.mockRejectedValue(boom); + + await expect(navigateWithAuthFallback(d)).rejects.toBe(boom); + expect(d.sessionProbe).not.toHaveBeenCalled(); + expect(d.waitForAuth).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/selectors.test.ts b/tests/selectors.test.ts new file mode 100644 index 0000000..d6431e3 --- /dev/null +++ b/tests/selectors.test.ts @@ -0,0 +1,28 @@ +import { describe, it, expect } from "vitest"; +import { SELECTORS, TEXT_MARKERS } from "../src/scraper/selectors.js"; + +describe("SELECTORS", () => { + it("never uses Playwright's :has-text substring match", () => { + for (const value of Object.values(SELECTORS)) { + const all = Array.isArray(value) ? value : [value]; + for (const sel of all) expect(sel).not.toContain("has-text"); + } + }); + + it.each([ + ["accountButton", SELECTORS.accountButton, "SignOutOptions"], + ["signInLink", SELECTORS.signInLink, "ServiceLogin"], + ])("matches %s by its accounts.google.com href only", (_name, sel, path) => { + expect(sel).toBe(`a[href^="https://accounts.google.com/${path}"]`); + expect(sel).not.toContain("aria-label"); + }); +}); + +describe("TEXT_MARKERS", () => { + it("holds a lower-case limited-view phrase longer than 'limited view'", () => { + const marker = TEXT_MARKERS.limitedViewBanner; + expect(marker).toBe(marker.toLowerCase()); + expect(marker.length).toBeGreaterThan("limited view".length); + expect(marker).toContain("limited view"); + }); +}); diff --git a/tests/unrecoverable.test.ts b/tests/unrecoverable.test.ts index e468601..a63b8bd 100644 --- a/tests/unrecoverable.test.ts +++ b/tests/unrecoverable.test.ts @@ -1,6 +1,26 @@ import { describe, it, expect } from "vitest"; import { isUnrecoverable } from "../src/core/retry.js"; -import { UnrecoverableError } from "../src/core/errors.js"; +import { UnrecoverableError, hasUnrecoverableKind } from "../src/core/errors.js"; + +describe("hasUnrecoverableKind", () => { + it("is true for an UnrecoverableError of the given kind", () => { + expect( + hasUnrecoverableKind(new UnrecoverableError("AUTH_REQUIRED", "x"), "AUTH_REQUIRED"), + ).toBe(true); + }); + + it("is false for an UnrecoverableError of another kind", () => { + expect( + hasUnrecoverableKind(new UnrecoverableError("NOT_A_PLACE", "x"), "AUTH_REQUIRED"), + ).toBe(false); + }); + + it("is false for plain errors and non-errors", () => { + expect(hasUnrecoverableKind(new Error("AUTH_REQUIRED"), "AUTH_REQUIRED")).toBe(false); + expect(hasUnrecoverableKind("AUTH_REQUIRED", "AUTH_REQUIRED")).toBe(false); + expect(hasUnrecoverableKind(undefined, "AUTH_REQUIRED")).toBe(false); + }); +}); describe("isUnrecoverable", () => { it("detects 'invalid input'", () => { @@ -52,6 +72,11 @@ describe("isUnrecoverable", () => { expect(isUnrecoverable(new UnrecoverableError("SORT_VERIFY", ""))).toBe(true); }); + it("detects the AUTH_REQUIRED and NOT_A_PLACE kinds", () => { + expect(isUnrecoverable(new UnrecoverableError("AUTH_REQUIRED", "limited view"))).toBe(true); + expect(isUnrecoverable(new UnrecoverableError("NOT_A_PLACE", "search page"))).toBe(true); + }); + it("matches the exact navigation verification error template thrown by navigator.ts", () => { // Pin the exact message shape so retry.ts classifier and navigator.ts // thrower cannot silently drift apart. Mirrors navigator.ts:58-62 template. diff --git a/tests/url.test.ts b/tests/url.test.ts index 4b264fa..daf369c 100644 --- a/tests/url.test.ts +++ b/tests/url.test.ts @@ -5,8 +5,59 @@ import { extractPlaceIdFromUrl, placeIdsMatch, canVerifyPlaceIdFormat, + isSearchResultsUrl, + isShortLinkUrl, + SHORT_LINK_HOST, } from "../src/utils/url.js"; +describe("isShortLinkUrl", () => { + it("is true for a maps.app.goo.gl share link", () => { + expect(SHORT_LINK_HOST).toBe("maps.app.goo.gl"); + expect(isShortLinkUrl("https://maps.app.goo.gl/MTVGWdpd8vVqTouv9")).toBe(true); + expect(isShortLinkUrl("http://maps.app.goo.gl/abc?g_st=ic")).toBe(true); + }); + + it.each([ + "https://www.google.com/maps/place/Test/@0,0,15z", + "https://www.google.com/maps?continue=https://maps.app.goo.gl/abc", + "https://maps.app.goo.gl.example.com/abc", + "https://evilmaps.app.goo.gl/abc", + "not a url", + "", + ])("is false for %s", (url) => { + expect(isShortLinkUrl(url)).toBe(false); + }); + + it("is the same host that parseGoogleMapsInput treats as a short URL", () => { + expect(parseGoogleMapsInput(`https://${SHORT_LINK_HOST}/abc123`).isShortUrl).toBe(true); + expect(() => parseGoogleMapsInput("https://mapsXappXgooXgl/abc123")).toThrow(/Invalid input/); + }); +}); + +describe("isSearchResultsUrl", () => { + it("is true for a /maps/search/ page, tracking params included", () => { + expect( + isSearchResultsUrl( + "https://www.google.com/maps/search/coffee+near+me/@52.23,21.01,14z?entry=ttu&g_ep=EgoyMDI2", + ), + ).toBe(true); + expect(isSearchResultsUrl("https://www.google.pl/maps/search/foo/@1,2,3z?hl=en")).toBe(true); + }); + + it.each([ + "https://www.google.com/maps/place/Optimo+Nakheel/@24.74,46.64,867m/data=!1s0x3e2ee3641f7016d7:0x8e3a8bcf52dad296", + "https://www.google.com/maps?cid=1234567890", + "https://www.google.com/maps?ftid=0x3e2ee3641f7016d7:0x8e3a8bcf52dad296", + "https://www.google.com/maps/place/?q=place_id:ChIJN1t_tDeuEmsRUsoyG83frY4", + "https://www.google.com/maps/place/Caf%C3%A9+S%C5%82odki/@52.2,21.0,17z", + "https://www.google.com/maps/searchable-place/", + "not a url", + "", + ])("is false for %s", (url) => { + expect(isSearchResultsUrl(url)).toBe(false); + }); +}); + describe("parseGoogleMapsInput", () => { it("parses a long Google Maps URL", () => { const url =