@itsaakashpatel/seo-webmaster-mcp 0.0.0-stage → 1.1.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/CHANGELOG.md +36 -0
- package/LICENSE +21 -0
- package/README.md +380 -2
- package/build/approvals/format.d.ts +29 -0
- package/build/approvals/format.js +88 -0
- package/build/approvals/gate.d.ts +23 -0
- package/build/approvals/gate.js +102 -0
- package/build/approvals/groups.d.ts +14 -0
- package/build/approvals/groups.js +113 -0
- package/build/approvals/session.d.ts +8 -0
- package/build/approvals/session.js +23 -0
- package/build/cli/args.d.ts +18 -0
- package/build/cli/args.js +41 -0
- package/build/cli/commands.d.ts +8 -0
- package/build/cli/commands.js +64 -0
- package/build/cli/engines.d.ts +1 -0
- package/build/cli/engines.js +6 -0
- package/build/cli/help.d.ts +2 -0
- package/build/cli/help.js +29 -0
- package/build/cli/install/clients.d.ts +18 -0
- package/build/cli/install/clients.js +46 -0
- package/build/cli/install/command.d.ts +21 -0
- package/build/cli/install/command.js +44 -0
- package/build/cli/install/exec.d.ts +3 -0
- package/build/cli/install/exec.js +14 -0
- package/build/cli/install/flow.d.ts +14 -0
- package/build/cli/install/flow.js +114 -0
- package/build/cli/install/json-config.d.ts +24 -0
- package/build/cli/install/json-config.js +70 -0
- package/build/cli/prompter.d.ts +21 -0
- package/build/cli/prompter.js +15 -0
- package/build/cli/run.d.ts +17 -0
- package/build/cli/run.js +48 -0
- package/build/cli/screens.d.ts +45 -0
- package/build/cli/screens.js +83 -0
- package/build/cli/setup/approvals.d.ts +2 -0
- package/build/cli/setup/approvals.js +59 -0
- package/build/cli/setup/bing.d.ts +2 -0
- package/build/cli/setup/bing.js +35 -0
- package/build/cli/setup/flow.d.ts +8 -0
- package/build/cli/setup/flow.js +91 -0
- package/build/cli/setup/google.d.ts +2 -0
- package/build/cli/setup/google.js +94 -0
- package/build/cli/setup/helpers.d.ts +13 -0
- package/build/cli/setup/helpers.js +38 -0
- package/build/cli/setup/indexnow.d.ts +3 -0
- package/build/cli/setup/indexnow.js +89 -0
- package/build/cli/setup/services.d.ts +5 -0
- package/build/cli/setup/services.js +62 -0
- package/build/cli/setup/text.d.ts +10 -0
- package/build/cli/setup/text.js +40 -0
- package/build/cli/setup/types.d.ts +35 -0
- package/build/cli/setup/types.js +1 -0
- package/build/cli/status.d.ts +14 -0
- package/build/cli/status.js +54 -0
- package/build/cli/terminal.d.ts +6 -0
- package/build/cli/terminal.js +134 -0
- package/build/config/file.d.ts +29 -0
- package/build/config/file.js +58 -0
- package/build/config/index.d.ts +24 -0
- package/build/config/index.js +72 -0
- package/build/config/paths.d.ts +11 -0
- package/build/config/paths.js +19 -0
- package/build/core/analytics.d.ts +5 -0
- package/build/core/analytics.js +18 -0
- package/build/core/constants.d.ts +9 -0
- package/build/core/constants.js +9 -0
- package/build/core/errors.d.ts +18 -0
- package/build/core/errors.js +53 -0
- package/build/core/filters.d.ts +14 -0
- package/build/core/filters.js +42 -0
- package/build/core/guards.d.ts +11 -0
- package/build/core/guards.js +32 -0
- package/build/core/http.d.ts +17 -0
- package/build/core/http.js +51 -0
- package/build/core/insights/compare.d.ts +32 -0
- package/build/core/insights/compare.js +56 -0
- package/build/core/insights/crawl.d.ts +9 -0
- package/build/core/insights/crawl.js +61 -0
- package/build/core/insights/links.d.ts +5 -0
- package/build/core/insights/links.js +20 -0
- package/build/core/insights/metrics.d.ts +8 -0
- package/build/core/insights/metrics.js +15 -0
- package/build/core/insights/opportunities.d.ts +15 -0
- package/build/core/insights/opportunities.js +40 -0
- package/build/core/insights/periods.d.ts +12 -0
- package/build/core/insights/periods.js +38 -0
- package/build/core/insights/types.d.ts +31 -0
- package/build/core/insights/types.js +1 -0
- package/build/core/markdown.d.ts +14 -0
- package/build/core/markdown.js +28 -0
- package/build/core/paging.d.ts +11 -0
- package/build/core/paging.js +5 -0
- package/build/core/provider.d.ts +15 -0
- package/build/core/provider.js +1 -0
- package/build/core/rate-limit.d.ts +8 -0
- package/build/core/rate-limit.js +19 -0
- package/build/core/registry.d.ts +11 -0
- package/build/core/registry.js +16 -0
- package/build/core/responses.d.ts +13 -0
- package/build/core/responses.js +9 -0
- package/build/core/secrets.d.ts +2 -0
- package/build/core/secrets.js +9 -0
- package/build/core/types.d.ts +137 -0
- package/build/core/types.js +13 -0
- package/build/core/untrusted.d.ts +11 -0
- package/build/core/untrusted.js +34 -0
- package/build/core/urls.d.ts +16 -0
- package/build/core/urls.js +80 -0
- package/build/core/validation.d.ts +23 -0
- package/build/core/validation.js +100 -0
- package/build/index.d.ts +2 -0
- package/build/index.js +30 -0
- package/build/providers/bing/auth.d.ts +11 -0
- package/build/providers/bing/auth.js +87 -0
- package/build/providers/bing/mappers.d.ts +18 -0
- package/build/providers/bing/mappers.js +87 -0
- package/build/providers/bing/operations.d.ts +8 -0
- package/build/providers/bing/operations.js +40 -0
- package/build/providers/bing/provider.d.ts +16 -0
- package/build/providers/bing/provider.js +132 -0
- package/build/providers/bing/records.d.ts +11 -0
- package/build/providers/bing/records.js +47 -0
- package/build/providers/bing/wire.d.ts +86 -0
- package/build/providers/bing/wire.js +38 -0
- package/build/providers/bing/writes.d.ts +9 -0
- package/build/providers/bing/writes.js +31 -0
- package/build/providers/google/auth.d.ts +13 -0
- package/build/providers/google/auth.js +174 -0
- package/build/providers/google/indexing.d.ts +14 -0
- package/build/providers/google/indexing.js +89 -0
- package/build/providers/google/mappers.d.ts +6 -0
- package/build/providers/google/mappers.js +96 -0
- package/build/providers/google/probe.d.ts +9 -0
- package/build/providers/google/probe.js +42 -0
- package/build/providers/google/provider.d.ts +15 -0
- package/build/providers/google/provider.js +118 -0
- package/build/providers/index.d.ts +4 -0
- package/build/providers/index.js +7 -0
- package/build/providers/indexnow/probe.d.ts +8 -0
- package/build/providers/indexnow/probe.js +17 -0
- package/build/providers/indexnow/provider.d.ts +21 -0
- package/build/providers/indexnow/provider.js +96 -0
- package/build/providers/insights/bing.d.ts +2 -0
- package/build/providers/insights/bing.js +73 -0
- package/build/providers/insights/google.d.ts +2 -0
- package/build/providers/insights/google.js +67 -0
- package/build/providers/insights/index.d.ts +5 -0
- package/build/providers/insights/index.js +15 -0
- package/build/providers/insights/source.d.ts +14 -0
- package/build/providers/insights/source.js +1 -0
- package/build/server.d.ts +2 -0
- package/build/server.js +14 -0
- package/build/tools/bing/catalog-crawl.d.ts +2 -0
- package/build/tools/bing/catalog-crawl.js +125 -0
- package/build/tools/bing/catalog-settings.d.ts +2 -0
- package/build/tools/bing/catalog-settings.js +51 -0
- package/build/tools/bing/catalog-site.d.ts +2 -0
- package/build/tools/bing/catalog-site.js +70 -0
- package/build/tools/bing/catalog-traffic.d.ts +2 -0
- package/build/tools/bing/catalog-traffic.js +88 -0
- package/build/tools/bing/index.d.ts +6 -0
- package/build/tools/bing/index.js +26 -0
- package/build/tools/bing/inputs.d.ts +21 -0
- package/build/tools/bing/inputs.js +34 -0
- package/build/tools/bing/read-tool.d.ts +23 -0
- package/build/tools/bing/read-tool.js +71 -0
- package/build/tools/bing/render.d.ts +8 -0
- package/build/tools/bing/render.js +50 -0
- package/build/tools/bing/write-tool.d.ts +25 -0
- package/build/tools/bing/write-tool.js +127 -0
- package/build/tools/bing/writes-settings.d.ts +2 -0
- package/build/tools/bing/writes-settings.js +227 -0
- package/build/tools/bing/writes-sites.d.ts +2 -0
- package/build/tools/bing/writes-sites.js +172 -0
- package/build/tools/engine-status.d.ts +14 -0
- package/build/tools/engine-status.js +81 -0
- package/build/tools/get-sitemap.d.ts +4 -0
- package/build/tools/get-sitemap.js +46 -0
- package/build/tools/index.d.ts +6 -0
- package/build/tools/index.js +43 -0
- package/build/tools/insights/bing-crawl-overview.d.ts +2 -0
- package/build/tools/insights/bing-crawl-overview.js +46 -0
- package/build/tools/insights/bing-link-evidence.d.ts +2 -0
- package/build/tools/insights/bing-link-evidence.js +65 -0
- package/build/tools/insights/declining-pages.d.ts +2 -0
- package/build/tools/insights/declining-pages.js +59 -0
- package/build/tools/insights/performance-overview.d.ts +2 -0
- package/build/tools/insights/performance-overview.js +39 -0
- package/build/tools/insights/report.d.ts +50 -0
- package/build/tools/insights/report.js +86 -0
- package/build/tools/insights/search-opportunities.d.ts +2 -0
- package/build/tools/insights/search-opportunities.js +30 -0
- package/build/tools/insights/shared.d.ts +44 -0
- package/build/tools/insights/shared.js +90 -0
- package/build/tools/inspect-url.d.ts +4 -0
- package/build/tools/inspect-url.js +104 -0
- package/build/tools/list-sitemaps.d.ts +4 -0
- package/build/tools/list-sitemaps.js +37 -0
- package/build/tools/list-sites.d.ts +4 -0
- package/build/tools/list-sites.js +56 -0
- package/build/tools/search-analytics.d.ts +4 -0
- package/build/tools/search-analytics.js +108 -0
- package/build/tools/shared.d.ts +29 -0
- package/build/tools/shared.js +63 -0
- package/build/tools/sitemaps.d.ts +2 -0
- package/build/tools/sitemaps.js +140 -0
- package/build/tools/submit-google.d.ts +4 -0
- package/build/tools/submit-google.js +68 -0
- package/build/tools/submit-urls.d.ts +4 -0
- package/build/tools/submit-urls.js +65 -0
- package/package.json +66 -4
- package/server.json +58 -0
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { isRecord } from "./guards.js";
|
|
2
|
+
const JSON_ARRAY_ERROR = 'URL JSON must be an array of strings (e.g. ["https://..."]).';
|
|
3
|
+
const NON_STRING_ERROR = "URL JSON must be an array of strings; found non-string entry.";
|
|
4
|
+
/** Parses a value as an http(s) URL. Returns `undefined` for any other scheme or bad input. */
|
|
5
|
+
export function parseHttpUrl(value) {
|
|
6
|
+
const trimmed = value.trim();
|
|
7
|
+
if (!URL.canParse(trimmed)) {
|
|
8
|
+
return undefined;
|
|
9
|
+
}
|
|
10
|
+
const url = new URL(trimmed);
|
|
11
|
+
return url.protocol === "http:" || url.protocol === "https:" ? url : undefined;
|
|
12
|
+
}
|
|
13
|
+
export function isHttpUrl(value) {
|
|
14
|
+
return parseHttpUrl(value) !== undefined;
|
|
15
|
+
}
|
|
16
|
+
/** Trims each URL, drops empty entries, and removes duplicates. Keeps the first-seen order. */
|
|
17
|
+
export function dedupeUrls(urls) {
|
|
18
|
+
return [...new Set(urls.map((url) => url.trim()).filter((url) => url.length > 0))];
|
|
19
|
+
}
|
|
20
|
+
/** Returns the entries that are not valid http(s) URLs. */
|
|
21
|
+
export function validateHttpsUrls(urls) {
|
|
22
|
+
return urls.filter((url) => !isHttpUrl(url));
|
|
23
|
+
}
|
|
24
|
+
/** Returns the entries that are not http(s) URLs on exactly this host. */
|
|
25
|
+
export function urlsBelongToHost(urls, host) {
|
|
26
|
+
const expected = host.toLowerCase();
|
|
27
|
+
return urls.filter((url) => parseHttpUrl(url)?.hostname.toLowerCase() !== expected);
|
|
28
|
+
}
|
|
29
|
+
function splitDelimitedList(text) {
|
|
30
|
+
return text
|
|
31
|
+
.split(/[\r\n,]+/)
|
|
32
|
+
.map((url) => url.trim())
|
|
33
|
+
.filter((url) => url.length > 0);
|
|
34
|
+
}
|
|
35
|
+
function tryParseJson(text) {
|
|
36
|
+
try {
|
|
37
|
+
const json = JSON.parse(text);
|
|
38
|
+
return json;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
// Not JSON. The caller decides whether to fall back to a delimited list.
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function toStringList(list) {
|
|
46
|
+
if (!Array.isArray(list)) {
|
|
47
|
+
throw new Error(JSON_ARRAY_ERROR);
|
|
48
|
+
}
|
|
49
|
+
const strings = list.filter((entry) => typeof entry === "string");
|
|
50
|
+
if (strings.length !== list.length) {
|
|
51
|
+
throw new Error(NON_STRING_ERROR);
|
|
52
|
+
}
|
|
53
|
+
return strings.map((url) => url.trim()).filter((url) => url.length > 0);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Parses a URL list from tool input. It accepts a JSON array, a JSON object with a `urls` array,
|
|
57
|
+
* or a comma- or newline-separated list.
|
|
58
|
+
*/
|
|
59
|
+
export function parseUrlList(raw) {
|
|
60
|
+
const trimmed = raw.trim();
|
|
61
|
+
const isJsonArray = trimmed.startsWith("[") && trimmed.endsWith("]");
|
|
62
|
+
const isJsonObject = trimmed.startsWith("{") && trimmed.endsWith("}");
|
|
63
|
+
if (!isJsonArray && !isJsonObject) {
|
|
64
|
+
return splitDelimitedList(trimmed);
|
|
65
|
+
}
|
|
66
|
+
const parsed = tryParseJson(trimmed);
|
|
67
|
+
if (parsed === undefined && isJsonArray) {
|
|
68
|
+
// Tolerate an unquoted list such as [https://a.com, https://b.com].
|
|
69
|
+
return splitDelimitedList(trimmed.slice(1, -1));
|
|
70
|
+
}
|
|
71
|
+
return toStringList(isRecord(parsed) ? parsed.urls : parsed);
|
|
72
|
+
}
|
|
73
|
+
/** Returns the URLs whose host is not the host of the site or a subdomain of it. */
|
|
74
|
+
export function urlsOutsideSite(urls, siteUrl) {
|
|
75
|
+
const site = parseHttpUrl(siteUrl)?.hostname.toLowerCase();
|
|
76
|
+
return urls.filter((url) => {
|
|
77
|
+
const host = parseHttpUrl(url)?.hostname.toLowerCase();
|
|
78
|
+
return !site || !host || (host !== site && !host.endsWith(`.${site}`));
|
|
79
|
+
});
|
|
80
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { RE2JS } from "re2js";
|
|
2
|
+
import { type Dimension } from "./types.js";
|
|
3
|
+
/** Trims a value and throws when nothing is left. */
|
|
4
|
+
export declare function requireText(value: string, label: string): string;
|
|
5
|
+
/** Maps dimension names to their canonical spelling. Drops unknown names and duplicates. */
|
|
6
|
+
export declare function normalizeDimensions(input?: readonly string[]): Dimension[];
|
|
7
|
+
export declare function parseDimensionList(raw: string | undefined): Dimension[];
|
|
8
|
+
/** Checks the YYYY-MM-DD format, that both dates exist, and that start is not after end. */
|
|
9
|
+
export declare function validateDateRange(startDate: string, endDate: string): void;
|
|
10
|
+
/**
|
|
11
|
+
* Compiles a user-supplied filter pattern with RE2 semantics.
|
|
12
|
+
*
|
|
13
|
+
* RE2 matches in linear time, so no pattern can cause catastrophic backtracking (ReDoS). It also
|
|
14
|
+
* uses the same syntax as the Google Search Console API, so a `regex:` filter behaves the same
|
|
15
|
+
* way on every engine.
|
|
16
|
+
*/
|
|
17
|
+
export declare function buildSafeRegExp(pattern: string, label: string): RE2JS;
|
|
18
|
+
/** Reduces `https://Example.com:443/path` to `example.com`. */
|
|
19
|
+
export declare function normalizeHost(rawHost: string): string;
|
|
20
|
+
/** Builds a comparison key for a sitemap URL or path: lowercase, no scheme, no trailing slash. */
|
|
21
|
+
export declare function normalizeSitemapKey(pathOrUrl: string): string;
|
|
22
|
+
export declare function clampRowLimit(requested: number | undefined, max: number, fallback: number): number;
|
|
23
|
+
export declare function clampStartRow(requested: number | undefined): number;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { RE2JS } from "re2js";
|
|
2
|
+
import { MAX_REGEX_LENGTH } from "./constants.js";
|
|
3
|
+
import { isPresent } from "./guards.js";
|
|
4
|
+
import { DIMENSIONS } from "./types.js";
|
|
5
|
+
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
6
|
+
const HOST_RE = /^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/;
|
|
7
|
+
const DIMENSION_BY_KEY = new Map(DIMENSIONS.map((dimension) => [dimension.toLowerCase(), dimension]));
|
|
8
|
+
const DEFAULT_DIMENSIONS = ["query"];
|
|
9
|
+
/** Trims a value and throws when nothing is left. */
|
|
10
|
+
export function requireText(value, label) {
|
|
11
|
+
const trimmed = value.trim();
|
|
12
|
+
if (trimmed.length === 0) {
|
|
13
|
+
throw new Error(`${label} must be non-empty.`);
|
|
14
|
+
}
|
|
15
|
+
return trimmed;
|
|
16
|
+
}
|
|
17
|
+
/** Maps dimension names to their canonical spelling. Drops unknown names and duplicates. */
|
|
18
|
+
export function normalizeDimensions(input = []) {
|
|
19
|
+
const known = input.map((raw) => DIMENSION_BY_KEY.get(raw.trim().toLowerCase()));
|
|
20
|
+
const unique = [...new Set(known.filter(isPresent))];
|
|
21
|
+
return unique.length > 0 ? unique : [...DEFAULT_DIMENSIONS];
|
|
22
|
+
}
|
|
23
|
+
export function parseDimensionList(raw) {
|
|
24
|
+
return normalizeDimensions(raw?.split(",") ?? []);
|
|
25
|
+
}
|
|
26
|
+
function parseCalendarDate(value) {
|
|
27
|
+
const time = Date.parse(`${value}T00:00:00Z`);
|
|
28
|
+
const isRealDate = !Number.isNaN(time) && new Date(time).toISOString().slice(0, 10) === value;
|
|
29
|
+
if (!isRealDate) {
|
|
30
|
+
throw new Error(`Invalid calendar date "${value}".`);
|
|
31
|
+
}
|
|
32
|
+
return time;
|
|
33
|
+
}
|
|
34
|
+
/** Checks the YYYY-MM-DD format, that both dates exist, and that start is not after end. */
|
|
35
|
+
export function validateDateRange(startDate, endDate) {
|
|
36
|
+
const start = startDate.trim();
|
|
37
|
+
const end = endDate.trim();
|
|
38
|
+
if (!DATE_RE.test(start) || !DATE_RE.test(end)) {
|
|
39
|
+
throw new Error(`Invalid date format. Use YYYY-MM-DD (got "${startDate}" to "${endDate}").`);
|
|
40
|
+
}
|
|
41
|
+
if (parseCalendarDate(start) > parseCalendarDate(end)) {
|
|
42
|
+
throw new Error(`Invalid date range: startDate "${start}" is after endDate "${end}".`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Compiles a user-supplied filter pattern with RE2 semantics.
|
|
47
|
+
*
|
|
48
|
+
* RE2 matches in linear time, so no pattern can cause catastrophic backtracking (ReDoS). It also
|
|
49
|
+
* uses the same syntax as the Google Search Console API, so a `regex:` filter behaves the same
|
|
50
|
+
* way on every engine.
|
|
51
|
+
*/
|
|
52
|
+
export function buildSafeRegExp(pattern, label) {
|
|
53
|
+
const trimmed = pattern.trim();
|
|
54
|
+
if (trimmed.length === 0) {
|
|
55
|
+
throw new Error(`Invalid ${label} regex: pattern is empty.`);
|
|
56
|
+
}
|
|
57
|
+
if (trimmed.length > MAX_REGEX_LENGTH) {
|
|
58
|
+
throw new Error(`Invalid ${label} regex: pattern exceeds ${MAX_REGEX_LENGTH} chars.`);
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
return RE2JS.compile(trimmed, RE2JS.CASE_INSENSITIVE);
|
|
62
|
+
}
|
|
63
|
+
catch (err) {
|
|
64
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
65
|
+
throw new Error(`Invalid ${label} regex "${trimmed}": ${msg}`, { cause: err });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** Reduces `https://Example.com:443/path` to `example.com`. */
|
|
69
|
+
export function normalizeHost(rawHost) {
|
|
70
|
+
const withoutScheme = rawHost
|
|
71
|
+
.trim()
|
|
72
|
+
.toLowerCase()
|
|
73
|
+
.replace(/^https?:\/\//, "");
|
|
74
|
+
const host = (withoutScheme.split(/[/:]/)[0] ?? "").replace(/\.+$/, "");
|
|
75
|
+
if (!host.includes(".") || !HOST_RE.test(host)) {
|
|
76
|
+
throw new Error(`Invalid host "${rawHost}". Use a bare domain like "example.com".`);
|
|
77
|
+
}
|
|
78
|
+
return host;
|
|
79
|
+
}
|
|
80
|
+
/** Builds a comparison key for a sitemap URL or path: lowercase, no scheme, no trailing slash. */
|
|
81
|
+
export function normalizeSitemapKey(pathOrUrl) {
|
|
82
|
+
const trimmed = pathOrUrl.trim();
|
|
83
|
+
if (!URL.canParse(trimmed)) {
|
|
84
|
+
return trimmed.replace(/\/+$/, "").toLowerCase();
|
|
85
|
+
}
|
|
86
|
+
const url = new URL(trimmed);
|
|
87
|
+
return `${url.hostname}${url.pathname.replace(/\/+$/, "")}`.toLowerCase();
|
|
88
|
+
}
|
|
89
|
+
export function clampRowLimit(requested, max, fallback) {
|
|
90
|
+
if (requested === undefined || !Number.isFinite(requested)) {
|
|
91
|
+
return fallback;
|
|
92
|
+
}
|
|
93
|
+
return Math.min(Math.max(Math.floor(requested), 1), max);
|
|
94
|
+
}
|
|
95
|
+
export function clampStartRow(requested) {
|
|
96
|
+
if (requested === undefined || !Number.isFinite(requested)) {
|
|
97
|
+
return 0;
|
|
98
|
+
}
|
|
99
|
+
return Math.max(Math.floor(requested), 0);
|
|
100
|
+
}
|
package/build/index.d.ts
ADDED
package/build/index.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { ConfigError } from "./config/file.js";
|
|
3
|
+
import { isAnyEngineConfigured } from "./cli/engines.js";
|
|
4
|
+
import { createCommands } from "./cli/commands.js";
|
|
5
|
+
import { EXIT_FAILURE, runCli } from "./cli/run.js";
|
|
6
|
+
import { getErrorMessage } from "./core/errors.js";
|
|
7
|
+
const out = (text) => console.log(text);
|
|
8
|
+
const err = (text) => console.error(text);
|
|
9
|
+
async function main() {
|
|
10
|
+
const stdinIsTerminal = process.stdin.isTTY === true;
|
|
11
|
+
return runCli(process.argv.slice(2), {
|
|
12
|
+
stdinIsTerminal,
|
|
13
|
+
anyEngineConfigured: isAnyEngineConfigured,
|
|
14
|
+
out,
|
|
15
|
+
err,
|
|
16
|
+
...createCommands({ out, err, stdinIsTerminal }),
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
main()
|
|
20
|
+
.then((code) => {
|
|
21
|
+
if (code !== 0) {
|
|
22
|
+
process.exitCode = code;
|
|
23
|
+
}
|
|
24
|
+
})
|
|
25
|
+
.catch((error) => {
|
|
26
|
+
// A configuration error has a clear message. Other errors show the stack for a bug report.
|
|
27
|
+
const message = error instanceof ConfigError ? error.message : `Fatal error: ${getErrorMessage(error)}`;
|
|
28
|
+
console.error(message);
|
|
29
|
+
process.exit(EXIT_FAILURE);
|
|
30
|
+
});
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const BING_SETUP_GUIDE: string;
|
|
2
|
+
export declare function isBingConfigured(): boolean;
|
|
3
|
+
export declare function formatBingError(error: unknown): string;
|
|
4
|
+
/** Lists the sites of a key that is not saved yet. Setup uses this to test a key. */
|
|
5
|
+
export declare function countBingSitesForKey(apiKey: string): Promise<number>;
|
|
6
|
+
/** Calls a Bing method that reads with `GET`. */
|
|
7
|
+
export declare function bingGet(method: string, params?: Readonly<Record<string, string>>): Promise<unknown>;
|
|
8
|
+
/** Calls a Bing method that takes a JSON body. */
|
|
9
|
+
export declare function bingPost(method: string, body: Readonly<Record<string, unknown>>): Promise<unknown>;
|
|
10
|
+
/** Runs a Bing call and rethrows any failure with a formatted message. */
|
|
11
|
+
export declare function withBingErrors<T>(action: () => Promise<T>): Promise<T>;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { BING_REQUESTS_PER_SECOND, USER_AGENT } from "../../core/constants.js";
|
|
2
|
+
import { getErrorCode, getErrorMessage } from "../../core/errors.js";
|
|
3
|
+
import { isRecord } from "../../core/guards.js";
|
|
4
|
+
import { ensureOk, fetchWithTimeout, readJsonSafe } from "../../core/http.js";
|
|
5
|
+
import { createRateLimiter } from "../../core/rate-limit.js";
|
|
6
|
+
import { redactSecret } from "../../core/secrets.js";
|
|
7
|
+
import { getSetting } from "../../config/index.js";
|
|
8
|
+
const BING_API_BASE = "https://ssl.bing.com/webmaster/api.svc/json";
|
|
9
|
+
export const BING_SETUP_GUIDE = [
|
|
10
|
+
"Bing Webmaster Tools is not configured.",
|
|
11
|
+
"",
|
|
12
|
+
"To configure:",
|
|
13
|
+
"1. Sign in to Bing Webmaster Tools (https://www.bing.com/webmasters).",
|
|
14
|
+
"2. Navigate to Settings (top right gear icon) → API Access → API Key.",
|
|
15
|
+
"3. Generate an API Key and copy it.",
|
|
16
|
+
"4. Run `npx -y @itsaakashpatel/seo-webmaster-mcp setup` and paste the key, or set the `BING_WEBMASTER_API_KEY` environment variable in your MCP client configuration.",
|
|
17
|
+
"5. Restart your MCP client. The server lists the Bing tools only when it starts with a key.",
|
|
18
|
+
"6. Ensure your site is added and verified in Bing Webmaster Tools.",
|
|
19
|
+
].join("\n");
|
|
20
|
+
function readApiKey() {
|
|
21
|
+
return getSetting("bingApiKey");
|
|
22
|
+
}
|
|
23
|
+
export function isBingConfigured() {
|
|
24
|
+
return readApiKey() !== undefined;
|
|
25
|
+
}
|
|
26
|
+
export function formatBingError(error) {
|
|
27
|
+
const code = getErrorCode(error);
|
|
28
|
+
const msg = getErrorMessage(error);
|
|
29
|
+
// Bing reports a bad key as HTTP 400 with "InvalidApiKey", not as 401.
|
|
30
|
+
if (msg.includes("InvalidApiKey")) {
|
|
31
|
+
return `Bing Webmaster API rejected the API key: ${msg}\n\nCheck \`BING_WEBMASTER_API_KEY\`. Create a key in Bing Webmaster Tools Settings → API Access.`;
|
|
32
|
+
}
|
|
33
|
+
if (code === 401 || msg.includes("Unauthorized") || msg.includes("Invalid API Key")) {
|
|
34
|
+
return `Bing Webmaster API authentication failed (401 Invalid API Key): ${msg}\n\nPlease verify your \`BING_WEBMASTER_API_KEY\` in Bing Webmaster Tools Settings → API Access.`;
|
|
35
|
+
}
|
|
36
|
+
if (code === 403 || msg.includes("Forbidden")) {
|
|
37
|
+
return `Bing Webmaster permission denied (403): ${msg}\n\nEnsure your Bing account has verified ownership of the requested site property.`;
|
|
38
|
+
}
|
|
39
|
+
return msg;
|
|
40
|
+
}
|
|
41
|
+
const acquireSlot = createRateLimiter({ limit: BING_REQUESTS_PER_SECOND, intervalMs: 1000 });
|
|
42
|
+
/**
|
|
43
|
+
* Sends one request, with no retry, and unwraps the `{ d: ... }` envelope. The API key is removed
|
|
44
|
+
* from the response body before any code reads it, so no error or result can show it.
|
|
45
|
+
*/
|
|
46
|
+
async function bingRequest(method, request, apiKey = readApiKey()) {
|
|
47
|
+
if (!apiKey) {
|
|
48
|
+
throw new Error(BING_SETUP_GUIDE);
|
|
49
|
+
}
|
|
50
|
+
const url = new URL(`${BING_API_BASE}/${method}`);
|
|
51
|
+
url.search = new URLSearchParams({ ...request.params, apikey: apiKey }).toString();
|
|
52
|
+
await acquireSlot();
|
|
53
|
+
const res = await fetchWithTimeout(url, {
|
|
54
|
+
method: request.body ? "POST" : "GET",
|
|
55
|
+
headers: {
|
|
56
|
+
Accept: "application/json",
|
|
57
|
+
"User-Agent": USER_AGENT,
|
|
58
|
+
...(request.body && { "Content-Type": "application/json" }),
|
|
59
|
+
},
|
|
60
|
+
body: request.body && JSON.stringify(request.body),
|
|
61
|
+
});
|
|
62
|
+
const safe = new Response(redactSecret(await res.text(), apiKey), { status: res.status });
|
|
63
|
+
const json = await readJsonSafe(await ensureOk(safe, "Bing Webmaster API"));
|
|
64
|
+
return isRecord(json) && "d" in json ? json.d : json;
|
|
65
|
+
}
|
|
66
|
+
/** Lists the sites of a key that is not saved yet. Setup uses this to test a key. */
|
|
67
|
+
export async function countBingSitesForKey(apiKey) {
|
|
68
|
+
const sites = await withBingErrors(() => bingRequest("GetUserSites", {}, apiKey));
|
|
69
|
+
return Array.isArray(sites) ? sites.length : 0;
|
|
70
|
+
}
|
|
71
|
+
/** Calls a Bing method that reads with `GET`. */
|
|
72
|
+
export function bingGet(method, params = {}) {
|
|
73
|
+
return bingRequest(method, { params });
|
|
74
|
+
}
|
|
75
|
+
/** Calls a Bing method that takes a JSON body. */
|
|
76
|
+
export function bingPost(method, body) {
|
|
77
|
+
return bingRequest(method, { body });
|
|
78
|
+
}
|
|
79
|
+
/** Runs a Bing call and rethrows any failure with a formatted message. */
|
|
80
|
+
export async function withBingErrors(action) {
|
|
81
|
+
try {
|
|
82
|
+
return await action();
|
|
83
|
+
}
|
|
84
|
+
catch (err) {
|
|
85
|
+
throw new Error(formatBingError(err), { cause: err });
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { AnalyticsRow, SiteInfo, SitemapInfo } from "../../core/types.js";
|
|
2
|
+
type BingRecord = Record<string, unknown>;
|
|
3
|
+
/** Converts a Bing date (WCF string, ISO string, or epoch number) to an ISO string. */
|
|
4
|
+
export declare function parseBingDate(raw: unknown): string | undefined;
|
|
5
|
+
export declare function toSiteInfo(site: BingRecord): SiteInfo;
|
|
6
|
+
/**
|
|
7
|
+
* Maps a Bing `Feed`. Bing supplies no indexed, error, or warning counts, so those fields stay
|
|
8
|
+
* `undefined` instead of a false 0.
|
|
9
|
+
*/
|
|
10
|
+
export declare function toSitemapInfo(feed: BingRecord): SitemapInfo;
|
|
11
|
+
export declare function rowKey(row: BingRecord): string;
|
|
12
|
+
/** Bing returns one row per key per week. Merge them into one row per key, top clicks first. */
|
|
13
|
+
export declare function aggregateRows(rows: readonly BingRecord[]): AnalyticsRow[];
|
|
14
|
+
/** Keeps rows whose weekly bucket date is inside the range. Rows without a date are kept. */
|
|
15
|
+
export declare function isInDateRange(row: BingRecord, startDate: string, endDate: string): boolean;
|
|
16
|
+
/** Returns the newest crawl date in a `GetCrawlStats` response. */
|
|
17
|
+
export declare function latestCrawlDate(entries: readonly BingRecord[]): string | undefined;
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { ratio } from "../../core/analytics.js";
|
|
2
|
+
import { asFiniteNumber, asOptionalNumber, asString, isPresent } from "../../core/guards.js";
|
|
3
|
+
// WCF JSON date, for example "/Date(1690000000000-0700)/". The offset does not change the instant.
|
|
4
|
+
const WCF_DATE_RE = /^\/?Date\(([+-]?\d+)(?:[+-]\d{4})?\)\/?$/i;
|
|
5
|
+
function toIsoString(epochMs) {
|
|
6
|
+
const date = new Date(epochMs);
|
|
7
|
+
// An out-of-range epoch gives an Invalid Date, and toISOString() would throw.
|
|
8
|
+
return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
|
|
9
|
+
}
|
|
10
|
+
/** Converts a Bing date (WCF string, ISO string, or epoch number) to an ISO string. */
|
|
11
|
+
export function parseBingDate(raw) {
|
|
12
|
+
if (typeof raw === "number") {
|
|
13
|
+
return toIsoString(raw);
|
|
14
|
+
}
|
|
15
|
+
const text = typeof raw === "string" ? raw.trim() : "";
|
|
16
|
+
if (text.length === 0) {
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
const wcf = WCF_DATE_RE.exec(text);
|
|
20
|
+
return toIsoString(wcf?.[1] ? Number(wcf[1]) : Date.parse(text));
|
|
21
|
+
}
|
|
22
|
+
export function toSiteInfo(site) {
|
|
23
|
+
return {
|
|
24
|
+
siteUrl: asString(site.Url, ""),
|
|
25
|
+
permissionLevel: asString(site.Role, "Unknown"),
|
|
26
|
+
engine: "bing",
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Maps a Bing `Feed`. Bing supplies no indexed, error, or warning counts, so those fields stay
|
|
31
|
+
* `undefined` instead of a false 0.
|
|
32
|
+
*/
|
|
33
|
+
export function toSitemapInfo(feed) {
|
|
34
|
+
return {
|
|
35
|
+
path: asString(feed.Url, ""),
|
|
36
|
+
engine: "bing",
|
|
37
|
+
lastSubmitted: parseBingDate(feed.Submitted),
|
|
38
|
+
lastDownloaded: parseBingDate(feed.LastCrawled),
|
|
39
|
+
type: asString(feed.Type, "Sitemap"),
|
|
40
|
+
status: asString(feed.Status, "Submitted"),
|
|
41
|
+
submittedUrls: asOptionalNumber(feed.UrlCount),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** Bing sends -1 when it has no position. Prefer the impression position, then the click one. */
|
|
45
|
+
function toPosition(row) {
|
|
46
|
+
const candidates = [row.AvgImpressionPosition, row.AvgClickPosition].map((value) => asFiniteNumber(value, 0));
|
|
47
|
+
return candidates.find((position) => position > 0) ?? 0;
|
|
48
|
+
}
|
|
49
|
+
function toAggregateRow(key, group) {
|
|
50
|
+
const totals = group.reduce((acc, row) => {
|
|
51
|
+
const impressions = asFiniteNumber(row.Impressions, 0);
|
|
52
|
+
return {
|
|
53
|
+
clicks: acc.clicks + asFiniteNumber(row.Clicks, 0),
|
|
54
|
+
impressions: acc.impressions + impressions,
|
|
55
|
+
weightedPosition: acc.weightedPosition + toPosition(row) * impressions,
|
|
56
|
+
};
|
|
57
|
+
}, { clicks: 0, impressions: 0, weightedPosition: 0 });
|
|
58
|
+
return {
|
|
59
|
+
keys: [key],
|
|
60
|
+
clicks: totals.clicks,
|
|
61
|
+
impressions: totals.impressions,
|
|
62
|
+
ctr: ratio(totals.clicks, totals.impressions),
|
|
63
|
+
position: ratio(totals.weightedPosition, totals.impressions),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
export function rowKey(row) {
|
|
67
|
+
return typeof row.Query === "number" ? String(row.Query) : asString(row.Query, "unknown");
|
|
68
|
+
}
|
|
69
|
+
/** Bing returns one row per key per week. Merge them into one row per key, top clicks first. */
|
|
70
|
+
export function aggregateRows(rows) {
|
|
71
|
+
return [...Map.groupBy(rows, rowKey)]
|
|
72
|
+
.map(([key, group]) => toAggregateRow(key, group))
|
|
73
|
+
.toSorted((a, b) => b.clicks - a.clicks || b.impressions - a.impressions);
|
|
74
|
+
}
|
|
75
|
+
/** Keeps rows whose weekly bucket date is inside the range. Rows without a date are kept. */
|
|
76
|
+
export function isInDateRange(row, startDate, endDate) {
|
|
77
|
+
const day = parseBingDate(row.Date)?.slice(0, 10);
|
|
78
|
+
return day === undefined || (day >= startDate && day <= endDate);
|
|
79
|
+
}
|
|
80
|
+
/** Returns the newest crawl date in a `GetCrawlStats` response. */
|
|
81
|
+
export function latestCrawlDate(entries) {
|
|
82
|
+
return entries
|
|
83
|
+
.map((entry) => parseBingDate(entry.Date))
|
|
84
|
+
.filter(isPresent)
|
|
85
|
+
.toSorted()
|
|
86
|
+
.at(-1);
|
|
87
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export interface BingOperation {
|
|
2
|
+
readonly method: string;
|
|
3
|
+
readonly params?: Readonly<Record<string, string>>;
|
|
4
|
+
/** Set for the methods that take a JSON body. */
|
|
5
|
+
readonly body?: Readonly<Record<string, unknown>>;
|
|
6
|
+
}
|
|
7
|
+
/** Calls one Bing method. Returns a list of plain records, one plain record, or `null`. */
|
|
8
|
+
export declare function readBingOperation(operation: BingOperation): Promise<unknown>;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { asRecordArray, isRecord } from "../../core/guards.js";
|
|
2
|
+
import { bingGet, bingPost, withBingErrors } from "./auth.js";
|
|
3
|
+
import { toPlainRecord } from "./records.js";
|
|
4
|
+
/** The names of the Bing numbers, for all operations. A string value is never renamed. */
|
|
5
|
+
const NAMES = {
|
|
6
|
+
enums: {
|
|
7
|
+
role: ["administrator", "readOnly", "readWrite"],
|
|
8
|
+
blockReason: ["unknown(0)", "adultContent", "copyright", "illegalContent", "other"],
|
|
9
|
+
entityType: ["page", "directory"],
|
|
10
|
+
requestType: ["cacheOnly", "fullRemoval"],
|
|
11
|
+
type: ["page", "directory", "domain", "subdomain"],
|
|
12
|
+
weight: ["disabled", "low", "normal", "high"],
|
|
13
|
+
},
|
|
14
|
+
flags: {
|
|
15
|
+
issues: {
|
|
16
|
+
1: "code301",
|
|
17
|
+
2: "code302",
|
|
18
|
+
4: "code4xx",
|
|
19
|
+
8: "code5xx",
|
|
20
|
+
16: "blockedByRobotsTxt",
|
|
21
|
+
32: "containsMalware",
|
|
22
|
+
64: "importantUrlBlockedByRobotsTxt",
|
|
23
|
+
128: "dnsErrors",
|
|
24
|
+
256: "timeOutErrors",
|
|
25
|
+
},
|
|
26
|
+
},
|
|
27
|
+
// Bing sends -1 when it has no position.
|
|
28
|
+
absentWhenNegative: ["avgClickPosition", "avgImpressionPosition"],
|
|
29
|
+
};
|
|
30
|
+
/** Calls one Bing method. Returns a list of plain records, one plain record, or `null`. */
|
|
31
|
+
export function readBingOperation(operation) {
|
|
32
|
+
return withBingErrors(async () => {
|
|
33
|
+
const { method, params, body } = operation;
|
|
34
|
+
const data = body ? await bingPost(method, body) : await bingGet(method, params);
|
|
35
|
+
if (Array.isArray(data)) {
|
|
36
|
+
return asRecordArray(data).map((record) => toPlainRecord(record, NAMES));
|
|
37
|
+
}
|
|
38
|
+
return isRecord(data) ? toPlainRecord(data, NAMES) : null;
|
|
39
|
+
});
|
|
40
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { SearchEngineProvider } from "../../core/provider.js";
|
|
2
|
+
import type { AnalyticsResult, SearchAnalyticsQuery, SiteInfo, SitemapInfo, UrlInspectionResult } from "../../core/types.js";
|
|
3
|
+
/** The adapter for the Bing Webmaster JSON API. */
|
|
4
|
+
export declare class BingWebmasterProvider implements SearchEngineProvider {
|
|
5
|
+
readonly engine: "bing";
|
|
6
|
+
readonly displayName = "Bing Webmaster Tools";
|
|
7
|
+
readonly authMethod = "API Key (BING_WEBMASTER_API_KEY)";
|
|
8
|
+
isConfigured(): boolean;
|
|
9
|
+
getConfigurationGuide(): string;
|
|
10
|
+
listSites(): Promise<SiteInfo[]>;
|
|
11
|
+
queryAnalytics(query: SearchAnalyticsQuery): Promise<AnalyticsResult>;
|
|
12
|
+
/** Bing has no URL-level inspection. The result is UNKNOWN, with site-level crawl context. */
|
|
13
|
+
inspectUrl(siteUrl: string, url: string): Promise<UrlInspectionResult>;
|
|
14
|
+
listSitemaps(siteUrl: string): Promise<SitemapInfo[]>;
|
|
15
|
+
getSitemap(siteUrl: string, feedpath: string): Promise<SitemapInfo>;
|
|
16
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { summarizeRows } from "../../core/analytics.js";
|
|
2
|
+
import { createTextMatcher, parseTextFilter } from "../../core/filters.js";
|
|
3
|
+
import { asRecordArray } from "../../core/guards.js";
|
|
4
|
+
import { clampRowLimit, clampStartRow, normalizeSitemapKey, requireText, validateDateRange, } from "../../core/validation.js";
|
|
5
|
+
import { BING_SETUP_GUIDE, bingGet, isBingConfigured, withBingErrors } from "./auth.js";
|
|
6
|
+
import { aggregateRows, isInDateRange, latestCrawlDate, rowKey, toSiteInfo, toSitemapInfo, } from "./mappers.js";
|
|
7
|
+
const BING_MAX_ROWS = 5000;
|
|
8
|
+
const DEFAULT_ROW_LIMIT = 100;
|
|
9
|
+
function resolveMode(query) {
|
|
10
|
+
const dimensions = query.dimensions ?? [];
|
|
11
|
+
const wantsPages = dimensions.includes("page") && !dimensions.includes("query");
|
|
12
|
+
const filtersPages = Boolean(query.pageFilter) && !query.queryFilter;
|
|
13
|
+
return wantsPages || filtersPages ? "page" : "query";
|
|
14
|
+
}
|
|
15
|
+
/** Explains every requested option that Bing cannot honor. */
|
|
16
|
+
function buildNotes(query, mode) {
|
|
17
|
+
const otherDimensions = (query.dimensions ?? []).filter((dimension) => dimension !== mode);
|
|
18
|
+
const rules = [
|
|
19
|
+
[
|
|
20
|
+
mode === "page" && Boolean(query.queryFilter),
|
|
21
|
+
"queryFilter was ignored because page mode was active.",
|
|
22
|
+
],
|
|
23
|
+
[
|
|
24
|
+
mode === "query" && Boolean(query.pageFilter),
|
|
25
|
+
"pageFilter was ignored because query mode was active. Specify dimensions: ['page'] to query page stats.",
|
|
26
|
+
],
|
|
27
|
+
[Boolean(query.countryFilter), "countryFilter is ignored for Bing."],
|
|
28
|
+
[Boolean(query.deviceFilter), "deviceFilter is ignored for Bing."],
|
|
29
|
+
[
|
|
30
|
+
query.searchType !== undefined && query.searchType !== "web",
|
|
31
|
+
`searchType '${query.searchType}' is not supported by Bing; web results returned.`,
|
|
32
|
+
],
|
|
33
|
+
[
|
|
34
|
+
query.dataState !== undefined && query.dataState !== "all",
|
|
35
|
+
`dataState '${query.dataState}' is ignored for Bing.`,
|
|
36
|
+
],
|
|
37
|
+
[
|
|
38
|
+
otherDimensions.length > 0,
|
|
39
|
+
`Bing returns single-dimension statistics (${mode}). Additional requested dimensions are not supported.`,
|
|
40
|
+
],
|
|
41
|
+
[
|
|
42
|
+
true,
|
|
43
|
+
`Bing returns weekly bucketed statistics. Data was filtered client-side between ${query.startDate} and ${query.endDate} and aggregated per ${mode}.`,
|
|
44
|
+
],
|
|
45
|
+
];
|
|
46
|
+
return rules.filter(([applies]) => applies).map(([, note]) => note);
|
|
47
|
+
}
|
|
48
|
+
function createRowFilter(query, mode) {
|
|
49
|
+
const rawFilter = mode === "page" ? query.pageFilter : query.queryFilter;
|
|
50
|
+
const matches = rawFilter
|
|
51
|
+
? createTextMatcher(parseTextFilter(rawFilter, `${mode}Filter`))
|
|
52
|
+
: () => true;
|
|
53
|
+
return (row) => isInDateRange(row, query.startDate, query.endDate) && matches(rowKey(row));
|
|
54
|
+
}
|
|
55
|
+
/** The adapter for the Bing Webmaster JSON API. */
|
|
56
|
+
export class BingWebmasterProvider {
|
|
57
|
+
engine = "bing";
|
|
58
|
+
displayName = "Bing Webmaster Tools";
|
|
59
|
+
authMethod = "API Key (BING_WEBMASTER_API_KEY)";
|
|
60
|
+
isConfigured() {
|
|
61
|
+
return isBingConfigured();
|
|
62
|
+
}
|
|
63
|
+
getConfigurationGuide() {
|
|
64
|
+
return BING_SETUP_GUIDE;
|
|
65
|
+
}
|
|
66
|
+
listSites() {
|
|
67
|
+
return withBingErrors(async () => asRecordArray(await bingGet("GetUserSites")).map(toSiteInfo));
|
|
68
|
+
}
|
|
69
|
+
queryAnalytics(query) {
|
|
70
|
+
return withBingErrors(async () => {
|
|
71
|
+
validateDateRange(query.startDate, query.endDate);
|
|
72
|
+
const siteUrl = requireText(query.siteUrl, "siteUrl");
|
|
73
|
+
const mode = resolveMode(query);
|
|
74
|
+
const endpoint = mode === "page" ? "GetPageStats" : "GetQueryStats";
|
|
75
|
+
const keepRow = createRowFilter(query, mode);
|
|
76
|
+
const rows = aggregateRows(asRecordArray(await bingGet(endpoint, { siteUrl })).filter(keepRow));
|
|
77
|
+
const effectiveLimit = clampRowLimit(query.rowLimit, BING_MAX_ROWS, DEFAULT_ROW_LIMIT);
|
|
78
|
+
const startRow = clampStartRow(query.startRow);
|
|
79
|
+
const paged = rows.slice(startRow, startRow + effectiveLimit);
|
|
80
|
+
return {
|
|
81
|
+
engine: this.engine,
|
|
82
|
+
siteUrl: query.siteUrl,
|
|
83
|
+
startDate: query.startDate,
|
|
84
|
+
endDate: query.endDate,
|
|
85
|
+
columns: [mode],
|
|
86
|
+
summary: summarizeRows(paged),
|
|
87
|
+
rows: paged,
|
|
88
|
+
effectiveLimit,
|
|
89
|
+
note: buildNotes(query, mode).join(" "),
|
|
90
|
+
};
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
/** Bing has no URL-level inspection. The result is UNKNOWN, with site-level crawl context. */
|
|
94
|
+
inspectUrl(siteUrl, url) {
|
|
95
|
+
return withBingErrors(async () => {
|
|
96
|
+
if (!isBingConfigured()) {
|
|
97
|
+
throw new Error(BING_SETUP_GUIDE);
|
|
98
|
+
}
|
|
99
|
+
const site = requireText(siteUrl, "siteUrl");
|
|
100
|
+
const inspectionUrl = requireText(url, "inspectionUrl");
|
|
101
|
+
const crawlStats = await bingGet("GetCrawlStats", { siteUrl: site }).catch(
|
|
102
|
+
// Crawl stats are best-effort context. The inspection stays UNKNOWN without them.
|
|
103
|
+
() => []);
|
|
104
|
+
return {
|
|
105
|
+
engine: this.engine,
|
|
106
|
+
inspectionUrl,
|
|
107
|
+
siteUrl: site,
|
|
108
|
+
verdict: "UNKNOWN",
|
|
109
|
+
coverageState: "UNKNOWN: Bing Webmaster API does not provide URL-level inspection. Site crawl context is provided at property level.",
|
|
110
|
+
siteLastCrawlTime: latestCrawlDate(asRecordArray(crawlStats)),
|
|
111
|
+
referringUrls: [],
|
|
112
|
+
sitemaps: [],
|
|
113
|
+
};
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
listSitemaps(siteUrl) {
|
|
117
|
+
return withBingErrors(async () => {
|
|
118
|
+
const site = requireText(siteUrl, "siteUrl");
|
|
119
|
+
return asRecordArray(await bingGet("GetFeeds", { siteUrl: site })).map(toSitemapInfo);
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
async getSitemap(siteUrl, feedpath) {
|
|
123
|
+
const feed = requireText(feedpath, "feedpath");
|
|
124
|
+
const target = normalizeSitemapKey(feed);
|
|
125
|
+
const sitemaps = await this.listSitemaps(siteUrl);
|
|
126
|
+
const found = sitemaps.find((sitemap) => normalizeSitemapKey(sitemap.path) === target);
|
|
127
|
+
if (!found) {
|
|
128
|
+
throw new Error(`Sitemap feed "${feed}" not found in Bing Webmaster Tools for ${siteUrl.trim()}`);
|
|
129
|
+
}
|
|
130
|
+
return found;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** How to name the numbers of one Bing response. Keys are the `lowerCamelCase` field names. */
|
|
2
|
+
export interface RecordNames {
|
|
3
|
+
/** The array index is the Bing number. */
|
|
4
|
+
readonly enums?: Readonly<Record<string, readonly string[]>>;
|
|
5
|
+
/** The object key is the Bing bit. */
|
|
6
|
+
readonly flags?: Readonly<Record<string, Readonly<Record<number, string>>>>;
|
|
7
|
+
/** Fields in which a negative number means that Bing has no value. */
|
|
8
|
+
readonly absentWhenNegative?: readonly string[];
|
|
9
|
+
}
|
|
10
|
+
/** Converts a Bing object: `lowerCamelCase` fields, no `__type`, ISO dates, named numbers. */
|
|
11
|
+
export declare function toPlainRecord(record: Readonly<Record<string, unknown>>, names?: RecordNames): Record<string, unknown>;
|