@canonry/canonry 7.51.5 → 7.51.6

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.
Files changed (116) hide show
  1. package/dist/ads-ABAT3K4K.js +544 -0
  2. package/dist/agent-5G4DRLYX.js +70 -0
  3. package/dist/agent-ask-UDVCZRO7.js +139 -0
  4. package/dist/agent-conversations-5E4JP2QZ.js +52 -0
  5. package/dist/agent-memory-7IIJ4HGZ.js +92 -0
  6. package/dist/agent-providers-BOXPUXZ4.js +55 -0
  7. package/dist/agent-transcript-4O56G6PQ.js +77 -0
  8. package/dist/analytics-PKMWX5XL.js +240 -0
  9. package/dist/apply-OK4XEBDA.js +175 -0
  10. package/dist/backfill-2OT56CX2.js +41 -0
  11. package/dist/backlinks-547WCHND.js +303 -0
  12. package/dist/bing-ZVBV4ZD5.js +418 -0
  13. package/dist/bootstrap-HUB7XQ73.js +326 -0
  14. package/dist/cdp-KQKQ4PWJ.js +162 -0
  15. package/dist/chunk-2G6IP3MO.js +517 -0
  16. package/dist/chunk-42D2LE2B.js +1273 -0
  17. package/dist/chunk-4MJYGB56.js +124 -0
  18. package/dist/chunk-63ISSSGX.js +9150 -0
  19. package/dist/{chunk-PLYJX67A.js → chunk-6G6FTDWC.js} +8080 -13939
  20. package/dist/chunk-6GO5VVAC.js +15 -0
  21. package/dist/{chunk-4YCGZGA3.js → chunk-73P65KPW.js} +2 -2
  22. package/dist/chunk-7B2Q4NJE.js +133 -0
  23. package/dist/{chunk-JBZZEIM2.js → chunk-7WZ2FPB4.js} +2 -13
  24. package/dist/chunk-AOJU5LKX.js +8 -0
  25. package/dist/chunk-B2FR2ZQ4.js +420 -0
  26. package/dist/{chunk-HAHXPJQ5.js → chunk-B5J675KK.js} +16 -1684
  27. package/dist/{chunk-SFMWHPMX.js → chunk-D6COIM3U.js} +17128 -17143
  28. package/dist/{chunk-A3WSAAQS.js → chunk-DGVUTH7W.js} +9086 -34522
  29. package/dist/chunk-ELCLGWUT.js +83 -0
  30. package/dist/chunk-GO2J7SYT.js +1034 -0
  31. package/dist/chunk-HACZUMGM.js +145 -0
  32. package/dist/chunk-HM4NNKLG.js +94 -0
  33. package/dist/chunk-I3A56PFP.js +58 -0
  34. package/dist/chunk-I77PLCWG.js +961 -0
  35. package/dist/chunk-ISOQPVPY.js +232 -0
  36. package/dist/chunk-KFT5LOP2.js +610 -0
  37. package/dist/chunk-MLKGABMK.js +9 -0
  38. package/dist/chunk-MMEO22MF.js +38 -0
  39. package/dist/chunk-NHQ2U5I4.js +78 -0
  40. package/dist/chunk-PCXRFT3N.js +530 -0
  41. package/dist/chunk-PITHTCAX.js +15376 -0
  42. package/dist/chunk-QWKPSFGL.js +30 -0
  43. package/dist/chunk-RKIXES2B.js +609 -0
  44. package/dist/chunk-TSENU4GG.js +18 -0
  45. package/dist/{chunk-HLVEB5TB.js → chunk-TUTKNUMV.js} +7 -5
  46. package/dist/chunk-U3AHE2RT.js +1160 -0
  47. package/dist/chunk-UQ3MOZGC.js +644 -0
  48. package/dist/{chunk-AZFPA7JV.js → chunk-VBCE4CLX.js} +6 -4
  49. package/dist/chunk-VJWDBFSL.js +69 -0
  50. package/dist/chunk-VYMZ3QXG.js +8264 -0
  51. package/dist/chunk-WAULJDKO.js +2686 -0
  52. package/dist/chunk-WDFI5YMD.js +204 -0
  53. package/dist/chunk-XEBKF4N5.js +8 -0
  54. package/dist/chunk-Z7IUAJOF.js +13 -0
  55. package/dist/{chunk-KEATAHXH.js → chunk-ZWJRY5UI.js} +358 -581
  56. package/dist/chunk-ZXUAWVWM.js +15 -0
  57. package/dist/citations-UYB2RU5U.js +106 -0
  58. package/dist/{cli-catalog-MO6Z2CIZ.js → cli-catalog-F6FI7NB2.js} +5 -3
  59. package/dist/cli-commands-ZG5ILKDA.js +19 -0
  60. package/dist/cli.js +35 -29
  61. package/dist/competitor-EKP4R7YY.js +561 -0
  62. package/dist/content-DREE6JF3.js +257 -0
  63. package/dist/dashboard-ZALEOLLU.js +71 -0
  64. package/dist/demo-JG4Y22O4.js +75 -0
  65. package/dist/{demo-server-GIWDJGJX.js → demo-server-3A4J2C65.js} +22 -9
  66. package/dist/discover-W6GMD2HS.js +372 -0
  67. package/dist/discover-eval-CKFZHRBW.js +282 -0
  68. package/dist/doctor-TNGBSUMA.js +152 -0
  69. package/dist/evidence-3H2GFQBZ.js +57 -0
  70. package/dist/export-cmd-WUIKU5GK.js +49 -0
  71. package/dist/ga-JI6REFO4.js +911 -0
  72. package/dist/gbp-4ENDM5NS.js +370 -0
  73. package/dist/google-HKQSCLOC.js +946 -0
  74. package/dist/google-marketing-KQR5J2S4.js +403 -0
  75. package/dist/health-cmd-TS7EMMCS.js +64 -0
  76. package/dist/history-MSD5DK6K.js +90 -0
  77. package/dist/index.d.ts +47 -47
  78. package/dist/index.js +29 -6
  79. package/dist/init-L6WAEOWX.js +432 -0
  80. package/dist/insights-RTZ3IZTD.js +63 -0
  81. package/dist/intelligence-service-TH52PCNJ.js +15 -0
  82. package/dist/keys-625DZBRM.js +116 -0
  83. package/dist/keyword-CW46RNRR.js +164 -0
  84. package/dist/logs-V33SHBIW.js +30 -0
  85. package/dist/mcp-DFEDPSEG.js +14 -0
  86. package/dist/mcp.js +14 -5
  87. package/dist/measurement-plan-6W37RUOP.js +42 -0
  88. package/dist/notify-DSUOT7WO.js +125 -0
  89. package/dist/organic-evidence-BMN6L4OB.js +53 -0
  90. package/dist/overview-WRRMBZ6S.js +213 -0
  91. package/dist/project-2GJIU3FE.js +460 -0
  92. package/dist/query-3XPMGJUA.js +211 -0
  93. package/dist/research-V433CKJ4.js +200 -0
  94. package/dist/results-export-RGBU7QQQ.js +27 -0
  95. package/dist/run-NIAC6OJN.js +31 -0
  96. package/dist/schedule-KDWXRIE7.js +177 -0
  97. package/dist/search-626MPUJN.js +42 -0
  98. package/dist/serve-73SMMASI.js +557 -0
  99. package/dist/session-7WWOETZB.js +47 -0
  100. package/dist/settings-VKFQO6F2.js +107 -0
  101. package/dist/skills-5HC5H7TE.js +33 -0
  102. package/dist/snapshot-BSJUHFBC.js +538 -0
  103. package/dist/src-F6HM73TN.js +316 -0
  104. package/dist/status-V4OWP7LZ.js +126 -0
  105. package/dist/support-ARF4HER7.js +24 -0
  106. package/dist/technical-aeo-TG7CGU3F.js +625 -0
  107. package/dist/telemetry-O2IUNUBW.js +118 -0
  108. package/dist/tools-2GJIDKND.js +41 -0
  109. package/dist/traffic-XV4I3UPH.js +1295 -0
  110. package/dist/users-VGBLDL5K.js +170 -0
  111. package/dist/visibility-stats-UKJYJ6PP.js +241 -0
  112. package/dist/wordpress-JZA7CGC6.js +600 -0
  113. package/package.json +1 -1
  114. package/dist/chunk-4QQYYRHV.js +0 -23082
  115. package/dist/cli-commands-FOJR3HHU.js +0 -15
  116. package/dist/intelligence-service-XQCNWAPL.js +0 -9
@@ -0,0 +1,911 @@
1
+ import {
2
+ createApiClient
3
+ } from "./chunk-B5J675KK.js";
4
+ import "./chunk-UQ3MOZGC.js";
5
+ import {
6
+ emitJsonl
7
+ } from "./chunk-Z7IUAJOF.js";
8
+ import "./chunk-AOJU5LKX.js";
9
+ import {
10
+ CliError,
11
+ isMachineFormat,
12
+ usageError
13
+ } from "./chunk-HGMYEDAQ.js";
14
+ import {
15
+ GA_SEARCH_LANDING_WINDOW_DAYS,
16
+ GaMoverChangeBases,
17
+ describeError,
18
+ formatPercent,
19
+ formatValidationIssues,
20
+ gaAcquisitionQuerySchema,
21
+ gaSearchLandingHasSearchData,
22
+ gaSearchLandingPageLabel
23
+ } from "./chunk-D6COIM3U.js";
24
+ import "./chunk-MLKGABMK.js";
25
+
26
+ // src/commands/ga.ts
27
+ function getClient() {
28
+ return createApiClient();
29
+ }
30
+ function rangeParams(opts, extra) {
31
+ const params = { ...extra };
32
+ if (opts?.window) params.window = opts.window;
33
+ if (opts?.startDate) params.startDate = opts.startDate;
34
+ if (opts?.endDate) params.endDate = opts.endDate;
35
+ return Object.keys(params).length > 0 ? params : void 0;
36
+ }
37
+ function isRangeScoped(opts) {
38
+ return Boolean(opts?.window || opts?.startDate || opts?.endDate);
39
+ }
40
+ async function gaAcquisition(project, opts) {
41
+ const { format, ...input } = opts;
42
+ const parsed = gaAcquisitionQuerySchema.safeParse(input);
43
+ if (!parsed.success) throw usageError(formatValidationIssues(parsed.error.issues), { details: { issues: parsed.error.issues.map(({ path, message }) => ({ path, message })) } });
44
+ const result = await createApiClient().gaAcquisition(project, parsed.data);
45
+ if (isMachineFormat(format)) {
46
+ if (format === "jsonl") emitJsonl(result.rows.map((row) => ({ project, windowStart: result.window.startDate, windowEnd: result.window.endDate, ...row })));
47
+ else console.log(JSON.stringify(result, null, 2));
48
+ return;
49
+ }
50
+ console.log(`Stored GA4 acquisition for "${project}": ${result.rows.length} of ${result.totalRows} rows, ${result.totalSessions} sessions in window`);
51
+ console.log(`Status: ${result.status}; synced: ${result.syncedAt ?? "never"}; coverage: ${result.coverage.earliestDate ?? "-"} to ${result.coverage.latestDate ?? "-"}`);
52
+ if (result.error) console.log(`Stored sync error: ${result.error}`);
53
+ console.log([...result.groupBy, "sessions"].join(" "));
54
+ for (const row of result.rows) console.log([...result.groupBy.map((key) => row[key] ?? "-"), row.sessions].join(" "));
55
+ }
56
+ async function gaConnect(project, opts) {
57
+ if (!opts.propertyId) {
58
+ throw new CliError({
59
+ code: "GA_PROPERTY_ID_REQUIRED",
60
+ message: "Property ID is required (pass --property-id)",
61
+ displayMessage: "Error: --property-id is required",
62
+ details: { project }
63
+ });
64
+ }
65
+ const body = {
66
+ propertyId: opts.propertyId
67
+ };
68
+ if (opts.keyFile) {
69
+ const fs = await import("fs");
70
+ try {
71
+ const content = fs.readFileSync(opts.keyFile, "utf-8");
72
+ JSON.parse(content);
73
+ body.keyJson = content;
74
+ } catch (e) {
75
+ const msg = describeError(e);
76
+ throw new CliError({
77
+ code: "GA_KEY_FILE_READ_ERROR",
78
+ message: `Failed to read key file: ${msg}`,
79
+ displayMessage: `Error: failed to read key file "${opts.keyFile}": ${msg}`,
80
+ details: { project, keyFile: opts.keyFile }
81
+ });
82
+ }
83
+ } else if (opts.keyJson) {
84
+ body.keyJson = opts.keyJson;
85
+ }
86
+ const client = getClient();
87
+ const result = await client.gaConnect(project, body);
88
+ if (isMachineFormat(opts.format)) {
89
+ console.log(JSON.stringify(result, null, 2));
90
+ return;
91
+ }
92
+ console.log(`GA4 connected for project "${project}".`);
93
+ console.log(` Property ID: ${result.propertyId}`);
94
+ if (result.authMethod === "service-account" && result.clientEmail) {
95
+ console.log(` Auth: service account (${result.clientEmail})`);
96
+ } else {
97
+ console.log(` Auth: OAuth (canonry google connect --type ga4)`);
98
+ }
99
+ }
100
+ async function gaDisconnect(project, format) {
101
+ const client = getClient();
102
+ await client.gaDisconnect(project);
103
+ if (isMachineFormat(format)) {
104
+ console.log(JSON.stringify({ project, disconnected: true }, null, 2));
105
+ return;
106
+ }
107
+ console.log(`GA4 disconnected from project "${project}".`);
108
+ }
109
+ async function gaStatus(project, format) {
110
+ const client = getClient();
111
+ const result = await client.gaStatus(project);
112
+ if (isMachineFormat(format)) {
113
+ console.log(JSON.stringify(result, null, 2));
114
+ return;
115
+ }
116
+ if (!result.connected) {
117
+ console.log(`No GA4 connection for project "${project}".`);
118
+ console.log("Options:");
119
+ console.log(" With service account: canonry ga connect <project> --property-id <id> --key-file <path>");
120
+ console.log(" With OAuth: canonry google connect <project> --type ga4");
121
+ console.log(" canonry ga connect <project> --property-id <id>");
122
+ return;
123
+ }
124
+ console.log(`GA4 for "${project}":
125
+ `);
126
+ console.log(` Property ID: ${result.propertyId}`);
127
+ if (result.authMethod === "service-account") {
128
+ console.log(` Auth: service account (${result.clientEmail})`);
129
+ } else {
130
+ console.log(` Auth: OAuth`);
131
+ }
132
+ console.log(` Last Synced: ${result.lastSyncedAt ?? "(never)"}`);
133
+ console.log(` Connected: ${result.createdAt ?? "unknown"}`);
134
+ }
135
+ async function gaProperties(project, format) {
136
+ const client = getClient();
137
+ const result = await client.gaProperties(project);
138
+ if (format === "jsonl") {
139
+ emitJsonl(result.properties.map((p) => ({ project, ...p })));
140
+ return;
141
+ }
142
+ if (isMachineFormat(format)) {
143
+ console.log(JSON.stringify(result, null, 2));
144
+ return;
145
+ }
146
+ if (result.properties.length === 0) {
147
+ console.log(`No GA4 properties visible to the connected account for "${project}".`);
148
+ return;
149
+ }
150
+ console.log("Available GA4 properties:\n");
151
+ const idWidth = Math.max(11, ...result.properties.map((p) => p.propertyId.length));
152
+ const nameWidth = Math.max(12, ...result.properties.map((p) => p.displayName.length));
153
+ console.log(` ${"PROPERTY ID".padEnd(idWidth)} ${"DISPLAY NAME".padEnd(nameWidth)} ACCOUNT`);
154
+ console.log(` ${"\u2500".repeat(idWidth)} ${"\u2500".repeat(nameWidth)} ${"\u2500".repeat(12)}`);
155
+ for (const p of result.properties) {
156
+ console.log(` ${p.propertyId.padEnd(idWidth)} ${p.displayName.padEnd(nameWidth)} ${p.accountName}`);
157
+ }
158
+ console.log('\nUse "canonry ga connect <project> --property-id <id>" to select one.');
159
+ }
160
+ async function gaSync(project, opts) {
161
+ const client = getClient();
162
+ const body = {};
163
+ if (opts?.days) body.days = opts.days;
164
+ if (opts?.only) body.only = opts.only;
165
+ const result = await client.gaSync(project, body);
166
+ if (result.clamped) {
167
+ console.error(
168
+ `Warning: requested ${result.requestedDays} days but synced ${result.days} \u2014 GA4's supported sync window bounded the request. Only ${result.days} days of history were written.`
169
+ );
170
+ }
171
+ if (isMachineFormat(opts?.format)) {
172
+ console.log(JSON.stringify(result, null, 2));
173
+ return;
174
+ }
175
+ console.log(`GA4 sync complete for "${project}".`);
176
+ if (result.syncedComponents) {
177
+ console.log(` Components: ${result.syncedComponents.join(", ")}`);
178
+ }
179
+ console.log(` Page rows: ${result.rowCount}`);
180
+ console.log(` AI rows: ${result.aiReferralCount}`);
181
+ console.log(` Social rows: ${result.socialReferralCount}`);
182
+ console.log(` Period: ${result.days} days${result.clamped ? ` (requested ${result.requestedDays})` : ""}`);
183
+ const searchLanding = result.measurement.searchLandingPages;
184
+ if (searchLanding) {
185
+ console.log(` Search Console landing pages: ${searchLanding.status} (${searchLanding.rowCount} rows)`);
186
+ if (searchLanding.error) console.log(` Error: ${searchLanding.error}`);
187
+ }
188
+ console.log(` Synced at: ${result.syncedAt}`);
189
+ }
190
+ var SEARCH_LANDING_NOT_AVAILABLE = "n/a";
191
+ function searchLandingCells(metrics) {
192
+ return [
193
+ metrics.organicGoogleSearchClicks.toLocaleString("en-US"),
194
+ metrics.organicGoogleSearchImpressions.toLocaleString("en-US"),
195
+ metrics.organicGoogleSearchClickThroughRate === null ? SEARCH_LANDING_NOT_AVAILABLE : formatPercent(metrics.organicGoogleSearchClickThroughRate),
196
+ metrics.organicGoogleSearchAveragePosition === null ? SEARCH_LANDING_NOT_AVAILABLE : metrics.organicGoogleSearchAveragePosition.toFixed(1),
197
+ metrics.activeUsers.toLocaleString("en-US")
198
+ ];
199
+ }
200
+ async function gaSearchLandingPages(project, opts) {
201
+ const client = getClient();
202
+ const params = {};
203
+ if (opts?.window) params.window = opts.window;
204
+ if (opts?.limit) params.limit = opts.limit;
205
+ if (opts?.offset) params.offset = opts.offset;
206
+ const result = await client.gaSearchLandingPages(
207
+ project,
208
+ Object.keys(params).length > 0 ? params : void 0
209
+ );
210
+ if (opts?.format === "json") {
211
+ console.log(JSON.stringify(result, null, 2));
212
+ return;
213
+ } else if (opts?.format === "jsonl") {
214
+ emitJsonl(result.rows.map((row) => ({
215
+ project,
216
+ window: result.window,
217
+ windowStart: result.windowStart,
218
+ windowEnd: result.windowEnd,
219
+ ...row
220
+ })));
221
+ return;
222
+ }
223
+ if (result.status === "never-synced") {
224
+ console.log(`No GA4 Search Console landing-page data for "${project}" yet. Run "canonry ga sync ${project}".`);
225
+ return;
226
+ }
227
+ console.log(`Google organic search traffic: landing page + query string (GA4 Search Console link) for "${project}"`);
228
+ if (result.windowStart && result.windowEnd) {
229
+ console.log(`Last ${result.windowDays ?? GA_SEARCH_LANDING_WINDOW_DAYS[result.window]} days: ${result.windowStart} to ${result.windowEnd}${result.timeZone ? ` (${result.timeZone})` : ""}`);
230
+ }
231
+ if (result.status === "unavailable") {
232
+ console.log(`Status: unavailable. GA4 did not return Search Console data: ${result.error ?? "no reason given"}`);
233
+ console.log(`Link Search Console to this GA4 property (GA4 Admin, Product links, Search Console links), then run "canonry ga sync ${project}".`);
234
+ } else if (result.status === "error") {
235
+ console.log(`Status: the last refresh failed${result.attemptedAt ? ` (${result.attemptedAt})` : ""}: ${result.error ?? "unknown error"}`);
236
+ }
237
+ if (result.status !== "ready" && result.total) {
238
+ console.log(`Showing the snapshot synced ${result.syncedAt ?? "earlier"}.`);
239
+ }
240
+ if (!result.total) {
241
+ console.log("No stored snapshot.");
242
+ return;
243
+ }
244
+ const headers = ["LANDING PAGE", "CLICKS", "IMPRESSIONS", "CTR", "AVG POSITION", "ACTIVE USERS"];
245
+ const table = [
246
+ ["Total", ...searchLandingCells(result.total)],
247
+ ...result.rows.map((row) => [gaSearchLandingPageLabel(row.landingPage), ...searchLandingCells(row)])
248
+ ];
249
+ const pageWidth = Math.min(60, Math.max(headers[0].length, ...table.map((row) => row[0].length)));
250
+ const widths = headers.map((header, index) => index === 0 ? pageWidth : Math.max(header.length, ...table.map((row) => row[index].length)));
251
+ const line = (cells) => ` ${cells.map((cell, index) => index === 0 ? (cell.length > pageWidth ? `${cell.slice(0, pageWidth - 3)}...` : cell).padEnd(pageWidth) : cell.padStart(widths[index])).join(" ")}`;
252
+ console.log();
253
+ console.log(line(headers));
254
+ console.log(` ${widths.map((width) => "\u2500".repeat(width)).join(" ")}`);
255
+ for (const row of table) console.log(line(row));
256
+ console.log();
257
+ if (result.rows.length > 0) {
258
+ console.log(` Showing ${result.offset + 1}-${result.offset + result.rows.length} of ${result.totalRows} pages.`);
259
+ } else if (result.totalRows > 0) {
260
+ console.log(` No landing-page rows at offset ${result.offset} (${result.totalRows} stored).`);
261
+ }
262
+ if (!gaSearchLandingHasSearchData(result.total)) {
263
+ console.log(" No landing pages had Google organic search traffic in this window.");
264
+ console.log(" If the property should have some, check its Search Console link in GA4 (Admin, Product links, Search Console links).");
265
+ }
266
+ if (result.rowsCapped && result.reportRowCount !== null) {
267
+ console.log(` GA4 reported ${result.reportRowCount} rows; the ${result.totalRows} with the most clicks are stored.`);
268
+ }
269
+ if (result.subjectToThresholding) {
270
+ console.log(" GA4 applied thresholding to this report, so some rows may be withheld.");
271
+ }
272
+ if (result.status === "ready" && result.syncedAt) {
273
+ console.log(` Synced at: ${result.syncedAt}`);
274
+ }
275
+ }
276
+ async function gaTraffic(project, opts) {
277
+ const client = getClient();
278
+ const params = rangeParams(opts, opts?.limit ? { limit: String(opts.limit) } : void 0);
279
+ const result = await client.gaTraffic(project, params);
280
+ if (isMachineFormat(opts?.format)) {
281
+ console.log(JSON.stringify(result, null, 2));
282
+ return;
283
+ }
284
+ if (result.topPages.length === 0 && result.aiReferrals.length === 0 && result.aiReferralLandingPages.length === 0 && result.socialReferrals.length === 0) {
285
+ if (!result.lastSyncedAt) {
286
+ console.log('No GA4 traffic data. Run "canonry ga sync <project>" first.');
287
+ } else {
288
+ console.log(`No GA4 traffic data for the selected period.${isRangeScoped(opts) ? " Try a wider range, or omit --window / --start / --end." : ""}`);
289
+ }
290
+ return;
291
+ }
292
+ console.log(`GA4 Traffic for "${project}"
293
+ `);
294
+ console.log(` Total Sessions: ${result.totalSessions}`);
295
+ console.log(` Organic Sessions: ${result.totalOrganicSessions}`);
296
+ console.log(` Total Users: ${result.totalUsers ?? "unavailable for this range"}`);
297
+ if (result.aiSessionsDeduped > 0) {
298
+ console.log(` AI Sessions (deduped): ${result.aiSessionsDeduped} (${result.aiSharePctDisplay} of total)`);
299
+ if (result.paidAiSessionsDeduped > 0) {
300
+ console.log(` Paid AI: ${result.paidAiSessionsDeduped} (${result.paidAiSharePctDisplay} of total)`);
301
+ }
302
+ }
303
+ console.log();
304
+ if ((result.aiEngines?.length ?? 0) > 0) {
305
+ printReferralGroups("AI REFERRALS BY ENGINE", "ENGINE", result.aiEngines);
306
+ }
307
+ if (result.aiReferrals.length > 0) {
308
+ const attrWidth = 12;
309
+ const classWidth = 8;
310
+ console.log(" AI REFERRAL SOURCES");
311
+ console.log(` ${"SOURCE".padEnd(25)} ${"MEDIUM".padEnd(15)} ${"CLASS".padEnd(classWidth)} ${"ATTRIBUTION".padEnd(attrWidth)} ${"SESSIONS".padEnd(10)} SHARE`);
312
+ console.log(` ${"\u2500".repeat(25)} ${"\u2500".repeat(15)} ${"\u2500".repeat(classWidth)} ${"\u2500".repeat(attrWidth)} ${"\u2500".repeat(10)} ${"\u2500".repeat(6)}`);
313
+ for (const ref of result.aiReferrals) {
314
+ const dimLabel = ref.sourceDimension === "first_user" ? "first-visit" : ref.sourceDimension === "manual_utm" ? "utm" : "session";
315
+ const classLabel = ref.trafficClass === "paid" ? "paid" : "organic";
316
+ console.log(
317
+ ` ${ref.source.padEnd(25)} ${ref.medium.padEnd(15)} ${classLabel.padEnd(classWidth)} ${dimLabel.padEnd(attrWidth)} ${String(ref.sessions).padEnd(10)} ${formatPercent(ref.share)}`
318
+ );
319
+ }
320
+ console.log();
321
+ }
322
+ if (result.aiReferralLandingPages.length > 0) {
323
+ const attrWidth = 12;
324
+ console.log(" AI REFERRAL LANDING PAGES");
325
+ console.log(` ${"LANDING PAGE".padEnd(30)} ${"SOURCE".padEnd(25)} ${"ATTRIBUTION".padEnd(attrWidth)} ${"SESSIONS".padEnd(10)}`);
326
+ console.log(` ${"\u2500".repeat(30)} ${"\u2500".repeat(25)} ${"\u2500".repeat(attrWidth)} ${"\u2500".repeat(10)}`);
327
+ for (const row of result.aiReferralLandingPages) {
328
+ const dimLabel = row.sourceDimension === "first_user" ? "first-visit" : row.sourceDimension === "manual_utm" ? "utm" : "session";
329
+ const page = row.landingPage.length > 30 ? row.landingPage.slice(0, 27) + "..." : row.landingPage;
330
+ const source = row.source.length > 25 ? row.source.slice(0, 22) + "..." : row.source;
331
+ console.log(
332
+ ` ${page.padEnd(30)} ${source.padEnd(25)} ${dimLabel.padEnd(attrWidth)} ${String(row.sessions).padEnd(10)}`
333
+ );
334
+ }
335
+ console.log();
336
+ }
337
+ if (result.socialReferrals.length > 0) {
338
+ const chanWidth = 12;
339
+ if (result.socialSessions > 0) {
340
+ console.log(` Social Sessions: ${result.socialSessions} (${result.socialSharePctDisplay} of total)`);
341
+ if ((result.paidSocialSessions ?? 0) > 0) {
342
+ console.log(` Paid Social: ${result.paidSocialSessions} (${formatPercent(result.paidSocialShare)} of social)`);
343
+ }
344
+ console.log();
345
+ }
346
+ if ((result.socialPlatforms?.length ?? 0) > 0) {
347
+ printReferralGroups("SOCIAL PLATFORMS", "PLATFORM", result.socialPlatforms);
348
+ }
349
+ console.log(" SOCIAL REFERRAL SOURCES");
350
+ console.log(` ${"SOURCE".padEnd(25)} ${"MEDIUM".padEnd(15)} ${"CHANNEL".padEnd(chanWidth)} ${"SESSIONS".padEnd(10)} SHARE`);
351
+ console.log(` ${"\u2500".repeat(25)} ${"\u2500".repeat(15)} ${"\u2500".repeat(chanWidth)} ${"\u2500".repeat(10)} ${"\u2500".repeat(6)}`);
352
+ for (const ref of result.socialReferrals) {
353
+ const chanLabel = ref.channelGroup === "Paid Social" ? "paid" : "organic";
354
+ console.log(
355
+ ` ${ref.source.padEnd(25)} ${ref.medium.padEnd(15)} ${chanLabel.padEnd(chanWidth)} ${String(ref.sessions).padEnd(10)} ${formatPercent(ref.share)}`
356
+ );
357
+ }
358
+ console.log();
359
+ }
360
+ if (result.topPages.length > 0) {
361
+ const pageWidth = Math.min(60, Math.max(15, ...result.topPages.map((r) => r.landingPage.length)));
362
+ console.log(` TOP LANDING PAGES`);
363
+ console.log(` ${"PAGE".padEnd(pageWidth)} ${"SESSIONS".padEnd(10)}${"ORGANIC".padEnd(10)}ORGANIC %`);
364
+ console.log(` ${"\u2500".repeat(pageWidth)} ${"\u2500".repeat(10)}${"\u2500".repeat(10)}${"\u2500".repeat(9)}`);
365
+ for (const row of result.topPages) {
366
+ const page = row.landingPage.length > pageWidth ? row.landingPage.slice(0, pageWidth - 3) + "..." : row.landingPage;
367
+ console.log(
368
+ ` ${page.padEnd(pageWidth)} ${String(row.sessions).padEnd(10)}${String(row.organicSessions).padEnd(10)}${formatPercent(row.organicShare)}`
369
+ );
370
+ }
371
+ }
372
+ if (result.lastSyncedAt) {
373
+ console.log(`
374
+ Last synced: ${result.lastSyncedAt}`);
375
+ }
376
+ }
377
+ var AI_ENGINE_LEAD_RATE_NOTES = {
378
+ "no-data": null,
379
+ "sync-not-ready": "the latest acquisition or lead sync failed, so sessions and lead events may cover different days; rerun the GA sync for lead rates.",
380
+ "channel-leads-unfiltered": "lead events are channel-level here, so host and path filters narrow sessions but not leads; rerun with --host-scope all and no --path-prefix for lead rates.",
381
+ "paid-split-needs-landing-page": "lead events are channel-level here, so the paid/organic split cannot read landing-page utm tags, and some AI sessions were paid only by those tags (counted as organic above); tag paid AI links with a paid utm_medium such as cpc for lead rates.",
382
+ "sessions-behind-leads": "stored lead events run past the last stored session date, so recent leads have no sessions to divide by; rerun the GA sync for lead rates.",
383
+ "sessions-missing-on-lead-days": "some days in this window have stored lead events but no stored sessions, so those leads have no sessions to divide by; rerun the GA sync with --days covering the window for lead rates."
384
+ };
385
+ function hasAiEngineLeadRows(block) {
386
+ return block.engines.length > 0 || block.unattributed.sources.length > 0;
387
+ }
388
+ function printAiEngineLeadClass(heading, block) {
389
+ const cell = (period) => `${period.eventCount} / ${period.sessions} ${formatPercent(period.leadRate)}`;
390
+ const rows = [
391
+ ...block.engines.map((engine) => ({ label: engine.label, cells: engine.periods.map(cell) })),
392
+ ...block.unattributed.sources.length > 0 ? [{ label: "Other AI Assistant", cells: block.unattributed.periods.map(cell) }] : [],
393
+ { label: "All AI", cells: block.periods.map(cell) }
394
+ ];
395
+ const labelWidth = Math.max("ENGINE".length, ...rows.map((row) => row.label.length));
396
+ const widths = block.periods.map((period, index) => Math.max(
397
+ period.label.length,
398
+ ...rows.map((row) => row.cells[index]?.length ?? 0)
399
+ ));
400
+ const line = (label, cells) => ` ${label.padEnd(labelWidth)} ${cells.map((value, index) => value.padEnd(widths[index] ?? 0)).join(" ")}`.trimEnd();
401
+ console.log(` ${heading} (lead events / AI sessions, lead rate)`);
402
+ console.log(line("ENGINE", block.periods.map((period) => period.label.toUpperCase())));
403
+ for (const row of rows) console.log(line(row.label, row.cells));
404
+ }
405
+ function printAiEngineLeads(aiEngines) {
406
+ if (!aiEngines) return;
407
+ if (aiEngines.organic.periods.length === 0) return;
408
+ if (!hasAiEngineLeadRows(aiEngines.organic) && !hasAiEngineLeadRows(aiEngines.paid)) {
409
+ console.log(" Leads by AI engine: no AI engine sessions or lead events in this window");
410
+ return;
411
+ }
412
+ printAiEngineLeadClass("Leads by AI engine, organic", aiEngines.organic);
413
+ if (hasAiEngineLeadRows(aiEngines.paid)) {
414
+ printAiEngineLeadClass("Leads by AI engine, paid clicks", aiEngines.paid);
415
+ }
416
+ const note = aiEngines.leadRateUnavailableReason === null ? null : AI_ENGINE_LEAD_RATE_NOTES[aiEngines.leadRateUnavailableReason];
417
+ if (note) console.log(` Note: ${note}`);
418
+ }
419
+ async function gaMeasurementAnalysis(project, opts) {
420
+ const client = getClient();
421
+ const params = {};
422
+ if (opts?.window) params.window = opts.window;
423
+ if (opts?.hostScope) params.hostScope = opts.hostScope;
424
+ if (opts?.pathPrefix) params.pathPrefix = opts.pathPrefix;
425
+ if (opts?.limit) params.limit = String(opts.limit);
426
+ const result = await client.gaMeasurementAnalysis(
427
+ project,
428
+ Object.keys(params).length > 0 ? params : void 0
429
+ );
430
+ if (isMachineFormat(opts?.format)) {
431
+ console.log(JSON.stringify(result, null, 2));
432
+ return;
433
+ }
434
+ console.log(`GA4 Measurement Analysis for "${project}" (${result.window})
435
+ `);
436
+ console.log(` Acquisition: ${result.acquisition.status}`);
437
+ if (result.acquisition.error) console.log(` Error: ${result.acquisition.error}`);
438
+ for (const period of result.acquisition.periods) {
439
+ console.log(` ${period.label.padEnd(8)} ${period.sessions} sessions ${period.startDate} to ${period.endDate}`);
440
+ }
441
+ if (result.acquisition.channels.length > 0) {
442
+ console.log(" Native channels (latest cohort)");
443
+ for (const channel of result.acquisition.channels) {
444
+ console.log(` ${channel.channelGroup}: ${channel.periods.at(-1)?.sessions ?? 0}`);
445
+ }
446
+ }
447
+ console.log(` Leads: ${result.leads.status}${result.leads.attributionScope ? ` (${result.leads.attributionScope} attribution)` : ""}`);
448
+ if (result.leads.error) console.log(` Error: ${result.leads.error}`);
449
+ for (const period of result.leads.periods) {
450
+ console.log(` ${period.label.padEnd(8)} ${period.eventCount} leads ${period.startDate} to ${period.endDate}`);
451
+ }
452
+ printAiEngineLeads(result.leads.aiEngines);
453
+ console.log(` Search demand: ${result.searchDemand.status}`);
454
+ for (const period of result.searchDemand.periods) {
455
+ console.log(` ${period.label.padEnd(8)} ${period.propertyClicks} clicks / ${period.propertyImpressions} impressions (${period.brandedClicks} branded clicks / ${period.brandedImpressions} branded impressions; ${period.nonBrandedClicks} reported non-brand clicks / ${period.nonBrandedImpressions} reported non-brand impressions; ${period.unreportedClicks} unreported clicks / ${period.unreportedImpressions} unreported impressions)`);
456
+ }
457
+ if (!result.leads.hostAndPathFiltersApplied && result.leads.attributionScope === "channel") {
458
+ console.log(" Note: lead attribution is channel-level; host and path filters do not apply to leads.");
459
+ }
460
+ }
461
+ async function gaAiReferralHistory(project, opts) {
462
+ const client = getClient();
463
+ const result = await client.gaAiReferralHistory(project, rangeParams(opts));
464
+ if (opts?.format === "json") {
465
+ console.log(JSON.stringify(result, null, 2));
466
+ return;
467
+ } else if (opts?.format === "jsonl") {
468
+ emitJsonl(result.map((row) => ({ project, window: opts?.window, startDate: opts?.startDate, endDate: opts?.endDate, ...row })));
469
+ return;
470
+ }
471
+ if (result.length === 0) {
472
+ console.log(`No AI referral history.${isRangeScoped(opts) ? " Try a wider range, or omit --window / --start / --end." : ' Run "canonry ga sync <project>" first.'}`);
473
+ return;
474
+ }
475
+ const dateWidth = 12;
476
+ const sourceWidth = Math.min(30, Math.max(10, ...result.map((r) => r.source.length)));
477
+ const attrWidth = 12;
478
+ console.log(`GA4 AI Referral History for "${project}":
479
+ `);
480
+ console.log(` ${"DATE".padEnd(dateWidth)} ${"SOURCE".padEnd(sourceWidth)} ${"ATTRIBUTION".padEnd(attrWidth)} ${"SESSIONS".padEnd(10)}`);
481
+ console.log(` ${"\u2500".repeat(dateWidth)} ${"\u2500".repeat(sourceWidth)} ${"\u2500".repeat(attrWidth)} ${"\u2500".repeat(10)}`);
482
+ for (const row of result) {
483
+ const dimLabel = row.sourceDimension === "first_user" ? "first-visit" : row.sourceDimension === "manual_utm" ? "utm" : "session";
484
+ console.log(
485
+ ` ${row.date.padEnd(dateWidth)} ${row.source.padEnd(sourceWidth)} ${dimLabel.padEnd(attrWidth)} ${String(row.sessions).padEnd(10)}`
486
+ );
487
+ }
488
+ }
489
+ function printReferralGroups(heading, column, groups) {
490
+ const labelWidth = Math.min(30, Math.max(column.length, ...groups.map((group) => group.label.length)));
491
+ console.log(` ${heading}`);
492
+ console.log(` ${column.padEnd(labelWidth)} ${"SESSIONS".padEnd(10)}${"ORGANIC".padEnd(9)}${"PAID".padEnd(8)}${"SHARE".padEnd(8)}SOURCES`);
493
+ console.log(` ${"\u2500".repeat(labelWidth)} ${"\u2500".repeat(10)}${"\u2500".repeat(9)}${"\u2500".repeat(8)}${"\u2500".repeat(8)}${"\u2500".repeat(7)}`);
494
+ for (const group of groups) {
495
+ const label = group.label.length > labelWidth ? group.label.slice(0, labelWidth - 3) + "..." : group.label;
496
+ console.log(
497
+ ` ${label.padEnd(labelWidth)} ${String(group.sessions).padEnd(10)}${String(group.organicSessions).padEnd(9)}${String(group.paidSessions).padEnd(8)}${formatPercent(group.share).padEnd(8)}${group.sources.length}`
498
+ );
499
+ }
500
+ console.log();
501
+ }
502
+ async function gaAiReferralDaily(project, opts) {
503
+ const client = getClient();
504
+ const result = await client.gaAiReferralDaily(project, rangeParams(opts));
505
+ if (opts?.format === "json") {
506
+ console.log(JSON.stringify(result, null, 2));
507
+ return;
508
+ } else if (opts?.format === "jsonl") {
509
+ emitJsonl(result.days.map((day) => ({ project, window: opts?.window, startDate: opts?.startDate, endDate: opts?.endDate, ...day })));
510
+ return;
511
+ }
512
+ if (result.days.length === 0) {
513
+ console.log(`No AI referral sessions.${isRangeScoped(opts) ? " Try a wider range, or omit --window / --start / --end." : ' Run "canonry ga sync <project>" first.'}`);
514
+ return;
515
+ }
516
+ const dateWidth = 12;
517
+ const sourceWidth = Math.min(30, Math.max(10, ...result.sources.map((s) => s.length)));
518
+ console.log(`GA4 AI Referral Sessions per Day for "${project}":
519
+ `);
520
+ console.log(` ${"DATE".padEnd(dateWidth)} ${"SOURCE".padEnd(sourceWidth)} ${"SESSIONS".padEnd(10)}${"PAID".padEnd(8)}${"ORGANIC".padEnd(9)}`);
521
+ console.log(` ${"\u2500".repeat(dateWidth)} ${"\u2500".repeat(sourceWidth)} ${"\u2500".repeat(10)}${"\u2500".repeat(8)}${"\u2500".repeat(9)}`);
522
+ for (const day of result.days) {
523
+ for (const entry of day.bySource) {
524
+ console.log(
525
+ ` ${day.date.padEnd(dateWidth)} ${entry.source.padEnd(sourceWidth)} ${String(entry.sessions).padEnd(10)}${String(entry.paidSessions).padEnd(8)}${String(entry.organicSessions).padEnd(9)}`
526
+ );
527
+ }
528
+ }
529
+ console.log(`
530
+ Total: ${result.totalSessions} sessions (${result.totalPaidSessions} paid, ${result.totalOrganicSessions} organic)`);
531
+ if (result.byEngine && result.byEngine.series.length > 0) {
532
+ const folded = result.byEngine.otherCount > 0 ? ` (Other folds ${result.byEngine.otherCount})` : "";
533
+ console.log(` By engine${folded}: ${result.byEngine.series.map((series) => `${series.label} ${series.sessions}`).join(" \xB7 ")}`);
534
+ }
535
+ }
536
+ async function gaSocialReferralHistory(project, opts) {
537
+ const client = getClient();
538
+ const result = await client.gaSocialReferralHistory(project, rangeParams(opts));
539
+ if (opts?.format === "json") {
540
+ console.log(JSON.stringify(result, null, 2));
541
+ return;
542
+ } else if (opts?.format === "jsonl") {
543
+ emitJsonl(result.map((row) => ({ project, window: opts?.window, startDate: opts?.startDate, endDate: opts?.endDate, ...row })));
544
+ return;
545
+ }
546
+ if (result.length === 0) {
547
+ console.log(`No social referral history.${isRangeScoped(opts) ? " Try a wider range, or omit --window / --start / --end." : ' Run "canonry ga sync <project>" first.'}`);
548
+ return;
549
+ }
550
+ const dateWidth = 12;
551
+ const sourceWidth = Math.min(30, Math.max(10, ...result.map((r) => r.source.length)));
552
+ const chanWidth = 12;
553
+ console.log(`GA4 Social Referral History for "${project}":
554
+ `);
555
+ console.log(` ${"DATE".padEnd(dateWidth)} ${"SOURCE".padEnd(sourceWidth)} ${"CHANNEL".padEnd(chanWidth)} ${"SESSIONS".padEnd(10)}${"USERS".padEnd(8)}`);
556
+ console.log(` ${"\u2500".repeat(dateWidth)} ${"\u2500".repeat(sourceWidth)} ${"\u2500".repeat(chanWidth)} ${"\u2500".repeat(10)}${"\u2500".repeat(8)}`);
557
+ for (const row of result) {
558
+ const chanLabel = row.channelGroup === "Paid Social" ? "paid" : "organic";
559
+ console.log(
560
+ ` ${row.date.padEnd(dateWidth)} ${row.source.padEnd(sourceWidth)} ${chanLabel.padEnd(chanWidth)} ${String(row.sessions).padEnd(10)}${String(row.users).padEnd(8)}`
561
+ );
562
+ }
563
+ }
564
+ async function gaSessionHistory(project, opts) {
565
+ const client = getClient();
566
+ const result = await client.gaSessionHistory(project, rangeParams(opts));
567
+ if (opts?.format === "json") {
568
+ console.log(JSON.stringify(result, null, 2));
569
+ return;
570
+ } else if (opts?.format === "jsonl") {
571
+ emitJsonl(result.map((row) => ({ project, window: opts?.window, startDate: opts?.startDate, endDate: opts?.endDate, ...row })));
572
+ return;
573
+ }
574
+ if (result.length === 0) {
575
+ console.log(`No session history.${isRangeScoped(opts) ? " Try a wider range, or omit --window / --start / --end." : ' Run "canonry ga sync <project>" first.'}`);
576
+ return;
577
+ }
578
+ const dateWidth = 12;
579
+ console.log(`GA4 Session History for "${project}":
580
+ `);
581
+ console.log(` ${"DATE".padEnd(dateWidth)} ${"SESSIONS".padEnd(10)}${"ORGANIC".padEnd(10)}${"USERS".padEnd(8)}`);
582
+ console.log(` ${"\u2500".repeat(dateWidth)} ${"\u2500".repeat(10)}${"\u2500".repeat(10)}${"\u2500".repeat(8)}`);
583
+ for (const row of result) {
584
+ const users = row.usersSource === "deduplicated" ? String(row.users) : `${row.users}*`;
585
+ console.log(
586
+ ` ${row.date.padEnd(dateWidth)} ${String(row.sessions).padEnd(10)}${String(row.organicSessions).padEnd(10)}${users.padEnd(8)}`
587
+ );
588
+ }
589
+ if (result.some((row) => row.usersSource !== "deduplicated")) {
590
+ console.log("\n * Visitor count is approximate \u2014 it adds up each page a visitor landed on,");
591
+ console.log(" so someone who read several pages is counted more than once. Run");
592
+ console.log(` "canonry ga sync ${project}" to replace these with exact counts.`);
593
+ }
594
+ }
595
+ async function gaCoverage(project, format) {
596
+ const client = getClient();
597
+ const result = await client.gaCoverage(project);
598
+ if (format === "json") {
599
+ console.log(JSON.stringify(result, null, 2));
600
+ return;
601
+ } else if (format === "jsonl") {
602
+ emitJsonl(result.pages.map((row) => ({ project, ...row })));
603
+ return;
604
+ }
605
+ if (result.pages.length === 0) {
606
+ console.log('No GA4 coverage data. Run "canonry ga sync <project>" first.');
607
+ return;
608
+ }
609
+ console.log(`GA4 Page Coverage (${result.pages.length} pages with traffic):
610
+ `);
611
+ const pageWidth = Math.min(60, Math.max(15, ...result.pages.map((r) => r.landingPage.length)));
612
+ console.log(` ${"LANDING PAGE".padEnd(pageWidth)} ${"SESSIONS".padEnd(10)}${"ORGANIC".padEnd(10)}${"USERS".padEnd(8)}`);
613
+ console.log(` ${"\u2500".repeat(pageWidth)} ${"\u2500".repeat(10)}${"\u2500".repeat(10)}${"\u2500".repeat(8)}`);
614
+ for (const row of result.pages) {
615
+ const page = row.landingPage.length > pageWidth ? row.landingPage.slice(0, pageWidth - 3) + "..." : row.landingPage;
616
+ console.log(
617
+ ` ${page.padEnd(pageWidth)} ${String(row.sessions).padEnd(10)}${String(row.organicSessions).padEnd(10)}${String(row.users).padEnd(8)}`
618
+ );
619
+ }
620
+ }
621
+ function fmtTrend(pct) {
622
+ return pct === null ? "n/a" : `${pct >= 0 ? "+" : ""}${formatPercent(pct, "percent")}`;
623
+ }
624
+ function fmtMoverChange(mover) {
625
+ switch (mover.changeBasis) {
626
+ case GaMoverChangeBases.new:
627
+ return "new";
628
+ case GaMoverChangeBases["small-base"]:
629
+ return `${mover.changeSessions > 0 ? "+" : ""}${mover.changeSessions} sessions`;
630
+ case GaMoverChangeBases.percent:
631
+ return fmtTrend(mover.changePct);
632
+ }
633
+ }
634
+ function windowLine(traffic) {
635
+ if (!traffic.windowStart || !traffic.windowEnd) return null;
636
+ const span = traffic.windowDays === null ? "" : ` (${traffic.windowDays} days)`;
637
+ return ` Window: ${traffic.windowStart} to ${traffic.windowEnd}${span}`;
638
+ }
639
+ async function gaSocialReferralSummary(project, opts) {
640
+ const client = getClient();
641
+ const traffic = await client.gaTraffic(project);
642
+ if (opts?.trend) {
643
+ const trend = await client.gaSocialReferralTrend(project);
644
+ if (isMachineFormat(opts.format)) {
645
+ console.log(JSON.stringify({
646
+ socialSessions: traffic.socialSessions,
647
+ totalSessions: traffic.totalSessions,
648
+ socialSharePct: traffic.socialSharePct,
649
+ windowStart: traffic.windowStart,
650
+ windowEnd: traffic.windowEnd,
651
+ windowDays: traffic.windowDays,
652
+ topSources: traffic.socialReferrals.slice(0, 5).map((r) => ({ source: r.source, sessions: r.sessions, channel: r.channelGroup })),
653
+ trend
654
+ }, null, 2));
655
+ return;
656
+ }
657
+ console.log(`Social Traffic Summary for "${project}"
658
+ `);
659
+ const trendWindow = windowLine(traffic);
660
+ if (trendWindow) console.log(`${trendWindow}
661
+ `);
662
+ console.log(` Sessions: ${traffic.socialSessions} (${traffic.socialSharePctDisplay} of ${traffic.totalSessions} total)`);
663
+ console.log();
664
+ console.log(` 7d trend: ${fmtTrend(trend.trend7dPct)} (${trend.socialSessions7d} vs ${trend.socialSessionsPrev7d})`);
665
+ console.log(` 30d trend: ${fmtTrend(trend.trend30dPct)} (${trend.socialSessions30d} vs ${trend.socialSessionsPrev30d})`);
666
+ if (trend.biggestMover) {
667
+ const m = trend.biggestMover;
668
+ console.log(` Mover: ${m.source} (${fmtMoverChange(m)}, ${m.sessionsPrev7d}\u2192${m.sessions7d})`);
669
+ }
670
+ console.log();
671
+ if (traffic.socialReferrals.length > 0) {
672
+ console.log(" TOP SOURCES");
673
+ for (const ref of traffic.socialReferrals.slice(0, 5)) {
674
+ const chanLabel = ref.channelGroup === "Paid Social" ? "paid" : "organic";
675
+ console.log(` ${ref.source.padEnd(20)} ${String(ref.sessions).padEnd(8)} sessions (${chanLabel})`);
676
+ }
677
+ }
678
+ return;
679
+ }
680
+ if (isMachineFormat(opts?.format)) {
681
+ console.log(JSON.stringify({
682
+ socialSessions: traffic.socialSessions,
683
+ totalSessions: traffic.totalSessions,
684
+ socialSharePct: traffic.socialSharePct,
685
+ windowStart: traffic.windowStart,
686
+ windowEnd: traffic.windowEnd,
687
+ windowDays: traffic.windowDays,
688
+ topSources: traffic.socialReferrals.slice(0, 5).map((r) => ({ source: r.source, sessions: r.sessions, channel: r.channelGroup }))
689
+ }, null, 2));
690
+ return;
691
+ }
692
+ console.log(`Social Traffic Summary for "${project}"
693
+ `);
694
+ const socialWindow = windowLine(traffic);
695
+ if (socialWindow) console.log(`${socialWindow}
696
+ `);
697
+ console.log(` Sessions: ${traffic.socialSessions} (${traffic.socialSharePctDisplay} of ${traffic.totalSessions} total)`);
698
+ if (traffic.socialReferrals.length > 0) {
699
+ console.log();
700
+ console.log(" TOP SOURCES");
701
+ for (const ref of traffic.socialReferrals.slice(0, 5)) {
702
+ const chanLabel = ref.channelGroup === "Paid Social" ? "paid" : "organic";
703
+ console.log(` ${ref.source.padEnd(20)} ${String(ref.sessions).padEnd(8)} sessions (${chanLabel})`);
704
+ }
705
+ }
706
+ }
707
+ async function gaAttribution(project, opts) {
708
+ const client = getClient();
709
+ const traffic = await client.gaTraffic(project);
710
+ if (opts?.trend) {
711
+ const trend = await client.gaAttributionTrend(project);
712
+ if (isMachineFormat(opts.format)) {
713
+ console.log(JSON.stringify({
714
+ totalSessions: traffic.totalSessions,
715
+ totalUsers: traffic.totalUsers,
716
+ organicSessions: traffic.totalOrganicSessions,
717
+ aiSessions: traffic.aiSessionsDeduped,
718
+ paidAiSessions: traffic.paidAiSessionsDeduped,
719
+ organicAiSessions: traffic.organicAiSessionsDeduped,
720
+ aiSessionsBySession: traffic.aiSessionsBySession,
721
+ paidAiSessionsBySession: traffic.paidAiSessionsBySession,
722
+ organicAiSessionsBySession: traffic.organicAiSessionsBySession,
723
+ socialSessions: traffic.socialSessions,
724
+ directSessions: traffic.totalDirectSessions,
725
+ aiSharePct: traffic.aiSharePct,
726
+ aiSharePctBySession: traffic.aiSharePctBySession,
727
+ paidAiSharePct: traffic.paidAiSharePct,
728
+ paidAiSharePctBySession: traffic.paidAiSharePctBySession,
729
+ organicAiSharePct: traffic.organicAiSharePct,
730
+ organicAiSharePctBySession: traffic.organicAiSharePctBySession,
731
+ socialSharePct: traffic.socialSharePct,
732
+ organicSharePct: traffic.organicSharePct,
733
+ directSharePct: traffic.directSharePct,
734
+ organicSharePctDisplay: traffic.organicSharePctDisplay,
735
+ aiSharePctDisplay: traffic.aiSharePctDisplay,
736
+ aiSharePctBySessionDisplay: traffic.aiSharePctBySessionDisplay,
737
+ paidAiSharePctDisplay: traffic.paidAiSharePctDisplay,
738
+ paidAiSharePctBySessionDisplay: traffic.paidAiSharePctBySessionDisplay,
739
+ organicAiSharePctDisplay: traffic.organicAiSharePctDisplay,
740
+ organicAiSharePctBySessionDisplay: traffic.organicAiSharePctBySessionDisplay,
741
+ socialSharePctDisplay: traffic.socialSharePctDisplay,
742
+ directSharePctDisplay: traffic.directSharePctDisplay,
743
+ otherSessions: traffic.otherSessions,
744
+ otherSharePct: traffic.otherSharePct,
745
+ otherSharePctDisplay: traffic.otherSharePctDisplay,
746
+ channelBreakdown: traffic.channelBreakdown,
747
+ aiReferrals: traffic.aiReferrals,
748
+ aiReferralLandingPages: traffic.aiReferralLandingPages,
749
+ socialReferrals: traffic.socialReferrals,
750
+ windowStart: traffic.windowStart,
751
+ windowEnd: traffic.windowEnd,
752
+ windowDays: traffic.windowDays,
753
+ trend
754
+ }, null, 2));
755
+ return;
756
+ }
757
+ if (traffic.totalSessions === 0) {
758
+ console.log('No GA4 traffic data. Run "canonry ga sync <project>" first.');
759
+ return;
760
+ }
761
+ console.log(`GA4 Attribution Overview for "${project}"
762
+ `);
763
+ const trendWindow = windowLine(traffic);
764
+ if (trendWindow) console.log(`${trendWindow}
765
+ `);
766
+ console.log(` Total Sessions: ${traffic.totalSessions}`);
767
+ console.log(` Total Users: ${traffic.totalUsers ?? "unavailable for this range"}`);
768
+ console.log();
769
+ console.log(` CHANNEL BREAKDOWN${" ".repeat(20)}7d trend 30d trend`);
770
+ console.log(` Organic Search: ${String(traffic.channelBreakdown.organic.sessions).padEnd(6)} (${traffic.channelBreakdown.organic.sharePctDisplay.padStart(6)}) ${fmtTrend(trend.organic.trend7dPct).padEnd(12)} ${fmtTrend(trend.organic.trend30dPct)}`);
771
+ console.log(` Social: ${String(traffic.channelBreakdown.social.sessions).padEnd(6)} (${traffic.channelBreakdown.social.sharePctDisplay.padStart(6)}) ${fmtTrend(trend.social.trend7dPct).padEnd(12)} ${fmtTrend(trend.social.trend30dPct)}`);
772
+ console.log(` Direct: ${String(traffic.channelBreakdown.direct.sessions).padEnd(6)} (${traffic.channelBreakdown.direct.sharePctDisplay.padStart(6)}) ${fmtTrend(trend.direct.trend7dPct).padEnd(12)} ${fmtTrend(trend.direct.trend30dPct)}`);
773
+ console.log(` AI Referrals: ${String(traffic.channelBreakdown.ai.sessions).padEnd(6)} (${traffic.channelBreakdown.ai.sharePctDisplay.padStart(6)}) ${fmtTrend(trend.ai.trend7dPct).padEnd(12)} ${fmtTrend(trend.ai.trend30dPct)} (lower bound \u2014 sessionSource only; referrer-stripped traffic falls under Direct)`);
774
+ if (traffic.paidAiSessionsBySession > 0) {
775
+ console.log(` Paid AI: ${String(traffic.paidAiSessionsBySession).padEnd(6)} (${traffic.paidAiSharePctBySessionDisplay.padStart(6)})`);
776
+ }
777
+ console.log(` Other: ${String(traffic.channelBreakdown.other.sessions).padEnd(6)} (${traffic.channelBreakdown.other.sharePctDisplay.padStart(6)})`);
778
+ console.log(` \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500`);
779
+ console.log(` Total: ${String(traffic.totalSessions).padEnd(6)}${" ".repeat(13)}${fmtTrend(trend.total.trend7dPct).padEnd(12)} ${fmtTrend(trend.total.trend30dPct)}`);
780
+ if (trend.aiBiggestMover) {
781
+ const m = trend.aiBiggestMover;
782
+ console.log(`
783
+ AI Mover: ${m.source} (${fmtMoverChange(m)}, ${m.sessionsPrev7d}\u2192${m.sessions7d} sessions/7d)`);
784
+ }
785
+ if (trend.socialBiggestMover) {
786
+ const m = trend.socialBiggestMover;
787
+ console.log(` Social Mover: ${m.source} (${fmtMoverChange(m)}, ${m.sessionsPrev7d}\u2192${m.sessions7d} sessions/7d)`);
788
+ }
789
+ if (traffic.lastSyncedAt) {
790
+ console.log(`
791
+ Last synced: ${traffic.lastSyncedAt}`);
792
+ }
793
+ return;
794
+ }
795
+ if (isMachineFormat(opts?.format)) {
796
+ console.log(JSON.stringify({
797
+ totalSessions: traffic.totalSessions,
798
+ totalUsers: traffic.totalUsers,
799
+ organicSessions: traffic.totalOrganicSessions,
800
+ aiSessions: traffic.aiSessionsDeduped,
801
+ paidAiSessions: traffic.paidAiSessionsDeduped,
802
+ organicAiSessions: traffic.organicAiSessionsDeduped,
803
+ aiSessionsBySession: traffic.aiSessionsBySession,
804
+ paidAiSessionsBySession: traffic.paidAiSessionsBySession,
805
+ organicAiSessionsBySession: traffic.organicAiSessionsBySession,
806
+ socialSessions: traffic.socialSessions,
807
+ directSessions: traffic.totalDirectSessions,
808
+ aiSharePct: traffic.aiSharePct,
809
+ aiSharePctBySession: traffic.aiSharePctBySession,
810
+ paidAiSharePct: traffic.paidAiSharePct,
811
+ paidAiSharePctBySession: traffic.paidAiSharePctBySession,
812
+ organicAiSharePct: traffic.organicAiSharePct,
813
+ organicAiSharePctBySession: traffic.organicAiSharePctBySession,
814
+ socialSharePct: traffic.socialSharePct,
815
+ organicSharePct: traffic.organicSharePct,
816
+ directSharePct: traffic.directSharePct,
817
+ organicSharePctDisplay: traffic.organicSharePctDisplay,
818
+ aiSharePctDisplay: traffic.aiSharePctDisplay,
819
+ aiSharePctBySessionDisplay: traffic.aiSharePctBySessionDisplay,
820
+ paidAiSharePctDisplay: traffic.paidAiSharePctDisplay,
821
+ paidAiSharePctBySessionDisplay: traffic.paidAiSharePctBySessionDisplay,
822
+ organicAiSharePctDisplay: traffic.organicAiSharePctDisplay,
823
+ organicAiSharePctBySessionDisplay: traffic.organicAiSharePctBySessionDisplay,
824
+ socialSharePctDisplay: traffic.socialSharePctDisplay,
825
+ directSharePctDisplay: traffic.directSharePctDisplay,
826
+ otherSessions: traffic.otherSessions,
827
+ otherSharePct: traffic.otherSharePct,
828
+ otherSharePctDisplay: traffic.otherSharePctDisplay,
829
+ channelBreakdown: traffic.channelBreakdown,
830
+ aiReferrals: traffic.aiReferrals,
831
+ aiReferralLandingPages: traffic.aiReferralLandingPages,
832
+ socialReferrals: traffic.socialReferrals,
833
+ windowStart: traffic.windowStart,
834
+ windowEnd: traffic.windowEnd,
835
+ windowDays: traffic.windowDays,
836
+ periodStart: traffic.periodStart,
837
+ periodEnd: traffic.periodEnd
838
+ }, null, 2));
839
+ return;
840
+ }
841
+ if (traffic.totalSessions === 0) {
842
+ console.log('No GA4 traffic data. Run "canonry ga sync <project>" first.');
843
+ return;
844
+ }
845
+ console.log(`GA4 Attribution Overview for "${project}"
846
+ `);
847
+ const attributionWindow = windowLine(traffic);
848
+ if (attributionWindow) console.log(`${attributionWindow}
849
+ `);
850
+ console.log(` Total Sessions: ${traffic.totalSessions}`);
851
+ console.log(` Total Users: ${traffic.totalUsers ?? "unavailable for this range"}`);
852
+ console.log();
853
+ console.log(" CHANNEL BREAKDOWN");
854
+ console.log(` Organic Search: ${traffic.channelBreakdown.organic.sessions} sessions (${traffic.channelBreakdown.organic.sharePctDisplay})`);
855
+ console.log(` Social: ${traffic.channelBreakdown.social.sessions} sessions (${traffic.channelBreakdown.social.sharePctDisplay})`);
856
+ console.log(` Direct: ${traffic.channelBreakdown.direct.sessions} sessions (${traffic.channelBreakdown.direct.sharePctDisplay})`);
857
+ console.log(` AI Referrals: ${traffic.channelBreakdown.ai.sessions} sessions (${traffic.channelBreakdown.ai.sharePctDisplay}) (lower bound \u2014 sessionSource only; referrer-stripped traffic falls under Direct)`);
858
+ if (traffic.paidAiSessionsBySession > 0) {
859
+ console.log(` Paid AI: ${traffic.paidAiSessionsBySession} sessions (${traffic.paidAiSharePctBySessionDisplay})`);
860
+ }
861
+ console.log(` Other: ${traffic.channelBreakdown.other.sessions} sessions (${traffic.channelBreakdown.other.sharePctDisplay})`);
862
+ if (traffic.aiReferrals.length > 0) {
863
+ console.log();
864
+ console.log(" AI SOURCES");
865
+ for (const ref of traffic.aiReferrals.slice(0, 10)) {
866
+ const dimLabel = ref.sourceDimension === "first_user" ? "first-visit" : ref.sourceDimension === "manual_utm" ? "utm" : "session";
867
+ const classLabel = ref.trafficClass === "paid" ? "paid" : "organic";
868
+ console.log(` ${ref.source.padEnd(25)} ${String(ref.sessions).padEnd(8)} sessions (${classLabel}, ${dimLabel})`);
869
+ }
870
+ }
871
+ if (traffic.aiReferralLandingPages.length > 0) {
872
+ console.log();
873
+ console.log(" AI LANDING PAGES");
874
+ for (const row of traffic.aiReferralLandingPages.slice(0, 10)) {
875
+ const dimLabel = row.sourceDimension === "first_user" ? "first-visit" : row.sourceDimension === "manual_utm" ? "utm" : "session";
876
+ const page = row.landingPage.length > 30 ? row.landingPage.slice(0, 27) + "..." : row.landingPage;
877
+ const source = row.source.length > 22 ? row.source.slice(0, 19) + "..." : row.source;
878
+ console.log(` ${page.padEnd(30)} ${source.padEnd(22)} ${String(row.sessions).padEnd(8)} sessions (${dimLabel})`);
879
+ }
880
+ }
881
+ if (traffic.socialReferrals.length > 0) {
882
+ console.log();
883
+ console.log(" SOCIAL SOURCES");
884
+ for (const ref of traffic.socialReferrals.slice(0, 10)) {
885
+ const chanLabel = ref.channelGroup === "Paid Social" ? "paid" : "organic";
886
+ console.log(` ${ref.source.padEnd(25)} ${String(ref.sessions).padEnd(8)} sessions (${chanLabel})`);
887
+ }
888
+ }
889
+ if (traffic.lastSyncedAt) {
890
+ console.log(`
891
+ Last synced: ${traffic.lastSyncedAt}`);
892
+ }
893
+ }
894
+ export {
895
+ gaAcquisition,
896
+ gaAiReferralDaily,
897
+ gaAiReferralHistory,
898
+ gaAttribution,
899
+ gaConnect,
900
+ gaCoverage,
901
+ gaDisconnect,
902
+ gaMeasurementAnalysis,
903
+ gaProperties,
904
+ gaSearchLandingPages,
905
+ gaSessionHistory,
906
+ gaSocialReferralHistory,
907
+ gaSocialReferralSummary,
908
+ gaStatus,
909
+ gaSync,
910
+ gaTraffic
911
+ };