@nebulacomponents/citable 1.5.1 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/README.md +2 -0
- package/dist/universal/.agents/skills/citable/SKILL.md +7 -1
- package/dist/universal/.agents/skills/citable/VERSION +1 -1
- package/dist/universal/.agents/skills/citable/commands/measurement.md +16 -1
- package/dist/universal/.agents/skills/citable/manifest.json +7 -7
- package/dist/universal/.agents/skills/citable/schemas/connection.schema.json +1 -0
- package/dist/universal/.claude/skills/citable/SKILL.md +7 -1
- package/dist/universal/.claude/skills/citable/VERSION +1 -1
- package/dist/universal/.claude/skills/citable/commands/measurement.md +16 -1
- package/dist/universal/.claude/skills/citable/manifest.json +7 -7
- package/dist/universal/.claude/skills/citable/schemas/connection.schema.json +1 -0
- package/dist/universal/.cursor/skills/citable/SKILL.md +7 -1
- package/dist/universal/.cursor/skills/citable/VERSION +1 -1
- package/dist/universal/.cursor/skills/citable/commands/measurement.md +16 -1
- package/dist/universal/.cursor/skills/citable/manifest.json +7 -7
- package/dist/universal/.cursor/skills/citable/schemas/connection.schema.json +1 -0
- package/dist/universal/.gemini/skills/citable/SKILL.md +7 -1
- package/dist/universal/.gemini/skills/citable/VERSION +1 -1
- package/dist/universal/.gemini/skills/citable/commands/measurement.md +16 -1
- package/dist/universal/.gemini/skills/citable/manifest.json +7 -7
- package/dist/universal/.gemini/skills/citable/schemas/connection.schema.json +1 -0
- package/dist/universal/.github/skills/citable/SKILL.md +7 -1
- package/dist/universal/.github/skills/citable/VERSION +1 -1
- package/dist/universal/.github/skills/citable/commands/measurement.md +16 -1
- package/dist/universal/.github/skills/citable/manifest.json +7 -7
- package/dist/universal/.github/skills/citable/schemas/connection.schema.json +1 -0
- package/dist/universal/.kiro/skills/citable/SKILL.md +7 -1
- package/dist/universal/.kiro/skills/citable/VERSION +1 -1
- package/dist/universal/.kiro/skills/citable/commands/measurement.md +16 -1
- package/dist/universal/.kiro/skills/citable/manifest.json +7 -7
- package/dist/universal/.kiro/skills/citable/schemas/connection.schema.json +1 -0
- package/dist/universal/.opencode/skills/citable/SKILL.md +7 -1
- package/dist/universal/.opencode/skills/citable/VERSION +1 -1
- package/dist/universal/.opencode/skills/citable/commands/measurement.md +16 -1
- package/dist/universal/.opencode/skills/citable/manifest.json +7 -7
- package/dist/universal/.opencode/skills/citable/schemas/connection.schema.json +1 -0
- package/dist/universal/.pi/agent/skills/citable/SKILL.md +7 -1
- package/dist/universal/.pi/agent/skills/citable/VERSION +1 -1
- package/dist/universal/.pi/agent/skills/citable/commands/measurement.md +16 -1
- package/dist/universal/.pi/agent/skills/citable/manifest.json +7 -7
- package/dist/universal/.pi/agent/skills/citable/schemas/connection.schema.json +1 -0
- package/dist/universal/.qoder/skills/citable/SKILL.md +7 -1
- package/dist/universal/.qoder/skills/citable/VERSION +1 -1
- package/dist/universal/.qoder/skills/citable/commands/measurement.md +16 -1
- package/dist/universal/.qoder/skills/citable/manifest.json +7 -7
- package/dist/universal/.qoder/skills/citable/schemas/connection.schema.json +1 -0
- package/dist/universal/.rovodev/skills/citable/SKILL.md +7 -1
- package/dist/universal/.rovodev/skills/citable/VERSION +1 -1
- package/dist/universal/.rovodev/skills/citable/commands/measurement.md +16 -1
- package/dist/universal/.rovodev/skills/citable/manifest.json +7 -7
- package/dist/universal/.rovodev/skills/citable/schemas/connection.schema.json +1 -0
- package/dist/universal/.trae/skills/citable/SKILL.md +7 -1
- package/dist/universal/.trae/skills/citable/VERSION +1 -1
- package/dist/universal/.trae/skills/citable/commands/measurement.md +16 -1
- package/dist/universal/.trae/skills/citable/manifest.json +7 -7
- package/dist/universal/.trae/skills/citable/schemas/connection.schema.json +1 -0
- package/dist/universal/.trae-cn/skills/citable/SKILL.md +7 -1
- package/dist/universal/.trae-cn/skills/citable/VERSION +1 -1
- package/dist/universal/.trae-cn/skills/citable/commands/measurement.md +16 -1
- package/dist/universal/.trae-cn/skills/citable/manifest.json +7 -7
- package/dist/universal/.trae-cn/skills/citable/schemas/connection.schema.json +1 -0
- package/dist/universal/manifest.json +75 -75
- package/package.json +1 -1
- package/schemas/connection.schema.json +1 -0
- package/skill/SKILL.md +7 -1
- package/skill/commands/measurement.md +16 -1
- package/src/cli/index.js +41 -0
- package/src/commands/connect.js +90 -0
- package/src/connectors/ga4.js +59 -0
- package/src/connectors/gsc.js +41 -0
- package/src/connectors/http.js +19 -0
- package/src/connectors/index.js +14 -0
|
@@ -10,7 +10,7 @@ imports, and a disclosed custom citation-adapter protocol. It does not claim
|
|
|
10
10
|
Bing AI Performance automation or equivalence between an API adapter and a
|
|
11
11
|
consumer answer product. Preserve collector and product mode on every result.
|
|
12
12
|
|
|
13
|
-
# implemented metric and objective workflow
|
|
13
|
+
# implemented metric, connector, and objective workflow
|
|
14
14
|
|
|
15
15
|
`citable metrics import --provider <name> --input <csv|json>` validates every
|
|
16
16
|
row against a declared entry in `metrics.yaml` and writes immutable metric
|
|
@@ -27,6 +27,21 @@ absence of provider credentials is `not_configured`, not a finding and not
|
|
|
27
27
|
evidence of zero activity. Credentials must never enter registries or evidence
|
|
28
28
|
packages.
|
|
29
29
|
|
|
30
|
+
Live GSC and GA4 connections are explicitly optional. Configure only a
|
|
31
|
+
property identifier and the name of the environment variable that holds its
|
|
32
|
+
OAuth token; never place the token itself in `.citable/connections.yaml`.
|
|
33
|
+
`citable connect configure` and `disconnect` are dry runs unless `--write` is
|
|
34
|
+
used. `connect discover`, `validate`, and `sync` require read-only provider
|
|
35
|
+
authorization. `sync` writes declared metric observations with provider
|
|
36
|
+
limitations and advances a non-secret cursor. Provider errors are recorded as
|
|
37
|
+
connection state, not converted into zero observations or audit findings.
|
|
38
|
+
|
|
39
|
+
The GSC adapter collects final Search Analytics rows and inherits Search
|
|
40
|
+
Console aggregation, privacy filtering, and top-row availability limits. The GA4 adapter collects Data API
|
|
41
|
+
rows restricted to the `Organic Search` default channel group and inherits the
|
|
42
|
+
property's reporting identity, thresholding, attribution, and consent choices.
|
|
43
|
+
Neither source establishes that an intervention caused an observed change.
|
|
44
|
+
|
|
30
45
|
# measure seo
|
|
31
46
|
Inputs the operator exports (Search Console/Bing/analytics CSV or JSON).
|
|
32
47
|
Workflow: validate segmentation (brand vs non-brand, intent, page type,
|
package/src/cli/index.js
CHANGED
|
@@ -16,6 +16,7 @@ import { observe } from '../commands/observe.js';
|
|
|
16
16
|
import { applyRemediation } from '../commands/applyRemediation.js';
|
|
17
17
|
import { monitor } from '../commands/monitor.js';
|
|
18
18
|
import { evaluateObjective, importMetrics, initializeObjective, validateObjectives } from '../commands/measurement.js';
|
|
19
|
+
import { configureConnection, connectionStatus, discoverConnections, disconnectConnection, syncConnection, validateConnection } from '../commands/connect.js';
|
|
19
20
|
|
|
20
21
|
const HELP = `citable — SEO / AEO / GEO audit, remediation, validation, and governance
|
|
21
22
|
|
|
@@ -43,6 +44,12 @@ Commands
|
|
|
43
44
|
apply Apply a reviewed, hash-locked remediation spec
|
|
44
45
|
monitor [runA runB] Compare observation runs and emit regression alerts
|
|
45
46
|
metrics import Import declared metric observations from CSV/JSON
|
|
47
|
+
connect status List optional connectors and configured connections
|
|
48
|
+
connect configure Configure non-secret connection state (--write to save)
|
|
49
|
+
connect discover Discover provider properties using environment auth
|
|
50
|
+
connect validate Verify configured property access
|
|
51
|
+
connect sync Collect declared metrics into immutable observations
|
|
52
|
+
connect disconnect Remove optional connection state (--write to confirm)
|
|
46
53
|
objectives init Validate/add one objective from --input (--write to save)
|
|
47
54
|
objectives validate Validate objective contracts and metric references
|
|
48
55
|
evaluate [objective-id] Compare objective baseline and evaluation windows
|
|
@@ -54,6 +61,11 @@ Options
|
|
|
54
61
|
--ref-date <YYYY-MM-DD> Reference date for expiry/staleness checks (default: today)
|
|
55
62
|
--input <file> Import file or remediation specification
|
|
56
63
|
--provider <name> Provider label for imported observations
|
|
64
|
+
--connection-id <id> Connection registry identifier
|
|
65
|
+
--property-id <id> Provider property or site identifier
|
|
66
|
+
--credential-env <name> Environment variable containing the access token
|
|
67
|
+
--start-date <YYYY-MM-DD> Connector collection window start
|
|
68
|
+
--end-date <YYYY-MM-DD> Connector collection window end
|
|
57
69
|
--api-key <key> API key (prefer provider environment variables)
|
|
58
70
|
--site-url <property> Search Console property for live URL inspection
|
|
59
71
|
--access-token <token> OAuth token (prefer provider environment variables)
|
|
@@ -76,6 +88,11 @@ function parseArgs(argv) {
|
|
|
76
88
|
else if (a === '--ref-date') args.refDate = argv[++i];
|
|
77
89
|
else if (a === '--input') args.input = argv[++i];
|
|
78
90
|
else if (a === '--provider') args.provider = argv[++i];
|
|
91
|
+
else if (a === '--connection-id') args.connectionId = argv[++i];
|
|
92
|
+
else if (a === '--property-id') args.propertyId = argv[++i];
|
|
93
|
+
else if (a === '--credential-env') args.credentialEnv = argv[++i];
|
|
94
|
+
else if (a === '--start-date') args.startDate = argv[++i];
|
|
95
|
+
else if (a === '--end-date') args.endDate = argv[++i];
|
|
79
96
|
else if (a === '--api-key') args.apiKey = argv[++i];
|
|
80
97
|
else if (a === '--site-url') args.siteUrl = argv[++i];
|
|
81
98
|
else if (a === '--access-token') args.accessToken = argv[++i];
|
|
@@ -178,6 +195,30 @@ export async function main(argv = process.argv.slice(2), options = {}) {
|
|
|
178
195
|
out(args, `metrics import: ${r.summary.total} observation(s) from ${args.provider}\nEvidence package: ${r.dir}`, r);
|
|
179
196
|
break;
|
|
180
197
|
}
|
|
198
|
+
case 'connect': {
|
|
199
|
+
const mode = args._[0];
|
|
200
|
+
if (mode === 'status') {
|
|
201
|
+
const r = connectionStatus(root);
|
|
202
|
+
out(args, `connect status: ${r.connections.length} configured connection(s)\n` + r.available.map((item) => ` ${item.provider}: token via ${item.credential_env}`).join('\n'), r);
|
|
203
|
+
} else if (mode === 'configure') {
|
|
204
|
+
const r = configureConnection(root, args);
|
|
205
|
+
out(args, `connect configure: ${r.connection.connection_id} ${r.written ? 'written' : 'valid (dry run; use --write to save)'}`, r);
|
|
206
|
+
} else if (mode === 'discover') {
|
|
207
|
+
const r = await discoverConnections(root, args);
|
|
208
|
+
out(args, `connect discover ${r.provider}: ${r.properties.length} accessible property/properties`, r);
|
|
209
|
+
} else if (mode === 'validate') {
|
|
210
|
+
const r = await validateConnection(root, args);
|
|
211
|
+
out(args, `connect validate ${r.connection_id}: ${r.valid ? 'accessible' : 'not accessible'}`, r);
|
|
212
|
+
if (!r.valid) process.exitCode = 1;
|
|
213
|
+
} else if (mode === 'sync') {
|
|
214
|
+
const r = await syncConnection(root, args);
|
|
215
|
+
out(args, `connect sync ${r.connection_id}: ${r.summary.total} metric observation(s)\nEvidence package: ${r.dir}`, r);
|
|
216
|
+
} else if (mode === 'disconnect') {
|
|
217
|
+
const r = disconnectConnection(root, args);
|
|
218
|
+
out(args, `connect disconnect ${r.connection_id}: ${r.disconnected ? 'removed' : 'dry run; use --write to remove'}`, r);
|
|
219
|
+
} else throw new Error('usage: citable connect <status|configure|discover|validate|sync> [options]');
|
|
220
|
+
break;
|
|
221
|
+
}
|
|
181
222
|
case 'objectives': {
|
|
182
223
|
const mode = args._[0];
|
|
183
224
|
if (mode === 'init') {
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { loadRegistries, saveRegistry } from '../registries/index.js';
|
|
2
|
+
import { envelope, observationRun } from '../observations/common.js';
|
|
3
|
+
import { getConnector, listConnectors } from '../connectors/index.js';
|
|
4
|
+
import { validateAgainst } from '../shared/schemaValidator.js';
|
|
5
|
+
|
|
6
|
+
function findConnection(root, connectionId) {
|
|
7
|
+
const loaded = loadRegistries(root);
|
|
8
|
+
if (loaded.problems.length) throw new Error(`registry validation failed: ${loaded.problems.join('; ')}`);
|
|
9
|
+
const connection = loaded.registries.connections.entries.find((item) => item.connection_id === connectionId);
|
|
10
|
+
if (!connection) throw new Error(`connection not found: ${connectionId}`);
|
|
11
|
+
return { ...loaded, connection };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function contextFor(connection, connector, options) {
|
|
15
|
+
const credentialEnv = connection.credential_env || connector.defaultCredentialEnv;
|
|
16
|
+
return { token: options.accessToken || options.env?.[credentialEnv] || process.env[credentialEnv], fetchImpl: options.fetchImpl, credentialEnv };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function connectionStatus(root) {
|
|
20
|
+
const { registries, problems } = loadRegistries(root);
|
|
21
|
+
if (problems.length) throw new Error(`registry validation failed: ${problems.join('; ')}`);
|
|
22
|
+
return { available: listConnectors(), connections: registries.connections.entries };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function configureConnection(root, { provider, connectionId, propertyId, credentialEnv, write = false }) {
|
|
26
|
+
if (!provider || !connectionId || !propertyId) throw new Error('connect configure requires --provider, --connection-id, and --property-id');
|
|
27
|
+
const connector = getConnector(provider);
|
|
28
|
+
const { registries, problems } = loadRegistries(root);
|
|
29
|
+
if (problems.length) throw new Error(`registry validation failed: ${problems.join('; ')}`);
|
|
30
|
+
const entry = { connection_id: connectionId, provider: connector.provider, property_id: String(propertyId), state: 'configured', authentication: 'environment', credential_env: credentialEnv || connector.defaultCredentialEnv, scopes: connector.readOnlyScopes, last_synchronized_at: null, cursor: null, limitations: [] };
|
|
31
|
+
const entries = registries.connections.entries.filter((item) => item.connection_id !== connectionId);
|
|
32
|
+
const candidate = { ...registries.connections, entries: [...entries, entry] };
|
|
33
|
+
const check = validateAgainst('connection.schema.json', candidate);
|
|
34
|
+
if (!check.valid) throw new Error(`connection violates contract: ${check.errors.join('; ')}`);
|
|
35
|
+
if (write) saveRegistry(root, 'connections', candidate);
|
|
36
|
+
return { connection: entry, written: write };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function discoverConnections(root, { provider, accessToken, env, fetchImpl } = {}) {
|
|
40
|
+
const connector = getConnector(provider);
|
|
41
|
+
const context = { token: accessToken || env?.[connector.defaultCredentialEnv] || process.env[connector.defaultCredentialEnv], fetchImpl };
|
|
42
|
+
return { provider: connector.provider, properties: await connector.discoverProperties(context), credential_env: connector.defaultCredentialEnv };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function validateConnection(root, { connectionId, accessToken, env, fetchImpl } = {}) {
|
|
46
|
+
const { connection } = findConnection(root, connectionId);
|
|
47
|
+
const connector = getConnector(connection.provider);
|
|
48
|
+
const result = await connector.validateConnection(connection, contextFor(connection, connector, { accessToken, env, fetchImpl }));
|
|
49
|
+
return { connection_id: connectionId, provider: connection.provider, state: result.valid ? 'configured' : 'permission_denied', ...result };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function disconnectConnection(root, { connectionId, write = false } = {}) {
|
|
53
|
+
const loaded = findConnection(root, connectionId);
|
|
54
|
+
const candidate = { ...loaded.registries.connections, entries: loaded.registries.connections.entries.filter((item) => item.connection_id !== connectionId) };
|
|
55
|
+
if (write) saveRegistry(root, 'connections', candidate);
|
|
56
|
+
return { connection_id: connectionId, disconnected: write, state: write ? 'not_configured' : loaded.connection.state };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function syncConnection(root, { connectionId, startDate, endDate, accessToken, env, fetchImpl } = {}) {
|
|
60
|
+
if (!startDate || !endDate) throw new Error('connect sync requires --start-date and --end-date');
|
|
61
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(startDate) || !/^\d{4}-\d{2}-\d{2}$/.test(endDate) || Number.isNaN(Date.parse(`${startDate}T00:00:00Z`)) || Number.isNaN(Date.parse(`${endDate}T00:00:00Z`))) throw new Error('connector dates must use valid YYYY-MM-DD values');
|
|
62
|
+
if (startDate > endDate) throw new Error('connector start-date must not be after end-date');
|
|
63
|
+
const loaded = findConnection(root, connectionId);
|
|
64
|
+
const connector = getConnector(loaded.connection.provider);
|
|
65
|
+
const metrics = loaded.registries.metrics.entries.filter((item) => item.provider.toLowerCase() === connector.provider && item.status !== 'deprecated');
|
|
66
|
+
if (!metrics.length) throw new Error(`no active metrics declared for provider ${connector.provider}`);
|
|
67
|
+
const supported = connector.describeMetrics();
|
|
68
|
+
const unsupported = metrics.filter((item) => !supported[item.external_name]);
|
|
69
|
+
if (unsupported.length) throw new Error(`unsupported ${connector.provider} metrics: ${unsupported.map((item) => item.external_name).join(', ')}`);
|
|
70
|
+
let result;
|
|
71
|
+
try {
|
|
72
|
+
result = await connector.sync(loaded.connection, metrics, { startDate, endDate, ...contextFor(loaded.connection, connector, { accessToken, env, fetchImpl }) });
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if (error.connectorState) {
|
|
75
|
+
const failed = { ...loaded.registries.connections, entries: loaded.registries.connections.entries.map((item) => item.connection_id === connectionId ? { ...item, state: error.connectorState, limitations: [`${connector.provider} synchronization did not complete; inspect command output and provider access.`] } : item) };
|
|
76
|
+
saveRegistry(root, 'connections', failed);
|
|
77
|
+
}
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
const observations = result.rows.map((row) => envelope('metric', {
|
|
81
|
+
metric_id: row.metric.metric_id, provider: connector.provider, external_name: row.metric.external_name,
|
|
82
|
+
value: Number(row.value), unit: row.metric.unit === 'custom' ? row.metric.custom_unit : row.metric.unit,
|
|
83
|
+
aggregation: row.metric.aggregation, observed_at: row.observed_at, period_start: row.observed_at,
|
|
84
|
+
period_end: row.observed_at, dimensions: row.dimensions,
|
|
85
|
+
}, { method: 'live_api', source: connector.provider, limitations: [...row.metric.limitations, ...result.limitations] }));
|
|
86
|
+
const run = observationRun(root, 'connect sync', loaded.connection.property_id, observations);
|
|
87
|
+
const updated = { ...loaded.registries.connections, entries: loaded.registries.connections.entries.map((item) => item.connection_id === connectionId ? { ...item, state: 'synchronized', last_synchronized_at: new Date().toISOString(), cursor: result.cursor, limitations: result.limitations } : item) };
|
|
88
|
+
saveRegistry(root, 'connections', updated);
|
|
89
|
+
return { ...run, connection_id: connectionId, provider: connector.provider };
|
|
90
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { providerRequest } from './http.js';
|
|
2
|
+
|
|
3
|
+
const DATA = 'https://analyticsdata.googleapis.com/v1beta';
|
|
4
|
+
const ADMIN = 'https://analyticsadmin.googleapis.com/v1beta';
|
|
5
|
+
const METRICS = {
|
|
6
|
+
sessions: { unit: 'count', value_type: 'integer' },
|
|
7
|
+
engagedSessions: { unit: 'count', value_type: 'integer' },
|
|
8
|
+
keyEvents: { unit: 'count', value_type: 'number' },
|
|
9
|
+
totalRevenue: { unit: 'currency', value_type: 'number' },
|
|
10
|
+
};
|
|
11
|
+
const DIMENSIONS = new Set(['date', 'landingPagePlusQueryString', 'sessionDefaultChannelGroup', 'country', 'deviceCategory']);
|
|
12
|
+
|
|
13
|
+
export const ga4Connector = {
|
|
14
|
+
provider: 'ga4', defaultCredentialEnv: 'GA4_ACCESS_TOKEN', readOnlyScopes: ['https://www.googleapis.com/auth/analytics.readonly'],
|
|
15
|
+
describeMetrics() { return METRICS; },
|
|
16
|
+
async discoverProperties(context) {
|
|
17
|
+
const properties = [];
|
|
18
|
+
let pageToken;
|
|
19
|
+
do {
|
|
20
|
+
const query = `?pageSize=200${pageToken ? `&pageToken=${encodeURIComponent(pageToken)}` : ''}`;
|
|
21
|
+
const result = await providerRequest(`${ADMIN}/accountSummaries${query}`, context);
|
|
22
|
+
for (const account of result.accountSummaries || []) for (const property of account.propertySummaries || []) {
|
|
23
|
+
properties.push({ property_id: property.property.replace(/^properties\//, ''), display_name: property.displayName, account: account.account });
|
|
24
|
+
}
|
|
25
|
+
pageToken = result.nextPageToken;
|
|
26
|
+
} while (pageToken);
|
|
27
|
+
return properties;
|
|
28
|
+
},
|
|
29
|
+
async validateConnection(connection, context) {
|
|
30
|
+
const properties = await this.discoverProperties(context);
|
|
31
|
+
return { valid: properties.some((item) => item.property_id === String(connection.property_id)), properties };
|
|
32
|
+
},
|
|
33
|
+
async sync(connection, metrics, { startDate, endDate, ...context }) {
|
|
34
|
+
const dimensions = [...new Set(metrics.flatMap((metric) => metric.dimensions).filter((item) => DIMENSIONS.has(item)))];
|
|
35
|
+
if (!dimensions.includes('date')) dimensions.unshift('date');
|
|
36
|
+
if (!dimensions.includes('landingPagePlusQueryString')) dimensions.push('landingPagePlusQueryString');
|
|
37
|
+
const rows = [];
|
|
38
|
+
const limitations = [];
|
|
39
|
+
let offset = 0;
|
|
40
|
+
do {
|
|
41
|
+
const result = await providerRequest(`${DATA}/properties/${encodeURIComponent(connection.property_id)}:runReport`, {
|
|
42
|
+
...context, method: 'POST', body: {
|
|
43
|
+
dateRanges: [{ startDate, endDate }], dimensions: dimensions.map((name) => ({ name })),
|
|
44
|
+
metrics: metrics.map((metric) => ({ name: metric.external_name })), limit: '100000', offset: String(offset),
|
|
45
|
+
dimensionFilter: { filter: { fieldName: 'sessionDefaultChannelGroup', stringFilter: { matchType: 'EXACT', value: 'Organic Search' } } },
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
for (const row of result.rows || []) {
|
|
49
|
+
const values = Object.fromEntries(dimensions.map((name, index) => [name === 'landingPagePlusQueryString' ? 'url' : name, row.dimensionValues[index]?.value]));
|
|
50
|
+
const date = values.date?.replace(/^(\d{4})(\d{2})(\d{2})$/, '$1-$2-$3');
|
|
51
|
+
rows.push(...metrics.map((metric, index) => ({ metric, value: Number(row.metricValues[index]?.value), dimensions: values, observed_at: `${date}T00:00:00.000Z` })));
|
|
52
|
+
}
|
|
53
|
+
if (result.metadata?.dataLossFromOtherRow) limitations.push('Provider reports data loss from the (other) row.');
|
|
54
|
+
offset += (result.rows || []).length;
|
|
55
|
+
if (!result.rowCount || offset >= result.rowCount || !(result.rows || []).length) break;
|
|
56
|
+
} while (true);
|
|
57
|
+
return { rows, cursor: endDate, limitations: [...new Set([...limitations, 'GA4 reporting identity, thresholding, attribution, and consent configuration affect results.', 'Sync is filtered to Organic Search sessions.'])] };
|
|
58
|
+
},
|
|
59
|
+
};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { providerRequest } from './http.js';
|
|
2
|
+
|
|
3
|
+
const BASE = 'https://www.googleapis.com/webmasters/v3';
|
|
4
|
+
const METRICS = {
|
|
5
|
+
clicks: { unit: 'count', value_type: 'integer' },
|
|
6
|
+
impressions: { unit: 'count', value_type: 'integer' },
|
|
7
|
+
ctr: { unit: 'ratio', value_type: 'number' },
|
|
8
|
+
position: { unit: 'position', value_type: 'number' },
|
|
9
|
+
};
|
|
10
|
+
const DIMENSIONS = new Set(['date', 'query', 'page', 'country', 'device', 'searchAppearance']);
|
|
11
|
+
|
|
12
|
+
export const gscConnector = {
|
|
13
|
+
provider: 'gsc', defaultCredentialEnv: 'GSC_ACCESS_TOKEN', readOnlyScopes: ['https://www.googleapis.com/auth/webmasters.readonly'],
|
|
14
|
+
describeMetrics() { return METRICS; },
|
|
15
|
+
async discoverProperties(context) {
|
|
16
|
+
const result = await providerRequest(`${BASE}/sites`, context);
|
|
17
|
+
return (result.siteEntry || []).map((item) => ({ property_id: item.siteUrl, permission: item.permissionLevel }));
|
|
18
|
+
},
|
|
19
|
+
async validateConnection(connection, context) {
|
|
20
|
+
const properties = await this.discoverProperties(context);
|
|
21
|
+
return { valid: properties.some((item) => item.property_id === connection.property_id), properties };
|
|
22
|
+
},
|
|
23
|
+
async sync(connection, metrics, { startDate, endDate, ...context }) {
|
|
24
|
+
const dimensions = [...new Set(metrics.flatMap((metric) => metric.dimensions).filter((item) => DIMENSIONS.has(item)))];
|
|
25
|
+
if (!dimensions.includes('date')) dimensions.unshift('date');
|
|
26
|
+
const rows = [];
|
|
27
|
+
let startRow = 0;
|
|
28
|
+
do {
|
|
29
|
+
const result = await providerRequest(`${BASE}/sites/${encodeURIComponent(connection.property_id)}/searchAnalytics/query`, {
|
|
30
|
+
...context, method: 'POST', body: { startDate, endDate, dimensions, rowLimit: 25000, startRow, dataState: 'final' },
|
|
31
|
+
});
|
|
32
|
+
for (const row of result.rows || []) {
|
|
33
|
+
const values = Object.fromEntries(dimensions.map((name, index) => [name === 'page' ? 'url' : name, row.keys[index]]));
|
|
34
|
+
for (const metric of metrics) rows.push({ metric, value: row[metric.external_name], dimensions: values, observed_at: `${values.date}T00:00:00.000Z` });
|
|
35
|
+
}
|
|
36
|
+
if ((result.rows || []).length < 25000) break;
|
|
37
|
+
startRow += 25000;
|
|
38
|
+
} while (true);
|
|
39
|
+
return { rows, cursor: endDate, limitations: ['Search Console privacy filtering and aggregation apply.', 'Search Analytics does not guarantee every data row; the API can return top rows only.', 'Final data can still be revised by the provider.'] };
|
|
40
|
+
},
|
|
41
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
const RETRYABLE = new Set([429, 500, 502, 503, 504]);
|
|
2
|
+
|
|
3
|
+
export async function providerRequest(url, { token, fetchImpl = globalThis.fetch, method = 'GET', body, attempts = 3 } = {}) {
|
|
4
|
+
if (!token) throw Object.assign(new Error('authorization is not configured'), { connectorState: 'not_configured' });
|
|
5
|
+
let response;
|
|
6
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
7
|
+
response = await fetchImpl(url, {
|
|
8
|
+
method,
|
|
9
|
+
headers: { authorization: `Bearer ${token}`, accept: 'application/json', ...(body ? { 'content-type': 'application/json' } : {}) },
|
|
10
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
11
|
+
});
|
|
12
|
+
if (response.ok) return response.json();
|
|
13
|
+
const detail = (await response.text()).slice(0, 300);
|
|
14
|
+
if (!RETRYABLE.has(response.status) || attempt === attempts) {
|
|
15
|
+
const states = { 401: 'authorization_expired', 403: 'permission_denied', 429: 'quota_limited' };
|
|
16
|
+
throw Object.assign(new Error(`provider returned ${response.status}: ${detail}`), { connectorState: states[response.status] || 'temporarily_unavailable' });
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { gscConnector } from './gsc.js';
|
|
2
|
+
import { ga4Connector } from './ga4.js';
|
|
3
|
+
|
|
4
|
+
const CONNECTORS = new Map([gscConnector, ga4Connector].map((connector) => [connector.provider, connector]));
|
|
5
|
+
|
|
6
|
+
export function getConnector(provider) {
|
|
7
|
+
const connector = CONNECTORS.get(String(provider).toLowerCase());
|
|
8
|
+
if (!connector) throw new Error(`unsupported connector provider: ${provider}`);
|
|
9
|
+
return connector;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function listConnectors() {
|
|
13
|
+
return [...CONNECTORS.values()].map((item) => ({ provider: item.provider, credential_env: item.defaultCredentialEnv, scopes: item.readOnlyScopes, metrics: Object.keys(item.describeMetrics()) }));
|
|
14
|
+
}
|