search-console-axi 0.1.3 → 0.1.4

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 CHANGED
@@ -57,6 +57,27 @@ Submit requires an explicit `--site` naming the exact property, even if a defaul
57
57
 
58
58
  Submission requests `https://www.googleapis.com/auth/webmasters`; reads still request only `webmasters.readonly`. Read-only user ADC cannot submit: explicitly reauthorize your own Desktop OAuth client with the write scope. Existing refresh tokens are never silently widened. The authenticated account also needs permission to submit sitemaps on the property; Restricted access is not sufficient. No confirmed live submissions should be used for development or tests.
59
59
 
60
+ ## List pages by indexing state
61
+
62
+ `coverage` reads URL Inspection for URLs you supply. The API does not expose the Page indexing report or its example URLs. Results describe Google's indexed version, not a live inspection or an exhaustive list of a property's pages.
63
+
64
+ ```sh
65
+ search-console-axi coverage --sitemap https://example.com/sitemap.xml --site sc-domain:example.com
66
+ search-console-axi coverage urls.txt --state /tmp/example-coverage.json
67
+ search-console-axi coverage - --format json < urls.txt
68
+ search-console-axi coverage urls.txt --format csv > coverage.csv
69
+ ```
70
+
71
+ File and stdin input contain one absolute HTTP or HTTPS URL per line. Blank lines are ignored and duplicates are inspected once. URLs outside the selected property are reported as skipped (`out of property`) without consuming inspection quota. Domain properties include subdomains; URL-prefix properties restrict requests to their origin and path. Narrow the input or select the matching property to inspect skipped URLs. An exact verified `--site` is preferred over broader properties. Sitemap input supports XML sitemap indexes, child sitemaps, and gzip. Index cycles are ignored. A run accepts at most 1,000 sitemap documents, each up to 50 MiB uncompressed, and 100,000 total sitemap entries. HTTP redirects are rejected, and child sitemaps must share the root sitemap's origin. To use a trusted external sitemap, invoke coverage with that sitemap directly. DTDs are rejected. Coverage never submits URLs or calls the Indexing API.
72
+
73
+ TOON output groups counts and URL lists by `coverageState`, `verdict`, Google's canonical URL (or `unknown`), canonical match (`same`, `different`, or `unknown`), and last-crawl age. Crawl buckets are under 7 days, 7–29 days, 30 days or older, and unknown. Missing canonical fields do not imply a mismatch. JSON output includes per-URL rows plus progress and quota metadata. CSV output contains per-URL rows on stdout and TOON progress metadata on stderr. Exports retain the documented field names `coverageState`, `verdict`, `googleCanonical`, `userCanonical`, and `lastCrawlTime`, plus `url` and `inspectedAt`.
74
+
75
+ Google's [URL Inspection limits](https://developers.google.com/webmaster-tools/limits#url_inspection) are 2,000 requests per property per day and 600 per minute. Coverage spaces requests at least 110 ms apart and uses a conservative rolling 24-hour local budget. It reserves quota before each attempt, including failed or interrupted requests. A shared per-property ledger prevents separate progress files from resetting local accounting. External usage is unknown, not reported as zero. Any API quota error stops the run and conservatively pauses that property for 24 hours. Output reports requests inspected in this run, URLs remaining, locally observed attempts, and the earliest local resume time. A quota stop exits successfully with partial results; check `remaining` and `stop` before treating an export as complete.
76
+
77
+ Rerun the same command to resume. Finished URLs are not inspected again unless you pass `--refresh`; refresh does not reset quota. A refresh pass saves its target URLs and completed URLs, so rerunning an interrupted or quota-limited pass continues the unfinished targets, even without `--refresh`. Once that pass finishes, `--refresh` starts a new one. Keep the same input when resuming a pass. Each result is appended to a private `<state>.jsonl` journal, then compacted into the state snapshot once the run ends. Interrupted final journal records are discarded, while committed rows are replayed on resume. Snapshot compaction and quota accounting use atomic file replacement. Keep the journal alongside the snapshot until compaction removes it. The default state lives under `$XDG_STATE_HOME/search-console-axi/coverage`, or `~/.local/state/search-console-axi/coverage`, never the repository. `--state` names a different progress file but leaves quota accounting in the user state directory. Do not delete the ledger to bypass limits. Progress files belong to one property and contain URL data; protect them accordingly.
78
+
79
+ Ctrl-C and SIGTERM finish the in-flight inspection, save it, and stop before the next URL. Concurrent runs for the same property or progress file fail with a lock error. After a forced kill, remove only the lock file named by the error, and only after confirming no coverage process is running. The saved results remain intact.
80
+
60
81
  ## Send Indexing API notifications
61
82
 
62
83
  Google supports the [Indexing API](https://developers.google.com/search/apis/indexing-api/v3/using-api) only for pages with `JobPosting` or `BroadcastEvent` embedded in `VideoObject` structured data. Job-posting pages fit this scope. It is not a general-purpose indexing API. A successful submission acknowledges a notification, not a crawl or index guarantee.
package/dist/src/cli.js CHANGED
@@ -3,6 +3,7 @@ import { encode } from "@toon-format/toon";
3
3
  import { command as setup } from "./commands/setup.js";
4
4
  import { command as report } from "./commands/report.js";
5
5
  import { command as inspect } from "./commands/inspect.js";
6
+ import { command as coverage } from "./commands/coverage.js";
6
7
  import { command as indexing } from "./commands/indexing.js";
7
8
  import { command as sitemaps } from "./commands/sitemaps.js";
8
9
  import { usage } from "./args.js";
@@ -11,7 +12,7 @@ import { getAuthClient, setupCommand } from "./auth.js";
11
12
  import { runHome } from "./google.js";
12
13
  import { resolveSite } from "./site.js";
13
14
  const description = "Google Search Console reporting, sitemaps, URL inspection, and preview-gated Indexing API notifications for agents";
14
- export const commands = [setup, report, inspect, indexing, sitemaps];
15
+ export const commands = [setup, report, inspect, coverage, indexing, sitemaps];
15
16
  const registry = new Map(commands.map((command) => [command.name, command]));
16
17
  export function getCommandHelp(args) {
17
18
  if (!args.length)
@@ -0,0 +1,75 @@
1
+ import { decode, encode } from "@toon-format/toon";
2
+ import { parseArgs, usage } from "../args.js";
3
+ import { getAuthClient } from "../auth.js";
4
+ import { inspectUrl } from "../google.js";
5
+ import { resolveSite, validateSite } from "../site.js";
6
+ import { helpText } from "../help.js";
7
+ import { readUrls, validateUrl } from "../coverage-input.js";
8
+ import { collectCoverage, coverageCsv, groupCoverage } from "../coverage.js";
9
+ export const help = {
10
+ purpose: "Read URL Inspection coverage for explicit URLs (not the Page indexing report). Saves progress locally; rerun to resume.",
11
+ flags: {
12
+ "--sitemap <url>": "Fetch a sitemap or sitemap index; mutually exclusive with file/stdin input",
13
+ "--site <site>": "Prefer exact verified property; out-of-property URLs are skipped (default: configured or first verified)",
14
+ "--state <file>": "Progress file; default: user state directory, per property",
15
+ "--refresh": "Start or resume a refresh pass without resetting quota accounting",
16
+ "--format <toon|json|csv>": "Default toon: grouped counts and URL lists; json/csv: per-URL rows",
17
+ "--quota-project <id>": "Set quota project",
18
+ "--help": "Show help",
19
+ },
20
+ examples: [
21
+ "search-console-axi coverage --sitemap https://example.com/sitemap.xml --site sc-domain:example.com",
22
+ "search-console-axi coverage urls.txt --state coverage.json --format json",
23
+ "search-console-axi coverage - --format csv < urls.txt",
24
+ ],
25
+ next: ["search-console-axi inspect <url>", "search-console-axi coverage --help"],
26
+ };
27
+ export async function run(args = []) {
28
+ const parsed = parseArgs(args, ["--sitemap", "--site", "--state", "--format", "--quota-project"], ["--refresh"]);
29
+ const value = (flag) => {
30
+ const v = parsed.flags.get(flag);
31
+ return typeof v === "string" ? v : undefined;
32
+ };
33
+ const sitemap = value("--sitemap");
34
+ if (sitemap ? parsed.positionals.length !== 0 : parsed.positionals.length !== 1)
35
+ usage("usage: search-console-axi coverage <file|-> OR coverage --sitemap <url>");
36
+ if (sitemap)
37
+ validateUrl(sitemap);
38
+ const format = value("--format") ?? "toon";
39
+ if (!["toon", "json", "csv"].includes(format))
40
+ usage("--format must be toon, json or csv");
41
+ const requestedSite = value("--site");
42
+ if (requestedSite)
43
+ validateSite(requestedSite);
44
+ const urls = await readUrls(sitemap ? { sitemap } : { file: parsed.positionals[0] });
45
+ const auth = await getAuthClient({ quotaProject: value("--quota-project") });
46
+ const resolution = await resolveSite(auth, requestedSite);
47
+ if (resolution.kind === "unavailable")
48
+ usage("No verified Search Console sites visible; configure --site or grant access.");
49
+ const result = await collectCoverage({
50
+ site: resolution.site,
51
+ urls,
52
+ state: value("--state"),
53
+ refresh: parsed.flags.has("--refresh"),
54
+ inspect: async (url) => decode(await inspectUrl(auth, url, resolution.site)),
55
+ });
56
+ const output = {
57
+ ...result,
58
+ help: [
59
+ ...(result.remaining ? ["Rerun the same command after quota is available; finished URLs are saved."] : []),
60
+ ...(result.skipped.length
61
+ ? ["Out-of-property URLs were skipped; narrow the input or select their property with --site."]
62
+ : []),
63
+ ],
64
+ };
65
+ if (format === "json")
66
+ return JSON.stringify(output);
67
+ const { rows, ...summary } = output;
68
+ if (format === "csv") {
69
+ process.stderr.write(encode(summary) + "\n");
70
+ return coverageCsv(rows);
71
+ }
72
+ return encode({ ...summary, groups: groupCoverage(rows) });
73
+ }
74
+ export const name = "coverage";
75
+ export const command = { name, help: helpText(name, help), run };
@@ -0,0 +1,121 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { gunzipSync } from "node:zlib";
3
+ import { XMLParser, XMLValidator } from "fast-xml-parser";
4
+ import { AxiError } from "axi-sdk-js";
5
+ import { usage } from "./args.js";
6
+ const MAX_SITEMAP_ENTRIES = 100_000;
7
+ export function validateUrl(value) {
8
+ let url;
9
+ try {
10
+ url = new URL(value);
11
+ }
12
+ catch {
13
+ return usage("coverage requires absolute HTTP(S) URLs");
14
+ }
15
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash || /\s/.test(value))
16
+ usage("coverage URLs must be HTTP(S), without credentials, fragments or whitespace");
17
+ return value;
18
+ }
19
+ function object(value) {
20
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
21
+ }
22
+ export async function readUrls(source) {
23
+ if ("file" in source) {
24
+ let text;
25
+ try {
26
+ if (source.file === "-") {
27
+ process.stdin.setEncoding("utf8");
28
+ text = "";
29
+ for await (const chunk of process.stdin)
30
+ text += chunk;
31
+ }
32
+ else
33
+ text = await readFile(source.file, "utf8");
34
+ }
35
+ catch {
36
+ throw new AxiError("Cannot read URL input; provide a readable file or stdin.", "INPUT_ERROR");
37
+ }
38
+ return [
39
+ ...new Set(text
40
+ .split(/\r?\n/)
41
+ .map((line) => line.trim())
42
+ .filter(Boolean)
43
+ .map(validateUrl)),
44
+ ];
45
+ }
46
+ const rootOrigin = new URL(validateUrl(source.sitemap)).origin;
47
+ const pending = [source.sitemap];
48
+ const visited = new Set();
49
+ const urls = new Set();
50
+ let entryCount = 0;
51
+ const parser = new XMLParser({
52
+ ignoreAttributes: true,
53
+ removeNSPrefix: true,
54
+ parseTagValue: false,
55
+ processEntities: true,
56
+ });
57
+ while (pending.length) {
58
+ const sitemap = pending.pop();
59
+ if (visited.has(sitemap))
60
+ continue;
61
+ if (visited.size >= 1000)
62
+ usage("Sitemap index exceeds 1000 documents; use a URL file instead.");
63
+ visited.add(sitemap);
64
+ let xml;
65
+ try {
66
+ const response = await fetch(sitemap, { redirect: "error", signal: AbortSignal.timeout(30_000) });
67
+ if (!response.ok)
68
+ throw new Error();
69
+ if (!response.body)
70
+ throw new Error();
71
+ const reader = response.body.getReader();
72
+ const chunks = [];
73
+ let size = 0;
74
+ while (true) {
75
+ const { done, value } = await reader.read();
76
+ if (done)
77
+ break;
78
+ size += value.byteLength;
79
+ if (size > 52_428_800) {
80
+ await reader.cancel();
81
+ throw new Error();
82
+ }
83
+ chunks.push(value);
84
+ }
85
+ const bytes = Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)), size);
86
+ xml = (bytes[0] === 0x1f && bytes[1] === 0x8b ? gunzipSync(bytes, { maxOutputLength: 52_428_800 }) : bytes).toString("utf8");
87
+ }
88
+ catch {
89
+ throw new AxiError("Cannot fetch sitemap; check its URL and network access.", "INPUT_ERROR");
90
+ }
91
+ if (/<!DOCTYPE|<!ENTITY/i.test(xml) || XMLValidator.validate(xml) !== true)
92
+ usage("Invalid sitemap XML (DTDs are not supported).");
93
+ for (const match of xml.matchAll(/<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<(?:[^\s<>/:]+:)?(?:url|sitemap)(?=[\s/>])/g)) {
94
+ if (match[0].startsWith("<") && !match[0].startsWith("<!--") && !match[0].startsWith("<![CDATA[")) {
95
+ if (++entryCount > MAX_SITEMAP_ENTRIES)
96
+ usage("Sitemap exceeds 100000 total entries.");
97
+ }
98
+ }
99
+ const doc = object(parser.parse(xml));
100
+ const index = "sitemapindex" in doc;
101
+ if (!index && !("urlset" in doc))
102
+ usage("Sitemap must contain urlset or sitemapindex.");
103
+ const root = object(doc[index ? "sitemapindex" : "urlset"]);
104
+ const entries = root[index ? "sitemap" : "url"];
105
+ const list = entries === undefined ? [] : Array.isArray(entries) ? entries : [entries];
106
+ for (const entry of list) {
107
+ const loc = object(entry).loc;
108
+ if (typeof loc !== "string" || !loc.trim())
109
+ usage("Every sitemap entry requires a loc URL.");
110
+ const url = validateUrl(loc.trim());
111
+ if (index) {
112
+ if (new URL(url).origin !== rootOrigin)
113
+ usage("Child sitemaps must share the root sitemap origin.");
114
+ pending.push(url);
115
+ }
116
+ else
117
+ urls.add(url);
118
+ }
119
+ }
120
+ return [...urls];
121
+ }
@@ -0,0 +1,137 @@
1
+ import { appendFile, readFile, rename, unlink, writeFile } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import { AxiError } from "axi-sdk-js";
4
+ function object(value) {
5
+ if (!value || typeof value !== "object" || Array.isArray(value))
6
+ throw new Error("Expected object");
7
+ return value;
8
+ }
9
+ function strings(value) {
10
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
11
+ }
12
+ function parseRow(value) {
13
+ const row = object(value);
14
+ if (!["url", "inspectedAt", "coverageState", "verdict", "googleCanonical", "userCanonical", "lastCrawlTime"].every((key) => typeof row[key] === "string"))
15
+ throw new Error("Invalid row");
16
+ return row;
17
+ }
18
+ function parseRefresh(value) {
19
+ const refresh = object(value);
20
+ if (typeof refresh.id !== "string" || !strings(refresh.urls) || !strings(refresh.done))
21
+ throw new Error("Invalid refresh");
22
+ return { id: refresh.id, urls: refresh.urls, done: refresh.done };
23
+ }
24
+ function parseSnapshot(value, site) {
25
+ const state = object(value);
26
+ if (state.version !== 1 || state.site !== site || !Array.isArray(state.rows))
27
+ throw new Error("State mismatch");
28
+ return {
29
+ version: 1,
30
+ site,
31
+ rows: state.rows.map(parseRow),
32
+ ...(state.refresh === undefined ? {} : { refresh: parseRefresh(state.refresh) }),
33
+ };
34
+ }
35
+ function parseEvent(value) {
36
+ const event = object(value);
37
+ if (event.kind === "row" && (event.refresh === null || typeof event.refresh === "string"))
38
+ return { kind: "row", row: parseRow(event.row), refresh: event.refresh };
39
+ if (event.kind === "refresh" && typeof event.id === "string" && strings(event.urls))
40
+ return { kind: "refresh", id: event.id, urls: event.urls };
41
+ throw new Error("Invalid journal event");
42
+ }
43
+ export async function readJson(path, empty, parse) {
44
+ try {
45
+ return parse(JSON.parse(await readFile(path, "utf8")));
46
+ }
47
+ catch (error) {
48
+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT")
49
+ return empty;
50
+ throw new AxiError("Cannot read coverage state or quota ledger; restore a valid file before retrying.", "STATE_ERROR");
51
+ }
52
+ }
53
+ async function replace(path, data) {
54
+ const temp = `${path}.${randomUUID()}.tmp`;
55
+ try {
56
+ await writeFile(temp, data, { mode: 0o600, flag: "wx" });
57
+ await rename(temp, path);
58
+ }
59
+ finally {
60
+ await unlink(temp).catch(() => { });
61
+ }
62
+ }
63
+ export async function saveJson(path, value) {
64
+ await replace(path, JSON.stringify(value));
65
+ }
66
+ // Each successful row is a durable journal record. Compaction publishes the snapshot
67
+ // before removing the journal; replaying both after a crash is idempotent.
68
+ export async function openCoverageState(path, site) {
69
+ const loaded = await readJson(path, undefined, (value) => parseSnapshot(value, site));
70
+ const snapshot = loaded ?? { version: 1, site, rows: [] };
71
+ if (!loaded)
72
+ await saveJson(path, snapshot);
73
+ const rows = new Map(snapshot.rows.map((row) => [row.url, row]));
74
+ let refresh = snapshot.refresh;
75
+ let done = new Set(refresh?.done);
76
+ const journal = `${path}.jsonl`;
77
+ const apply = (event) => {
78
+ if (event.kind === "refresh") {
79
+ refresh = { id: event.id, urls: event.urls, done: [] };
80
+ done = new Set();
81
+ }
82
+ else {
83
+ rows.set(event.row.url, event.row);
84
+ if (refresh?.id === event.refresh)
85
+ done.add(event.row.url);
86
+ }
87
+ };
88
+ try {
89
+ const text = await readFile(journal, "utf8");
90
+ const committed = text.slice(0, text.lastIndexOf("\n") + 1);
91
+ for (const line of committed.split("\n").filter(Boolean))
92
+ apply(parseEvent(JSON.parse(line)));
93
+ // A killed append can leave an uncommitted partial final record. Remove only that tail.
94
+ if (committed.length !== text.length)
95
+ await replace(journal, committed);
96
+ }
97
+ catch (error) {
98
+ if (!(error && typeof error === "object" && "code" in error && error.code === "ENOENT"))
99
+ throw new AxiError("Cannot read coverage journal; restore a valid file before retrying.", "STATE_ERROR");
100
+ }
101
+ const append = async (event) => {
102
+ await appendFile(journal, JSON.stringify(event) + "\n", { mode: 0o600 });
103
+ apply(event);
104
+ };
105
+ const finishRefresh = () => {
106
+ if (refresh?.urls.every((url) => done.has(url))) {
107
+ refresh = undefined;
108
+ done.clear();
109
+ }
110
+ };
111
+ finishRefresh();
112
+ return {
113
+ rows,
114
+ async pending(urls, requestedRefresh) {
115
+ if (requestedRefresh && !refresh)
116
+ await append({ kind: "refresh", id: randomUUID(), urls });
117
+ const targets = new Set(refresh?.urls);
118
+ return urls.filter((url) => !rows.has(url) || (targets.has(url) && !done.has(url)));
119
+ },
120
+ async record(row) {
121
+ await append({ kind: "row", row, refresh: refresh?.id ?? null });
122
+ },
123
+ async compact() {
124
+ finishRefresh();
125
+ await saveJson(path, {
126
+ version: 1,
127
+ site,
128
+ rows: [...rows.values()],
129
+ ...(refresh ? { refresh: { ...refresh, done: [...done] } } : {}),
130
+ });
131
+ await unlink(journal).catch((error) => {
132
+ if (error.code !== "ENOENT")
133
+ throw error;
134
+ });
135
+ },
136
+ };
137
+ }
@@ -0,0 +1,233 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdir, unlink, writeFile } from "node:fs/promises";
3
+ import { dirname, isAbsolute, join, resolve } from "node:path";
4
+ import { homedir } from "node:os";
5
+ import { setTimeout } from "node:timers/promises";
6
+ import { AxiError } from "axi-sdk-js";
7
+ import { openCoverageState, readJson as load, saveJson as save } from "./coverage-state.js";
8
+ import { matchesSite } from "./site.js";
9
+ // Official per-property URL Inspection limits: 2,000/day, 600/minute.
10
+ // https://developers.google.com/webmaster-tools/limits#url_inspection
11
+ export const DAILY_LIMIT = 2000;
12
+ export const INTERVAL_MS = 110; // Below 600/minute, including across resumed runs.
13
+ const DAY = 86_400_000;
14
+ const fields = ["coverageState", "verdict", "googleCanonical", "userCanonical", "lastCrawlTime"];
15
+ function record(value) {
16
+ if (!value || typeof value !== "object" || Array.isArray(value))
17
+ throw new Error("Expected object");
18
+ return value;
19
+ }
20
+ // Fields documented at https://developers.google.com/webmaster-tools/v1/urlInspection.index/UrlInspectionResult
21
+ export function inspectionRow(url, value, now) {
22
+ const result = record(value);
23
+ const status = record(result.indexStatusResult ?? {});
24
+ const text = (key) => {
25
+ const value = status[key];
26
+ if (value !== undefined && typeof value !== "string")
27
+ throw new Error("Invalid inspection field");
28
+ return value ?? "";
29
+ };
30
+ return {
31
+ url,
32
+ inspectedAt: new Date(now).toISOString(),
33
+ coverageState: text("coverageState"),
34
+ verdict: text("verdict"),
35
+ googleCanonical: text("googleCanonical"),
36
+ userCanonical: text("userCanonical"),
37
+ lastCrawlTime: text("lastCrawlTime"),
38
+ };
39
+ }
40
+ async function lock(path) {
41
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
42
+ // Never guess whether a concurrent writer is alive. A crash leaves a removable lock, not corrupt state.
43
+ try {
44
+ await writeFile(path, String(process.pid), { flag: "wx", mode: 0o600 });
45
+ }
46
+ catch {
47
+ throw new AxiError(`Coverage state is locked or unwritable: ${path}. If no coverage process is running, remove the stale lock and retry.`, "STATE_ERROR");
48
+ }
49
+ return () => unlink(path);
50
+ }
51
+ export function coveragePaths(site, state) {
52
+ const xdg = process.env.XDG_STATE_HOME;
53
+ const root = join(xdg && isAbsolute(xdg) ? xdg : join(homedir(), ".local", "state"), "search-console-axi", "coverage");
54
+ const id = createHash("sha256").update(site).digest("hex");
55
+ return { state: resolve(state ?? join(root, `${id}.json`)), ledger: join(root, `${id}.quota.json`) };
56
+ }
57
+ function parseLedger(value) {
58
+ const ledger = record(value);
59
+ if (!Array.isArray(ledger.attempts) ||
60
+ !ledger.attempts.every((time) => typeof time === "number" && Number.isFinite(time) && time >= 0) ||
61
+ typeof ledger.blockedUntil !== "number" ||
62
+ !Number.isFinite(ledger.blockedUntil))
63
+ throw new Error("Invalid ledger");
64
+ return { attempts: ledger.attempts, blockedUntil: ledger.blockedUntil };
65
+ }
66
+ export function isQuotaError(error) {
67
+ if (!error || typeof error !== "object" || !("response" in error))
68
+ return false;
69
+ if (!error.response || typeof error.response !== "object")
70
+ return false;
71
+ const response = record(error.response);
72
+ if (response.status === 429)
73
+ return true;
74
+ if (response.status !== 403)
75
+ return false;
76
+ return /quotaExceeded|dailyLimitExceeded|rateLimitExceeded|userRateLimitExceeded|RESOURCE_EXHAUSTED|RATE_LIMIT_EXCEEDED|QUOTA_EXCEEDED/.test(JSON.stringify(response.data));
77
+ }
78
+ export async function collectCoverage(options) {
79
+ const now = options.now ?? Date.now;
80
+ const monotonicNow = options.monotonicNow ?? (() => performance.now());
81
+ const sleep = options.sleep ?? setTimeout;
82
+ const paths = coveragePaths(options.site, options.state);
83
+ if (paths.state === paths.ledger || paths.state === `${paths.ledger}.lock`)
84
+ throw new AxiError("State path conflicts with quota ledger.", "VALIDATION_ERROR");
85
+ const unlockLedger = await lock(`${paths.ledger}.lock`);
86
+ let unlockState;
87
+ let store;
88
+ const acquiredAt = monotonicNow();
89
+ let interrupted = false;
90
+ const interrupt = () => {
91
+ interrupted = true;
92
+ };
93
+ process.on("SIGINT", interrupt);
94
+ process.on("SIGTERM", interrupt);
95
+ try {
96
+ unlockState = await lock(`${paths.state}.lock`);
97
+ store = await openCoverageState(paths.state, options.site);
98
+ const ledger = await load(paths.ledger, { attempts: [], blockedUntil: 0 }, parseLedger);
99
+ ledger.attempts = ledger.attempts.map((time) => Math.min(time, now()));
100
+ const rows = store.rows;
101
+ const allUrls = [...new Set(options.urls)];
102
+ const skipped = allUrls
103
+ .filter((url) => !matchesSite(url, options.site))
104
+ .map((url) => ({ url, reason: "out of property" }));
105
+ const urls = allUrls.filter((url) => matchesSite(url, options.site));
106
+ const pending = await store.pending(urls, options.refresh ?? false);
107
+ let inspected = 0;
108
+ let lastRequestAt = acquiredAt;
109
+ let stop = "complete";
110
+ for (const url of pending) {
111
+ if (interrupted) {
112
+ stop = "interrupted";
113
+ break;
114
+ }
115
+ ledger.attempts = ledger.attempts.filter((time) => time > now() - DAY);
116
+ if (ledger.blockedUntil > now()) {
117
+ stop = "api_quota";
118
+ break;
119
+ }
120
+ if (ledger.attempts.length >= DAILY_LIMIT) {
121
+ stop = "daily_limit";
122
+ break;
123
+ }
124
+ while (monotonicNow() - lastRequestAt < INTERVAL_MS && !interrupted)
125
+ await sleep(INTERVAL_MS - (monotonicNow() - lastRequestAt));
126
+ if (interrupted) {
127
+ stop = "interrupted";
128
+ break;
129
+ }
130
+ // Reserve quota before sending: interruptions and failed calls must not refund an attempt.
131
+ ledger.attempts.push(now());
132
+ await save(paths.ledger, ledger);
133
+ if (interrupted) {
134
+ stop = "interrupted";
135
+ break;
136
+ }
137
+ let result;
138
+ try {
139
+ lastRequestAt = monotonicNow();
140
+ result = await options.inspect(url);
141
+ }
142
+ catch (error) {
143
+ if (isQuotaError(error)) {
144
+ ledger.blockedUntil = now() + DAY;
145
+ await save(paths.ledger, ledger);
146
+ stop = "api_quota";
147
+ break;
148
+ }
149
+ throw new AxiError("URL Inspection failed; progress was saved. Check access and network, then rerun the same command.", "API_ERROR");
150
+ }
151
+ const row = inspectionRow(url, result, now());
152
+ await store.record(row);
153
+ inspected++;
154
+ if (interrupted) {
155
+ stop = "interrupted";
156
+ break;
157
+ }
158
+ }
159
+ ledger.attempts = ledger.attempts.filter((time) => time > now() - DAY);
160
+ const resumeAt = Math.max(ledger.blockedUntil, ledger.attempts.length >= DAILY_LIMIT ? Math.min(...ledger.attempts) + DAY : 0);
161
+ return {
162
+ site: options.site,
163
+ state: paths.state,
164
+ total: allUrls.length,
165
+ skipped,
166
+ inspected,
167
+ remaining: pending.length - inspected,
168
+ stop,
169
+ quota: {
170
+ per_day: DAILY_LIMIT,
171
+ per_minute: 600,
172
+ local_attempts_24h: ledger.attempts.length,
173
+ local_remaining: Math.max(0, DAILY_LIMIT - ledger.attempts.length),
174
+ resume_after: resumeAt > now() ? new Date(resumeAt).toISOString() : "",
175
+ scope: "Local coverage attempts only; external usage is unknown. Conservative rolling 24h budget; API quota errors pause 24h.",
176
+ },
177
+ rows: urls.flatMap((url) => (rows.has(url) ? [rows.get(url)] : [])),
178
+ };
179
+ }
180
+ finally {
181
+ try {
182
+ await store?.compact();
183
+ }
184
+ finally {
185
+ try {
186
+ await unlockState?.();
187
+ }
188
+ finally {
189
+ try {
190
+ await unlockLedger();
191
+ }
192
+ finally {
193
+ process.off("SIGINT", interrupt);
194
+ process.off("SIGTERM", interrupt);
195
+ }
196
+ }
197
+ }
198
+ }
199
+ }
200
+ export function groupCoverage(rows, now = Date.now()) {
201
+ const groups = new Map();
202
+ for (const row of rows) {
203
+ const age = now - Date.parse(row.lastCrawlTime);
204
+ const values = {
205
+ coverage_state: row.coverageState || "unknown",
206
+ verdict: row.verdict || "unknown",
207
+ canonical: row.googleCanonical || "unknown",
208
+ canonical_match: !row.googleCanonical || !row.userCanonical
209
+ ? "unknown"
210
+ : row.googleCanonical === row.userCanonical
211
+ ? "same"
212
+ : "different",
213
+ last_crawl: !Number.isFinite(age) || age < 0
214
+ ? "unknown"
215
+ : age < 7 * DAY
216
+ ? "under_7d"
217
+ : age < 30 * DAY
218
+ ? "7_to_29d"
219
+ : "30d_or_older",
220
+ };
221
+ const key = JSON.stringify(values);
222
+ const group = groups.get(key) ?? { ...values, count: 0, urls: [] };
223
+ group.count++;
224
+ group.urls.push(row.url);
225
+ groups.set(key, group);
226
+ }
227
+ return [...groups.values()];
228
+ }
229
+ export function coverageCsv(rows) {
230
+ const columns = ["url", ...fields, "inspectedAt"];
231
+ const quote = (value) => `"${value.replaceAll('"', '""')}"`;
232
+ return [columns.join(","), ...rows.map((row) => columns.map((key) => quote(row[key])).join(","))].join("\r\n");
233
+ }
package/dist/src/site.js CHANGED
@@ -26,6 +26,24 @@ export function selectVerifiedSite(sites, candidates) {
26
26
  const site = [...sites].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))[0];
27
27
  return site ? { site, site_source: "first_verified" } : undefined;
28
28
  }
29
+ export function matchesSite(candidate, property) {
30
+ if (candidate === property)
31
+ return true;
32
+ try {
33
+ const url = new URL(candidate);
34
+ if (property.startsWith("sc-domain:")) {
35
+ const domain = property.slice("sc-domain:".length);
36
+ return url.hostname === domain || url.hostname.endsWith(`.${domain}`);
37
+ }
38
+ const verifiedUrl = new URL(property);
39
+ return (verifiedUrl.origin === url.origin &&
40
+ (url.pathname === verifiedUrl.pathname ||
41
+ url.pathname.startsWith(verifiedUrl.pathname.endsWith("/") ? verifiedUrl.pathname : `${verifiedUrl.pathname}/`)));
42
+ }
43
+ catch {
44
+ return false;
45
+ }
46
+ }
29
47
  export async function resolveSite(auth, flag) {
30
48
  const environment = process.env["SEARCH_CONSOLE_AXI_SITE"];
31
49
  const saved = savedDefaultSite();
@@ -37,31 +55,11 @@ export async function resolveSite(auth, flag) {
37
55
  { site: saved, source: "saved_config" },
38
56
  ];
39
57
  const requested = candidates.find((candidate) => candidate.site);
40
- const matches = (candidate, property) => {
41
- if (candidate === property)
42
- return true;
43
- try {
44
- const url = new URL(candidate);
45
- if (property.startsWith("sc-domain:")) {
46
- const domain = property.slice("sc-domain:".length);
47
- if (url.hostname === domain || url.hostname.endsWith(`.${domain}`))
48
- return true;
49
- return false;
50
- }
51
- const verifiedUrl = new URL(property);
52
- return (verifiedUrl.origin === url.origin &&
53
- (url.pathname === verifiedUrl.pathname ||
54
- url.pathname.startsWith(verifiedUrl.pathname.endsWith("/") ? verifiedUrl.pathname : `${verifiedUrl.pathname}/`)));
55
- }
56
- catch {
57
- return false;
58
- }
59
- };
60
- if (requested && !verified.some((entry) => matches(requested.site, entry.siteUrl)))
58
+ if (requested && !verified.some((entry) => matchesSite(requested.site, entry.siteUrl)))
61
59
  return usage(`Selected site '${requested.site}' is not a verified property`);
62
60
  const selectedCandidate = requested &&
63
61
  (verified.find((entry) => entry.siteUrl === requested.site) ??
64
- verified.find((entry) => matches(requested.site, entry.siteUrl)));
62
+ verified.find((entry) => matchesSite(requested.site, entry.siteUrl)));
65
63
  const selected = selectedCandidate
66
64
  ? { site: selectedCandidate.siteUrl, site_source: requested.source }
67
65
  : selectVerifiedSite(verified.map((entry) => entry.siteUrl), candidates);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "search-console-axi",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "Google Search Console reporting and preview-gated Indexing API CLI for agents",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -49,6 +49,7 @@
49
49
  "dependencies": {
50
50
  "@toon-format/toon": "2.3.1",
51
51
  "axi-sdk-js": "0.1.13",
52
+ "fast-xml-parser": "5.12.1",
52
53
  "google-auth-library": "11.3.2"
53
54
  },
54
55
  "devDependencies": {
@@ -57,5 +58,5 @@
57
58
  "prettier": "3.9.10",
58
59
  "typescript": "5.9.3"
59
60
  },
60
- "gitHead": "82c795b4c7a2f3760b0d2d37c9f5394ce6f41711"
61
+ "gitHead": "a241f5212422fdc30fa6e61944696f5a946d83cd"
61
62
  }
@@ -12,6 +12,7 @@ If `search-console-axi` is not installed globally (`command -v search-console-ax
12
12
  Run `search-console-axi` for the default site's clicks, impressions, CTR, average position, top queries/pages, and low-CTR opportunities. Run `search-console-axi setup` to check access. Run `search-console-axi inspect <url>` to inspect index status; `--site` is optional. See the [README usage guide](https://github.com/Dematom1/search-console-axi/blob/main/README.md#read-search-console) for site selection.
13
13
 
14
14
  Run `search-console-axi sitemaps list [--site <property>]` for submitted sitemaps and `sitemaps get <sitemap-url>` for one. Output includes last-read dates, pending/error-derived status, errors/warnings and per-content-type submitted counts (discovered pages); indexed counts are deprecated, and missing fields are unknown, not zero. `search-console-axi sitemaps submit <sitemap-url> --site <exact-property>` previews without credentials; add `--confirm` to submit. Submission requires the `https://www.googleapis.com/auth/webmasters` scope and property write permissions. Read-only ADC must be explicitly reauthorized, never silently widened.
15
+ Run `search-console-axi coverage --sitemap <sitemap-url>` or `search-console-axi coverage <file|->` to list supplied URLs by Google indexing state. Sitemap indexes expand to child sitemaps. Input is deduplicated. This reads URL Inspection, not the Page indexing report. TOON groups coverage state, verdict, Google's canonical URL (or unknown), canonical match, and last-crawl age with counts and URL lists. `--format json|csv` exports per-URL rows. `--state <file>` names the progress file; keep its `.jsonl` journal alongside it until automatic compaction. Rerun to resume without repeating completed URLs. `--refresh` starts a new pass only after any active pass finishes; interrupted refreshes resume their unfinished URLs. Out-of-property URLs are reported as skipped without quota use; select their property to inspect them. Coverage paces below 600 requests per minute, tracks a conservative 2,000-per-property rolling 24-hour budget in the user state directory, and stops on API quota errors. Check `remaining` and `stop` for partial output. Other clients' usage is unknown. Coverage is read-only.
15
16
 
16
17
  Run `search-console-axi indexing --help` for notification commands. `search-console-axi indexing publish <url> --type updated|deleted` and `search-console-axi indexing batch <file|-> --type updated|deleted` preview every URL until `--confirm`. Only pages with JobPosting or BroadcastEvent embedded in VideoObject structured data qualify. Service accounts must own the Search Console property. `search-console-axi indexing status <url>` reads notification receipt metadata, not index status. `search-console-axi indexing quota` reports readable project limits and observed requests today, with permission guidance when unavailable.
17
18