pi-chrome-search 2.0.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -3
- package/package.json +5 -3
- package/src/config/defaults.ts +41 -1
- package/src/config/doc.ts +5 -0
- package/src/config/schema.ts +4 -0
- package/src/engines/avito.ts +552 -0
- package/src/engines/google.ts +87 -2
- package/src/engines/index.ts +14 -3
- package/src/engines/ozon.ts +493 -0
- package/src/engines/types.ts +67 -7
- package/src/engines/yandex.ts +29 -3
- package/src/extract/compact.ts +61 -5
- package/src/extract/facts.ts +39 -0
- package/src/runtime/doctor.ts +30 -3
- package/src/runtime/limiter.ts +5 -5
- package/src/runtime/panel.ts +2 -2
- package/src/tools/web_search.ts +46 -7
package/src/engines/index.ts
CHANGED
|
@@ -19,12 +19,16 @@
|
|
|
19
19
|
*/
|
|
20
20
|
|
|
21
21
|
import type { Config } from "../config/index.ts";
|
|
22
|
+
import { resolveConfigPath } from "../config/env.ts";
|
|
23
|
+
import { avitoEngine } from "./avito.ts";
|
|
22
24
|
import { duckduckgoEngine } from "./duckduckgo.ts";
|
|
23
25
|
import { googleEngine } from "./google.ts";
|
|
26
|
+
import { ozonEngine } from "./ozon.ts";
|
|
24
27
|
import { yandexEngine } from "./yandex.ts";
|
|
25
28
|
import { WebSearchError } from "../runtime/error-codes.ts";
|
|
26
29
|
import {
|
|
27
30
|
ENGINE_IDS,
|
|
31
|
+
isPrimaryEngine,
|
|
28
32
|
type Engine,
|
|
29
33
|
type EngineId,
|
|
30
34
|
type EngineRegistry,
|
|
@@ -45,6 +49,8 @@ export const DEFAULT_ENGINES: EngineMap = Object.freeze({
|
|
|
45
49
|
google: googleEngine,
|
|
46
50
|
duckduckgo: duckduckgoEngine,
|
|
47
51
|
yandex: yandexEngine,
|
|
52
|
+
avito: avitoEngine,
|
|
53
|
+
ozon: ozonEngine,
|
|
48
54
|
});
|
|
49
55
|
|
|
50
56
|
/**
|
|
@@ -84,13 +90,16 @@ function missingEngine(id: EngineId): WebSearchError {
|
|
|
84
90
|
}
|
|
85
91
|
|
|
86
92
|
function disabledEngine(id: EngineId): WebSearchError {
|
|
93
|
+
// S9.2: the hint names the real file and the real key, because "enable it in
|
|
94
|
+
// config" sends the agent hunting. A special engine (avito) ships disabled, so
|
|
95
|
+
// this is the first thing a user of it sees.
|
|
87
96
|
return new WebSearchError({
|
|
88
97
|
code: "E_UNSUPPORTED",
|
|
89
98
|
engine: id,
|
|
90
99
|
stage: "resolve",
|
|
91
100
|
retryable: false,
|
|
92
101
|
message: `engine "${id}" is disabled in config`,
|
|
93
|
-
hint: `set config.engines.${id}.enabled = true (or pick another engine); /web-doctor shows the current state`,
|
|
102
|
+
hint: `set config.engines.${id}.enabled = true in ${resolveConfigPath(process.env)} (or pick another engine); /web-doctor shows the current state`,
|
|
94
103
|
});
|
|
95
104
|
}
|
|
96
105
|
|
|
@@ -122,8 +131,10 @@ class Registry implements EngineRegistry {
|
|
|
122
131
|
|
|
123
132
|
select(requested: EngineSelection): EngineId[] {
|
|
124
133
|
const usable = new Set(this.enabled());
|
|
125
|
-
// `auto` is the canonical order by construction: `enabled()` walks ENGINE_IDS
|
|
126
|
-
|
|
134
|
+
// `auto` is the canonical order by construction: `enabled()` walks ENGINE_IDS,
|
|
135
|
+
// and the primary filter is what keeps a special engine (avito) out of it
|
|
136
|
+
// (SPEC S4.7/D11). A caller that wants it names it.
|
|
137
|
+
if (requested === "auto") return this.enabled().filter(isPrimaryEngine);
|
|
127
138
|
|
|
128
139
|
const list = Array.isArray(requested) ? requested : [requested];
|
|
129
140
|
const selected: EngineId[] = [];
|
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ozon adapter (SPEC S6.5, §15 D14) — the second *special* engine: marketplace
|
|
3
|
+
* goods for one site, reachable only by naming it (`engines: "ozon"`).
|
|
4
|
+
*
|
|
5
|
+
* What the live SERP actually gives us (captured 2026-11-16 on the owner's
|
|
6
|
+
* profile; fixtures `tests/fixtures/ozon-serp.html.gz` and
|
|
7
|
+
* `ozon-no-match.html.gz` are the results area of those pages):
|
|
8
|
+
*
|
|
9
|
+
* - `https://www.ozon.ru/search/?text=…` answers with a *semantic redirect* to
|
|
10
|
+
* `/<category-slug>/?text=…` when Ozon predicts a catalog. Both shapes render
|
|
11
|
+
* the same grid, so one URL builder covers them and the landed URL is not
|
|
12
|
+
* evidence of a failed search. `page=N` survives the redirect (verified on a
|
|
13
|
+
* `page=2` navigation: a different product set came back).
|
|
14
|
+
* - A card is `.tile-root[data-index]`. The product link is the anchor that
|
|
15
|
+
* wraps the title; the image anchor carries the same href, so the title
|
|
16
|
+
* anchor is resolved from the title node instead of by position.
|
|
17
|
+
* - `span.tsBody500Medium` is the title, `span.tsHeadline500Medium` the visible
|
|
18
|
+
* price ("31 209 ₽"), `span.tsBodyControl300XSmall` the score-then-count pair
|
|
19
|
+
* ("4.7", "65 отзывов"). Those `ts*` tokens are Ozon's design-system
|
|
20
|
+
* typography, not hashed CSS-module names (`q4b1_6_0-a`), which is what makes
|
|
21
|
+
* them usable as markers at all.
|
|
22
|
+
* - A card carries no description, so `snippet` is empty on purpose: an Ozon
|
|
23
|
+
* tile has price and rating, not prose, and inventing a snippet from badges
|
|
24
|
+
* ("Чёрная пятница", "Стало дешевле") would be a lie with formatting.
|
|
25
|
+
* - A no-match query is answered with recommendations under the headline
|
|
26
|
+
* "Ничего не нашлось" (statusWidget). The cards are real, they just do not
|
|
27
|
+
* answer the query, so they are returned under an authored `notice` (S7.6).
|
|
28
|
+
* - The home page renders 20 `.tile-root` cards of its own, so a bare card
|
|
29
|
+
* selector would let the typed warm-up settle on the home page and read a
|
|
30
|
+
* carousel as results. The gate is therefore the *results* chrome
|
|
31
|
+
* (`searchResultsV2`/`searchResultsSort`/`statusWidget`), which the home page
|
|
32
|
+
* does not have (measured on the capture).
|
|
33
|
+
*
|
|
34
|
+
* Extraction is a self-contained in-page function (same `toString()` rule as the
|
|
35
|
+
* other adapters): live code sends `(${extractFromDocument})(document, arg)`
|
|
36
|
+
* through `Runtime.evaluate`, tests run the *same* source through `runInPage` in
|
|
37
|
+
* a `node:vm` context.
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
import type { CdpPage } from "../cdp/types.ts";
|
|
41
|
+
import { waitForMarker } from "../cdp/humanize.ts";
|
|
42
|
+
import { asFacts } from "../extract/facts.ts";
|
|
43
|
+
import { normalizeUrl } from "../extract/urls.ts";
|
|
44
|
+
import { fail } from "../runtime/errors.ts";
|
|
45
|
+
import type { Clock } from "../runtime/types.ts";
|
|
46
|
+
import type {
|
|
47
|
+
Engine,
|
|
48
|
+
EngineInteraction,
|
|
49
|
+
Query,
|
|
50
|
+
RawSerp,
|
|
51
|
+
SerpItem,
|
|
52
|
+
Wall,
|
|
53
|
+
} from "./types.ts";
|
|
54
|
+
|
|
55
|
+
/** A server-rendered page that hydrates a large client bundle; 12 s is generous. */
|
|
56
|
+
export const OZON_SETTLE_DEADLINE_MS = 12_000;
|
|
57
|
+
const SETTLE_POLL_MS = 200;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Readiness gate. The two observed markers are the results chrome:
|
|
61
|
+
*
|
|
62
|
+
* - `searchResultsSort` — the sort/filter bar of a catalog-shaped result page
|
|
63
|
+
* (every captured search landed on one of these);
|
|
64
|
+
* - `statusWidget` — the notice slot a zero-match search renders instead of a
|
|
65
|
+
* list, so "no exact match" settles too and is reported as a notice instead of
|
|
66
|
+
* burning the deadline.
|
|
67
|
+
*
|
|
68
|
+
* `searchResultsV2` is *anticipated, never observed*: it is the widget name of the
|
|
69
|
+
* plain `/search/?text=` result list, and every capture of 2026-11-16 was
|
|
70
|
+
* redirected to a category page. It costs one alternation to keep, and without it
|
|
71
|
+
* a non-redirected search list would time out instead of extracting. The canaries
|
|
72
|
+
* report its count, so a layout that uses it says so.
|
|
73
|
+
*
|
|
74
|
+
* The captcha half exists for the same reason Google keeps `#captcha-form` next
|
|
75
|
+
* to `#rso`: a wall page has no results chrome, so without it the settle would
|
|
76
|
+
* spend its whole deadline *before* `detectWall()` can report the wall it is
|
|
77
|
+
* looking at (S8.5).
|
|
78
|
+
*/
|
|
79
|
+
export const OZON_CAPTCHA_SELECTOR =
|
|
80
|
+
'#captcha, .h-captcha, #h-captcha, iframe[src*="captcha"], form[action*="captcha"], [class*="captcha"]';
|
|
81
|
+
export const OZON_READY_SELECTOR = `[data-widget="searchResultsV2"], [data-widget="searchResultsSort"], [data-widget="statusWidget"], ${OZON_CAPTCHA_SELECTOR}`;
|
|
82
|
+
export const OZON_TILE_SELECTOR = ".tile-root";
|
|
83
|
+
|
|
84
|
+
const BOX_SELECTOR = 'input[name="text"]';
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Typed-search profile. The box is `maxlength="255"` (captured), so a longer
|
|
88
|
+
* query is never typed — a truncated query would search for something the user
|
|
89
|
+
* did not ask for (the caller falls back to the pinned SERP URL instead).
|
|
90
|
+
*/
|
|
91
|
+
const TYPE_PROFILE = Object.freeze({
|
|
92
|
+
box: BOX_SELECTOR,
|
|
93
|
+
maxChars: 255,
|
|
94
|
+
keyDelayMs: Object.freeze([30, 70] as const),
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
const INTERACTION: EngineInteraction = Object.freeze({
|
|
98
|
+
homeUrl: "https://www.ozon.ru/",
|
|
99
|
+
homeHosts: Object.freeze(["ozon.ru"]),
|
|
100
|
+
boxSelectors: Object.freeze([BOX_SELECTOR, '[data-widget="searchBarDesktop"] input']),
|
|
101
|
+
marker: "",
|
|
102
|
+
selector: OZON_READY_SELECTOR,
|
|
103
|
+
minCount: 1,
|
|
104
|
+
typeProfile: TYPE_PROFILE,
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Wall markers (S9.3). Ozon's block page could not be captured: reaching it
|
|
109
|
+
* means provoking the firewall, which the hard rules forbid, and a fixture
|
|
110
|
+
* written from memory would be a claim, not evidence. So this list is
|
|
111
|
+
* *defensive* and text-first, corroborated exactly like the other adapters (a
|
|
112
|
+
* phrase alone is not a wall — a product title may quote it, but a wall has no
|
|
113
|
+
* cards). `docs/engines.md` says so in the same words.
|
|
114
|
+
*/
|
|
115
|
+
const CAPTCHA_URL_MARKERS: readonly string[] = Object.freeze(["/captcha", "/blocked"]);
|
|
116
|
+
const CAPTCHA_TITLE_MARKERS: readonly string[] = Object.freeze([
|
|
117
|
+
"Доступ ограничен",
|
|
118
|
+
"Access denied",
|
|
119
|
+
"Request blocked",
|
|
120
|
+
]);
|
|
121
|
+
const CAPTCHA_TEXT_MARKERS: readonly string[] = Object.freeze([
|
|
122
|
+
"Подтвердите, что вы не робот",
|
|
123
|
+
"проверка на робота",
|
|
124
|
+
"Доступ ограничен",
|
|
125
|
+
"Ограниченный доступ",
|
|
126
|
+
"Access denied",
|
|
127
|
+
"Too many requests",
|
|
128
|
+
]);
|
|
129
|
+
const TILE_COUNT_EXPRESSION = `document.querySelectorAll(${JSON.stringify(OZON_TILE_SELECTOR)}).length`;
|
|
130
|
+
// ---------------------------------------------------------------------------
|
|
131
|
+
// In-page extraction (self-contained: no imports, no closures)
|
|
132
|
+
// ---------------------------------------------------------------------------
|
|
133
|
+
|
|
134
|
+
export interface OzonExtractedItem {
|
|
135
|
+
title: string;
|
|
136
|
+
url: string;
|
|
137
|
+
snippet: string;
|
|
138
|
+
facts: string[];
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export interface OzonExtraction {
|
|
142
|
+
results: OzonExtractedItem[];
|
|
143
|
+
/** True when the page carried more cards than were returned. */
|
|
144
|
+
pageCarried: boolean;
|
|
145
|
+
/**
|
|
146
|
+
* Text of the notice headline the page rendered instead of a result list
|
|
147
|
+
* ("Ничего не нашлось" on the capture). Empty on a normal SERP.
|
|
148
|
+
*
|
|
149
|
+
* The adapter reports its *presence* as a no-match notice; it never keys on the
|
|
150
|
+
* words, because a locale or an A/B test may change them and a wrong-match is
|
|
151
|
+
* worse than a missing one.
|
|
152
|
+
*/
|
|
153
|
+
headline: string;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export interface OzonExtractionArg {
|
|
157
|
+
n: number;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* One-off in-page extractor. Everything it needs lives inside the body, because
|
|
162
|
+
* only its `toString()` crosses the CDP boundary.
|
|
163
|
+
*/
|
|
164
|
+
export function extractFromDocument(doc: Document, arg: OzonExtractionArg): OzonExtraction {
|
|
165
|
+
const WHITESPACE = /[\s\u00a0\u202f]+/g;
|
|
166
|
+
const normalize = (value: string | null | undefined): string =>
|
|
167
|
+
(value === null || value === undefined ? "" : value).replace(WHITESPACE, " ").trim();
|
|
168
|
+
|
|
169
|
+
const base = doc.baseURI !== "" ? doc.baseURI : doc.URL;
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* http(s) only. A product link is its *path*: every query parameter Ozon
|
|
173
|
+
* attaches (`at`, `avtc`, `avts`, …) is attribution or session state, and the
|
|
174
|
+
* link the user clicks is the clean one (S7.4). Other links keep their query,
|
|
175
|
+
* because there the parameters may be the destination.
|
|
176
|
+
*/
|
|
177
|
+
const toHttpUrl = (raw: string): string | null => {
|
|
178
|
+
const trimmed = raw.trim();
|
|
179
|
+
if (trimmed === "") return null;
|
|
180
|
+
let parsed: URL;
|
|
181
|
+
try {
|
|
182
|
+
parsed = new URL(trimmed, base === "" ? undefined : base);
|
|
183
|
+
} catch {
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
|
|
187
|
+
if (parsed.pathname.indexOf("/product/") === 0) parsed.search = "";
|
|
188
|
+
parsed.hash = "";
|
|
189
|
+
return parsed.href;
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
const textOf = (node: Element | null): string => (node === null ? "" : normalize(node.textContent));
|
|
193
|
+
|
|
194
|
+
const limit =
|
|
195
|
+
typeof arg.n === "number" && Number.isFinite(arg.n) ? Math.max(0, Math.floor(arg.n)) : 0;
|
|
196
|
+
|
|
197
|
+
const bodyText = normalize(doc.body === null ? "" : doc.body.textContent);
|
|
198
|
+
if (bodyText === "") return { results: [], pageCarried: false, headline: "" };
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* A zero-match search keeps its result chrome and replaces the grid with a
|
|
202
|
+
* status notice. The headline is only *reported* here; the meaning is the
|
|
203
|
+
* adapter's own constant (S7.6).
|
|
204
|
+
*/
|
|
205
|
+
const headline = textOf(doc.querySelector('[data-widget="statusWidget"] .tsHeadline800XxLarge'));
|
|
206
|
+
|
|
207
|
+
const results: OzonExtractedItem[] = [];
|
|
208
|
+
const seenUrls: { [url: string]: boolean } = {};
|
|
209
|
+
let cards = 0;
|
|
210
|
+
|
|
211
|
+
for (const card of Array.from(doc.querySelectorAll(".tile-root"))) {
|
|
212
|
+
const titleNode = card.querySelector("span.tsBody500Medium");
|
|
213
|
+
const title = textOf(titleNode);
|
|
214
|
+
if (title === "") continue;
|
|
215
|
+
const anchor = titleNode === null ? null : titleNode.closest("a[href]");
|
|
216
|
+
const href = anchor === null ? null : anchor.getAttribute("href");
|
|
217
|
+
if (href === null || href === "") continue;
|
|
218
|
+
const url = toHttpUrl(href);
|
|
219
|
+
if (url === null) continue;
|
|
220
|
+
cards += 1;
|
|
221
|
+
if (seenUrls[url] === true) continue;
|
|
222
|
+
seenUrls[url] = true;
|
|
223
|
+
if (results.length >= limit) continue;
|
|
224
|
+
|
|
225
|
+
const facts: string[] = [];
|
|
226
|
+
const price = textOf(card.querySelector("span.tsHeadline500Medium"));
|
|
227
|
+
if (price !== "") facts.push(price);
|
|
228
|
+
/**
|
|
229
|
+
* Score then review count, both `tsBodyControl300XSmall`. Which one is which
|
|
230
|
+
* is decided by *shape* (a leaf that is only a number is the score; the
|
|
231
|
+
* other node is copied whole, whatever language it is in), never by the
|
|
232
|
+
* word for "reviews" (S7.7).
|
|
233
|
+
*/
|
|
234
|
+
let rating = "";
|
|
235
|
+
let reviews = "";
|
|
236
|
+
for (const node of Array.from(card.querySelectorAll("span.tsBodyControl300XSmall"))) {
|
|
237
|
+
const text = textOf(node);
|
|
238
|
+
if (text === "") continue;
|
|
239
|
+
if (rating === "" && /^\d+(?:[.,]\d+)?$/.test(text)) {
|
|
240
|
+
rating = text;
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
if (reviews === "") reviews = text;
|
|
244
|
+
}
|
|
245
|
+
if (rating !== "") facts.push(rating);
|
|
246
|
+
if (reviews !== "") facts.push(reviews);
|
|
247
|
+
|
|
248
|
+
results.push({ title, url, snippet: "", facts });
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
return { results, pageCarried: cards > results.length, headline };
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// ---------------------------------------------------------------------------
|
|
255
|
+
// Selector canaries (self-contained, same toString() rule)
|
|
256
|
+
// ---------------------------------------------------------------------------
|
|
257
|
+
|
|
258
|
+
export function canaryCounts(doc: Document): Record<string, number> {
|
|
259
|
+
const SELECTORS = [
|
|
260
|
+
".tile-root",
|
|
261
|
+
'[data-widget="tileGridDesktop"]',
|
|
262
|
+
'[data-widget="searchResultsV2"]',
|
|
263
|
+
'[data-widget="searchResultsSort"]',
|
|
264
|
+
'[data-widget="statusWidget"]',
|
|
265
|
+
"span.tsBody500Medium",
|
|
266
|
+
"span.tsHeadline500Medium",
|
|
267
|
+
"span.tsBodyControl300XSmall",
|
|
268
|
+
];
|
|
269
|
+
const counts: Record<string, number> = {};
|
|
270
|
+
for (const selector of SELECTORS) {
|
|
271
|
+
counts[selector] = doc.querySelectorAll(selector).length;
|
|
272
|
+
}
|
|
273
|
+
return counts;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* 1 when the document carries a captcha widget, 0 otherwise. A JS scan instead
|
|
278
|
+
* of a CSS selector because the class test must be case-insensitive and
|
|
279
|
+
* `[attr*="captcha" i]` is not portable across the DOM implementations the
|
|
280
|
+
* offline harness uses.
|
|
281
|
+
*/
|
|
282
|
+
export function captchaNodeCount(doc: Document): number {
|
|
283
|
+
if (doc.querySelector('#captcha, #h-captcha, iframe[src*="captcha"], form[action*="captcha"]') !== null) {
|
|
284
|
+
return 1;
|
|
285
|
+
}
|
|
286
|
+
for (const node of Array.from(doc.querySelectorAll("[class]"))) {
|
|
287
|
+
const className = node.getAttribute("class") ?? "";
|
|
288
|
+
if (className.toLowerCase().indexOf("captcha") !== -1) return 1;
|
|
289
|
+
}
|
|
290
|
+
return 0;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// ---------------------------------------------------------------------------
|
|
294
|
+
// Result validation (TS side: the page is untrusted even when we wrote the code)
|
|
295
|
+
// ---------------------------------------------------------------------------
|
|
296
|
+
|
|
297
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
298
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function parseFailure(message: string): Error {
|
|
302
|
+
return fail("E_PARSE", "extract", {
|
|
303
|
+
engine: "ozon",
|
|
304
|
+
message,
|
|
305
|
+
hint: "the Ozon page returned an unexpected shape; run /web-doctor and inspect the artifact",
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function asExtraction(value: unknown): OzonExtraction {
|
|
310
|
+
if (!isRecord(value)) throw parseFailure("in-page extractor returned no object");
|
|
311
|
+
const rawResults = value.results;
|
|
312
|
+
if (!Array.isArray(rawResults)) throw parseFailure("in-page extractor returned no results array");
|
|
313
|
+
|
|
314
|
+
const results: OzonExtractedItem[] = [];
|
|
315
|
+
const seenUrls = new Set<string>();
|
|
316
|
+
for (const rawItem of rawResults) {
|
|
317
|
+
if (!isRecord(rawItem)) throw parseFailure("in-page extractor returned a malformed result");
|
|
318
|
+
const { title, url, snippet } = rawItem;
|
|
319
|
+
if (typeof title !== "string" || typeof url !== "string" || typeof snippet !== "string") {
|
|
320
|
+
throw parseFailure("in-page extractor returned a result with non-string fields");
|
|
321
|
+
}
|
|
322
|
+
if (title === "") continue;
|
|
323
|
+
// Second, TS-side hygiene pass: the in-page copy cannot import `urls.ts`.
|
|
324
|
+
const normalized = normalizeUrl(url);
|
|
325
|
+
if (normalized === null || seenUrls.has(normalized)) continue;
|
|
326
|
+
seenUrls.add(normalized);
|
|
327
|
+
results.push({
|
|
328
|
+
title,
|
|
329
|
+
url: normalized,
|
|
330
|
+
snippet,
|
|
331
|
+
facts: asFacts(rawItem.facts),
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
return {
|
|
336
|
+
results,
|
|
337
|
+
pageCarried: value.pageCarried === true,
|
|
338
|
+
headline: typeof value.headline === "string" ? value.headline : "",
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function asCanaries(value: unknown): Record<string, number> {
|
|
343
|
+
const counts: Record<string, number> = {};
|
|
344
|
+
if (!isRecord(value)) return counts;
|
|
345
|
+
for (const [selector, count] of Object.entries(value)) {
|
|
346
|
+
if (typeof count === "number" && Number.isFinite(count)) counts[selector] = count;
|
|
347
|
+
}
|
|
348
|
+
return counts;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// ---------------------------------------------------------------------------
|
|
352
|
+
// Settle / wall
|
|
353
|
+
// ---------------------------------------------------------------------------
|
|
354
|
+
|
|
355
|
+
export interface OzonSettleOptions {
|
|
356
|
+
signal?: AbortSignal;
|
|
357
|
+
/** Test/live knob; defaults to 12 s. */
|
|
358
|
+
deadlineMs?: number;
|
|
359
|
+
/** Test/live knob; defaults to 200 ms plus humanize jitter. */
|
|
360
|
+
pollMs?: number;
|
|
361
|
+
clock?: Clock;
|
|
362
|
+
rng?: () => number;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** Bounded settle on the structural gate; abort/timeout use the shared taxonomy. */
|
|
366
|
+
export async function settleOzon(page: CdpPage, options: OzonSettleOptions = {}): Promise<void> {
|
|
367
|
+
await waitForMarker(page, {
|
|
368
|
+
marker: INTERACTION.marker,
|
|
369
|
+
selector: INTERACTION.selector,
|
|
370
|
+
minCount: INTERACTION.minCount ?? 1,
|
|
371
|
+
deadlineMs: options.deadlineMs ?? OZON_SETTLE_DEADLINE_MS,
|
|
372
|
+
pollMs: options.pollMs ?? SETTLE_POLL_MS,
|
|
373
|
+
...(options.clock === undefined ? {} : { clock: options.clock }),
|
|
374
|
+
...(options.rng === undefined ? {} : { rng: options.rng }),
|
|
375
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
async function tileCount(page: CdpPage): Promise<number> {
|
|
380
|
+
const count = await page.evaluate<unknown>(TILE_COUNT_EXPRESSION);
|
|
381
|
+
return typeof count === "number" && Number.isFinite(count) ? count : 0;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
async function captchaNodes(page: CdpPage): Promise<number> {
|
|
385
|
+
const count = await page.evaluate<unknown>(`(${captchaNodeCount.toString()})(document)`);
|
|
386
|
+
return typeof count === "number" && Number.isFinite(count) ? count : 0;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Markers present in a lowercased haystack, in list order. */
|
|
390
|
+
function markersIn(haystack: string, markers: readonly string[]): string[] {
|
|
391
|
+
const found: string[] = [];
|
|
392
|
+
for (const marker of markers) {
|
|
393
|
+
if (haystack.indexOf(marker.toLowerCase()) !== -1) found.push(marker);
|
|
394
|
+
}
|
|
395
|
+
return found;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Wall detection. Nobody clicks anything here: the tool surfaces the window, the
|
|
400
|
+
* human solves it and retries (D5). The markers are defensive (see the top of
|
|
401
|
+
* this file): the one thing we can honestly say is that a wall has no product
|
|
402
|
+
* cards, so a phrase needs zero cards as corroboration.
|
|
403
|
+
*/
|
|
404
|
+
export async function detectOzonWall(page: CdpPage): Promise<Wall | null> {
|
|
405
|
+
const url = page.url();
|
|
406
|
+
const urlMarkers = markersIn(url.toLowerCase(), CAPTCHA_URL_MARKERS);
|
|
407
|
+
if (urlMarkers.length > 0) return { kind: "captcha", url, markers: urlMarkers };
|
|
408
|
+
|
|
409
|
+
const title = await page.title().catch((): string => "");
|
|
410
|
+
const text = await page.innerText();
|
|
411
|
+
const markers = [
|
|
412
|
+
...markersIn(title.toLowerCase(), CAPTCHA_TITLE_MARKERS),
|
|
413
|
+
...markersIn(text.toLowerCase(), CAPTCHA_TEXT_MARKERS),
|
|
414
|
+
];
|
|
415
|
+
|
|
416
|
+
// A captcha widget is evidence on its own: its label lives in an iframe the
|
|
417
|
+
// page-text scan cannot see.
|
|
418
|
+
if ((await captchaNodes(page)) > 0) {
|
|
419
|
+
return { kind: "captcha", url, markers: markers.length > 0 ? markers : ["captcha-node"] };
|
|
420
|
+
}
|
|
421
|
+
// A phrase can be quoted by a product title; a wall has no cards.
|
|
422
|
+
if (markers.length > 0 && (await tileCount(page)) === 0) {
|
|
423
|
+
return { kind: "blocked", url, markers };
|
|
424
|
+
}
|
|
425
|
+
return null;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// ---------------------------------------------------------------------------
|
|
429
|
+
// URL builder + engine
|
|
430
|
+
// ---------------------------------------------------------------------------
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Pure: `https://www.ozon.ru/search/?text=<query>[&page=<page>]`.
|
|
434
|
+
*
|
|
435
|
+
* Verified live (2026-11-16): Ozon answers `?text=` either with the search grid
|
|
436
|
+
* or with a `307`-style redirect to a predicted catalog
|
|
437
|
+
* (`/category/<slug>/?…&text=<query>`), and both carry the same cards. `page` is
|
|
438
|
+
* 1-based and survives the redirect. Page 1 is the bare URL, because `page=1` is
|
|
439
|
+
* a parameter the SERP does not need.
|
|
440
|
+
*/
|
|
441
|
+
function buildUrl(q: Query): string {
|
|
442
|
+
const parts = [`text=${encodeURIComponent(q.text)}`];
|
|
443
|
+
const page = typeof q.page === "number" && Number.isFinite(q.page) ? Math.floor(q.page) : 1;
|
|
444
|
+
if (page > 1) parts.push(`page=${page}`);
|
|
445
|
+
return `https://www.ozon.ru/search/?${parts.join("&")}`;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
export const ozonEngine: Engine = {
|
|
449
|
+
id: "ozon",
|
|
450
|
+
interaction: INTERACTION,
|
|
451
|
+
buildUrl,
|
|
452
|
+
|
|
453
|
+
async settle(page: CdpPage, signal?: AbortSignal): Promise<void> {
|
|
454
|
+
await settleOzon(page, signal === undefined ? {} : { signal });
|
|
455
|
+
},
|
|
456
|
+
|
|
457
|
+
detectWall: detectOzonWall,
|
|
458
|
+
|
|
459
|
+
async extract(page: CdpPage, q: Query): Promise<RawSerp> {
|
|
460
|
+
const startedAt = Date.now();
|
|
461
|
+
const arg: OzonExtractionArg = { n: q.n };
|
|
462
|
+
const raw = await page.evaluate<unknown>(
|
|
463
|
+
`(${extractFromDocument.toString()})(document, ${JSON.stringify(arg)})`,
|
|
464
|
+
);
|
|
465
|
+
const parsed = asExtraction(raw);
|
|
466
|
+
const results: SerpItem[] = parsed.results.map((item) => ({
|
|
467
|
+
title: item.title,
|
|
468
|
+
url: item.url,
|
|
469
|
+
snippet: item.snippet,
|
|
470
|
+
...(item.facts.length === 0 ? {} : { facts: item.facts }),
|
|
471
|
+
}));
|
|
472
|
+
const timings = { extractMs: Math.max(0, Date.now() - startedAt) };
|
|
473
|
+
return {
|
|
474
|
+
engine: "ozon",
|
|
475
|
+
query: q.text,
|
|
476
|
+
results,
|
|
477
|
+
pageCarried: parsed.pageCarried,
|
|
478
|
+
...(parsed.headline === "" ? {} : { notice: NO_MATCH_NOTICE }),
|
|
479
|
+
timings,
|
|
480
|
+
};
|
|
481
|
+
},
|
|
482
|
+
|
|
483
|
+
async canaries(page: CdpPage): Promise<Record<string, number>> {
|
|
484
|
+
const raw = await page.evaluate<unknown>(`(${canaryCounts.toString()})(document)`);
|
|
485
|
+
return asCanaries(raw);
|
|
486
|
+
},
|
|
487
|
+
};
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* Adapter-authored (never page text): the caller must not read a page of
|
|
491
|
+
* recommendations as an answer to its query (S7.6).
|
|
492
|
+
*/
|
|
493
|
+
export const NO_MATCH_NOTICE = "no exact match: Ozon answered with recommendations";
|
package/src/engines/types.ts
CHANGED
|
@@ -9,10 +9,41 @@
|
|
|
9
9
|
|
|
10
10
|
import type { CdpPage } from "../cdp/types.ts";
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
/**
|
|
13
|
+
* Primary engines answer a general web query. Canonical order; `auto` keeps this
|
|
14
|
+
* order and yandex stays last by policy (SPEC §15 D10).
|
|
15
|
+
*/
|
|
16
|
+
export const PRIMARY_ENGINES = ["google", "duckduckgo", "yandex"] as const;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Special engines answer one site, not the web (SPEC §15 D11). They are never
|
|
20
|
+
* part of `auto`: a marketplace listing is not an answer to "search the web",
|
|
21
|
+
* so a caller must name the engine (`engines: "avito"`, `engines: "ozon"`).
|
|
22
|
+
*/
|
|
23
|
+
export const SPECIAL_ENGINES = ["avito", "ozon"] as const;
|
|
13
24
|
|
|
14
|
-
|
|
15
|
-
export
|
|
25
|
+
export type PrimaryEngineId = (typeof PRIMARY_ENGINES)[number];
|
|
26
|
+
export type SpecialEngineId = (typeof SPECIAL_ENGINES)[number];
|
|
27
|
+
export type EngineId = PrimaryEngineId | SpecialEngineId;
|
|
28
|
+
|
|
29
|
+
/** Every id the contract knows, primary first. `auto` walks the primary part only. */
|
|
30
|
+
export const ENGINE_IDS = [...PRIMARY_ENGINES, ...SPECIAL_ENGINES] as const satisfies readonly EngineId[];
|
|
31
|
+
|
|
32
|
+
export type EngineClass = "primary" | "special";
|
|
33
|
+
|
|
34
|
+
/** Primary/special is data, so `auto` and the tool's docs cannot drift apart. */
|
|
35
|
+
export const ENGINE_CLASS: Readonly<Record<EngineId, EngineClass>> = Object.freeze({
|
|
36
|
+
google: "primary",
|
|
37
|
+
duckduckgo: "primary",
|
|
38
|
+
yandex: "primary",
|
|
39
|
+
avito: "special",
|
|
40
|
+
ozon: "special",
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
/** True when `auto` may pick this engine (SPEC S4.7). */
|
|
44
|
+
export function isPrimaryEngine(id: EngineId): boolean {
|
|
45
|
+
return ENGINE_CLASS[id] === "primary";
|
|
46
|
+
}
|
|
16
47
|
|
|
17
48
|
export interface Query {
|
|
18
49
|
text: string;
|
|
@@ -42,6 +73,17 @@ export interface SerpItem {
|
|
|
42
73
|
* resolved link (S3.5, S7.4).
|
|
43
74
|
*/
|
|
44
75
|
unresolved?: boolean;
|
|
76
|
+
/**
|
|
77
|
+
* Short facts the card shows around the snippet, in display order: price,
|
|
78
|
+
* availability, rating, location, listing date (SPEC §15 D13).
|
|
79
|
+
*
|
|
80
|
+
* Additive and optional on purpose: a SERP that does not surface them leaves
|
|
81
|
+
* this absent, and an adapter never invents one. Google already prints
|
|
82
|
+
* `103 500,00 ₽ · В наличии · 5,0 ★` under some results; Avito prints price,
|
|
83
|
+
* location and date on every card. The renderer joins them after the snippet
|
|
84
|
+
* and caps the line (`COMPACT_CAPS.factsMaxChars`).
|
|
85
|
+
*/
|
|
86
|
+
facts?: readonly string[];
|
|
45
87
|
}
|
|
46
88
|
|
|
47
89
|
/**
|
|
@@ -121,6 +163,15 @@ export interface RawSerp {
|
|
|
121
163
|
pageCarried: boolean;
|
|
122
164
|
/** True only for the keyless HTTP fallback (SPEC §6.5); never for a real SERP. */
|
|
123
165
|
degraded?: boolean;
|
|
166
|
+
/**
|
|
167
|
+
* One adapter-authored line about the page the caller must not have to guess
|
|
168
|
+
* (S7.6/S7.7): Avito answers a no-match query with "similar listings", and
|
|
169
|
+
* saying so is the difference between a labelled fallback and a silent lie.
|
|
170
|
+
*
|
|
171
|
+
* A fixed adapter constant, never page text — a SERP cannot inject prose into
|
|
172
|
+
* the output through it.
|
|
173
|
+
*/
|
|
174
|
+
notice?: string;
|
|
124
175
|
timings: SerpTimings;
|
|
125
176
|
}
|
|
126
177
|
|
|
@@ -171,6 +222,12 @@ export interface EngineInteraction {
|
|
|
171
222
|
minCount?: number;
|
|
172
223
|
/** Optional typing profile; without it `humanize: "typing"` uses the generic delays. */
|
|
173
224
|
typeProfile?: EngineTypeProfile;
|
|
225
|
+
/**
|
|
226
|
+
* Per-query home page, when the engine's home is parameterized (SPEC D12:
|
|
227
|
+
* Avito's typed search starts on `https://www.avito.ru/<location>/`, so the
|
|
228
|
+
* configured region must reach the warm-up page too). Absent means `homeUrl`.
|
|
229
|
+
*/
|
|
230
|
+
homeUrlFor?(q: Query): string;
|
|
174
231
|
/**
|
|
175
232
|
* Where the typed path starts (P10-C). `home` (default) opens the engine home
|
|
176
233
|
* page and types into its box. `serp` navigates the SERP URL first and types
|
|
@@ -216,18 +273,21 @@ export type ArgumentSupport = "yes" | "flag";
|
|
|
216
273
|
export const SUPPORT_MATRIX: Readonly<
|
|
217
274
|
Record<SupportArgument, Readonly<Record<EngineId, ArgumentSupport>>>
|
|
218
275
|
> = Object.freeze({
|
|
219
|
-
n: Object.freeze({ google: "yes", duckduckgo: "yes", yandex: "yes" }),
|
|
276
|
+
n: Object.freeze({ google: "yes", duckduckgo: "yes", yandex: "yes", avito: "yes", ozon: "yes" }),
|
|
220
277
|
// DuckDuckGo has no pagination in this adapter: page > 1 is served as page 1
|
|
221
278
|
// and must be reported as `ignored.page`, never silently dropped (S4.2, S7.1).
|
|
222
|
-
|
|
223
|
-
|
|
279
|
+
// Avito paginates with `&p=` and Ozon with `&page=` (both verified live).
|
|
280
|
+
page: Object.freeze({ google: "yes", duckduckgo: "flag", yandex: "yes", avito: "yes", ozon: "yes" }),
|
|
281
|
+
// Neither marketplace has a native AI block (SPEC D12/D14): asking is reported
|
|
282
|
+
// as `ignored.summary`, never answered with an invented summary.
|
|
283
|
+
summary: Object.freeze({ google: "yes", duckduckgo: "yes", yandex: "yes", avito: "flag", ozon: "flag" }),
|
|
224
284
|
});
|
|
225
285
|
|
|
226
286
|
export interface EngineRegistry {
|
|
227
287
|
/** Throws E_UNSUPPORTED when the adapter is missing or disabled. */
|
|
228
288
|
get(id: EngineId): Engine;
|
|
229
289
|
has(id: EngineId): boolean;
|
|
230
|
-
/** Enabled engines in canonical order;
|
|
290
|
+
/** Enabled engines in canonical order; the primaries first, special engines last. */
|
|
231
291
|
enabled(): EngineId[];
|
|
232
292
|
/**
|
|
233
293
|
* Resolve a user selection to a try-order (D9/D10): `auto` uses the canonical order
|