search-console-axi 0.1.1 → 0.1.3

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
@@ -5,9 +5,20 @@
5
5
  Google Search Console reporting, URL inspection, and preview-gated Indexing API notifications for agents. `search-console-axi` is an [AXI](https://github.com/kunchenguid/axi) CLI. Output uses compact [TOON](https://toonformat.dev/) format. Requires Node.js 22.12 or newer.
6
6
 
7
7
  ```sh
8
- npm install
9
- npm run build
10
- node dist/bin/search-console-axi.js --help
8
+ npx skills add Dematom1/search-console-axi --skill search-console-axi -g
9
+ ```
10
+
11
+ No install needed: tell your agent "Execute `npx -y search-console-axi` to read Google Search Console clicks, impressions, top queries and URL indexing status."
12
+
13
+ Either way, Google credentials are required first: see [Authentication](#authentication).
14
+
15
+ ### Optional
16
+
17
+ Install the CLI globally:
18
+
19
+ ```sh
20
+ npm i -g search-console-axi
21
+ search-console-axi --help
11
22
  ```
12
23
 
13
24
  ## Authentication
@@ -21,19 +32,34 @@ The CLI validates credential JSON locally and authenticates through `google-auth
21
32
  3. Load its JSON key from your secret manager into `SEARCH_CONSOLE_AXI_SA_KEY`. Never commit the key.
22
33
  4. In Search Console, add the service-account email under **Settings > Users and permissions** with Restricted access.
23
34
 
24
- For local key files, set `GOOGLE_APPLICATION_CREDENTIALS` or run `node dist/bin/search-console-axi.js setup service-account <key.json>`. Credential precedence is `SEARCH_CONSOLE_AXI_SA_KEY`, `GOOGLE_APPLICATION_CREDENTIALS` (with `google_application_credentials` as a fallback alias), the saved path configured by `setup service-account`, then user ADC. Credential files must contain `authorized_user` or `service_account` JSON; service-account registration and `SEARCH_CONSOLE_AXI_SA_KEY` require `service_account` JSON. To switch from a saved key to ADC, run `node dist/bin/search-console-axi.js setup uninstall`; this also removes the CLI's saved quota-project setting. Set the ADC quota project with `gcloud auth application-default set-quota-project <project>` or use `GOOGLE_CLOUD_QUOTA_PROJECT`.
35
+ For local key files, set `GOOGLE_APPLICATION_CREDENTIALS` or run `search-console-axi setup service-account <key.json>`. Credential precedence is `SEARCH_CONSOLE_AXI_SA_KEY`, `GOOGLE_APPLICATION_CREDENTIALS` (with `google_application_credentials` as a fallback alias), the saved path configured by `search-console-axi setup service-account`, then user ADC. Credential files must contain `authorized_user` or `service_account` JSON; service-account registration and `SEARCH_CONSOLE_AXI_SA_KEY` require `service_account` JSON. To switch from a saved key to ADC, run `search-console-axi setup uninstall`; this also removes the CLI's saved quota-project setting. Set the ADC quota project with `gcloud auth application-default set-quota-project <project>` or use `GOOGLE_CLOUD_QUOTA_PROJECT`.
25
36
 
26
- Run `node dist/bin/search-console-axi.js setup` to check credentials and accessible sites. `node dist/bin/search-console-axi.js setup status` reports local credential configuration, not API access or token validity. It includes the credential type and available account email, never credential contents. `node dist/bin/search-console-axi.js setup uninstall` removes only the CLI's local configuration. Registration, saved quota-project updates, and removal re-read the configuration before reporting success.
37
+ Run `search-console-axi setup` to check credentials and accessible sites. `search-console-axi setup status` reports local credential configuration, not API access or token validity. It includes the credential type and available account email, never credential contents. `search-console-axi setup uninstall` removes only the CLI's local configuration. Registration, saved quota-project updates, and removal re-read the configuration before reporting success.
27
38
 
28
- Invalid setup arguments, malformed config, and malformed or unsupported credential data produce `VALIDATION_ERROR` with exit code 2. Config I/O failures produce `CONFIG_ERROR`; missing or unreadable credential-file paths produce `AUTH_CONFIG_ERROR`, both with exit code 1 and repair guidance. `setup status` instead reports invalid config or credentials as `auth.status: invalid` with exit code 0; config I/O failures remain errors. Missing credentials produce setup guidance with `auth.status: not configured` for `setup`, `setup check`, and `setup status`. The default command also reports credential status when credentials cannot be loaded.
39
+ Invalid setup arguments, malformed config, and malformed or unsupported credential data produce `VALIDATION_ERROR` with exit code 2. Config I/O failures produce `CONFIG_ERROR`; missing or unreadable credential-file paths produce `AUTH_CONFIG_ERROR`, both with exit code 1 and repair guidance. `search-console-axi setup status` instead reports invalid config or credentials as `auth.status: invalid` with exit code 0; config I/O failures remain errors. Missing credentials produce setup guidance with `auth.status: not configured` for `search-console-axi setup`, `search-console-axi setup check`, and `search-console-axi setup status`.
29
40
 
30
41
  ## Read Search Console
31
42
 
32
- Run `node dist/bin/search-console-axi.js` for the default site's last seven complete days of clicks, impressions, CTR, position, top queries and pages, and low-CTR opportunities. Use `node dist/bin/search-console-axi.js inspect <url> --site <site-url>` to inspect indexing for a URL. Reporting and inspection do not modify Search Console data; setup may write or remove local configuration.
43
+ Run `search-console-axi` for the default site's last seven complete days of clicks, impressions, CTR, position, top queries and pages, and low-CTR opportunities. Set a default site with `search-console-axi setup site <site-url>`. Reports resolve the site from `--site`, `SEARCH_CONSOLE_AXI_SITE`, the saved default, then the first verified site. Use `search-console-axi inspect <url>` to inspect indexing for a URL; `--site` is optional and uses the same resolution order. Reporting and inspection do not modify Search Console data; setup may write or remove local configuration.
44
+
45
+ ## Read and submit sitemaps
46
+
47
+ ```sh
48
+ search-console-axi sitemaps list --site sc-domain:example.com
49
+ search-console-axi sitemaps get https://example.com/sitemap.xml --site sc-domain:example.com
50
+ search-console-axi sitemaps submit https://example.com/sitemap.xml --site sc-domain:example.com
51
+ search-console-axi sitemaps submit https://example.com/sitemap.xml --site sc-domain:example.com --confirm
52
+ ```
53
+
54
+ Reads use the same credentials and site resolution as reports. Lists include the path, type, `isSitemapsIndex`, `lastSubmitted`, `lastDownloaded` (last read), `isPending`, derived status, errors, warnings, and `contents[]` counts. Status is derived from pending/error fields, not the Search Console UI's status text. Discovered pages are `contents[].submitted` counts by content type; the API has no separate UI discovered-pages column, so no total across content types is invented. `contents[].indexed` is deprecated and is shown only as returned, not reliable index coverage. Missing fields are null (unknown), not zero.
55
+
56
+ Submit requires an explicit `--site` naming the exact property, even if a default is configured. Without `--confirm`, it previews the exact property, sitemap and PUT request locally without credentials or network access. With `--confirm`, it submits once, without retries. An acknowledgement does not guarantee a crawl or indexing. If the outcome is unknown, use `sitemaps get` before retrying.
57
+
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.
33
59
 
34
60
  ## Send Indexing API notifications
35
61
 
36
- 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. DFJ job pages fit this scope. It is not a general-purpose indexing API. A successful submission acknowledges a notification, not a crawl or index guarantee.
62
+ 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.
37
63
 
38
64
  Enable the Indexing API in your Google Cloud project. The service account must be an **owner** of the Search Console property, not merely a Restricted or Full user. The same credential precedence and local configuration apply. Notification commands request `https://www.googleapis.com/auth/indexing`; reporting still requests only `webmasters.readonly`. For user ADC, reauthorize your own Desktop OAuth client with the indexing scope as well as the reporting scopes above. Existing refresh tokens cannot gain scopes automatically.
39
65
 
@@ -49,13 +75,13 @@ search-console-axi indexing quota
49
75
 
50
76
  `publish` and `batch` are local previews until `--confirm`. Previews list every explicit URL target, the notification count, and the HTTP request count without loading credentials or calling Google. Batch input contains one absolute HTTP or HTTPS URL per line; blank lines are ignored. Duplicate URLs remain separate requests. URLs with embedded credentials, fragments, or whitespace are rejected. All input is validated before any submission. Each multipart batch contains at most 100 notifications, and each notification consumes quota separately.
51
77
 
52
- Before `--type deleted`, the page must return HTTP 404 or 410 or contain a `noindex` directive. `status` reads `urlNotifications.getMetadata`: the last notification times, not the page's indexing status. Use `inspect` for index status.
78
+ Before `--type deleted`, the page must return HTTP 404 or 410 or contain a `noindex` directive. `status` reads `urlNotifications.getMetadata`: the last notification times, not the page's indexing status. Use `search-console-axi inspect` for index status.
53
79
 
54
80
  Confirmed batches report every URL as `submitted`, `failed`, or `unknown`, with an HTTP status where available. Any failed or unknown result sets exit code 1. Authentication, API, and transport errors omit raw server messages and credential contents. A 403 explains the owner, API enablement, and scope requirements; a 429 explains quota exhaustion. Requests are not automatically retried. An unknown outcome may already have reached Google; check notification status before retrying. Successful URLs in a partially failed batch must not be resubmitted blindly.
55
81
 
56
82
  ### Read project quota
57
83
 
58
- The Indexing API has no usage endpoint. `indexing quota` reads effective limits from Service Usage and today's observed request counts from Cloud Monitoring. The selected project is the configured quota project sent with requests, or the credential's `project_id` if no override exists. The output identifies that project and the source. User ADC without either project requires `setup --quota-project <project>`.
84
+ The Indexing API has no usage endpoint. `search-console-axi indexing quota` reads effective limits from Service Usage and today's observed request counts from Cloud Monitoring. The selected project is the configured quota project sent with requests, or the credential's `project_id` if no override exists. The output identifies that project and the source. User ADC without either project requires `search-console-axi setup --quota-project <project>`.
59
85
 
60
86
  Quota reads request `cloud-platform.read-only` and `monitoring.read` OAuth scopes. User ADC with `cloud-platform` also supports both endpoints. Limits require `serviceusage.quotas.get`; usage requires `monitoring.timeSeries.list` on the selected project. These optional IAM permissions are separate from Search Console ownership. The Service Usage and Cloud Monitoring APIs must be enabled.
61
87
 
@@ -1,30 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import { runAxiCli } from "axi-sdk-js";
3
- import { readFileSync } from "node:fs";
4
- import { getAuthClient, setupCommand } from "./auth.js";
5
- import { runHome } from "./setup-check.js";
6
- import { indexingCommand } from "./indexing.js";
7
- const version = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
8
- const description = "Google Search Console reporting, URL inspection, and preview-gated Indexing API notifications for agents";
9
- const args = process.argv.slice(2);
10
- await runAxiCli({
11
- description,
12
- version,
13
- argv: args,
14
- topLevelHelp: `${description}\n\nUsage: search-console-axi [--help] [--version]\n\nCommands:\n setup Configure, inspect, or remove authentication\n inspect Inspect a URL's index status\n indexing Publish notifications, read metadata, batch, and view quota`,
15
- commands: {
16
- setup: setupCommand,
17
- indexing: (args) => indexingCommand(args),
18
- inspect: (args) => args.includes("--help") || args.includes("-h")
19
- ? "usage: search-console-axi inspect <url> --site <site> [--quota-project <project>]\n"
20
- : setupCommand(["inspect", ...args]),
21
- },
22
- home: async () => {
23
- try {
24
- return await runHome(await getAuthClient());
25
- }
26
- catch {
27
- return setupCommand(["status"]);
28
- }
29
- },
30
- });
2
+ import { runAxiCli } from "../src/cli.js";
3
+ await runAxiCli();
@@ -0,0 +1,33 @@
1
+ import { AxiError } from "axi-sdk-js";
2
+ export function parseArgs(args, valueFlags, booleanFlags = []) {
3
+ const values = new Set(valueFlags);
4
+ const booleans = new Set(booleanFlags);
5
+ const positionals = [];
6
+ const flags = new Map();
7
+ for (let i = 0; i < args.length; i++) {
8
+ const token = args[i];
9
+ if (token === "-" || !token.startsWith("-")) {
10
+ positionals.push(token);
11
+ continue;
12
+ }
13
+ const equal = token.indexOf("=");
14
+ const name = equal < 0 ? token : token.slice(0, equal);
15
+ const inline = equal < 0 ? undefined : token.slice(equal + 1);
16
+ if (flags.has(name))
17
+ throw usage(`Repeated option '${name}'`);
18
+ if (values.has(name)) {
19
+ const value = inline ?? args[++i];
20
+ if (value === undefined || value === "" || (inline === undefined && value.startsWith("--")))
21
+ throw usage(`${name} requires a value`);
22
+ flags.set(name, value);
23
+ }
24
+ else if (booleans.has(name) && inline === undefined)
25
+ flags.set(name, true);
26
+ else
27
+ throw usage(`Unknown option '${name}'`);
28
+ }
29
+ return { positionals, flags };
30
+ }
31
+ export function usage(message) {
32
+ throw new AxiError(message, "VALIDATION_ERROR", ["Run `search-console-axi --help` for valid commands and options"]);
33
+ }
@@ -0,0 +1,374 @@
1
+ import { GoogleAuth, JWT, UserRefreshClient } from "google-auth-library";
2
+ import { encode } from "@toon-format/toon";
3
+ import { AxiError } from "axi-sdk-js";
4
+ import { runSetupCheck, setupGuide } from "./setup-check.js";
5
+ import { mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
6
+ import { randomUUID } from "node:crypto";
7
+ import { homedir } from "node:os";
8
+ import { join, resolve } from "node:path";
9
+ import { parseArgs } from "./args.js";
10
+ import { resolveSite, validateSite } from "./site.js";
11
+ const SCOPES = ["https://www.googleapis.com/auth/webmasters.readonly"];
12
+ const NO_ADC_MESSAGE = "Could not load the default credentials";
13
+ const NO_CREDENTIALS_GUIDANCE = "No service-account key or user ADC is configured. Load the key JSON into SEARCH_CONSOLE_AXI_SA_KEY or configure your own Desktop OAuth client.";
14
+ const QUOTA_PROJECT_APIS = "Enable the Google Search Console API in the quota project.";
15
+ const configDir = () => process.env["XDG_CONFIG_HOME"]
16
+ ? join(process.env["XDG_CONFIG_HOME"], "search-console-axi")
17
+ : join(homedir(), ".config", "search-console-axi");
18
+ const configFile = () => join(configDir(), "config.json");
19
+ const fail = (message) => {
20
+ throw new AxiError(message, "VALIDATION_ERROR", [
21
+ "Run `search-console-axi setup --help` to see valid actions and options",
22
+ ]);
23
+ };
24
+ const configError = (error, action) => {
25
+ const detail = error instanceof Error ? error.message : String(error);
26
+ return new AxiError(`Could not ${action} Search Console config at ${configFile()}: ${detail}`, "CONFIG_ERROR", [
27
+ `Check that ${configDir()} is writable and the config file is readable, then retry`,
28
+ ]);
29
+ };
30
+ class AuthConfigError extends AxiError {
31
+ kind;
32
+ constructor(kind, message) {
33
+ super(message, kind === "invalid-service-account" || kind === "invalid-credential-file"
34
+ ? "VALIDATION_ERROR"
35
+ : "AUTH_CONFIG_ERROR", [
36
+ kind === "missing-credentials"
37
+ ? NO_CREDENTIALS_GUIDANCE
38
+ : kind === "invalid-credentials-path"
39
+ ? "Check that the credential file exists and is readable"
40
+ : "Provide valid authorized_user or service_account JSON credentials",
41
+ ]);
42
+ this.kind = kind;
43
+ }
44
+ }
45
+ function isObject(value) {
46
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
47
+ }
48
+ function readJsonFile(path, isValid, onFailure, optional = false) {
49
+ let text;
50
+ try {
51
+ text = readFileSync(path, "utf8");
52
+ }
53
+ catch (error) {
54
+ if (optional && error && typeof error === "object" && "code" in error && error.code === "ENOENT")
55
+ return undefined;
56
+ throw onFailure("read", error);
57
+ }
58
+ let value;
59
+ try {
60
+ value = JSON.parse(text);
61
+ }
62
+ catch (error) {
63
+ throw onFailure("parse", error);
64
+ }
65
+ if (!isValid(value))
66
+ throw onFailure("shape", new Error("JSON does not match the expected format"));
67
+ return value;
68
+ }
69
+ function isConfig(value) {
70
+ return (isObject(value) &&
71
+ (!("serviceAccountPath" in value) || typeof value.serviceAccountPath === "string") &&
72
+ (!("quotaProjectId" in value) || typeof value.quotaProjectId === "string") &&
73
+ (!("defaultSite" in value) || typeof value.defaultSite === "string"));
74
+ }
75
+ function readConfig() {
76
+ const config = readJsonFile(configFile(), isConfig, (failure, error) => {
77
+ if (failure === "read")
78
+ return configError(error, "read");
79
+ return new AxiError(`Config file ${configFile()} contains invalid ${failure === "parse" ? "JSON" : "format"}`, "VALIDATION_ERROR", ["Repair or remove the invalid config file"]);
80
+ }, true);
81
+ return config ?? {};
82
+ }
83
+ function saveConfig(config) {
84
+ const path = configFile();
85
+ const temporaryFile = `${path}.${randomUUID()}.tmp`;
86
+ try {
87
+ mkdirSync(configDir(), { recursive: true, mode: 0o700 });
88
+ writeFileSync(temporaryFile, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600, flag: "wx" });
89
+ renameSync(temporaryFile, path);
90
+ }
91
+ catch (error) {
92
+ try {
93
+ unlinkSync(temporaryFile);
94
+ }
95
+ catch (cleanupError) {
96
+ if (!(cleanupError instanceof Error && "code" in cleanupError && cleanupError.code === "ENOENT"))
97
+ throw configError(cleanupError, "clean up temporary");
98
+ }
99
+ throw configError(error, "write");
100
+ }
101
+ }
102
+ function isCredentialFile(value) {
103
+ if (!isObject(value))
104
+ return false;
105
+ const required = value.type === "service_account"
106
+ ? ["client_email", "private_key"]
107
+ : value.type === "authorized_user"
108
+ ? ["client_id", "client_secret", "refresh_token"]
109
+ : undefined;
110
+ if (!required)
111
+ return false;
112
+ return (required.every((field) => typeof value[field] === "string" && value[field].trim().length > 0) &&
113
+ ["private_key_id", "project_id", "quota_project_id"].every((field) => !(field in value) || (typeof value[field] === "string" && value[field].trim().length > 0)) &&
114
+ (!("universe_domain" in value) || value.universe_domain === "googleapis.com"));
115
+ }
116
+ function isServiceAccountFile(value) {
117
+ return isCredentialFile(value) && value.type === "service_account";
118
+ }
119
+ function readServiceAccount(path, source) {
120
+ const data = readJsonFile(path, isServiceAccountFile, (failure) => failure === "read"
121
+ ? new AuthConfigError("invalid-credentials-path", `${source} at ${path} is unreadable; check that the file exists and is readable`)
122
+ : new AuthConfigError("invalid-service-account", `${source} at ${path} is not a valid Google service-account key`));
123
+ if (!data)
124
+ throw new AuthConfigError("invalid-service-account", `${source} at ${path} is invalid`);
125
+ return data;
126
+ }
127
+ export function savedDefaultSite() {
128
+ return readConfig().defaultSite;
129
+ }
130
+ export function saveDefaultSite(site) {
131
+ saveConfig({ ...readConfig(), defaultSite: site });
132
+ }
133
+ export async function getAuthClient(options = {}) {
134
+ const config = readConfig();
135
+ const serviceAccountJson = process.env["SEARCH_CONSOLE_AXI_SA_KEY"];
136
+ const credentialsPath = process.env["GOOGLE_APPLICATION_CREDENTIALS"] ?? process.env["google_application_credentials"];
137
+ const configuredPath = config.serviceAccountPath;
138
+ let fileCredentials;
139
+ if (serviceAccountJson !== undefined) {
140
+ let parsed;
141
+ try {
142
+ parsed = JSON.parse(serviceAccountJson);
143
+ }
144
+ catch {
145
+ throw new AuthConfigError("invalid-service-account", "SEARCH_CONSOLE_AXI_SA_KEY must contain valid service-account JSON");
146
+ }
147
+ if (!isServiceAccountFile(parsed))
148
+ throw new AuthConfigError("invalid-service-account", "SEARCH_CONSOLE_AXI_SA_KEY does not contain a valid Google service-account key");
149
+ fileCredentials = parsed;
150
+ }
151
+ else if (credentialsPath === undefined && configuredPath) {
152
+ fileCredentials = readServiceAccount(configuredPath, "Configured service-account key file");
153
+ }
154
+ else {
155
+ if (credentialsPath === "")
156
+ throw new AuthConfigError("invalid-credentials-path", "GOOGLE_APPLICATION_CREDENTIALS must not be empty");
157
+ const adcDir = process.env["CLOUDSDK_CONFIG"] ||
158
+ (process.platform === "win32"
159
+ ? process.env["APPDATA"] && join(process.env["APPDATA"], "gcloud")
160
+ : process.env["HOME"] && join(process.env["HOME"], ".config", "gcloud"));
161
+ const path = credentialsPath ?? (adcDir ? join(adcDir, "application_default_credentials.json") : undefined);
162
+ if (path) {
163
+ const source = credentialsPath === undefined ? "Application Default Credentials" : "GOOGLE_APPLICATION_CREDENTIALS";
164
+ fileCredentials = readJsonFile(path, isCredentialFile, (failure) => failure === "read"
165
+ ? new AuthConfigError("invalid-credentials-path", `Could not read ${source} at ${path}; check that the file exists and is readable`)
166
+ : new AuthConfigError("invalid-credential-file", `${source} at ${path} contains invalid JSON or credential data; use authorized_user or service_account credentials`), credentialsPath === undefined);
167
+ }
168
+ }
169
+ const source = serviceAccountJson !== undefined
170
+ ? "SEARCH_CONSOLE_AXI_SA_KEY"
171
+ : credentialsPath
172
+ ? "GOOGLE_APPLICATION_CREDENTIALS"
173
+ : configuredPath
174
+ ? "service-account-path"
175
+ : "ADC";
176
+ const quotaOverride = options.quotaProject ?? process.env["GOOGLE_CLOUD_QUOTA_PROJECT"] ?? config.quotaProjectId;
177
+ if (fileCredentials) {
178
+ const credential = fileCredentials.type === "service_account"
179
+ ? new JWT({
180
+ email: fileCredentials.client_email,
181
+ key: fileCredentials.private_key,
182
+ keyId: fileCredentials.private_key_id,
183
+ projectId: fileCredentials.project_id,
184
+ universeDomain: fileCredentials.universe_domain,
185
+ scopes: options.scopes ?? SCOPES,
186
+ })
187
+ : new UserRefreshClient({
188
+ clientId: fileCredentials.client_id,
189
+ clientSecret: fileCredentials.client_secret,
190
+ refreshToken: fileCredentials.refresh_token,
191
+ universeDomain: fileCredentials.universe_domain,
192
+ });
193
+ credential.quotaProjectId = quotaOverride ?? fileCredentials.quota_project_id;
194
+ return {
195
+ client: credential,
196
+ type: fileCredentials.type,
197
+ source,
198
+ ...(fileCredentials.type === "service_account" ? { email: fileCredentials.client_email } : {}),
199
+ ...(credential.quotaProjectId ? { quotaProjectId: credential.quotaProjectId } : {}),
200
+ ...(fileCredentials.project_id ? { projectId: fileCredentials.project_id } : {}),
201
+ };
202
+ }
203
+ const auth = (options.authFactory ?? ((opts) => new GoogleAuth(opts)))({
204
+ scopes: options.scopes ?? SCOPES,
205
+ ...(quotaOverride ? { clientOptions: { quotaProjectId: quotaOverride } } : {}),
206
+ });
207
+ let credential;
208
+ let projectId;
209
+ try {
210
+ ({ credential, projectId } = await auth.getApplicationDefault());
211
+ }
212
+ catch (error) {
213
+ if (error instanceof Error && error.message.includes(NO_ADC_MESSAGE))
214
+ throw new AuthConfigError("missing-credentials", "Google Application Default Credentials are not configured");
215
+ throw error;
216
+ }
217
+ if (quotaOverride)
218
+ credential.quotaProjectId = quotaOverride;
219
+ if (credential instanceof UserRefreshClient)
220
+ return {
221
+ client: credential,
222
+ type: "authorized_user",
223
+ source,
224
+ ...((quotaOverride ?? credential.quotaProjectId)
225
+ ? { quotaProjectId: quotaOverride ?? credential.quotaProjectId }
226
+ : {}),
227
+ ...(projectId ? { projectId } : {}),
228
+ };
229
+ if (credential instanceof JWT)
230
+ return {
231
+ client: credential,
232
+ type: "service_account",
233
+ source,
234
+ ...(credential.email ? { email: credential.email } : {}),
235
+ ...((quotaOverride ?? credential.quotaProjectId)
236
+ ? { quotaProjectId: quotaOverride ?? credential.quotaProjectId }
237
+ : {}),
238
+ ...(projectId ? { projectId } : {}),
239
+ };
240
+ throw new AuthConfigError("invalid-credential-file", "Unsupported Google credentials type; use authorized_user or service_account credentials");
241
+ }
242
+ function setupGuideOutput(missing) {
243
+ return result({ auth: { status: "not configured" }, setup: { status: "incomplete", missing, guide: setupGuide } });
244
+ }
245
+ function invalidAuthOutput(message, type) {
246
+ return result({
247
+ auth: { status: "invalid", ...(type ? { type } : {}), error: message },
248
+ setup: { status: "incomplete", missing: [message], guide: setupGuide },
249
+ });
250
+ }
251
+ async function setupWithChecks(options) {
252
+ try {
253
+ const auth = await getAuthClient(options);
254
+ return runSetupCheck(auth);
255
+ }
256
+ catch (error) {
257
+ if (error instanceof AuthConfigError && error.kind === "missing-credentials")
258
+ return setupGuideOutput([NO_CREDENTIALS_GUIDANCE]);
259
+ throw error;
260
+ }
261
+ }
262
+ function result(data) {
263
+ return encode(data);
264
+ }
265
+ async function authStatus(quotaProject, providerOptions = {}) {
266
+ try {
267
+ const auth = await getAuthClient({ ...providerOptions, quotaProject });
268
+ const help = auth.type === "authorized_user" && !auth.quotaProjectId
269
+ ? [
270
+ "Set a quota project with `gcloud auth application-default set-quota-project <project>`.",
271
+ QUOTA_PROJECT_APIS,
272
+ ]
273
+ : [];
274
+ return result({
275
+ auth: {
276
+ status: "configured",
277
+ type: auth.type,
278
+ source: auth.source,
279
+ ...(auth.email ? { account_email: auth.email } : {}),
280
+ quota_project: auth.quotaProjectId ?? "none",
281
+ },
282
+ help,
283
+ });
284
+ }
285
+ catch (error) {
286
+ if (error instanceof AuthConfigError && error.kind === "missing-credentials")
287
+ return setupGuideOutput([NO_CREDENTIALS_GUIDANCE]);
288
+ if (error instanceof AuthConfigError)
289
+ return invalidAuthOutput(error.message, error.kind === "invalid-service-account" ? "service_account" : undefined);
290
+ if (error instanceof AxiError && error.code === "VALIDATION_ERROR")
291
+ return invalidAuthOutput(error.message);
292
+ throw error;
293
+ }
294
+ }
295
+ export async function setupCommand(args, providerOptions = {}) {
296
+ const [first, ...rest] = args;
297
+ const implicitSetup = !first || first.startsWith("-");
298
+ const action = implicitSetup ? "setup" : first;
299
+ const operands = implicitSetup ? args : rest;
300
+ const parsed = parseArgs(operands, ["--quota-project"], []);
301
+ const rawQuotaProject = parsed.flags.get("--quota-project");
302
+ if (rawQuotaProject !== undefined && typeof rawQuotaProject !== "string")
303
+ fail("--quota-project requires a project ID");
304
+ const quotaProject = typeof rawQuotaProject === "string" ? rawQuotaProject : undefined;
305
+ const positionals = parsed.positionals;
306
+ if (action === "site") {
307
+ if (quotaProject !== undefined)
308
+ fail("setup site does not accept --quota-project");
309
+ if (positionals.length !== 1)
310
+ fail("usage: search-console-axi setup site <url>");
311
+ const site = positionals[0] ?? fail("usage: search-console-axi setup site <url>");
312
+ validateSite(site);
313
+ const auth = await getAuthClient();
314
+ const resolution = await resolveSite(auth, site);
315
+ if (resolution.kind === "unavailable")
316
+ return fail("No verified Search Console sites visible");
317
+ saveDefaultSite(resolution.site);
318
+ if (savedDefaultSite() !== resolution.site)
319
+ throw configError(new Error("saved site does not match requested value"), "verify saved");
320
+ return result({ site: resolution.site, status: "saved" });
321
+ }
322
+ if (action === "status") {
323
+ if (positionals.length)
324
+ fail("usage: search-console-axi setup status [--quota-project <project>]");
325
+ return authStatus(quotaProject, providerOptions);
326
+ }
327
+ if (action === "uninstall") {
328
+ if (positionals.length || quotaProject)
329
+ fail("usage: search-console-axi setup uninstall");
330
+ try {
331
+ unlinkSync(configFile());
332
+ const verified = readConfig();
333
+ if (verified.serviceAccountPath || verified.quotaProjectId || verified.defaultSite)
334
+ throw configError(new Error("saved registration remains after removal"), "verify removal of");
335
+ return result({ auth: { status: "removed", config: "removed" } });
336
+ }
337
+ catch (error) {
338
+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT")
339
+ return result({ auth: { status: "not configured", config: "already absent" } });
340
+ throw error instanceof AxiError ? error : configError(error, "remove");
341
+ }
342
+ }
343
+ if (action === "service-account") {
344
+ const [path] = positionals;
345
+ if (positionals.length !== 1 || !path)
346
+ return fail("usage: search-console-axi setup service-account <key.json> [--quota-project <project>]");
347
+ const key = readServiceAccount(path, "Service-account key file");
348
+ const saved = {
349
+ ...readConfig(),
350
+ serviceAccountPath: resolve(path),
351
+ ...(quotaProject ? { quotaProjectId: quotaProject } : {}),
352
+ };
353
+ saveConfig(saved);
354
+ const verified = readConfig();
355
+ if (verified.serviceAccountPath !== saved.serviceAccountPath || verified.quotaProjectId !== saved.quotaProjectId)
356
+ throw configError(new Error("saved registration does not match requested values"), "verify saved");
357
+ return result({ auth: { status: "configured", type: "service_account", account_email: key.client_email } });
358
+ }
359
+ if (action === "check") {
360
+ if (positionals.length)
361
+ fail("usage: search-console-axi setup check");
362
+ return setupWithChecks({ ...providerOptions, ...(quotaProject ? { quotaProject } : {}) });
363
+ }
364
+ if (action !== "setup")
365
+ fail(`unknown setup action '${action}'; valid actions are setup, check, status, site, service-account, uninstall`);
366
+ if (positionals.length)
367
+ fail("usage: search-console-axi setup [--quota-project <project>]");
368
+ if (quotaProject) {
369
+ saveConfig({ ...readConfig(), quotaProjectId: quotaProject });
370
+ if (readConfig().quotaProjectId !== quotaProject)
371
+ throw configError(new Error("saved quota project does not match requested value"), "verify saved");
372
+ }
373
+ return setupWithChecks({ ...providerOptions, ...(quotaProject ? { quotaProject } : {}) });
374
+ }
@@ -0,0 +1,76 @@
1
+ import { AxiError } from "axi-sdk-js";
2
+ import { encode } from "@toon-format/toon";
3
+ import { command as setup } from "./commands/setup.js";
4
+ import { command as report } from "./commands/report.js";
5
+ import { command as inspect } from "./commands/inspect.js";
6
+ import { command as indexing } from "./commands/indexing.js";
7
+ import { command as sitemaps } from "./commands/sitemaps.js";
8
+ import { usage } from "./args.js";
9
+ import { helpText } from "./help.js";
10
+ import { getAuthClient, setupCommand } from "./auth.js";
11
+ import { runHome } from "./google.js";
12
+ import { resolveSite } from "./site.js";
13
+ 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
+ const registry = new Map(commands.map((command) => [command.name, command]));
16
+ export function getCommandHelp(args) {
17
+ if (!args.length)
18
+ return helpText("search-console-axi", {
19
+ purpose: description,
20
+ flags: { "--help": "Show help", "--version": "Show version" },
21
+ examples: ["search-console-axi", "search-console-axi report"],
22
+ next: commands.map((command) => `search-console-axi ${command.name}`),
23
+ });
24
+ const command = registry.get(args[0]);
25
+ if (command) {
26
+ const action = args[1];
27
+ if (action && "subcommands" in command && action in command.subcommands)
28
+ return command.subcommands[action];
29
+ return command.help;
30
+ }
31
+ return getCommandHelp([]);
32
+ }
33
+ export async function runAxiCli(args = process.argv.slice(2)) {
34
+ process.env.METADATA_SERVER_DETECTION ??= "none";
35
+ try {
36
+ if (args.includes("--help") || args.includes("-h")) {
37
+ const helpIndex = args.findIndex((arg) => arg === "--help" || arg === "-h");
38
+ const prefix = args.slice(0, helpIndex);
39
+ if (prefix.some((arg) => arg.startsWith("-") && arg !== "-"))
40
+ usage("Help cannot follow command options");
41
+ process.stdout.write(getCommandHelp(prefix) + "\n");
42
+ return;
43
+ }
44
+ if (args.length === 0) {
45
+ try {
46
+ const auth = await getAuthClient();
47
+ process.stdout.write((await runHome(auth, resolveSite(auth))) + "\n");
48
+ }
49
+ catch (error) {
50
+ if (error instanceof AxiError && error.code === "VALIDATION_ERROR")
51
+ throw error;
52
+ process.stdout.write((await setupCommand(["status"])) + "\n");
53
+ }
54
+ return;
55
+ }
56
+ const [name, ...rest] = args;
57
+ if (name === "--version" || name === "-v" || name === "-V") {
58
+ const { readFileSync } = await import("node:fs");
59
+ process.stdout.write(`${JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version}\n`);
60
+ return;
61
+ }
62
+ const command = registry.get(name);
63
+ if (!command)
64
+ usage(`Unknown command '${name}'`);
65
+ process.stdout.write((await command.run(rest)) + "\n");
66
+ }
67
+ catch (error) {
68
+ const axi = error instanceof AxiError ? error : undefined;
69
+ const code = axi?.code ?? "INTERNAL_ERROR";
70
+ process.stdout.write(encode({
71
+ error: { code, message: error instanceof Error ? error.message : String(error) },
72
+ help: axi?.suggestions ?? [],
73
+ }) + "\n");
74
+ process.exitCode = code === "VALIDATION_ERROR" ? 2 : 1;
75
+ }
76
+ }