falseok 0.0.0-stage → 0.5.1

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/index.d.ts ADDED
@@ -0,0 +1,171 @@
1
+ // Types for falseok: is this "200 OK" page real content, or a block page in disguise?
2
+
3
+ /** Why a page is not usable, in priority order (the first one found wins). */
4
+ export type Category =
5
+ | "challenge" | "captcha" | "rate_limited" | "login_wall" | "consent_wall" | "soft_block" | "soft_404" | "empty_shell";
6
+
7
+ /** Every verdict checkPage can return (the values of VERDICTS). */
8
+ export type Verdict = "ok" | "not_html" | Category | "http_error";
9
+
10
+ /** What to do with the page. */
11
+ export type Action = "keep" | "render_js" | "backoff" | "retry" | "stop" | "drop" | "decompress";
12
+
13
+ export type Confidence = "high" | "medium" | "low";
14
+
15
+ /** What the response held. */
16
+ export type ContentKind = "html" | "empty" | "data" | "document" | "binary" | "compressed";
17
+
18
+ /** One piece of evidence behind a verdict. */
19
+ export interface Signal {
20
+ id: string;
21
+ category: Category;
22
+ /** Where it matched and what, e.g. `title: "Just a moment..."`. */
23
+ detail: string;
24
+ /** The anti-bot vendor this signal belongs to, when known. */
25
+ vendor: string | null;
26
+ }
27
+
28
+ /** The verdict on one page; the same keys and values as the Python package's PageResult.to_dict(). */
29
+ export interface PageResult {
30
+ verdict: Verdict;
31
+ reason: string;
32
+ vendor: string | null;
33
+ title: string;
34
+ text_length: number;
35
+ signals: Signal[];
36
+ action: Action;
37
+ confidence: Confidence;
38
+ /** Seconds to wait, from the Retry-After response header; null when absent or unreadable. */
39
+ retry_after: number | null;
40
+ content_kind: ContentKind;
41
+ canonical_url: string | null;
42
+ meta_refresh: string | null;
43
+ script_count: number;
44
+ }
45
+
46
+ /** One rule of signatures.json. */
47
+ export interface SignatureRule {
48
+ id?: string;
49
+ category: Category;
50
+ pattern: string;
51
+ regex?: boolean;
52
+ in?: "title" | "text" | "html" | "header" | "heading";
53
+ /** The header name, for rules with `in: "header"`. */
54
+ header?: string;
55
+ vendor?: string;
56
+ max_text?: number;
57
+ [key: string]: unknown;
58
+ }
59
+
60
+ /** A rule list as loadSignatures returns it (compiled; pass it back as `signatures`). */
61
+ export type Signatures = readonly SignatureRule[];
62
+
63
+ export type HeaderValue = string | Uint8Array;
64
+
65
+ /** Response headers: raw "Name: value" lines (what `curl -D` saves), an object, a Map or name/value pairs.
66
+ * For a fetch Headers, pass Object.fromEntries(headers). */
67
+ export type HeadersInput =
68
+ | string
69
+ | Uint8Array
70
+ | Record<string, HeaderValue>
71
+ | Map<string | Uint8Array, HeaderValue>
72
+ | ReadonlyArray<readonly [string | Uint8Array, HeaderValue]>;
73
+
74
+ export interface CheckOptions {
75
+ /** The HTTP status you got (100-599; anything else is ignored). */
76
+ status?: number | string | null;
77
+ headers?: HeadersInput | null;
78
+ /** The address you asked for. */
79
+ url?: string | null;
80
+ /** The address you ended up at after redirects; may be relative to `url`. */
81
+ finalUrl?: string | null;
82
+ /** Below this many characters of visible text a page is an empty shell (default 150). A number; other values are coerced as before (numeric strings, null), and TypeError only for what cannot be compared with a number (a Symbol). */
83
+ minText?: number;
84
+ /** Your own rules instead of the bundled ones. An array (or any iterable of compiled rules); TypeError if it is not iterable. */
85
+ signatures?: Signatures | null;
86
+ /** Ignore these signal ids: one id as a string, or any iterable of ids: array, Set, Map keys, generator (TypeError if not iterable). */
87
+ disableIds?: string | Iterable<string> | null;
88
+ /** Accept these categories, e.g. "login_wall" when you scrape behind a login: one name, or any iterable of names (TypeError if not iterable). Throws on an unknown name. */
89
+ allowCategories?: Category | Iterable<Category> | null;
90
+ /** The current time in epoch milliseconds, for Retry-After dates (default Date.now()). */
91
+ now?: number;
92
+ }
93
+
94
+ export type PageInput = string | Uint8Array;
95
+
96
+ /** The verdict on one page: a string, or the raw bytes (the charset is read from the headers and the page). */
97
+ export function checkPage(html: PageInput, options?: CheckOptions): PageResult;
98
+
99
+ /** checkPage over a list; an item is the page itself or `{ html, ...options }` overriding the shared options. */
100
+ export function checkPages(
101
+ pages: Iterable<PageInput | ({ html: PageInput } & CheckOptions)>,
102
+ options?: CheckOptions,
103
+ ): PageResult[];
104
+
105
+ /** The bundled rules, or your own, with extra rules added (same id replaces) and ids left out. */
106
+ export function loadSignatures(options?: {
107
+ signatures?: readonly SignatureRule[] | { signatures: readonly SignatureRule[] } | null;
108
+ extraSignatures?: readonly SignatureRule[] | { signatures: readonly SignatureRule[] } | null;
109
+ disableIds?: string | Iterable<string> | null;
110
+ }): Signatures;
111
+
112
+ export interface CheckApiOptions {
113
+ /** The HTTP status you got; an error status is read together with the body's own words. */
114
+ status?: number | string | null;
115
+ headers?: HeadersInput | null;
116
+ url?: string | null;
117
+ finalUrl?: string | null;
118
+ /** An empty answer ([], {}, {"data": []} ...) becomes empty_shell (action "retry") instead of a low-confidence "ok". */
119
+ emptyIsError?: boolean;
120
+ /** The current time in epoch milliseconds, for Retry-After dates (default Date.now()). */
121
+ now?: number;
122
+ }
123
+
124
+ /** The verdict on one answer from a JSON endpoint: the body as text or bytes, or JSON you already parsed. */
125
+ export function checkApi(body: PageInput | object | unknown[] | null, options?: CheckApiOptions): PageResult;
126
+
127
+ /** One remembered page: path key, home page or not, text length, 64-bit simhash, title hash. */
128
+ export interface MemoryRecord {
129
+ k: string;
130
+ r: boolean;
131
+ n: number;
132
+ h: bigint;
133
+ t: number;
134
+ }
135
+
136
+ /** The memory as plain data (Python's to_dict()); `h` is a BigInt. */
137
+ export interface MemoryData {
138
+ version: number;
139
+ per_host: number;
140
+ hosts: Record<string, MemoryRecord[]>;
141
+ }
142
+
143
+ /** Pages already judged "ok", per site: a deep address that shows the site's home page, or a page already seen at
144
+ * two other paths, becomes "soft_404". The saved file is the same as the Python package's. */
145
+ export class SiteMemory {
146
+ /** perHost: how many page records to keep for each site, the oldest dropped first (default 200). */
147
+ constructor(perHost?: number);
148
+ readonly perHost: number;
149
+ /** How many records are kept, all sites together. */
150
+ readonly size: number;
151
+ /** checkPage with the site's memory; `learn: false` checks without remembering. */
152
+ checkPage(html: PageInput, options?: CheckOptions & { learn?: boolean }): PageResult;
153
+ toDict(): MemoryData;
154
+ /** The JSON text the Python package's save() writes. */
155
+ dumps(): string;
156
+ save(path: string): void;
157
+ static fromDict(data: MemoryData | Map<string, unknown>): SiteMemory;
158
+ static loads(text: string): SiteMemory;
159
+ static load(path: string): SiteMemory;
160
+ }
161
+
162
+ /** Check many pages so their order does not matter: every "ok" page is remembered first, then each deep page is
163
+ * judged against all the others. */
164
+ export function checkPagesWithMemory(
165
+ items: Iterable<PageInput | ({ html: PageInput } & CheckOptions)>,
166
+ options?: CheckOptions & { memory?: SiteMemory },
167
+ ): PageResult[];
168
+
169
+ export const VERDICTS: readonly Verdict[];
170
+ export const version: string;
171
+ // No `export default` here: the package is CommonJS, so `import falseok from "falseok"` already gives this module.
package/index.js ADDED
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ // falseok: is this "200 OK" page real content, or a block page in disguise? Zero dependencies.
3
+ const { checkPage, loadSignatures, VERDICTS } = require("./lib/page");
4
+ const { SiteMemory, checkPagesWithMemory } = require("./lib/memory");
5
+ const { checkApi } = require("./lib/api");
6
+
7
+ const version = "0.5.1";
8
+
9
+ /** checkPage over a list of pages: each item is { html, ...options } or a bare html string/Buffer. */
10
+ function checkPages(pages, options = {}) {
11
+ return Array.from(pages, (p) => {
12
+ if (typeof p === "string" || p instanceof Uint8Array) return checkPage(p, options);
13
+ const { html, ...own } = p;
14
+ return checkPage(html, { ...options, ...own });
15
+ });
16
+ }
17
+
18
+ module.exports = { checkPage, checkPages, checkApi, SiteMemory, checkPagesWithMemory, loadSignatures, VERDICTS, version };
package/index.mjs ADDED
@@ -0,0 +1,5 @@
1
+ // ESM entry: the same functions as index.js.
2
+ import falseok from "./index.js";
3
+
4
+ export const { checkPage, checkPages, checkApi, SiteMemory, checkPagesWithMemory, loadSignatures, VERDICTS, version } = falseok;
5
+ export default falseok;
package/lib/api.js ADDED
@@ -0,0 +1,371 @@
1
+ "use strict";
2
+ // API check: is this "200 OK" JSON answer the data, or an error, a block page or nothing at all? Same verdicts as
3
+ // checkPage; reads only the top-level object and one level down in an envelope key, never data rows.
4
+ const { checkPage, pyStr, search, signal, asBytes, statusOf, headersOf, looksBinary, retryAfter, startsWithBytes,
5
+ LOGIN_TITLE, PACKED_HEADER, PACKED_START } = require("./page");
6
+ const { decode } = require("./decode");
7
+ const { rx } = require("./pyre");
8
+ const { cpLen, cpSlice, strip } = require("./text");
9
+ const { loads: pyLoads, dumps, floatRepr, JSONDecodeError } = require("./pyjson");
10
+ const { pyLower } = require("./memory");
11
+
12
+ /** JSON loads, with JSON nested too deep reported as unparseable JSON (as Python's check does), never thrown as a RangeError. */
13
+ function loads(text) {
14
+ try {
15
+ return pyLoads(text);
16
+ } catch (e) {
17
+ if (e instanceof RangeError) throw new JSONDecodeError("nested too deep", text, 0);
18
+ throw e;
19
+ }
20
+ }
21
+
22
+ const ENVELOPE = ["response", "result", "meta", "status", "header", "body"];
23
+ const TEXT_KEYS = ["message", "msg", "error_description", "error_message", "errorMessage", "detail", "title", "reason",
24
+ "description", "errmsg", "error"];
25
+ const WORD_KEYS = [...TEXT_KEYS, "type", "code", "error_code", "errorCode", "status"];
26
+ const ERROR_FIELDS = ["error", "errors", "error_code", "errorCode", "error_message", "errorMessage", "message", "msg",
27
+ "detail", "reason"];
28
+ const CODE_KEYS = ["status", "code", "statusCode", "status_code", "httpStatus", "http_status", "errorCode", "error_code"];
29
+ const RETRY_KEYS = ["retry_after", "retryAfter", "retry-after", "retry_after_seconds", "retryAfterSeconds"];
30
+ const COUNT_KEYS = new Set(["total", "count", "total_count", "totalCount", "totalResults", "total_results", "totalItems",
31
+ "total_items", "size", "length", "num_results", "numResults", "found", "nbHits", "hits_total"]);
32
+ const PAGING_KEYS = new Set(["page", "pages", "per_page", "perPage", "page_size", "pageSize", "limit", "offset", "start",
33
+ "next", "previous", "prev", "cursor", "next_cursor", "nextCursor", "has_more", "hasMore", "has_next", "hasNext",
34
+ "total_pages", "totalPages", "took", "timed_out", "query", "q", "success", "ok", "status", "message", "error", "errors",
35
+ "code", "version", "api_version", "kind", "type", "object", "url", "self"]);
36
+ const META_KEYS = new Set(["meta", "links", "_links", "pagination", "paging", "_meta", "page_info", "pageInfo", "headers", "params"]);
37
+ const COLLECTION_KEYS = new Set(["data", "results", "result", "items", "records", "rows", "hits", "entries", "list", "objects",
38
+ "nodes", "edges", "value", "values", "content", "products", "docs", "documents", "elements", "response", "payload"]);
39
+
40
+ const HIJACK = rx(String.raw`\A(?:\)\]\}'?,?|while\s*\(\s*1\s*\)\s*;|for\s*\(\s*;\s*;\s*\)\s*;)\s*`, "", "");
41
+ const JSONP = rx(String.raw`\A(?:/\*\*/\s*)?[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*\s*\((.*)\)\s*;?\s*\Z`, "s", "");
42
+ const HTML = rx(String.raw`<(?:!doctype\s+html|html|head|body|title|meta|div|script|h1|p|center|pre|style|iframe|noscript)`
43
+ + String.raw`(?=[\s/>])`, "i", "");
44
+ const CAPTCHA = rx("captcha|turnstile", "i", "");
45
+ const CHALLENGE = rx(String.raw`\bchallenge\b|\bbot (?:detection|protection)\b|verify (?:that )?you are (?:a )?human|`
46
+ + "are you a robot", "i", "");
47
+ const RATE = rx(String.raw`\brate[ _-]?limit|\bquota\b|throttl|too many requests|limit exceeded|\brequests? limit`, "i", "");
48
+ const AUTH = rx(String.raw`unauthori[sz]ed|unauthenticated|not authenticated|\bauth(?:entication)? required|\blog ?in\b|`
49
+ + String.raw`\bsign ?in\b|\btoken\b|not authed|invalid auth|api[ _-]?key|credential|session (?:expired|invalid)`, "i", "");
50
+ const DENIED = rx(String.raw`forbidden|access denied|permission|not allowed|\bblocked\b|\bbanned\b|\bdenied\b`, "i", "");
51
+ const NOT_FOUND = rx(String.raw`not[ _-]?found|no such|does not exist|doesn't exist|unknown (?:endpoint|resource|route)`, "i", "");
52
+ const RETRY_TEXT = /^[0-9]+(?:\.[0-9]+)?$/; // Python's re.fullmatch(r"\d+(?:\.\d+)?", ..., re.ASCII)
53
+ const BAD_STATUS = new Set(["error", "fail", "failed", "failure"]);
54
+
55
+ // Python values here: null, booleans, BigInt (int), Number (float), strings, arrays (list) and Map (dict).
56
+ const isDict = (v) => v instanceof Map;
57
+ const isNum = (v) => typeof v === "bigint" || typeof v === "number";
58
+ const get = (d, k) => (d.has(k) ? d.get(k) : null);
59
+ /** Python `v in (None, [], {}, "")`. */
60
+ const blank = (v) => v === null || v === "" || (Array.isArray(v) && !v.length) || (isDict(v) && !v.size);
61
+ /** Python `v not in (None, "", [], {}, False, 0)`. */
62
+ const filled = (v) => !(blank(v) || v === false || v === 0n || v === 0);
63
+
64
+ /** A JS value given by the caller in Python's shapes: integral numbers become int, objects dicts. */
65
+ function toPy(v) {
66
+ if (typeof v === "number") return Number.isInteger(v) ? BigInt(v) : v;
67
+ if (Array.isArray(v)) return v.map(toPy);
68
+ if (v instanceof Map) return new Map(Array.from(v, ([k, x]) => [k, toPy(x)]));
69
+ if (v && typeof v === "object") return new Map(Object.entries(v).map(([k, x]) => [k, toPy(x)]));
70
+ return v === undefined ? null : v;
71
+ }
72
+
73
+ /** Python str() of a JSON value inside a message. */
74
+ function show(v) {
75
+ return typeof v === "number" ? floatRepr(v) : pyStr(v);
76
+ }
77
+
78
+ /** A whole number from a number or a string of three ASCII digits 0-9; null otherwise, booleans too. */
79
+ function toInt(v) {
80
+ if (typeof v === "boolean") return null;
81
+ if (typeof v === "bigint") return v;
82
+ if (typeof v === "number" && Number.isInteger(v)) return BigInt(v);
83
+ if (typeof v === "string") {
84
+ const s = strip(v);
85
+ if (/^[0-9]{3}$/.test(s)) return BigInt(s);
86
+ }
87
+ return null;
88
+ }
89
+
90
+ /** An HTTP-like error code (400-599) from the usual keys of this object; a string counts only as `status`. */
91
+ function codeOf(d) {
92
+ if (!isDict(d)) return null;
93
+ for (const key of CODE_KEYS) {
94
+ const v = get(d, key);
95
+ if (typeof v === "string" && key !== "status") continue;
96
+ const n = toInt(v);
97
+ if (n !== null && n >= 400n && n <= 599n) return n;
98
+ }
99
+ return null;
100
+ }
101
+
102
+ /** The error's own words in this object, joined (at most a few hundred characters). */
103
+ function wordsOf(d) {
104
+ const parts = [];
105
+ for (const key of WORD_KEYS) {
106
+ const v = get(d, key);
107
+ if (typeof v === "string" && strip(v)) parts.push(cpSlice(strip(v), 200));
108
+ else if (isDict(v)) {
109
+ for (const x of [get(v, "message"), get(v, "type"), get(v, "code"), get(v, "reason")]) {
110
+ if (typeof x === "string" && strip(x)) parts.push(cpSlice(strip(x), 200));
111
+ }
112
+ }
113
+ }
114
+ return cpSlice(parts.join(" | "), 600);
115
+ }
116
+
117
+ /** High for success: false (or ok: false) together with an error field; else `otherwise`. */
118
+ function pair(d, otherwise) {
119
+ if (get(d, "success") === false || get(d, "ok") === false) {
120
+ if (ERROR_FIELDS.some((k) => filled(get(d, k)))) return "high";
121
+ }
122
+ return otherwise;
123
+ }
124
+
125
+ /**
126
+ * Seconds to wait from a retry-after field of the body, if one says so (ASCII digits only in a string); a value that is
127
+ * not finite as a float (1e999, an int past 1e308) counts as absent, like Python.
128
+ */
129
+ function retryField(...objs) {
130
+ for (const o of objs) {
131
+ if (!isDict(o)) continue;
132
+ for (const key of RETRY_KEYS) {
133
+ const v = get(o, key);
134
+ let n = null;
135
+ if (isNum(v) && v >= 0) n = Number(v);
136
+ else if (typeof v === "string" && RETRY_TEXT.test(strip(v))) n = Number(strip(v));
137
+ if (n !== null && Number.isFinite(n)) return n;
138
+ }
139
+ }
140
+ return null;
141
+ }
142
+
143
+ /** One result with every field checkApi sets (the page-only fields stay empty). */
144
+ function result(verdict, reason, signals, sent, kind, action, confidence, now, length = 0, retry = null) {
145
+ return { verdict, reason, vendor: null, title: "", text_length: length, signals, action, confidence,
146
+ retry_after: retry !== null ? retry : retryAfter(sent, now), content_kind: kind, canonical_url: null,
147
+ meta_refresh: null, script_count: 0 };
148
+ }
149
+
150
+ /** Map an error (its code and its words) to the closest page verdict, with its action. */
151
+ function error(code, words, found, sent, kind, confidence, where, now, length = 0, data = null) {
152
+ if (!found.length) found = [["api-http-status", code !== null ? `status ${code}` : "error status"]];
153
+ if (words) words = words.replace(/_/g, " ");
154
+ const n = code === null ? null : Number(code);
155
+ let verdict;
156
+ let action;
157
+ if (search(CAPTCHA, words)) [verdict, action] = ["captcha", "stop"];
158
+ else if (search(CHALLENGE, words)) [verdict, action] = ["challenge", "stop"];
159
+ else if (n === 429 || search(RATE, words)) [verdict, action] = ["rate_limited", "backoff"];
160
+ else if (n === 401 || n === 407) [verdict, action] = ["login_wall", "stop"];
161
+ else if (n === 403) [verdict, action] = [search(AUTH, words) && !search(DENIED, words) ? "login_wall" : "soft_block", "stop"];
162
+ else if (n === 404 || n === 410) [verdict, action] = ["soft_404", "drop"];
163
+ else if (n === null && (search(AUTH, words) || search(LOGIN_TITLE, words))) [verdict, action] = ["login_wall", "stop"];
164
+ else if (n === null && search(DENIED, words)) [verdict, action] = ["soft_block", "stop"];
165
+ else if (n === null && search(NOT_FOUND, words)) [verdict, action] = ["soft_404", "drop"];
166
+ else {
167
+ verdict = "http_error";
168
+ action = n === null || n >= 500 || n === 408 || n === 425 ? "retry" : "drop";
169
+ }
170
+ let retry = retryField(where, isDict(where) ? get(where, "error") : null, data);
171
+ if (retry === null) retry = retryAfter(sent, now);
172
+ if (verdict === "http_error" && action === "retry" && retry !== null) action = "backoff";
173
+ const signals = found.map(([id, detail]) => signal(id, verdict, detail));
174
+ const said = words ? `: ${cpSlice(words, 120)}` : "";
175
+ return result(verdict, `${found[0][0]} (${found[0][1]}${said})`, signals, sent, kind, action, confidence, now, length, retry);
176
+ }
177
+
178
+ /** True for an answer that holds nothing: null, "", [], {}, or an object of empty collections, zero counts and paging. */
179
+ function empty(v, depth) {
180
+ if (blank(v)) return true;
181
+ if (!isDict(v) || depth > 2) return false;
182
+ let saw = false;
183
+ for (const [key, val] of v) {
184
+ if (META_KEYS.has(key)) continue;
185
+ if (Array.isArray(val)) {
186
+ if (val.length) return false;
187
+ saw = true;
188
+ } else if (isDict(val)) {
189
+ if (!empty(val, depth + 1)) return false;
190
+ saw = true;
191
+ } else if (COLLECTION_KEYS.has(key) && val === null) saw = true;
192
+ else if (COUNT_KEYS.has(key)) {
193
+ if (isNum(val) && val > 0) return false;
194
+ } else if (!PAGING_KEYS.has(key)) return false;
195
+ }
196
+ return saw;
197
+ }
198
+
199
+ /** An error envelope in this object: [signal id, detail, code, words, confidence, the object with the words] or null. */
200
+ function envelope(d, ctype) {
201
+ const st = toInt(get(d, "status"));
202
+ if (st !== null && st >= 400n && (d.has("title") || d.has("type") || d.has("detail") || ctype.includes("problem"))) {
203
+ return ["api-problem-details", `problem details, status ${st}`, st, wordsOf(d), "high", d];
204
+ }
205
+ const errors = get(d, "errors");
206
+ if ((Array.isArray(errors) || isDict(errors)) && !blank(errors)) {
207
+ const first = Array.isArray(errors) ? errors[0] : errors;
208
+ const sub = isDict(first) ? first : new Map([["message", first]]);
209
+ const inner = codeOf(sub);
210
+ const data = get(d, "data");
211
+ const partial = d.has("data") && data !== null && !empty(data, 1);
212
+ const n = Array.isArray(errors) ? errors.length : errors.size;
213
+ const detail = `${n} error${n !== 1 ? "s" : ""}` + (partial ? " beside partial data" : "");
214
+ return ["api-errors", detail, inner, wordsOf(sub) || wordsOf(d), partial ? "low" : "medium", sub];
215
+ }
216
+ const err = get(d, "error");
217
+ const asInt = toInt(err);
218
+ if (asInt !== null && !(err === 0n || err === 0)) {
219
+ const inner = asInt >= 400n && asInt <= 599n ? asInt : codeOf(d);
220
+ return ["api-error-field", `error: ${show(err)}`, inner, wordsOf(d), pair(d, "medium"), d];
221
+ }
222
+ if (err === true || (typeof err === "string" && strip(err)) || (isDict(err) && err.size)) {
223
+ const sub = isDict(err) ? err : d;
224
+ let inner = isDict(err) ? codeOf(err) : null;
225
+ inner = inner !== null ? inner : codeOf(d);
226
+ const shown = typeof err === "string" ? "a text" : err === true ? "true" : "an object";
227
+ const words = [wordsOf(sub), sub !== d ? wordsOf(d) : ""].filter(Boolean).join(" | ");
228
+ return ["api-error-field", `error field (${shown})`, inner, words, pair(d, "medium"), d];
229
+ }
230
+ for (const key of ["success", "ok"]) {
231
+ if (get(d, key) === false) return [`api-${key}-false`, `${key}: false`, codeOf(d), wordsOf(d), pair(d, "medium"), d];
232
+ }
233
+ const stText = get(d, "status");
234
+ if (typeof stText === "string" && BAD_STATUS.has(pyLower(strip(stText)))) {
235
+ return ["api-status-error", `status: ${cpSlice(stText, 20)}`, codeOf(d), wordsOf(d), "medium", d];
236
+ }
237
+ const inner = codeOf(d);
238
+ if (inner !== null && inner >= 400n) {
239
+ const words = wordsOf(d);
240
+ if (words || d.size <= 4) {
241
+ if (!Array.from(d).some(([k, v]) => COLLECTION_KEYS.has(k) && !blank(v))) {
242
+ return ["api-error-code", `code ${inner} in the body`, inner, words, words ? "medium" : "low", d];
243
+ }
244
+ }
245
+ }
246
+ return null;
247
+ }
248
+
249
+ /** The verdict for a parsed JSON value: an error envelope first, then an error status, then an empty answer. */
250
+ function judge(data, code, sent, ctype, emptyIsError, length, now) {
251
+ let found = isDict(data) ? envelope(data, ctype) : null;
252
+ if (found === null && isDict(data)) {
253
+ for (const key of ENVELOPE) {
254
+ const inner = get(data, key);
255
+ if (isDict(inner)) {
256
+ found = envelope(inner, ctype);
257
+ if (found !== null) {
258
+ found = [found[0], `${key}.${found[1]}`, ...found.slice(2)];
259
+ break;
260
+ }
261
+ }
262
+ }
263
+ }
264
+ if (found !== null) {
265
+ const [id, detail, innerCode, words, confidence, where] = found;
266
+ const use = innerCode !== null ? innerCode : code !== null && code >= 400 ? code : null;
267
+ return error(use, words, [[id, detail]], sent, "data", confidence, where, now, length, data);
268
+ }
269
+ if (code !== null && code >= 400) {
270
+ const words = isDict(data) ? wordsOf(data) : "";
271
+ return error(code, words, [], sent, "data", "medium", isDict(data) ? data : new Map(), now, length, data);
272
+ }
273
+ if (empty(data, 0)) {
274
+ const sig = signal("api-empty-result", "empty_shell", `empty answer: ${cpSlice(dumps(data, { ensureAscii: false }), 80)}`);
275
+ if (emptyIsError) {
276
+ return result("empty_shell", `api-empty-result (${sig.detail})`, [sig], sent, "data", "retry", "medium", now, length);
277
+ }
278
+ return result("ok", `an empty answer (${sig.detail})`, [sig], sent, "data", "keep", "low", now, length);
279
+ }
280
+ return result("ok", "JSON with no error sign", [], sent, "data", "keep", "medium", now, length);
281
+ }
282
+
283
+ /** An HTML page where JSON was expected: the page check judges it, and the mismatch is noted. */
284
+ function html(body, code, headers, url, finalUrl, ctype, now) {
285
+ const res = checkPage(body, { status: code, headers, url, finalUrl, now });
286
+ const note = `HTML where JSON was expected${ctype ? " (sent as " + ctype.split(";")[0] + ")" : ""}`;
287
+ res.signals.push(signal("api-html-not-json", res.verdict, note));
288
+ if (res.verdict === "ok") {
289
+ res.reason = `api-html-not-json (${note}; no block sign on the page)`;
290
+ res.confidence = "low";
291
+ } else {
292
+ res.reason = `${res.reason}; ${note}`;
293
+ }
294
+ return res;
295
+ }
296
+
297
+ /**
298
+ * Return a verdict for one response from a JSON endpoint, as a plain object with the keys of checkPage's result.
299
+ * body: the response as bytes or text, or JSON already parsed (an object or an array). Options: status, headers, url,
300
+ * finalUrl as for checkPage; emptyIsError: an empty answer is empty_shell (action "retry") instead of a low-confidence
301
+ * "ok"; now (epoch ms for Retry-After dates).
302
+ */
303
+ function checkApi(body, opts = {}) {
304
+ const now = opts.now === undefined ? Date.now() : opts.now;
305
+ const url = opts.url === undefined ? null : opts.url;
306
+ const finalUrl = opts.finalUrl === undefined ? null : opts.finalUrl;
307
+ const emptyIsError = !!opts.emptyIsError;
308
+ const code = statusOf(opts.status);
309
+ const sent = headersOf(opts.headers);
310
+ const ctype = pyLower(sent.get("content-type") || "");
311
+ let packed = !!search(PACKED_HEADER, sent.get("content-encoding") || "");
312
+ if (body !== null && body !== undefined && typeof body === "object" && !asBytes(body)) {
313
+ return judge(toPy(body), code, sent, ctype, emptyIsError, 0, now);
314
+ }
315
+ if (body === null || body === undefined) body = Buffer.alloc(0);
316
+ let text;
317
+ const bytes = asBytes(body);
318
+ if (bytes) {
319
+ packed = packed || PACKED_START.some((p) => startsWithBytes(bytes, p));
320
+ text = decode(bytes, sent.has("content-type") ? sent.get("content-type") : null);
321
+ } else text = String(body);
322
+ text = text.replace(/^+/, "");
323
+ const stripped = strip(text);
324
+ if (!stripped) {
325
+ if (code === 204 || (code !== null && code < 300 && sent.get("content-length") === "0" && code !== 200)) {
326
+ return result("ok", "no content, as the status says", [], sent, "empty", "keep", "medium", now);
327
+ }
328
+ if (code !== null && code >= 400) return error(code, "", [], sent, "empty", "medium", new Map(), now);
329
+ const sig = signal("api-empty-body", "empty_shell", "the response is empty");
330
+ return result("empty_shell", "api-empty-body (the response is empty, JSON was expected)", [sig], sent, "empty", "retry", "medium", now);
331
+ }
332
+ if (looksBinary(stripped)) {
333
+ const sig = signal("api-not-json", "not_html", "binary or compressed data");
334
+ return result("not_html", "api-not-json (binary or compressed data, not JSON)", [sig], sent,
335
+ packed ? "compressed" : "binary", packed ? "decompress" : "drop", "medium", now);
336
+ }
337
+ if (stripped[0] === "<") {
338
+ if (search(HTML, cpSlice(stripped, 2048))) return html(body, code, opts.headers, url, finalUrl, ctype, now);
339
+ if (code !== null && code >= 400) return error(code, cpSlice(stripped, 300), [], sent, "data", "medium", new Map(), now);
340
+ const sig = signal("api-not-json", "not_html", "XML or markup where JSON was expected");
341
+ return result("not_html", "api-not-json (XML or markup where JSON was expected)", [sig], sent, "data", "drop", "medium", now);
342
+ }
343
+ const hijack = search(HIJACK, stripped);
344
+ const cleaned = hijack ? stripped.slice(hijack[0].length) : stripped;
345
+ let data;
346
+ try {
347
+ data = loads(cleaned);
348
+ } catch (e) {
349
+ const m = search(JSONP, cleaned);
350
+ let parsed = false;
351
+ if (m) {
352
+ try {
353
+ data = loads(m[1]);
354
+ parsed = true;
355
+ } catch (e2) {
356
+ // unparseable too: falls through to the verdict below
357
+ }
358
+ }
359
+ if (!parsed) {
360
+ if (code !== null && code >= 400) return error(code, cpSlice(stripped, 300), [], sent, "data", "medium", new Map(), now);
361
+ const pos = e.pos || 0;
362
+ const cut = (cleaned === "" || '{["'.includes(String.fromCodePoint(cleaned.codePointAt(0)))) && pos >= cpLen(cleaned) - 1;
363
+ const detail = cut ? `JSON cut off at character ${pos}` : `not valid JSON (${cpSlice(e.message, 80)})`;
364
+ const sig = signal(cut ? "api-truncated" : "api-not-json", "not_html", detail);
365
+ return result("not_html", `${sig.id} (${detail})`, [sig], sent, "data", cut ? "retry" : "drop", "medium", now);
366
+ }
367
+ }
368
+ return judge(data, code, sent, ctype, emptyIsError, cpLen(text), now);
369
+ }
370
+
371
+ module.exports = { checkApi };