@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,561 @@
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
+ CompetitorChangeKinds,
16
+ CompetitorShareImpactCaveats,
17
+ RatioUnits,
18
+ competitorAppendRequestSchema,
19
+ formatPercent,
20
+ normalizeCompetitorAliases,
21
+ normalizeCompetitorDomain,
22
+ shareOfVoiceLabel,
23
+ shareOfVoiceReason
24
+ } from "./chunk-D6COIM3U.js";
25
+ import "./chunk-MLKGABMK.js";
26
+
27
+ // src/commands/competitor.ts
28
+ import fs from "fs";
29
+ function getClient() {
30
+ return createApiClient();
31
+ }
32
+ function printCompetitorPreviewImpact(impact, preview) {
33
+ const before = impact.before;
34
+ const after = impact.after;
35
+ const beforeBasis = before.basis === "tracked" ? "tracked competitor" : "observed competitor";
36
+ const afterBasis = after.basis === "tracked" ? "tracked competitor" : "observed competitor";
37
+ const frame = impact.runIds.length > 0 ? `latest stored sweep, ${impact.runIds.length} run${impact.runIds.length === 1 ? "" : "s"}` : shareOfVoiceReason(before.reason ?? null) || "no latest stored sweep";
38
+ const classLabel = impact.queryClass === "pooled" ? "pooled queries" : `${impact.queryClass} queries`;
39
+ console.log(`Mention share ${formatPercent(before.percent, RatioUnits.percent)} -> ${formatPercent(after.percent, RatioUnits.percent)} (${frame}, ${classLabel}): project mentions ${before.projectMentions}, ${beforeBasis} mentions ${before.competitorMentions} -> ${afterBasis} mentions ${after.competitorMentions}; ${beforeBasis} competitors ${before.competitorCount} -> ${afterBasis} competitors ${after.competitorCount}. Restates every stored period.`);
40
+ if (preview) {
41
+ console.log("Dry run: no changes written.");
42
+ const plan = preview.plan;
43
+ const planParts = [
44
+ ...plan.added.length > 0 ? [`add ${plan.added.join(", ")}`] : [],
45
+ ...plan.removed.length > 0 ? [`remove ${plan.removed.join(", ")}`] : [],
46
+ ...plan.aliasChanges.length > 0 ? [`change aliases for ${plan.aliasChanges.map((change) => change.domain).join(", ")}`] : [],
47
+ ...plan.droppedAliases.length > 0 ? [`reject ${plan.droppedAliases.length} aliases`] : []
48
+ ];
49
+ console.log(`Plan: ${planParts.length > 0 ? planParts.join("; ") : "no stored changes"}.`);
50
+ if (preview.change === CompetitorChangeKinds.add) {
51
+ const requirement = preview.bulkAdd.acknowledgementRequired ? "requires --acknowledge-bulk-add for the real write" : "does not require bulk acknowledgement";
52
+ console.log(`Bulk add: ${plan.added.length} requested; ${preview.bulkAdd.count} additions in the trailing 24 hours, with a limit of ${preview.bulkAdd.limit}; ${requirement}.`);
53
+ }
54
+ }
55
+ for (const caveat of impact.caveats) {
56
+ if (caveat === CompetitorShareImpactCaveats["basis-changed"]) console.log(`Caveat: the competitor basis changed from ${beforeBasis} to ${afterBasis}.`);
57
+ if (caveat === CompetitorShareImpactCaveats["auto-alias-rescan-pending"]) console.log("Caveat: answer-derived aliases are pending a rescan.");
58
+ if (caveat === CompetitorShareImpactCaveats["pooled"]) console.log("Caveat: branded and non-brand queries are pooled because no usable project brand was configured.");
59
+ }
60
+ }
61
+ function completionTimeout(options, dryRun = false) {
62
+ const raw = options.waitTimeout;
63
+ if (raw !== void 0 && (!/^[1-9]\d*$/.test(raw) || !Number.isSafeInteger(Number(raw)))) {
64
+ throw usageError("--wait-timeout must be a positive integer number of seconds");
65
+ }
66
+ if (raw !== void 0 && !options.wait) throw usageError("--wait-timeout requires --wait");
67
+ if (options.wait && dryRun) throw usageError("--wait cannot be combined with --dry-run");
68
+ return options.wait ? Number(raw ?? "120") * 1e3 : void 0;
69
+ }
70
+ async function waitForCompetitorFields(client, project, timeout) {
71
+ if (timeout === void 0) return;
72
+ const deadline = Date.now() + timeout;
73
+ for (; ; ) {
74
+ const state = await client.getProject(project);
75
+ if (state.answerFieldsRecompute === null) return;
76
+ if (state.answerFieldsRecompute === void 0) {
77
+ throw new CliError({
78
+ code: "WAIT_STATUS_UNAVAILABLE",
79
+ message: "The write committed, but this server does not expose answer-field recomputation status. Upgrade the server to use --wait.",
80
+ details: { project, writeCommitted: true },
81
+ exitCode: 2
82
+ });
83
+ }
84
+ const remaining = deadline - Date.now();
85
+ if (remaining <= 0) {
86
+ throw new CliError({
87
+ code: "OPERATION_IN_PROGRESS",
88
+ message: "The write committed; stored answer fields are still being recomputed. Read the project status to check completion.",
89
+ details: { project, writeCommitted: true, answerFieldsRecompute: state.answerFieldsRecompute },
90
+ exitCode: 2
91
+ });
92
+ }
93
+ await new Promise((resolve) => setTimeout(resolve, Math.min(500, remaining)));
94
+ }
95
+ }
96
+ async function importCompetitors(project, filePath, format, completion = {}) {
97
+ const timeout = completionTimeout(completion);
98
+ if (!fs.existsSync(filePath)) {
99
+ throw new CliError({ code: "COMPETITOR_IMPORT_FILE_NOT_FOUND", message: `File not found: ${filePath}`, details: { filePath } });
100
+ }
101
+ const content = fs.readFileSync(filePath, "utf8");
102
+ let entries;
103
+ if (filePath.toLowerCase().endsWith(".json")) {
104
+ try {
105
+ entries = JSON.parse(content);
106
+ } catch {
107
+ throw new CliError({ code: "VALIDATION_ERROR", message: "Competitor import must contain a JSON array of domains or { domain, aliases } entries", details: { filePath } });
108
+ }
109
+ } else {
110
+ entries = content.split(/\r?\n/).map((line) => line.trim()).filter((line) => line && !line.startsWith("#")).map((line) => {
111
+ const [domain, ...aliases] = line.split(",").map((value) => value.trim());
112
+ return aliases.length ? { domain, aliases } : domain;
113
+ });
114
+ }
115
+ const parsed = competitorAppendRequestSchema.shape.competitors.safeParse(entries);
116
+ if (!parsed.success) {
117
+ throw new CliError({ code: "VALIDATION_ERROR", message: "Invalid competitor import entries", details: { filePath, issues: parsed.error.issues } });
118
+ }
119
+ const client = getClient();
120
+ const existing = new Set((await client.listCompetitors(project)).map((row) => normalizeCompetitorDomain(row.domain)));
121
+ const requested = new Set(parsed.data.map((entry) => normalizeCompetitorDomain(typeof entry === "string" ? entry : entry.domain)));
122
+ const current = completion.acknowledgeBulkAdd ? await client.appendCompetitors(project, parsed.data, { acknowledgeBulkAdd: true }) : await client.appendCompetitors(project, parsed.data);
123
+ await waitForCompetitorFields(client, project, timeout);
124
+ const domains = current.map((row) => row.domain);
125
+ const addedDomains = domains.filter((domain) => {
126
+ const normalized = normalizeCompetitorDomain(domain);
127
+ return requested.has(normalized) && !existing.has(normalized);
128
+ });
129
+ const result = { project, domains, addedDomains, addedCount: addedDomains.length };
130
+ if (format === "jsonl") emitJsonl([result]);
131
+ else if (format === "json") console.log(JSON.stringify(result, null, 2));
132
+ else console.log(`Imported ${addedDomains.length} new competitor(s) to "${project}".`);
133
+ }
134
+ async function addCompetitors(project, domains, format, aliases = [], dryRun = false, completion = {}) {
135
+ const timeout = completionTimeout(completion, dryRun);
136
+ const client = getClient();
137
+ if (dryRun) {
138
+ const preview = await client.previewCompetitorChange(project, { change: CompetitorChangeKinds.add, competitors: aliases.length ? [{ domain: domains[0], aliases }] : domains });
139
+ if (isMachineFormat(format)) console.log(JSON.stringify({ dryRun: true, ...preview }, null, 2));
140
+ else printCompetitorPreviewImpact(preview.impact, preview);
141
+ return;
142
+ }
143
+ const existing = await client.listCompetitors(project);
144
+ const existingDomains = existing.map((c) => c.domain);
145
+ const existingSet = new Set(existingDomains);
146
+ const requested = new Set(uniqueStrings(domains).map((domain) => normalizeCompetitorDomain(domain.trim())));
147
+ const entries = aliases.length > 0 ? domains.map((domain) => ({ domain, aliases })) : domains;
148
+ const current = completion.acknowledgeBulkAdd ? await client.appendCompetitors(project, entries, { acknowledgeBulkAdd: true }) : await client.appendCompetitors(project, entries);
149
+ await waitForCompetitorFields(client, project, timeout);
150
+ const currentDomains = current.map((c) => c.domain);
151
+ const addedDomains = currentDomains.filter((domain) => requested.has(domain) && !existingSet.has(domain));
152
+ const aliasTarget = aliases.length > 0 ? normalizeCompetitorDomain(domains[0].trim()) : null;
153
+ const aliasRow = aliasTarget ? current.find((c) => normalizeCompetitorDomain(c.domain) === aliasTarget) : void 0;
154
+ if (isMachineFormat(format)) {
155
+ console.log(JSON.stringify({
156
+ project,
157
+ domains: currentDomains,
158
+ addedDomains,
159
+ addedCount: addedDomains.length,
160
+ // The aliased competitor as the API returns it (`CompetitorDto`).
161
+ ...aliasRow ? { competitor: aliasRow } : {}
162
+ }, null, 2));
163
+ return;
164
+ }
165
+ if (addedDomains.length === 0) {
166
+ console.log(`No new competitors added to "${project}" (all already tracked).`);
167
+ } else {
168
+ console.log(`Added ${addedDomains.length} competitor(s) to "${project}".`);
169
+ }
170
+ if (aliasRow) console.log(`Aliases for ${aliasRow.domain}: ${formatAliases(storedAliases(aliasRow))}`);
171
+ }
172
+ function storedAliases(competitor) {
173
+ return competitor.aliases ?? [];
174
+ }
175
+ function formatAliases(aliases) {
176
+ return aliases.length > 0 ? aliases.join(", ") : "(none)";
177
+ }
178
+ function sameAliasName(a, b) {
179
+ return a.trim().toLowerCase() === b.trim().toLowerCase();
180
+ }
181
+ async function competitorAliases(project, domain, options) {
182
+ const timeout = completionTimeout(options, options.dryRun);
183
+ if (options.wait && !options.set && !options.clear && !options.add && !options.remove && !options.block && !options.unblock) {
184
+ throw usageError("--wait requires an alias change");
185
+ }
186
+ const client = getClient();
187
+ if (options.dryRun && (options.block !== void 0 || options.unblock !== void 0)) {
188
+ throw new CliError({
189
+ code: "VALIDATION_ERROR",
190
+ message: "--dry-run previews curated alias changes only; block and unblock are answer-derived detection controls",
191
+ displayMessage: "Error: --dry-run cannot preview --block or --unblock. Use competitor aliases detect for a read-only detection preview.",
192
+ details: { project, domain }
193
+ });
194
+ }
195
+ let result;
196
+ if (options.dryRun) {
197
+ const target = normalizeCompetitorDomain(domain.trim());
198
+ const matches = (await client.listCompetitors(project)).filter((c) => normalizeCompetitorDomain(c.domain) === target);
199
+ const current = matches.at(0);
200
+ if (!current) {
201
+ throw new CliError({
202
+ code: "NOT_FOUND",
203
+ message: `Competitor "${target}" is not tracked by project "${project}"`,
204
+ displayMessage: `Error: competitor "${target}" is not a project competitor of "${project}".`,
205
+ details: { project, domain: target }
206
+ });
207
+ }
208
+ const currentAliases = storedAliases(current);
209
+ const nextAliases = options.set !== void 0 || options.clear === true ? options.clear ? [] : options.set ?? [] : [
210
+ ...currentAliases.filter((alias) => !(options.remove ?? []).some((name) => sameAliasName(name, alias))),
211
+ ...options.add ?? []
212
+ ];
213
+ const preview = await client.previewCompetitorChange(project, {
214
+ change: CompetitorChangeKinds.aliases,
215
+ domain: current.domain,
216
+ aliases: nextAliases,
217
+ mode: "set"
218
+ });
219
+ if (isMachineFormat(options.format)) console.log(JSON.stringify({ dryRun: true, ...preview }, null, 2));
220
+ else printCompetitorPreviewImpact(preview.impact, preview);
221
+ return;
222
+ }
223
+ if (options.block !== void 0) {
224
+ result = await client.blockCompetitorAliases(project, domain, options.block);
225
+ } else if (options.unblock !== void 0) {
226
+ result = await client.unblockCompetitorAliases(project, domain, options.unblock);
227
+ } else if (options.set !== void 0 || options.clear === true) {
228
+ result = await client.setCompetitorAliases(project, domain, options.clear ? [] : options.set ?? []);
229
+ } else {
230
+ const target = normalizeCompetitorDomain(domain.trim());
231
+ const matches = (await client.listCompetitors(project)).filter((c) => normalizeCompetitorDomain(c.domain) === target);
232
+ if (matches.length > 1) {
233
+ const rows = [...matches].sort((a, b) => a.domain.localeCompare(b.domain));
234
+ const aliases = normalizeCompetitorAliases(rows.flatMap(storedAliases));
235
+ const addAgain = `canonry competitor add ${project} ${target}${aliases.map((alias) => ` --alias ${JSON.stringify(alias)}`).join("")}`;
236
+ const stored = `${matches.length} rows (${rows.map((c) => c.domain).join(", ")})`;
237
+ throw new CliError({
238
+ code: "VALIDATION_ERROR",
239
+ message: `Competitor ${target} is stored as ${stored}; remove the competitor (every row goes) and add it again: ${addAgain}`,
240
+ displayMessage: `Error: competitor ${target} is stored as ${stored}. Remove it with: canonry competitor remove ${project} ${target}, then add it again with: ${addAgain}`,
241
+ details: { project, domain: target, matches: rows.map((c) => ({ id: c.id, domain: c.domain })), aliases }
242
+ });
243
+ }
244
+ const current = matches.at(0);
245
+ if (!current) {
246
+ throw new CliError({
247
+ code: "NOT_FOUND",
248
+ message: `Competitor "${target}" is not tracked by project "${project}"`,
249
+ displayMessage: [
250
+ `Error: competitor "${target}" is not a project competitor of "${project}".`,
251
+ `If an Advanced market pins it, list its plan names and learned names with: canonry competitor aliases detect ${project}`,
252
+ `and block or unblock a learned name with: canonry competitor aliases ${project} ${target} --block <name> (or --unblock <name>); change its plan names in a measurement draft.`,
253
+ `To track it in every market instead (it then counts outside its markets): canonry competitor add ${project} ${target}`
254
+ ].join("\n"),
255
+ details: { project, domain: target }
256
+ });
257
+ }
258
+ const removed = options.remove ?? [];
259
+ const added = options.add ?? [];
260
+ if (added.length === 0 && removed.length === 0) {
261
+ result = current;
262
+ } else if (removed.length === 0) {
263
+ const listed = await client.appendCompetitors(project, [{ domain: current.domain, aliases: added }]);
264
+ result = listed.find((c) => c.domain === current.domain) ?? current;
265
+ } else {
266
+ const next = [
267
+ ...storedAliases(current).filter((alias) => !removed.some((name) => sameAliasName(name, alias))),
268
+ ...added
269
+ ];
270
+ result = await client.setCompetitorAliases(project, current.domain, next);
271
+ }
272
+ }
273
+ await waitForCompetitorFields(client, project, timeout);
274
+ if (isMachineFormat(options.format)) {
275
+ console.log(JSON.stringify(result, null, 2));
276
+ return;
277
+ }
278
+ printCompetitorNames(result);
279
+ }
280
+ function day(iso) {
281
+ return iso.slice(0, 10);
282
+ }
283
+ function autoAliasEvidence(record) {
284
+ const precision = record.precision === null ? "n/a" : formatPercent(record.precision, RatioUnits.fraction);
285
+ const lift = record.lift === void 0 || record.lift === null ? "" : ` (${record.lift}x the rate in answers that do not name it)`;
286
+ const cased = record.nameCasedAnswers === void 0 ? "" : `; written as a name in ${record.nameCasedAnswers}`;
287
+ const seen = record.firstSeen ? `; seen ${day(record.firstSeen)} to ${day(record.lastSeen)}` : "";
288
+ return `paired in ${record.directPairs} answers over ${record.runs} sweeps; ${precision} of ${record.namingAnswers} answers naming it cite the site${lift}${cased}; co-occurs in ${record.cooccurrences}${seen}`;
289
+ }
290
+ function printCompetitorNames(competitor) {
291
+ const auto = competitor.autoAliases ?? [];
292
+ const blocked = competitor.blockedAliases ?? [];
293
+ if (competitor.marketKeys) {
294
+ console.log(`Plan names for ${competitor.domain} (Advanced markets: ${competitor.marketKeys.join(", ")}): ${formatAliases(storedAliases(competitor))}`);
295
+ } else {
296
+ console.log(`Aliases for ${competitor.domain}: ${formatAliases(storedAliases(competitor))}`);
297
+ }
298
+ if (auto.length === 0) {
299
+ console.log("Auto-detected from stored answers: (none)");
300
+ } else {
301
+ console.log("Auto-detected from stored answers:");
302
+ for (const record of auto) console.log(` ${record.name} (${autoAliasEvidence(record)})`);
303
+ }
304
+ console.log(`Blocked from auto-detection: ${formatAliases(blocked)}`);
305
+ }
306
+ var CANDIDATE_MARKS = {
307
+ added: "+",
308
+ kept: "=",
309
+ removed: "-",
310
+ review: "?",
311
+ rejected: "x"
312
+ };
313
+ async function detectCompetitorAutoAliases(project, options) {
314
+ const client = getClient();
315
+ if (options.dryRun && options.apply) {
316
+ throw new CliError({
317
+ code: "VALIDATION_ERROR",
318
+ message: "--dry-run and --apply cannot be combined",
319
+ displayMessage: "Error: --dry-run and --apply cannot be combined.",
320
+ details: { project }
321
+ });
322
+ }
323
+ const result = options.apply ? await client.applyCompetitorAutoAliases(project) : await client.previewCompetitorAutoAliases(project);
324
+ if (options.format === "json") {
325
+ console.log(JSON.stringify(result, null, 2));
326
+ return;
327
+ }
328
+ if (options.format === "jsonl") {
329
+ emitJsonl(result.competitors.map((competitor) => ({ project: result.project, applied: result.applied, ...competitor })));
330
+ return;
331
+ }
332
+ const { scan, thresholds } = result;
333
+ console.log(`Competitor auto-alias detection for "${result.project}" (${result.applied ? "applied" : "dry run, nothing stored"})`);
334
+ console.log(`Scanned ${scan.runs} runs, ${scan.snapshots} snapshots, ${scan.answers} answers (newest ${scan.maxRuns} runs, up to ${scan.maxSnapshots} snapshots; provider citations ${scan.providerCitations ? "read" : "unavailable, answer-text pairings only"})`);
335
+ console.log(`Applies a name paired with the site in ${thresholds.minDirectPairs}+ answers over ${thresholds.minRuns}+ sweeps, named in ${thresholds.minNamingAnswers}+ answers, precision ${formatPercent(thresholds.minPrecision, RatioUnits.fraction)}+, cited ${thresholds.minLift}x+ more often when named than otherwise, written as a name in ${formatPercent(thresholds.minNameCasedShare, RatioUnits.fraction)}+ of them, ${thresholds.dominanceMultiple}x any other competitor's pairings, ${thresholds.minKeyLength}+ letters or digits, and visibly tied to the domain`);
336
+ console.log("Legend: + added = kept - removed ? review only x rejected");
337
+ if (result.impact) printCompetitorPreviewImpact(result.impact);
338
+ if (result.competitors.length === 0) {
339
+ console.log(`
340
+ No competitors tracked for "${result.project}".`);
341
+ return;
342
+ }
343
+ for (const competitor of result.competitors) {
344
+ console.log(competitor.marketKeys ? `
345
+ ${competitor.domain} (Advanced markets: ${competitor.marketKeys.join(", ")})` : `
346
+ ${competitor.domain}`);
347
+ if (competitor.aliases.length) console.log(` ${competitor.marketKeys ? "plan names" : "curated"}: ${competitor.aliases.join(", ")}`);
348
+ if (competitor.blockedAliases.length) console.log(` blocked: ${competitor.blockedAliases.join(", ")}`);
349
+ if (competitor.candidates.length === 0) {
350
+ console.log(" (no candidate names paired with this site)");
351
+ continue;
352
+ }
353
+ for (const candidate of competitor.candidates) {
354
+ const reason = candidate.reason ? ` [${candidate.reason}${candidate.conflictsWith ? `: ${candidate.conflictsWith}` : ""}]` : "";
355
+ console.log(` ${CANDIDATE_MARKS[candidate.status]} ${candidate.name}${reason} (${autoAliasEvidence(candidate)})`);
356
+ }
357
+ }
358
+ if (!result.applied && result.changed) {
359
+ console.log(`
360
+ Run with --apply to store these changes now (the server also applies them after the next sweep).`);
361
+ }
362
+ }
363
+ async function removeCompetitors(project, domains, format, dryRun = false) {
364
+ const client = getClient();
365
+ if (dryRun) {
366
+ const preview = await client.previewCompetitorChange(project, { change: CompetitorChangeKinds.remove, competitors: domains });
367
+ if (isMachineFormat(format)) console.log(JSON.stringify({ dryRun: true, ...preview }, null, 2));
368
+ else printCompetitorPreviewImpact(preview.impact, preview);
369
+ return;
370
+ }
371
+ const existing = await client.listCompetitors(project);
372
+ const existingDomains = existing.map((c) => c.domain);
373
+ const requested = new Set(uniqueStrings(domains).map((domain) => normalizeCompetitorDomain(domain.trim())));
374
+ const current = await client.deleteCompetitors(project, domains);
375
+ const currentSet = new Set(current.map((c) => c.domain));
376
+ const removedDomains = existingDomains.filter((domain) => requested.has(normalizeCompetitorDomain(domain)) && !currentSet.has(domain));
377
+ if (isMachineFormat(format)) {
378
+ console.log(JSON.stringify({
379
+ project,
380
+ domains: current.map((c) => c.domain),
381
+ removedDomains,
382
+ removedCount: removedDomains.length
383
+ }, null, 2));
384
+ return;
385
+ }
386
+ console.log(`Removed ${removedDomains.length} competitor(s) from "${project}".`);
387
+ }
388
+ function uniqueStrings(values) {
389
+ const seen = /* @__PURE__ */ new Set();
390
+ const result = [];
391
+ for (const value of values) {
392
+ if (seen.has(value)) continue;
393
+ seen.add(value);
394
+ result.push(value);
395
+ }
396
+ return result;
397
+ }
398
+ async function listCompetitors(project, format) {
399
+ const client = getClient();
400
+ const comps = await client.listCompetitors(project);
401
+ if (format === "json") {
402
+ console.log(JSON.stringify(comps, null, 2));
403
+ return;
404
+ } else if (format === "jsonl") {
405
+ emitJsonl(comps.map((c) => ({ project, ...c })));
406
+ return;
407
+ }
408
+ if (comps.length === 0) {
409
+ console.log(`No competitors found for "${project}".`);
410
+ return;
411
+ }
412
+ console.log(`Competitors for "${project}" (${comps.length}):
413
+ `);
414
+ for (const c of comps) {
415
+ const aliases = storedAliases(c);
416
+ const auto = (c.autoAliases ?? []).map((record) => record.name);
417
+ const names = [
418
+ ...aliases.length > 0 ? [`aliases: ${aliases.join(", ")}`] : [],
419
+ ...auto.length > 0 ? [`auto: ${auto.join(", ")}`] : []
420
+ ];
421
+ console.log(names.length > 0 ? ` ${c.domain} (${names.join("; ")})` : ` ${c.domain}`);
422
+ }
423
+ }
424
+ async function showCompetitorLandscape(project, options) {
425
+ const client = getClient();
426
+ const data = await client.getCompetitorLandscape(project, {
427
+ window: options.window,
428
+ scope: options.scope,
429
+ groupKey: options.groupKey,
430
+ provider: options.provider,
431
+ ...options.groupBy ? { groupBy: options.groupBy } : {},
432
+ ...options.model !== void 0 ? { model: options.model } : {},
433
+ queryClass: options.queryClass,
434
+ location: options.location,
435
+ runId: options.runId,
436
+ answers: options.answers
437
+ });
438
+ if (options.format === "json") {
439
+ console.log(JSON.stringify(data, null, 2));
440
+ return;
441
+ }
442
+ if (options.format === "jsonl") {
443
+ console.log(JSON.stringify(data));
444
+ return;
445
+ }
446
+ printCompetitorLandscape(data);
447
+ }
448
+ async function suggestCompetitors(project, options = {}) {
449
+ const client = getClient();
450
+ const data = await client.suggestCompetitors(project, {
451
+ window: options.window,
452
+ minAnswers: options.minAnswers,
453
+ queryClass: options.queryClass,
454
+ groupKey: options.groupKey,
455
+ limit: options.limit
456
+ });
457
+ if (options.format === "json") {
458
+ console.log(JSON.stringify(data, null, 2));
459
+ return;
460
+ }
461
+ if (options.format === "jsonl") {
462
+ emitJsonl(data.candidates.map((candidate) => ({
463
+ project: data.project,
464
+ window: data.window,
465
+ filters: data.filters,
466
+ ...candidate
467
+ })));
468
+ return;
469
+ }
470
+ printCompetitorSuggestions(data);
471
+ }
472
+ function printCompetitorSuggestions(data) {
473
+ console.log(`Competitor suggestions for "${data.project}" (${data.window})`);
474
+ const population = data.filters.queryClass === "all" ? "pooled (all)" : data.filters.queryClass;
475
+ console.log(`Counting ${population} queries, requiring ${data.thresholds.minAnswers} answer(s).`);
476
+ if (data.candidates.length === 0) {
477
+ console.log("No stored candidates met the threshold.");
478
+ } else {
479
+ for (const candidate of data.candidates) {
480
+ const names = candidate.names.length > 0 ? `; names: ${candidate.names.map((name) => `${name.name} (${name.answerCount})`).join(", ")}` : "";
481
+ console.log(` ${candidate.domain} ${candidate.status}, named in ${candidate.namingAnswers} answer(s), cited in ${candidate.citingAnswers}, both in ${candidate.bothAnswers}, paired in ${candidate.pairedAnswers}${candidate.reason ? `; reason: ${candidate.reason}` : ""}${names}`);
482
+ }
483
+ }
484
+ console.log(`Evidence: ${data.evidence.answeredResults} answer(s), ${data.evidence.sourceResults} source result(s), ${data.runCount} sweep(s).`);
485
+ }
486
+ function printCompetitorLandscape(data) {
487
+ const scope = data.scope.kind === "group" ? `market ${data.scope.groupKey}` : data.scope.kind === "all-markets" ? "all markets" : "project";
488
+ console.log(`Competitor landscape \xB7 ${scope} \xB7 ${data.window}`);
489
+ if (data.filters.model !== void 0) {
490
+ console.log(`Requested model filter: ${data.filters.provider} \xB7 ${data.filters.model}`);
491
+ }
492
+ console.log("Mention share is answer-text evidence; citations are independent source-list evidence.");
493
+ console.log(
494
+ data.filters.queryClass === "all" ? "Share of voice is blank: branded and non-brand queries are pooled here. Add --query-class non-brand for a ratio." : `Counting ${data.filters.queryClass} queries only.`
495
+ );
496
+ if (data.reason) console.log(shareOfVoiceReason(data.reason));
497
+ const changedAt = [data.competitorSetChangedAt, data.competitorIdentityChangedAt].filter((value) => value !== null && value !== void 0).sort().at(-1);
498
+ if (changedAt && data.competitorListRestated === true) {
499
+ console.log(`Competitor list changed ${changedAt}: earlier periods were restated`);
500
+ }
501
+ if (data.truncated) console.log("Top 100 observed competitors and top 100 other cited sources shown; pinned competitors are complete.");
502
+ console.log("");
503
+ printLandscapeRows("Your brand", [data.project], false, data, data.filters.queryClass);
504
+ printLandscapeRows("Pinned competitors", data.pinned, false, data, data.filters.queryClass);
505
+ printLandscapeRows("Observed competitors", data.observed, false, data, data.filters.queryClass);
506
+ printLandscapeRows("Other cited sources", data.otherSources, false, data, data.filters.queryClass);
507
+ console.log("");
508
+ console.log(
509
+ `Evidence: ${data.evidence.answeredResults} answer-text result(s), ${data.evidence.sourceResults} source result(s); excluded: ${data.evidence.excludedProbeResults} probe, ${data.evidence.excludedNonCompletedResults} non-completed.`
510
+ );
511
+ if (data.observedNames?.length) {
512
+ const total = data.observedNamesTotal ?? data.observedNames.length;
513
+ console.log(total > data.observedNames.length ? `Names observed in answers (not a comparison set), top ${data.observedNames.length} of ${total}:` : "Names observed in answers (not a comparison set):");
514
+ for (const row of data.observedNames) console.log(` ${row.name} \xB7 ${row.answerCount} answers`);
515
+ }
516
+ if (data.modelComparison) printModelComparison(data.modelComparison, data.filters.queryClass);
517
+ }
518
+ function describeServedModels(evidence) {
519
+ if (evidence.status === "unknown") return "Unknown (not disclosed)";
520
+ if (evidence.status === "known") return evidence.model;
521
+ return [...evidence.models, ...evidence.includesUnknown ? ["Unknown (not disclosed)"] : []].join(", ");
522
+ }
523
+ function printModelComparison(comparison, queryClass) {
524
+ console.log("");
525
+ console.log(`Model comparison \xB7 requested-model basis \xB7 ${comparison.groups.length} of ${comparison.totalGroups} groups`);
526
+ console.log("Groups use stored observations. They do not form a matched-query or equal-weight comparison.");
527
+ if (comparison.truncated) console.log("The first 50 provider/model groups are shown. Additional groups are omitted.");
528
+ for (const group of comparison.groups) {
529
+ console.log("");
530
+ console.log(`${group.provider} \xB7 requested model: ${group.model ?? "Unknown (not recorded)"}`);
531
+ console.log(`Served model evidence: ${describeServedModels(group.servedModels)}`);
532
+ console.log(`Samples: ${group.snapshotCount} snapshot(s), ${group.evidence.answeredResults} answer-text result(s), ${group.evidence.sourceResults} source result(s).`);
533
+ if (group.reason) console.log(shareOfVoiceReason(group.reason));
534
+ printLandscapeRows("Your brand", [group.project], true, group, queryClass);
535
+ printLandscapeRows("Pinned competitors", group.pinned, true, group, queryClass);
536
+ printLandscapeRows("Observed competitors", group.observed, true, group, queryClass);
537
+ printLandscapeRows("Other cited sources", group.otherSources, true, group, queryClass);
538
+ if (group.truncated) console.log("Top 100 observed competitors and top 100 other sources shown. Pinned competitors are complete.");
539
+ }
540
+ }
541
+ function printLandscapeRows(heading, rows, showSampleCount = false, context, queryClass = "all") {
542
+ console.log(`${heading}:`);
543
+ if (rows.length === 0) {
544
+ console.log(" \u2014");
545
+ return;
546
+ }
547
+ for (const row of rows) {
548
+ const sov = `${shareOfVoiceLabel(row.shareOfVoice, context)} \xB7 ${queryClass} queries`;
549
+ console.log(` ${row.domain} mention ${row.mentionCount} \xB7 citation ${row.citationCount} \xB7 SOV ${sov}${showSampleCount ? ` \xB7 answers ${row.answeredResults}` : ""}`);
550
+ }
551
+ }
552
+ export {
553
+ addCompetitors,
554
+ competitorAliases,
555
+ detectCompetitorAutoAliases,
556
+ importCompetitors,
557
+ listCompetitors,
558
+ removeCompetitors,
559
+ showCompetitorLandscape,
560
+ suggestCompetitors
561
+ };