search-console-axi 0.1.1 → 0.1.2
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 +7 -8
- package/dist/bin/search-console-axi.js +2 -29
- package/dist/src/args.js +33 -0
- package/dist/src/auth.js +374 -0
- package/dist/src/cli.js +75 -0
- package/dist/src/commands/indexing.js +473 -0
- package/dist/src/commands/inspect.js +52 -0
- package/dist/src/commands/report.js +35 -0
- package/dist/src/commands/setup.js +51 -0
- package/dist/src/google.js +1 -0
- package/dist/src/help.js +4 -0
- package/dist/src/period.js +12 -0
- package/dist/src/setup-check.js +225 -0
- package/dist/src/setup-guide.js +16 -0
- package/dist/src/site.js +69 -0
- package/package.json +4 -4
- package/skills/search-console-axi/SKILL.md +1 -1
package/README.md
CHANGED
|
@@ -5,9 +5,8 @@
|
|
|
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
|
|
9
|
-
|
|
10
|
-
node dist/bin/search-console-axi.js --help
|
|
8
|
+
npm i -g search-console-axi
|
|
9
|
+
search-console-axi --help
|
|
11
10
|
```
|
|
12
11
|
|
|
13
12
|
## Authentication
|
|
@@ -21,19 +20,19 @@ The CLI validates credential JSON locally and authenticates through `google-auth
|
|
|
21
20
|
3. Load its JSON key from your secret manager into `SEARCH_CONSOLE_AXI_SA_KEY`. Never commit the key.
|
|
22
21
|
4. In Search Console, add the service-account email under **Settings > Users and permissions** with Restricted access.
|
|
23
22
|
|
|
24
|
-
For local key files, set `GOOGLE_APPLICATION_CREDENTIALS` or run `
|
|
23
|
+
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 `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
24
|
|
|
26
|
-
Run `
|
|
25
|
+
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
26
|
|
|
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`.
|
|
27
|
+
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`.
|
|
29
28
|
|
|
30
29
|
## Read Search Console
|
|
31
30
|
|
|
32
|
-
Run `
|
|
31
|
+
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.
|
|
33
32
|
|
|
34
33
|
## Send Indexing API notifications
|
|
35
34
|
|
|
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.
|
|
35
|
+
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
36
|
|
|
38
37
|
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
38
|
|
|
@@ -1,30 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { runAxiCli } from "
|
|
3
|
-
|
|
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();
|
package/dist/src/args.js
ADDED
|
@@ -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
|
+
}
|
package/dist/src/auth.js
ADDED
|
@@ -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
|
+
}
|
package/dist/src/cli.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
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 { usage } from "./args.js";
|
|
8
|
+
import { helpText } from "./help.js";
|
|
9
|
+
import { getAuthClient, setupCommand } from "./auth.js";
|
|
10
|
+
import { runHome } from "./google.js";
|
|
11
|
+
import { resolveSite } from "./site.js";
|
|
12
|
+
const description = "Google Search Console reporting, URL inspection, and preview-gated Indexing API notifications for agents";
|
|
13
|
+
export const commands = [setup, report, inspect, indexing];
|
|
14
|
+
const registry = new Map(commands.map((command) => [command.name, command]));
|
|
15
|
+
export function getCommandHelp(args) {
|
|
16
|
+
if (!args.length)
|
|
17
|
+
return helpText("search-console-axi", {
|
|
18
|
+
purpose: description,
|
|
19
|
+
flags: { "--help": "Show help", "--version": "Show version" },
|
|
20
|
+
examples: ["search-console-axi", "search-console-axi report"],
|
|
21
|
+
next: commands.map((command) => `search-console-axi ${command.name}`),
|
|
22
|
+
});
|
|
23
|
+
const command = registry.get(args[0]);
|
|
24
|
+
if (command) {
|
|
25
|
+
const action = args[1];
|
|
26
|
+
if (action && "subcommands" in command && action in command.subcommands)
|
|
27
|
+
return command.subcommands[action];
|
|
28
|
+
return command.help;
|
|
29
|
+
}
|
|
30
|
+
return getCommandHelp([]);
|
|
31
|
+
}
|
|
32
|
+
export async function runAxiCli(args = process.argv.slice(2)) {
|
|
33
|
+
process.env.METADATA_SERVER_DETECTION ??= "none";
|
|
34
|
+
try {
|
|
35
|
+
if (args.includes("--help") || args.includes("-h")) {
|
|
36
|
+
const helpIndex = args.findIndex((arg) => arg === "--help" || arg === "-h");
|
|
37
|
+
const prefix = args.slice(0, helpIndex);
|
|
38
|
+
if (prefix.some((arg) => arg.startsWith("-") && arg !== "-"))
|
|
39
|
+
usage("Help cannot follow command options");
|
|
40
|
+
process.stdout.write(getCommandHelp(prefix) + "\n");
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
if (args.length === 0) {
|
|
44
|
+
try {
|
|
45
|
+
const auth = await getAuthClient();
|
|
46
|
+
process.stdout.write((await runHome(auth, resolveSite(auth))) + "\n");
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
if (error instanceof AxiError && error.code === "VALIDATION_ERROR")
|
|
50
|
+
throw error;
|
|
51
|
+
process.stdout.write((await setupCommand(["status"])) + "\n");
|
|
52
|
+
}
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const [name, ...rest] = args;
|
|
56
|
+
if (name === "--version") {
|
|
57
|
+
const { readFileSync } = await import("node:fs");
|
|
58
|
+
process.stdout.write(`${JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version}\n`);
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
const command = registry.get(name);
|
|
62
|
+
if (!command)
|
|
63
|
+
usage(`Unknown command '${name}'`);
|
|
64
|
+
process.stdout.write((await command.run(rest)) + "\n");
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
const axi = error instanceof AxiError ? error : undefined;
|
|
68
|
+
const code = axi?.code ?? "INTERNAL_ERROR";
|
|
69
|
+
process.stdout.write(encode({
|
|
70
|
+
error: { code, message: error instanceof Error ? error.message : String(error) },
|
|
71
|
+
help: axi?.suggestions ?? [],
|
|
72
|
+
}) + "\n");
|
|
73
|
+
process.exitCode = code === "VALIDATION_ERROR" ? 2 : 1;
|
|
74
|
+
}
|
|
75
|
+
}
|