@canonry/canonry 7.51.5 → 7.52.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.
Files changed (141) hide show
  1. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +8 -0
  2. package/assets/assets/{AccessControls-B5TqDgeq.js → AccessControls-CteIuEGI.js} +1 -1
  3. package/assets/assets/{AuditHistoryPanel-DgxiizOW.js → AuditHistoryPanel-DqJGiLsf.js} +1 -1
  4. package/assets/assets/{BacklinksPage-Ay6pdphx.js → BacklinksPage-DotWEPQt.js} +1 -1
  5. package/assets/assets/{HistoryPage-B11eFH21.js → HistoryPage-aOd198dT.js} +1 -1
  6. package/assets/assets/MeasurementPropertyPage-CuaKVK8x.js +4 -0
  7. package/assets/assets/{ProjectPage-DoY0hftd.js → ProjectPage-O9oufMgi.js} +4 -4
  8. package/assets/assets/{RunsPage-BPBmuQAS.js → RunsPage-DIXMrc-N.js} +1 -1
  9. package/assets/assets/{SettingsPage-ClKnP8xy.js → SettingsPage-BuGb6AGa.js} +1 -1
  10. package/assets/assets/SiteHealthSection-CweaKjCo.js +2 -0
  11. package/assets/assets/TrafficPage-B7MaQalp.js +40 -0
  12. package/assets/assets/{TrafficSourceDetailPage-DQu0YNt2.js → TrafficSourceDetailPage-BPtjnF9s.js} +1 -1
  13. package/assets/assets/{card-DYMyvhB9.js → card-DoV-8Txo.js} +1 -1
  14. package/assets/assets/{extract-error-message-BRM1I_3L.js → extract-error-message-DKQJJlZ-.js} +1 -1
  15. package/assets/assets/{format-helpers-DrkFERj3.js → format-helpers-BWnMmkiO.js} +1 -1
  16. package/assets/assets/index-Z63c4PeO.js +39 -0
  17. package/assets/assets/{query-client-gRFnU4VF.js → query-client-vB35tVTz.js} +1 -1
  18. package/assets/assets/{react-query-lH82FULK.js → react-query-BI0567qs.js} +1 -1
  19. package/assets/assets/{react-sigma_core.esm.min-D09H4byP.js → react-sigma_core.esm.min-hGyOC4V_.js} +1 -1
  20. package/assets/assets/{service-Cx0HSnE9.js → service-c4YvpVKX.js} +1 -1
  21. package/assets/index.html +6 -6
  22. package/dist/ads-MREK2AGL.js +544 -0
  23. package/dist/agent-4RUZ3MC4.js +70 -0
  24. package/dist/agent-ask-YLTYBEYH.js +139 -0
  25. package/dist/agent-conversations-QA6IKDGR.js +52 -0
  26. package/dist/agent-memory-MEQAJOB3.js +92 -0
  27. package/dist/agent-providers-AXYPDJHL.js +55 -0
  28. package/dist/agent-transcript-SMNQNYCD.js +77 -0
  29. package/dist/analytics-4OR64IGV.js +240 -0
  30. package/dist/apply-CQXCFXAH.js +175 -0
  31. package/dist/backfill-TMXCNVOB.js +41 -0
  32. package/dist/backlinks-6KFAQGYV.js +303 -0
  33. package/dist/bing-HFCACTAC.js +418 -0
  34. package/dist/bootstrap-SQVQXOJC.js +326 -0
  35. package/dist/cdp-IACL7EXU.js +162 -0
  36. package/dist/chunk-4MJYGB56.js +124 -0
  37. package/dist/chunk-5N6245R7.js +1160 -0
  38. package/dist/chunk-6BPZHNDC.js +617 -0
  39. package/dist/chunk-6GO5VVAC.js +15 -0
  40. package/dist/chunk-7244X3K6.js +609 -0
  41. package/dist/chunk-7XE2IRBG.js +204 -0
  42. package/dist/chunk-AOJU5LKX.js +8 -0
  43. package/dist/chunk-AWCWIQAU.js +2686 -0
  44. package/dist/{chunk-JBZZEIM2.js → chunk-BBOHY2DQ.js} +2 -13
  45. package/dist/{chunk-AZFPA7JV.js → chunk-BU3VAG5J.js} +6 -4
  46. package/dist/{chunk-4YCGZGA3.js → chunk-BYOK6Z4F.js} +2 -2
  47. package/dist/chunk-DSNSD5J3.js +971 -0
  48. package/dist/chunk-EGIZNSDA.js +94 -0
  49. package/dist/chunk-ELCLGWUT.js +83 -0
  50. package/dist/chunk-FC4XND45.js +38 -0
  51. package/dist/chunk-GNKOBKPW.js +58 -0
  52. package/dist/chunk-HEGXGCGL.js +524 -0
  53. package/dist/chunk-I6KNMZ77.js +232 -0
  54. package/dist/{chunk-HLVEB5TB.js → chunk-IIOEAJTV.js} +7 -5
  55. package/dist/chunk-ILDT4LPB.js +1273 -0
  56. package/dist/chunk-JY3RLZGB.js +30 -0
  57. package/dist/{chunk-PLYJX67A.js → chunk-K5I45PZI.js} +8084 -13939
  58. package/dist/chunk-KXAOMTXN.js +1034 -0
  59. package/dist/chunk-LK2BG6EX.js +145 -0
  60. package/dist/chunk-MJNUSPO4.js +15 -0
  61. package/dist/chunk-MKAC7HKH.js +9178 -0
  62. package/dist/chunk-MLKGABMK.js +9 -0
  63. package/dist/{chunk-SFMWHPMX.js → chunk-O4RMPA6H.js} +13765 -13737
  64. package/dist/chunk-O77IBNVO.js +8264 -0
  65. package/dist/chunk-OFL4PTYU.js +644 -0
  66. package/dist/chunk-QLPLENDT.js +133 -0
  67. package/dist/chunk-R2J4SNKF.js +78 -0
  68. package/dist/{chunk-KEATAHXH.js → chunk-RVUCY4ZV.js} +358 -581
  69. package/dist/chunk-SNFBJKAW.js +530 -0
  70. package/dist/chunk-TALC5DX5.js +420 -0
  71. package/dist/chunk-TSENU4GG.js +18 -0
  72. package/dist/{chunk-HAHXPJQ5.js → chunk-V5D4XNWV.js} +16 -1684
  73. package/dist/chunk-VJWDBFSL.js +69 -0
  74. package/dist/chunk-XEBKF4N5.js +8 -0
  75. package/dist/chunk-Y4GK7GCV.js +15376 -0
  76. package/dist/{chunk-A3WSAAQS.js → chunk-YSEC6TIB.js} +7917 -33199
  77. package/dist/chunk-Z7IUAJOF.js +13 -0
  78. package/dist/citations-NSBBWRZ4.js +106 -0
  79. package/dist/{cli-catalog-MO6Z2CIZ.js → cli-catalog-OFWJMNMD.js} +5 -3
  80. package/dist/cli-commands-WVBL337U.js +19 -0
  81. package/dist/cli.js +35 -29
  82. package/dist/competitor-V4OHORBC.js +561 -0
  83. package/dist/content-RUXRI5IC.js +257 -0
  84. package/dist/dashboard-JXB2YAQJ.js +71 -0
  85. package/dist/demo-55ZNUOXU.js +75 -0
  86. package/dist/{demo-server-GIWDJGJX.js → demo-server-XO7PHM4I.js} +22 -9
  87. package/dist/discover-JJQ564HS.js +372 -0
  88. package/dist/discover-eval-KLEKZ6U4.js +282 -0
  89. package/dist/doctor-JAMQZCMZ.js +152 -0
  90. package/dist/evidence-YRSB7GFE.js +57 -0
  91. package/dist/export-cmd-MHML4OYU.js +49 -0
  92. package/dist/ga-LSXPE2MN.js +911 -0
  93. package/dist/gbp-RMKMLOC7.js +370 -0
  94. package/dist/google-JQ4T6JTQ.js +946 -0
  95. package/dist/google-marketing-J6SEODYC.js +403 -0
  96. package/dist/health-cmd-MV2JM2C3.js +64 -0
  97. package/dist/history-SRRH7A2E.js +90 -0
  98. package/dist/index.d.ts +43 -4
  99. package/dist/index.js +29 -6
  100. package/dist/init-ZJZFUERV.js +432 -0
  101. package/dist/insights-PMMGNWZH.js +63 -0
  102. package/dist/intelligence-service-KCSU6ZUJ.js +15 -0
  103. package/dist/keys-TS7NZANS.js +116 -0
  104. package/dist/keyword-VNCKDUGC.js +164 -0
  105. package/dist/logs-VH3WOTZJ.js +30 -0
  106. package/dist/mcp-DG2RROB3.js +14 -0
  107. package/dist/mcp.js +14 -5
  108. package/dist/measurement-plan-4T35TUGG.js +42 -0
  109. package/dist/notify-BWHUSKL7.js +125 -0
  110. package/dist/organic-evidence-QX4SXXJP.js +53 -0
  111. package/dist/overview-7IHUTKUV.js +213 -0
  112. package/dist/project-JXLSWDE2.js +460 -0
  113. package/dist/query-S75EL25H.js +211 -0
  114. package/dist/research-KFTV3IP4.js +200 -0
  115. package/dist/results-export-GTKVBU34.js +27 -0
  116. package/dist/run-26HDIRHF.js +31 -0
  117. package/dist/schedule-N6G4SVHQ.js +177 -0
  118. package/dist/search-MI32EPYM.js +42 -0
  119. package/dist/serve-XLGE42AG.js +598 -0
  120. package/dist/session-W5DXWIYM.js +47 -0
  121. package/dist/settings-T7WI2UVE.js +107 -0
  122. package/dist/skills-F3WPKPTK.js +33 -0
  123. package/dist/snapshot-PD3EAVEX.js +538 -0
  124. package/dist/src-XDUXMJC3.js +316 -0
  125. package/dist/status-PUH7JFZ4.js +126 -0
  126. package/dist/support-ARF4HER7.js +24 -0
  127. package/dist/technical-aeo-AUFWWJIP.js +625 -0
  128. package/dist/telemetry-XBYT7G2K.js +118 -0
  129. package/dist/tools-GVHIRWSN.js +41 -0
  130. package/dist/traffic-B3HW2ZWG.js +1295 -0
  131. package/dist/users-M5HNQZYI.js +170 -0
  132. package/dist/visibility-stats-Y7GJKMHN.js +241 -0
  133. package/dist/wordpress-GCIURYPN.js +600 -0
  134. package/package.json +1 -1
  135. package/assets/assets/MeasurementPropertyPage-1UYI7mzP.js +0 -4
  136. package/assets/assets/SiteHealthSection-PWjKMmEn.js +0 -2
  137. package/assets/assets/TrafficPage-DkfGiJXR.js +0 -40
  138. package/assets/assets/index-CG1Jox52.js +0 -39
  139. package/dist/chunk-4QQYYRHV.js +0 -23082
  140. package/dist/cli-commands-FOJR3HHU.js +0 -15
  141. package/dist/intelligence-service-XQCNWAPL.js +0 -9
@@ -0,0 +1,1295 @@
1
+ import {
2
+ getCloudflareTrafficConnectionBySourceId
3
+ } from "./chunk-R2J4SNKF.js";
4
+ import {
5
+ createApiClient
6
+ } from "./chunk-V5D4XNWV.js";
7
+ import {
8
+ loadConfigRaw
9
+ } from "./chunk-OFL4PTYU.js";
10
+ import {
11
+ emitJsonl
12
+ } from "./chunk-Z7IUAJOF.js";
13
+ import "./chunk-AOJU5LKX.js";
14
+ import {
15
+ CliError,
16
+ isMachineFormat,
17
+ usageError
18
+ } from "./chunk-HGMYEDAQ.js";
19
+ import {
20
+ CLOUDFLARE_WORKER_BINDINGS,
21
+ CLOUDFLARE_WORKER_GENERATED_MARKER,
22
+ CLOUDFLARE_WRANGLER_GENERATED_MARKER,
23
+ DEFAULT_BOT_LIST,
24
+ generateWorkerScript,
25
+ generateWranglerToml
26
+ } from "./chunk-Y4GK7GCV.js";
27
+ import {
28
+ RunStatuses,
29
+ TrafficEventKinds,
30
+ TrafficSeriesGranularities,
31
+ describeError,
32
+ formatPercent,
33
+ formatValidationIssues,
34
+ parseTrafficAnalyticsPeriod,
35
+ referralAssessmentQuerySchema,
36
+ trafficSamplesQuerySchema
37
+ } from "./chunk-O4RMPA6H.js";
38
+ import "./chunk-MLKGABMK.js";
39
+
40
+ // src/commands/traffic.ts
41
+ import fs2 from "fs";
42
+
43
+ // src/cloudflare-worker-deploy.ts
44
+ import { spawn } from "child_process";
45
+ import { randomUUID } from "crypto";
46
+ import fs from "fs";
47
+ import os from "os";
48
+ import path from "path";
49
+ import { stripVTControlCharacters } from "util";
50
+ var MAX_WRANGLER_DIAGNOSTIC_LENGTH = 2e3;
51
+ function wranglerDiagnostic(output) {
52
+ const plain = stripVTControlCharacters(output).trim();
53
+ if (plain.length <= MAX_WRANGLER_DIAGNOSTIC_LENGTH) return plain;
54
+ const half = Math.floor(MAX_WRANGLER_DIAGNOSTIC_LENGTH / 2);
55
+ return `${plain.slice(0, half)}
56
+ ...
57
+ ${plain.slice(-half)}`;
58
+ }
59
+ function projectSlug(project) {
60
+ return project.trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "project";
61
+ }
62
+ function lstatIfPresent(filePath) {
63
+ try {
64
+ return fs.lstatSync(filePath);
65
+ } catch (error) {
66
+ if (error.code === "ENOENT") return null;
67
+ throw error;
68
+ }
69
+ }
70
+ function resolveCloudflareWorkerOutputDirectory(project, outputDirectory, cwd = process.cwd()) {
71
+ return path.resolve(cwd, outputDirectory ?? `canonry-cloudflare-${projectSlug(project)}`);
72
+ }
73
+ function prepareCloudflareWorkerOutputDirectory(outputDirectory) {
74
+ const resolved = path.resolve(outputDirectory);
75
+ const outputStat = lstatIfPresent(resolved);
76
+ if (outputStat) {
77
+ const stat = outputStat;
78
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
79
+ throw new Error(`output directory is not a regular directory: ${resolved}`);
80
+ }
81
+ } else {
82
+ fs.mkdirSync(resolved, { recursive: true, mode: 448 });
83
+ }
84
+ const artifacts = {
85
+ outputDirectory: resolved,
86
+ workerScriptPath: path.join(resolved, "worker.js"),
87
+ wranglerTomlPath: path.join(resolved, "wrangler.toml")
88
+ };
89
+ for (const artifactPath of [artifacts.workerScriptPath, artifacts.wranglerTomlPath]) {
90
+ const stat = lstatIfPresent(artifactPath);
91
+ if (!stat) continue;
92
+ if (!stat.isFile() || stat.isSymbolicLink()) {
93
+ throw new Error(`artifact path is not a regular file: ${artifactPath}`);
94
+ }
95
+ const contents = fs.readFileSync(artifactPath, "utf-8");
96
+ if (!isRecognizablyCanonryGenerated(artifactPath, contents)) {
97
+ throw new Error(`refusing to overwrite an operator-owned artifact: ${artifactPath}`);
98
+ }
99
+ }
100
+ return artifacts;
101
+ }
102
+ function readRegularArtifact(filePath) {
103
+ const stat = lstatIfPresent(filePath);
104
+ if (!stat) return null;
105
+ if (!stat.isFile() || stat.isSymbolicLink()) {
106
+ throw new Error(`artifact path is not a regular file: ${filePath}`);
107
+ }
108
+ return fs.readFileSync(filePath, "utf-8");
109
+ }
110
+ function isRecognizablyCanonryGenerated(filePath, contents) {
111
+ if (path.basename(filePath) === "worker.js") {
112
+ return contents.startsWith(`${CLOUDFLARE_WORKER_GENERATED_MARKER}
113
+ `);
114
+ }
115
+ if (path.basename(filePath) !== "wrangler.toml") return false;
116
+ if (contents.startsWith(`${CLOUDFLARE_WRANGLER_GENERATED_MARKER}
117
+ `)) return true;
118
+ return /^name = "canonry-traffic-[^"]+"$/m.test(contents) && /^main = "worker\.js"$/m.test(contents) && /^CANONRY_DELIVERY_MODE = "direct-push"$/m.test(contents) && /^CANONRY_SOURCE_ID = /m.test(contents) && /^CANONRY_INGEST_URL = /m.test(contents) && /^CANONRY_WORKER_VERSION = /m.test(contents) && contents.includes("[secrets]") && contents.includes(CLOUDFLARE_WORKER_BINDINGS.bearerToken) && contents.includes(CLOUDFLARE_WORKER_BINDINGS.hmacSecret);
119
+ }
120
+ function writePrivateTemporaryFile(filePath, contents) {
121
+ const temporaryPath = path.join(
122
+ path.dirname(filePath),
123
+ `.${path.basename(filePath)}.${randomUUID()}.tmp`
124
+ );
125
+ const fd = fs.openSync(temporaryPath, "wx", 384);
126
+ let closed = false;
127
+ try {
128
+ fs.writeFileSync(fd, contents, "utf-8");
129
+ fs.fsyncSync(fd);
130
+ fs.closeSync(fd);
131
+ closed = true;
132
+ } catch (error) {
133
+ if (!closed) {
134
+ try {
135
+ fs.closeSync(fd);
136
+ } catch {
137
+ }
138
+ }
139
+ try {
140
+ fs.unlinkSync(temporaryPath);
141
+ } catch {
142
+ }
143
+ throw error;
144
+ }
145
+ return temporaryPath;
146
+ }
147
+ function writeCloudflareWorkerArtifacts(artifacts, contents) {
148
+ const requested = [
149
+ { filePath: artifacts.workerScriptPath, contents: contents.workerScript },
150
+ { filePath: artifacts.wranglerTomlPath, contents: contents.wranglerToml }
151
+ ];
152
+ const changes = requested.flatMap((artifact) => {
153
+ const previous = readRegularArtifact(artifact.filePath);
154
+ if (previous === artifact.contents) return [];
155
+ if (previous !== null && !isRecognizablyCanonryGenerated(artifact.filePath, previous)) {
156
+ throw new Error(`refusing to overwrite an operator-owned artifact: ${artifact.filePath}`);
157
+ }
158
+ return [{ ...artifact, previous }];
159
+ });
160
+ const pending = [];
161
+ const applied = [];
162
+ try {
163
+ for (const change of changes) {
164
+ pending.push({
165
+ ...change,
166
+ temporaryPath: writePrivateTemporaryFile(change.filePath, change.contents)
167
+ });
168
+ }
169
+ for (const change of pending) {
170
+ if (readRegularArtifact(change.filePath) !== change.previous) {
171
+ throw new Error(`artifact changed during update: ${change.filePath}`);
172
+ }
173
+ if (change.previous === null) {
174
+ fs.linkSync(change.temporaryPath, change.filePath);
175
+ fs.unlinkSync(change.temporaryPath);
176
+ } else {
177
+ fs.renameSync(change.temporaryPath, change.filePath);
178
+ }
179
+ applied.push(change);
180
+ }
181
+ } catch (error) {
182
+ for (const change of applied.reverse()) {
183
+ try {
184
+ if (readRegularArtifact(change.filePath) !== change.contents) continue;
185
+ if (change.previous === null) {
186
+ fs.unlinkSync(change.filePath);
187
+ } else {
188
+ const restorePath = writePrivateTemporaryFile(change.filePath, change.previous);
189
+ fs.renameSync(restorePath, change.filePath);
190
+ }
191
+ } catch {
192
+ }
193
+ }
194
+ throw error;
195
+ } finally {
196
+ for (const change of pending) {
197
+ try {
198
+ if (fs.existsSync(change.temporaryPath)) fs.unlinkSync(change.temporaryPath);
199
+ } catch {
200
+ }
201
+ }
202
+ }
203
+ }
204
+ function assertCloudflareArtifactsDoNotContainSecrets(contents, secrets) {
205
+ const artifactText = [contents.workerScript, contents.wranglerToml, contents.instructions ?? ""];
206
+ const secretValues = "apiToken" in secrets ? [secrets.apiToken] : [secrets.bearerToken, secrets.hmacSecret];
207
+ for (const secret of secretValues) {
208
+ if (secret && artifactText.some((value) => value.includes(secret))) {
209
+ throw new Error("Cloudflare setup response unexpectedly contained a cleartext secret");
210
+ }
211
+ }
212
+ }
213
+ function redactCloudflareSecrets(message, secrets) {
214
+ let redacted = message;
215
+ const secretValues = "apiToken" in secrets ? [secrets.apiToken] : [secrets.bearerToken, secrets.hmacSecret];
216
+ for (const secret of secretValues) {
217
+ if (secret) redacted = redacted.replaceAll(secret, "[REDACTED]");
218
+ }
219
+ return redacted;
220
+ }
221
+ async function runWrangler(command, args, opts) {
222
+ await new Promise((resolve, reject) => {
223
+ const child = spawn(command, [...args], {
224
+ cwd: opts.cwd,
225
+ shell: false,
226
+ stdio: "inherit"
227
+ });
228
+ child.once("error", reject);
229
+ child.once("exit", (code, signal) => {
230
+ if (code === 0) {
231
+ resolve();
232
+ return;
233
+ }
234
+ reject(new Error(
235
+ signal ? `Wrangler exited after signal ${signal}` : `Wrangler exited with code ${code ?? "unknown"}`
236
+ ));
237
+ });
238
+ });
239
+ }
240
+ async function runWranglerCapture(command, args, opts) {
241
+ return new Promise((resolve, reject) => {
242
+ const child = spawn(command, [...args], {
243
+ cwd: opts.cwd,
244
+ shell: false,
245
+ stdio: ["ignore", "pipe", "pipe"]
246
+ });
247
+ let output = "";
248
+ child.stdout.setEncoding("utf-8");
249
+ child.stderr.setEncoding("utf-8");
250
+ child.stdout.on("data", (chunk) => {
251
+ output += String(chunk);
252
+ });
253
+ child.stderr.on("data", (chunk) => {
254
+ output += String(chunk);
255
+ });
256
+ child.once("error", reject);
257
+ child.once("exit", (code, signal) => {
258
+ if (code === 0) {
259
+ resolve(output);
260
+ return;
261
+ }
262
+ const diagnostic = wranglerDiagnostic(output);
263
+ const suffix = diagnostic ? `
264
+ ${diagnostic}` : "";
265
+ reject(new Error(
266
+ signal ? `Wrangler exited after signal ${signal}${suffix}` : `Wrangler exited with code ${code ?? "unknown"}${suffix}`
267
+ ));
268
+ });
269
+ });
270
+ }
271
+ async function preflightCloudflareWrangler(opts = {}) {
272
+ const runner = opts.run ?? runWranglerCapture;
273
+ const deliveryMode = opts.deliveryMode ?? "direct-push";
274
+ const help = await runner(
275
+ "wrangler",
276
+ ["deploy", "--help"],
277
+ { cwd: path.resolve(opts.cwd ?? process.cwd()) }
278
+ );
279
+ const requiredFlags = deliveryMode === "direct-push" ? ["--dry-run", "--secrets-file", "--strict"] : ["--dry-run", "--strict"];
280
+ const missing = requiredFlags.filter((flag) => !help.includes(flag));
281
+ if (missing.length > 0) {
282
+ throw new Error(`Wrangler deploy does not support required flags: ${missing.join(", ")}`);
283
+ }
284
+ const tempDirectory = fs.mkdtempSync(path.join(
285
+ opts.tempRoot ?? os.tmpdir(),
286
+ "canonry-cloudflare-wrangler-preflight-"
287
+ ));
288
+ const workerScriptPath = path.join(tempDirectory, "worker.js");
289
+ const wranglerTomlPath = path.join(tempDirectory, "wrangler.toml");
290
+ const secretsPath = path.join(tempDirectory, "secrets.json");
291
+ try {
292
+ fs.chmodSync(tempDirectory, 448);
293
+ fs.writeFileSync(workerScriptPath, generateWorkerScript({
294
+ deliveryMode,
295
+ workerVersion: "preflight",
296
+ botList: DEFAULT_BOT_LIST
297
+ }), { encoding: "utf-8", flag: "wx", mode: 384 });
298
+ fs.writeFileSync(wranglerTomlPath, generateWranglerToml(
299
+ deliveryMode === "queue-pull" ? {
300
+ deliveryMode,
301
+ sourceId: "preflight",
302
+ hostname: "example.invalid",
303
+ queueName: "canonry-preflight",
304
+ workerVersion: "preflight"
305
+ } : {
306
+ deliveryMode,
307
+ sourceId: "preflight",
308
+ hostname: "example.invalid",
309
+ ingestUrl: "https://canonry.example.invalid/api/v1/projects/preflight/traffic/cloudflare/ingest",
310
+ workerVersion: "preflight"
311
+ }
312
+ ), { encoding: "utf-8", flag: "wx", mode: 384 });
313
+ if (deliveryMode === "direct-push") {
314
+ fs.writeFileSync(secretsPath, JSON.stringify({
315
+ [CLOUDFLARE_WORKER_BINDINGS.bearerToken]: "preflight-bearer",
316
+ [CLOUDFLARE_WORKER_BINDINGS.hmacSecret]: "preflight-hmac"
317
+ }), { encoding: "utf-8", flag: "wx", mode: 384 });
318
+ }
319
+ const validationOutput = await runner(
320
+ "wrangler",
321
+ [
322
+ "deploy",
323
+ "--config",
324
+ wranglerTomlPath,
325
+ ...deliveryMode === "direct-push" ? ["--secrets-file", secretsPath] : [],
326
+ "--strict",
327
+ "--dry-run",
328
+ "--outdir",
329
+ path.join(tempDirectory, "dist")
330
+ ],
331
+ { cwd: tempDirectory }
332
+ );
333
+ const hasUnknownFields = /Unexpected fields found/i.test(validationOutput);
334
+ const hasExperimentalSecrets = /\bexperimental\b/i.test(validationOutput) && /\bsecrets?\b/i.test(validationOutput);
335
+ if (hasUnknownFields || hasExperimentalSecrets) {
336
+ throw new Error(
337
+ `Wrangler reported an incompatible generated configuration:
338
+ ${wranglerDiagnostic(validationOutput)}`
339
+ );
340
+ }
341
+ } finally {
342
+ fs.rmSync(tempDirectory, { recursive: true, force: true });
343
+ }
344
+ }
345
+ async function deployCloudflareWorker(opts) {
346
+ const deliveryMode = opts.deliveryMode ?? "direct-push";
347
+ if (deliveryMode === "queue-pull") {
348
+ const runner = opts.run ?? runWrangler;
349
+ await runner(
350
+ "wrangler",
351
+ ["deploy", "--config", path.resolve(opts.wranglerTomlPath), "--strict"],
352
+ { cwd: path.dirname(path.resolve(opts.wranglerTomlPath)) }
353
+ );
354
+ return;
355
+ }
356
+ if (!opts.secrets) throw new Error("Direct-push Worker deploy requires bearer and HMAC secrets");
357
+ const secrets = opts.secrets;
358
+ const tempDirectory = fs.mkdtempSync(path.join(opts.tempRoot ?? os.tmpdir(), "canonry-cloudflare-secrets-"));
359
+ const secretsPath = path.join(tempDirectory, "secrets.json");
360
+ try {
361
+ fs.chmodSync(tempDirectory, 448);
362
+ fs.writeFileSync(
363
+ secretsPath,
364
+ JSON.stringify({
365
+ [CLOUDFLARE_WORKER_BINDINGS.bearerToken]: secrets.bearerToken,
366
+ [CLOUDFLARE_WORKER_BINDINGS.hmacSecret]: secrets.hmacSecret
367
+ }),
368
+ { encoding: "utf-8", flag: "wx", mode: 384 }
369
+ );
370
+ fs.chmodSync(secretsPath, 384);
371
+ const runner = opts.run ?? runWrangler;
372
+ await runner(
373
+ "wrangler",
374
+ [
375
+ "deploy",
376
+ "--config",
377
+ path.resolve(opts.wranglerTomlPath),
378
+ "--secrets-file",
379
+ secretsPath,
380
+ "--strict"
381
+ ],
382
+ { cwd: path.dirname(path.resolve(opts.wranglerTomlPath)) }
383
+ );
384
+ } finally {
385
+ try {
386
+ if (fs.existsSync(secretsPath)) fs.unlinkSync(secretsPath);
387
+ } finally {
388
+ fs.rmSync(tempDirectory, { recursive: true, force: true });
389
+ }
390
+ }
391
+ }
392
+
393
+ // src/commands/traffic.ts
394
+ var DEFAULT_CLOUDFLARE_QUEUE_RETENTION_SECONDS = 345600;
395
+ var CLOUDFLARE_QUEUE_RETENTION_MIN_SECONDS = 60;
396
+ var CLOUDFLARE_QUEUE_RETENTION_MAX_SECONDS = 1209600;
397
+ function getClient() {
398
+ return createApiClient();
399
+ }
400
+ function configString(value, fallback = "(unset)") {
401
+ return typeof value === "string" ? value : fallback;
402
+ }
403
+ function errorMessage(error) {
404
+ return describeError(error);
405
+ }
406
+ function requireCloudflareQueueOption(project, value, option) {
407
+ if (value?.trim()) return value.trim();
408
+ const code = option === "--account-id" ? "TRAFFIC_CLOUDFLARE_QUEUE_ACCOUNT_REQUIRED" : option === "--queue-id" ? "TRAFFIC_CLOUDFLARE_QUEUE_ID_REQUIRED" : option === "--queue-name" ? "TRAFFIC_CLOUDFLARE_QUEUE_NAME_REQUIRED" : "TRAFFIC_CLOUDFLARE_QUEUE_TOKEN_FILE_REQUIRED";
409
+ throw new CliError({
410
+ code,
411
+ message: `${option} is required with --delivery-mode queue-pull`,
412
+ displayMessage: `Error: ${option} is required with --delivery-mode queue-pull`,
413
+ details: { project }
414
+ });
415
+ }
416
+ function readCloudflareQueueApiToken(project, tokenFile) {
417
+ try {
418
+ const stat = fs2.lstatSync(tokenFile);
419
+ if (!stat.isFile() || stat.isSymbolicLink()) {
420
+ throw new Error("not a regular file");
421
+ }
422
+ const apiToken = fs2.readFileSync(tokenFile, "utf-8").trim();
423
+ if (!apiToken) throw new Error("file is empty");
424
+ return apiToken;
425
+ } catch (error) {
426
+ const message = errorMessage(error);
427
+ throw new CliError({
428
+ code: "TRAFFIC_CLOUDFLARE_QUEUE_TOKEN_FILE_READ_ERROR",
429
+ message: `Failed to read --api-token-file: ${message}`,
430
+ displayMessage: `Error: failed to read --api-token-file "${tokenFile}": ${message}`,
431
+ details: { project, tokenFile }
432
+ });
433
+ }
434
+ }
435
+ async function trafficConnectCloudflare(project, opts, deps = {}) {
436
+ const deliveryMode = opts.deliveryMode ?? "direct-push";
437
+ let queuePull;
438
+ if (deliveryMode === "queue-pull") {
439
+ const accountId = requireCloudflareQueueOption(project, opts.accountId, "--account-id");
440
+ const queueId = requireCloudflareQueueOption(project, opts.queueId, "--queue-id");
441
+ const queueName = requireCloudflareQueueOption(project, opts.queueName, "--queue-name");
442
+ const tokenFile = requireCloudflareQueueOption(project, opts.apiTokenFile, "--api-token-file");
443
+ const retentionSeconds = opts.retentionSeconds ?? DEFAULT_CLOUDFLARE_QUEUE_RETENTION_SECONDS;
444
+ if (!Number.isInteger(retentionSeconds) || retentionSeconds < CLOUDFLARE_QUEUE_RETENTION_MIN_SECONDS || retentionSeconds > CLOUDFLARE_QUEUE_RETENTION_MAX_SECONDS) {
445
+ throw new CliError({
446
+ code: "TRAFFIC_CLOUDFLARE_QUEUE_RETENTION_INVALID",
447
+ message: "--retention-seconds must be an integer between 60 and 1209600",
448
+ displayMessage: "Error: --retention-seconds must be an integer between 60 and 1209600",
449
+ details: { project }
450
+ });
451
+ }
452
+ queuePull = {
453
+ accountId,
454
+ queueId,
455
+ queueName,
456
+ apiToken: readCloudflareQueueApiToken(project, tokenFile),
457
+ retentionSeconds
458
+ };
459
+ }
460
+ if (opts.deploy && !opts.zoneId) {
461
+ throw new CliError({
462
+ code: "TRAFFIC_CLOUDFLARE_DEPLOY_ZONE_REQUIRED",
463
+ message: "--zone-id is required with --deploy",
464
+ displayMessage: "Error: --zone-id <id> is required with --deploy",
465
+ details: { project }
466
+ });
467
+ }
468
+ if (opts.deploy && !opts.confirmRoute) {
469
+ throw new CliError({
470
+ code: "TRAFFIC_CLOUDFLARE_ROUTE_CONFIRMATION_REQUIRED",
471
+ message: "--confirm-route is required with --deploy",
472
+ displayMessage: "Error: inspect existing Worker routes first. Pass --confirm-route to acknowledge the required manual route attachment after Worker deployment.",
473
+ details: { project, zoneId: opts.zoneId }
474
+ });
475
+ }
476
+ if (opts.deploy && !opts.confirmFailOpen) {
477
+ throw new CliError({
478
+ code: "TRAFFIC_CLOUDFLARE_FAIL_OPEN_CONFIRMATION_REQUIRED",
479
+ message: "--confirm-fail-open is required with --deploy",
480
+ displayMessage: "Error: pass --confirm-fail-open to acknowledge the required Fail open setting during manual route attachment after Worker deployment.",
481
+ details: { project, zoneId: opts.zoneId }
482
+ });
483
+ }
484
+ if (opts.deploy) {
485
+ try {
486
+ await (deps.preflightWrangler ?? preflightCloudflareWrangler)({ deliveryMode });
487
+ } catch (error) {
488
+ const message = errorMessage(error);
489
+ throw new CliError({
490
+ code: "TRAFFIC_CLOUDFLARE_WRANGLER_UNSUPPORTED",
491
+ message,
492
+ displayMessage: `Error: Wrangler preflight failed before Canonry changed state.
493
+ ${message}`,
494
+ details: { project }
495
+ });
496
+ }
497
+ }
498
+ const outputDirectory = resolveCloudflareWorkerOutputDirectory(project, opts.outputDirectory);
499
+ let artifacts;
500
+ try {
501
+ artifacts = prepareCloudflareWorkerOutputDirectory(outputDirectory);
502
+ } catch (error) {
503
+ const message = errorMessage(error);
504
+ throw new CliError({
505
+ code: "TRAFFIC_CLOUDFLARE_OUTPUT_INVALID",
506
+ message,
507
+ displayMessage: `Error: cannot use Cloudflare Worker output directory: ${message}`,
508
+ details: { project, outputDirectory }
509
+ });
510
+ }
511
+ const client = deps.client ?? getClient();
512
+ const result = await client.trafficConnectCloudflare(
513
+ project,
514
+ deliveryMode === "queue-pull" ? {
515
+ deliveryMode,
516
+ displayName: opts.displayName,
517
+ zoneId: opts.zoneId,
518
+ ...queuePull
519
+ } : {
520
+ deliveryMode,
521
+ displayName: opts.displayName,
522
+ zoneId: opts.zoneId,
523
+ accountId: opts.accountId
524
+ }
525
+ );
526
+ const localConfig = (deps.loadLocalConfig ?? loadConfigRaw)();
527
+ const localCredential = localConfig ? getCloudflareTrafficConnectionBySourceId(localConfig, result.sourceId) : void 0;
528
+ const deploymentCredential = localCredential?.deliveryMode === result.deliveryMode ? localCredential : void 0;
529
+ const artifactSecrets = deploymentCredential ?? (queuePull ? { apiToken: queuePull.apiToken } : void 0);
530
+ if (artifactSecrets) {
531
+ try {
532
+ assertCloudflareArtifactsDoNotContainSecrets(result, artifactSecrets);
533
+ } catch {
534
+ throw new CliError({
535
+ code: "TRAFFIC_CLOUDFLARE_SECRET_EXPOSURE",
536
+ message: "Cloudflare setup response unexpectedly contained a cleartext secret",
537
+ displayMessage: "Error: refused to write Cloudflare artifacts because the response contained a cleartext secret",
538
+ details: { project, sourceId: result.sourceId }
539
+ });
540
+ }
541
+ }
542
+ try {
543
+ writeCloudflareWorkerArtifacts(artifacts, result);
544
+ } catch (error) {
545
+ const message = errorMessage(error);
546
+ throw new CliError({
547
+ code: "TRAFFIC_CLOUDFLARE_ARTIFACT_WRITE_FAILED",
548
+ message,
549
+ displayMessage: `Error: Cloudflare source connected, but artifact writing failed: ${message}`,
550
+ details: { project, sourceId: result.sourceId, outputDirectory }
551
+ });
552
+ }
553
+ if (opts.deploy && result.deliveryMode === "direct-push" && !deploymentCredential) {
554
+ throw new CliError({
555
+ code: "TRAFFIC_CLOUDFLARE_DEPLOY_CONFIG_UNSHARED",
556
+ message: "Cloudflare auto-deploy requires the CLI and Canonry server to share the same local config",
557
+ displayMessage: "Error: source connected and artifacts written, but auto-deploy is unavailable because this CLI cannot read the server-stored Worker credentials. Ask the Canonry server operator to deploy the Worker and install its secrets.",
558
+ details: {
559
+ project,
560
+ sourceId: result.sourceId,
561
+ outputDirectory
562
+ }
563
+ });
564
+ }
565
+ if (opts.deploy && result.deliveryMode === "direct-push" && deploymentCredential?.deliveryMode === "direct-push") {
566
+ try {
567
+ await (deps.deployWorker ?? deployCloudflareWorker)({
568
+ wranglerTomlPath: artifacts.wranglerTomlPath,
569
+ secrets: deploymentCredential
570
+ });
571
+ } catch (error) {
572
+ const message = redactCloudflareSecrets(errorMessage(error), deploymentCredential);
573
+ throw new CliError({
574
+ code: "TRAFFIC_CLOUDFLARE_DEPLOY_FAILED",
575
+ message,
576
+ displayMessage: `Error: Cloudflare source connected and artifacts written, but Wrangler deploy failed: ${message}`,
577
+ details: { project, sourceId: result.sourceId, outputDirectory }
578
+ });
579
+ }
580
+ }
581
+ if (opts.deploy && result.deliveryMode === "queue-pull") {
582
+ try {
583
+ await (deps.deployWorker ?? deployCloudflareWorker)({
584
+ wranglerTomlPath: artifacts.wranglerTomlPath,
585
+ deliveryMode: "queue-pull"
586
+ });
587
+ } catch (error) {
588
+ const message = artifactSecrets ? redactCloudflareSecrets(errorMessage(error), artifactSecrets) : errorMessage(error);
589
+ throw new CliError({
590
+ code: "TRAFFIC_CLOUDFLARE_DEPLOY_FAILED",
591
+ message,
592
+ displayMessage: `Error: Cloudflare source connected and artifacts written, but Wrangler deploy failed: ${message}`,
593
+ details: { project, sourceId: result.sourceId, outputDirectory }
594
+ });
595
+ }
596
+ }
597
+ const summary = {
598
+ sourceId: result.sourceId,
599
+ deliveryMode: result.deliveryMode,
600
+ activationRequired: result.activationRequired === true,
601
+ workerVersion: result.workerVersion,
602
+ outputDirectory: artifacts.outputDirectory,
603
+ files: {
604
+ workerScript: artifacts.workerScriptPath,
605
+ wranglerConfig: artifacts.wranglerTomlPath
606
+ },
607
+ autoDeployAvailable: result.deliveryMode === "queue-pull" || Boolean(deploymentCredential),
608
+ ...result.deliveryMode === "queue-pull" ? {
609
+ queuePullConsumer: {
610
+ required: true,
611
+ queueName: result.queueName,
612
+ configuredBy: "wrangler-or-cloudflare-dashboard"
613
+ }
614
+ } : {},
615
+ deployment: opts.deploy ? "worker-deployed-route-unattached" : "not-requested",
616
+ routeAttachment: "required-manual",
617
+ requestLimitFailureMode: {
618
+ required: "fail-open",
619
+ status: "required-during-manual-route-attachment",
620
+ configuredBy: "cloudflare-dashboard",
621
+ configuredByWrangler: false
622
+ },
623
+ postDeployInstructions: result.instructions
624
+ };
625
+ if (isMachineFormat(opts.format)) {
626
+ console.log(JSON.stringify(summary, null, 2));
627
+ return;
628
+ }
629
+ console.log(`Cloudflare ${result.deliveryMode} traffic source connected for project "${project}".`);
630
+ console.log(` Source ID: ${result.sourceId}`);
631
+ console.log(` Worker version: ${result.workerVersion}`);
632
+ console.log(` Worker script: ${artifacts.workerScriptPath}`);
633
+ console.log(` Wrangler config: ${artifacts.wranglerTomlPath}`);
634
+ console.log(` Deployment: ${opts.deploy ? "Worker deployed; route not attached" : "not requested"}`);
635
+ console.log("");
636
+ console.log("The required manual route is a catch-all. Inspect existing Worker routes before deployment.");
637
+ console.log("Wrangler deployment does not attach the route. Attach it manually after the Worker deploys.");
638
+ console.log("Required: set the route Request limit failure mode to Fail open before route activation.");
639
+ console.log("Wrangler cannot configure this toggle. Workers Free includes 100,000 requests per day for the account.");
640
+ console.log("Use one authoritative server-traffic source for this site. Overlapping adapters double-count project totals.");
641
+ if (result.deliveryMode === "queue-pull") {
642
+ console.log(`Required: enable HTTP pull with \`wrangler queues consumer http add ${result.queueName}\` before the first sync.`);
643
+ }
644
+ if (result.activationRequired) {
645
+ console.log(`Activation required: run \`canonry traffic activate ${project} --source ${result.sourceId}\`. This command does not activate delivery.`);
646
+ }
647
+ if (opts.deploy) {
648
+ console.log("");
649
+ console.log("Required Cloudflare Dashboard steps:");
650
+ console.log(result.instructions);
651
+ if (result.deliveryMode === "direct-push") {
652
+ console.log("Keep the Canonry public HTTPS URL reachable so the Worker can push events.");
653
+ }
654
+ } else if (deploymentCredential) {
655
+ console.log("Next: install and authenticate Wrangler. Inspect the route, then rerun with --deploy --confirm-route --confirm-fail-open and --zone-id <id>.");
656
+ } else if (result.deliveryMode === "queue-pull") {
657
+ console.log("Next: install and authenticate Wrangler externally, then rerun with --deploy --confirm-route --confirm-fail-open and --zone-id <id>.");
658
+ } else {
659
+ console.log("Auto-deploy is unavailable because this CLI and the Canonry server do not share local config. Ask the server operator to deploy and install the Worker secrets.");
660
+ }
661
+ }
662
+ async function trafficActivate(project, opts, deps = {}) {
663
+ const client = deps.client ?? getClient();
664
+ const source = await client.trafficActivate(project, opts.sourceId);
665
+ if (isMachineFormat(opts.format)) {
666
+ console.log(JSON.stringify(source, null, 2));
667
+ return;
668
+ }
669
+ const sourceMode = typeof source.config.deliveryMode === "string" ? source.config.deliveryMode : source.sourceType;
670
+ const trafficSync2 = sourceMode === "direct-push" ? "not required for direct-push delivery" : "enabled for this pull source";
671
+ console.log(`Traffic source activated for project "${project}".`);
672
+ console.log(` Source ID: ${source.id}`);
673
+ console.log(` Source mode: ${sourceMode}`);
674
+ console.log(` Status: ${source.status}`);
675
+ console.log(` Traffic sync: ${trafficSync2}`);
676
+ }
677
+ async function trafficConnectWordpress(project, opts) {
678
+ if (!opts.url) {
679
+ throw new CliError({
680
+ code: "TRAFFIC_WP_URL_REQUIRED",
681
+ message: "--url is required",
682
+ displayMessage: "Error: --url is required",
683
+ details: { project }
684
+ });
685
+ }
686
+ if (!opts.username) {
687
+ throw new CliError({
688
+ code: "TRAFFIC_WP_USERNAME_REQUIRED",
689
+ message: "--username is required",
690
+ displayMessage: "Error: --username is required",
691
+ details: { project }
692
+ });
693
+ }
694
+ if (opts.appPassword && opts.appPasswordFile) {
695
+ throw new CliError({
696
+ code: "TRAFFIC_WP_APP_PASSWORD_CONFLICT",
697
+ message: "--app-password and --app-password-file are mutually exclusive",
698
+ displayMessage: "Error: pass either --app-password <pw> or --app-password-file <path>, not both",
699
+ details: { project }
700
+ });
701
+ }
702
+ let applicationPassword = opts.appPassword?.trim() ?? "";
703
+ if (!applicationPassword && opts.appPasswordFile) {
704
+ const fs3 = await import("fs");
705
+ try {
706
+ applicationPassword = fs3.readFileSync(opts.appPasswordFile, "utf-8").trim();
707
+ } catch (e) {
708
+ const msg = describeError(e);
709
+ throw new CliError({
710
+ code: "TRAFFIC_WP_APP_PASSWORD_FILE_READ_ERROR",
711
+ message: `Failed to read --app-password-file: ${msg}`,
712
+ displayMessage: `Error: failed to read --app-password-file "${opts.appPasswordFile}": ${msg}`,
713
+ details: { project, appPasswordFile: opts.appPasswordFile }
714
+ });
715
+ }
716
+ }
717
+ if (!applicationPassword) {
718
+ throw new CliError({
719
+ code: "TRAFFIC_WP_APP_PASSWORD_REQUIRED",
720
+ message: "--app-password or --app-password-file is required",
721
+ displayMessage: "Error: pass --app-password <pw> or --app-password-file <path>",
722
+ details: { project }
723
+ });
724
+ }
725
+ const client = getClient();
726
+ const result = await client.trafficConnectWordpress(project, {
727
+ baseUrl: opts.url,
728
+ username: opts.username,
729
+ applicationPassword,
730
+ displayName: opts.displayName
731
+ });
732
+ if (isMachineFormat(opts.format)) {
733
+ console.log(JSON.stringify(result, null, 2));
734
+ return;
735
+ }
736
+ console.log(`WordPress traffic source connected for project "${project}".`);
737
+ console.log(` Source ID: ${result.id}`);
738
+ console.log(` Display name: ${result.displayName}`);
739
+ console.log(` Status: ${result.status}`);
740
+ console.log(` Site URL: ${configString(result.config.baseUrl)}`);
741
+ console.log(` Username: ${configString(result.config.username)}`);
742
+ console.log("");
743
+ console.log(`Next: canonry traffic sync ${project} --source ${result.id}`);
744
+ }
745
+ async function trafficConnectCloudRun(project, opts) {
746
+ if (!opts.gcpProject) {
747
+ throw new CliError({
748
+ code: "TRAFFIC_GCP_PROJECT_REQUIRED",
749
+ message: "--gcp-project is required",
750
+ displayMessage: "Error: --gcp-project is required",
751
+ details: { project }
752
+ });
753
+ }
754
+ if (!opts.serviceAccountKey) {
755
+ throw new CliError({
756
+ code: "TRAFFIC_KEY_FILE_REQUIRED",
757
+ message: "--service-account-key is required for v1 (OAuth-mode Cloud Run is not yet supported).",
758
+ displayMessage: "Error: --service-account-key <path-to-json> is required",
759
+ details: { project }
760
+ });
761
+ }
762
+ const fs3 = await import("fs");
763
+ let keyJson;
764
+ try {
765
+ keyJson = fs3.readFileSync(opts.serviceAccountKey, "utf-8");
766
+ JSON.parse(keyJson);
767
+ } catch (e) {
768
+ const msg = describeError(e);
769
+ throw new CliError({
770
+ code: "TRAFFIC_KEY_FILE_READ_ERROR",
771
+ message: `Failed to read service-account key: ${msg}`,
772
+ displayMessage: `Error: failed to read --service-account-key "${opts.serviceAccountKey}": ${msg}`,
773
+ details: { project, keyFile: opts.serviceAccountKey }
774
+ });
775
+ }
776
+ const client = getClient();
777
+ const result = await client.trafficConnectCloudRun(project, {
778
+ gcpProjectId: opts.gcpProject,
779
+ serviceName: opts.service,
780
+ location: opts.location,
781
+ displayName: opts.displayName,
782
+ keyJson
783
+ });
784
+ if (isMachineFormat(opts.format)) {
785
+ console.log(JSON.stringify(result, null, 2));
786
+ return;
787
+ }
788
+ console.log(`Cloud Run traffic source connected for project "${project}".`);
789
+ console.log(` Source ID: ${result.id}`);
790
+ console.log(` Display name: ${result.displayName}`);
791
+ console.log(` Status: ${result.status}`);
792
+ console.log(` GCP project: ${configString(result.config.gcpProjectId)}`);
793
+ if (result.config.serviceName) console.log(` Service: ${configString(result.config.serviceName)}`);
794
+ if (result.config.location) console.log(` Location: ${configString(result.config.location)}`);
795
+ console.log("");
796
+ console.log(`Next: canonry traffic sync ${project} --source ${result.id}`);
797
+ }
798
+ async function trafficConnectVercel(project, opts) {
799
+ if (!opts.projectId) {
800
+ throw new CliError({
801
+ code: "TRAFFIC_VERCEL_PROJECT_ID_REQUIRED",
802
+ message: "--project-id is required",
803
+ displayMessage: "Error: --project-id is required (the Vercel project id, e.g. prj_...)",
804
+ details: { project }
805
+ });
806
+ }
807
+ if (!opts.teamId) {
808
+ throw new CliError({
809
+ code: "TRAFFIC_VERCEL_TEAM_ID_REQUIRED",
810
+ message: "--team-id is required",
811
+ displayMessage: "Error: --team-id is required (the Vercel team or personal account that owns the project)",
812
+ details: { project }
813
+ });
814
+ }
815
+ if (opts.token && opts.tokenFile) {
816
+ throw new CliError({
817
+ code: "TRAFFIC_VERCEL_TOKEN_CONFLICT",
818
+ message: "--token and --token-file are mutually exclusive",
819
+ displayMessage: "Error: pass either --token <token> or --token-file <path>, not both",
820
+ details: { project }
821
+ });
822
+ }
823
+ let token = opts.token?.trim() ?? "";
824
+ if (!token && opts.tokenFile) {
825
+ const fs3 = await import("fs");
826
+ try {
827
+ token = fs3.readFileSync(opts.tokenFile, "utf-8").trim();
828
+ } catch (e) {
829
+ const msg = describeError(e);
830
+ throw new CliError({
831
+ code: "TRAFFIC_VERCEL_TOKEN_FILE_READ_ERROR",
832
+ message: `Failed to read --token-file: ${msg}`,
833
+ displayMessage: `Error: failed to read --token-file "${opts.tokenFile}": ${msg}`,
834
+ details: { project, tokenFile: opts.tokenFile }
835
+ });
836
+ }
837
+ }
838
+ if (!token) {
839
+ throw new CliError({
840
+ code: "TRAFFIC_VERCEL_TOKEN_REQUIRED",
841
+ message: "--token or --token-file is required",
842
+ displayMessage: "Error: pass the Vercel personal access token via --token <token> or --token-file <path>",
843
+ details: { project }
844
+ });
845
+ }
846
+ if (opts.environment && opts.environment !== "production" && opts.environment !== "preview") {
847
+ throw new CliError({
848
+ code: "TRAFFIC_VERCEL_INVALID_ENVIRONMENT",
849
+ message: '--environment must be "production" or "preview"',
850
+ displayMessage: 'Error: --environment must be "production" or "preview"',
851
+ details: { project, environment: opts.environment }
852
+ });
853
+ }
854
+ const client = getClient();
855
+ const result = await client.trafficConnectVercel(project, {
856
+ projectId: opts.projectId,
857
+ teamId: opts.teamId,
858
+ token,
859
+ environment: opts.environment,
860
+ displayName: opts.displayName
861
+ });
862
+ if (isMachineFormat(opts.format)) {
863
+ console.log(JSON.stringify(result, null, 2));
864
+ return;
865
+ }
866
+ console.log(`Vercel traffic source connected for project "${project}".`);
867
+ console.log(` Source ID: ${result.id}`);
868
+ console.log(` Display name: ${result.displayName}`);
869
+ console.log(` Status: ${result.status}`);
870
+ console.log(` Project ID: ${configString(result.config.projectId)}`);
871
+ console.log(` Team ID: ${configString(result.config.teamId)}`);
872
+ console.log(` Environment: ${configString(result.config.environment)}`);
873
+ console.log("");
874
+ console.log(`Next: canonry traffic sync ${project} --source ${result.id}`);
875
+ }
876
+ async function trafficBackfill(project, opts) {
877
+ if (!opts.source) {
878
+ throw new CliError({
879
+ code: "TRAFFIC_SOURCE_REQUIRED",
880
+ message: "--source <id> is required",
881
+ displayMessage: "Error: --source <id> is required (run `canonry traffic sources` to list connected sources)",
882
+ details: { project }
883
+ });
884
+ }
885
+ const client = getClient();
886
+ const submitted = await client.trafficBackfill(project, opts.source, {
887
+ days: opts.days
888
+ });
889
+ if (!opts.wait) {
890
+ if (isMachineFormat(opts.format)) {
891
+ console.log(JSON.stringify(submitted, null, 2));
892
+ return;
893
+ }
894
+ console.log(`Backfill submitted for "${project}" (source ${opts.source}).`);
895
+ console.log(` Run ID: ${submitted.runId}`);
896
+ console.log(` Window: ${submitted.windowStart} \u2192 ${submitted.windowEnd}`);
897
+ console.log(` Days applied: ${submitted.daysApplied} (requested ${submitted.daysRequested})`);
898
+ console.log(` Status: ${submitted.status}`);
899
+ console.log("");
900
+ console.log(`Poll: canonry runs get ${submitted.runId}`);
901
+ return;
902
+ }
903
+ const intervalMs = opts.pollIntervalMs ?? 1500;
904
+ const deadlineMs = Date.now() + 5 * 6e4;
905
+ let final = null;
906
+ while (Date.now() < deadlineMs) {
907
+ const run = await client.getRun(submitted.runId);
908
+ if (run.status !== RunStatuses.running && run.status !== RunStatuses.queued) {
909
+ final = run;
910
+ break;
911
+ }
912
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
913
+ }
914
+ if (!final) {
915
+ throw new CliError({
916
+ code: "TRAFFIC_BACKFILL_TIMEOUT",
917
+ message: `Backfill did not complete within 5 minutes (run ${submitted.runId} still running)`,
918
+ displayMessage: `Error: backfill run ${submitted.runId} did not finish within 5 minutes \u2014 check status with "canonry runs get ${submitted.runId}"`,
919
+ details: { project, runId: submitted.runId }
920
+ });
921
+ }
922
+ if (isMachineFormat(opts.format)) {
923
+ console.log(JSON.stringify({ ...submitted, finalStatus: final.status, finalRun: final }, null, 2));
924
+ return;
925
+ }
926
+ if (final.status === RunStatuses.completed) {
927
+ console.log(`Backfill complete for "${project}" (source ${opts.source}).`);
928
+ console.log(` Run ID: ${final.id}`);
929
+ console.log(` Window: ${submitted.windowStart} \u2192 ${submitted.windowEnd}`);
930
+ console.log(` Days applied: ${submitted.daysApplied}`);
931
+ console.log(` Started: ${final.startedAt ?? "unknown"}`);
932
+ console.log(` Finished: ${final.finishedAt ?? "unknown"}`);
933
+ console.log("");
934
+ console.log(`Inspect rebuilt rollups: canonry traffic events ${project} --source ${opts.source} --since-minutes ${submitted.daysApplied * 24 * 60}`);
935
+ return;
936
+ }
937
+ const errorMessage2 = final.error?.message ?? null;
938
+ throw new CliError({
939
+ code: "TRAFFIC_BACKFILL_FAILED",
940
+ message: errorMessage2 ?? "backfill run did not complete successfully",
941
+ displayMessage: `Error: backfill run ${final.id} ${final.status}${errorMessage2 ? ` \u2014 ${errorMessage2}` : ""}`,
942
+ details: { project, runId: final.id, status: final.status }
943
+ });
944
+ }
945
+ async function trafficSync(project, opts) {
946
+ if (!opts.source) {
947
+ throw new CliError({
948
+ code: "TRAFFIC_SOURCE_REQUIRED",
949
+ message: "--source <id> is required",
950
+ displayMessage: "Error: --source <id> is required (run `canonry traffic connect cloud-run` first if you have not connected a source)",
951
+ details: { project }
952
+ });
953
+ }
954
+ const client = getClient();
955
+ const result = await client.trafficSync(project, opts.source, {
956
+ sinceMinutes: opts.sinceMinutes
957
+ });
958
+ if (isMachineFormat(opts.format)) {
959
+ console.log(JSON.stringify(result, null, 2));
960
+ return;
961
+ }
962
+ console.log(`Traffic sync complete for "${project}" (source ${opts.source}).`);
963
+ console.log(` Run ID: ${result.runId}`);
964
+ console.log(` Window: ${result.windowStart} \u2192 ${result.windowEnd}`);
965
+ console.log(` Pulled events: ${result.pulledEvents}`);
966
+ if (result.selfTrafficExcluded > 0) {
967
+ console.log(` Self-traffic excl: ${result.selfTrafficExcluded} (Canonry's own tooling, dropped before rollup)`);
968
+ }
969
+ console.log(` Crawler hits: ${result.crawlerHits} (${result.crawlerBucketRows} hourly bucket${result.crawlerBucketRows === 1 ? "" : "s"})`);
970
+ console.log(` AI referral hits: ${result.aiReferralHits} (${result.aiReferralBucketRows} hourly bucket${result.aiReferralBucketRows === 1 ? "" : "s"})`);
971
+ console.log(` Unknown hits: ${result.unknownHits}`);
972
+ console.log(` Sample rows: ${result.sampleRows}`);
973
+ console.log(` Synced at: ${result.syncedAt}`);
974
+ }
975
+ async function trafficReset(project, opts) {
976
+ if (!opts.source) {
977
+ throw new CliError({
978
+ code: "TRAFFIC_SOURCE_REQUIRED",
979
+ message: "--source <id> is required",
980
+ displayMessage: "Error: --source <id> is required (run `canonry traffic sources` to list connected sources)",
981
+ details: { project }
982
+ });
983
+ }
984
+ if (!opts.advanceToNow) {
985
+ throw new CliError({
986
+ code: "TRAFFIC_RESET_REQUIRES_FLAG",
987
+ message: "--advance-to-now is required",
988
+ displayMessage: "Error: --advance-to-now is required. This skips history between the source's current lastSyncedAt and now. For WordPress, generic replace-mode backfill is unavailable; use a retention-aware repair that declares any unrecoverable span.",
989
+ details: { project, source: opts.source }
990
+ });
991
+ }
992
+ const client = getClient();
993
+ const updated = await client.trafficReset(project, opts.source);
994
+ if (isMachineFormat(opts.format)) {
995
+ console.log(JSON.stringify(updated, null, 2));
996
+ return;
997
+ }
998
+ console.log(`Traffic source reset for "${project}" (source ${opts.source}).`);
999
+ console.log(` Status: ${updated.status}`);
1000
+ console.log(` Last synced: ${updated.lastSyncedAt ?? "never"} (advanced to NOW)`);
1001
+ console.log(` Last error: ${updated.lastError ?? "none"}`);
1002
+ if (updated.skippedThroughAt) {
1003
+ console.log(" Historical repair: generic WordPress replace-mode backfill is unavailable until a retention-aware repair proves coverage.");
1004
+ }
1005
+ console.log("");
1006
+ console.log("Next scheduled sync will resume from this timestamp.");
1007
+ }
1008
+ function formatSourceLine(source) {
1009
+ const parts = [
1010
+ source.id,
1011
+ source.sourceType,
1012
+ source.status,
1013
+ source.lastSyncedAt ?? "never synced",
1014
+ source.displayName
1015
+ ];
1016
+ return parts.join(" ");
1017
+ }
1018
+ async function trafficSources(project, opts) {
1019
+ const client = createApiClient();
1020
+ const result = await client.trafficListSources(project);
1021
+ if (opts.format === "json") {
1022
+ console.log(JSON.stringify(result, null, 2));
1023
+ return;
1024
+ } else if (opts.format === "jsonl") {
1025
+ emitJsonl(result.sources.map((source) => ({ project, ...source })));
1026
+ return;
1027
+ }
1028
+ if (result.sources.length === 0) {
1029
+ console.log(`No traffic sources connected for project "${project}".`);
1030
+ console.log("Run: canonry traffic connect cloud-run <project> --gcp-project <id> --service-account-key <path>");
1031
+ return;
1032
+ }
1033
+ console.log(`Traffic sources for "${project}":`);
1034
+ console.log(" ID TYPE STATUS LAST_SYNCED DISPLAY_NAME");
1035
+ for (const source of result.sources) {
1036
+ console.log(` ${formatSourceLine(source)}`);
1037
+ }
1038
+ }
1039
+ async function trafficAnalytics(project, opts) {
1040
+ let period;
1041
+ try {
1042
+ period = parseTrafficAnalyticsPeriod(opts.period);
1043
+ } catch (error) {
1044
+ throw usageError(`Error: ${describeError(error)}
1045
+
1046
+ Usage: canonry traffic analytics <project> [--period 7|14|30|90] [--format json]`);
1047
+ }
1048
+ const result = await createApiClient().getTrafficAnalytics(project, period);
1049
+ if (isMachineFormat(opts.format)) {
1050
+ console.log(JSON.stringify(result, null, 2));
1051
+ return;
1052
+ }
1053
+ const activity = result.activity;
1054
+ if (!activity) {
1055
+ console.log(`No traffic sources connected for project "${project}".`);
1056
+ return;
1057
+ }
1058
+ console.log(`Traffic analytics for "${project}": ${activity.windowStart} to ${activity.windowEnd}`);
1059
+ console.log(` First stored observation: ${activity.coverageStart ?? "none"}`);
1060
+ if (!activity.priorWindowComplete) console.log(" Prior recording window is incomplete; percentage changes are unavailable.");
1061
+ for (const [label, counts] of [
1062
+ ["Verified crawler hits", activity.verifiedCrawlerHits],
1063
+ ["Unverified crawler hits", activity.unverifiedCrawlerHits],
1064
+ ["AI user-fetch hits", activity.aiUserFetchHits],
1065
+ ["AI-referral arrivals", activity.referralArrivals],
1066
+ ["Paid AI-referral arrivals", activity.referralArrivalsByClass.paid],
1067
+ ["Organic AI-referral arrivals", activity.referralArrivalsByClass.organic],
1068
+ ["Unclassified AI-referral arrivals", activity.referralArrivalsByClass.unclassified]
1069
+ ]) {
1070
+ console.log(` ${label}: ${counts.current} (prior ${counts.prior}; change ${counts.deltaPct === null ? "unavailable" : formatPercent(counts.deltaPct, "percent")})`);
1071
+ }
1072
+ console.log(` AI-referral redirect hops: ${activity.referralRedirects}`);
1073
+ console.log("Operators: OPERATOR VERIFIED UNVERIFIED USER_FETCH REFERRALS CHANGE");
1074
+ for (const row of activity.byOperator) console.log(` ${row.operator} ${row.verifiedHits} ${row.unverifiedHits} ${row.userFetchHits} ${row.referralArrivals} ${row.deltaPct === null ? "unavailable" : formatPercent(row.deltaPct, "percent")}`);
1075
+ console.log("Crawled paths: PATH VERIFIED UNVERIFIED OPERATORS");
1076
+ for (const row of activity.topCrawledPaths) console.log(` ${row.path} ${row.verifiedHits} ${row.unverifiedHits} ${row.distinctOperators}`);
1077
+ console.log("AI-referral products: PRODUCT ARRIVALS LANDING_PATHS");
1078
+ for (const row of activity.referralProducts) console.log(` ${row.product} ${row.arrivals} ${row.distinctLandingPaths}`);
1079
+ console.log("Daily history: DATE VERIFIED UNVERIFIED USER_FETCH REFERRALS");
1080
+ for (const row of activity.dailyTrend) console.log(` ${row.date} ${row.verifiedCrawlerHits} ${row.unverifiedCrawlerHits} ${row.userFetchHits} ${row.referralArrivals}`);
1081
+ console.log("AI-referral landing paths: PATH ARRIVALS PRODUCTS");
1082
+ for (const row of activity.topReferralLandingPaths) console.log(` ${row.path} ${row.arrivals} ${row.distinctProducts}`);
1083
+ }
1084
+ async function trafficStatus(project, opts) {
1085
+ const client = createApiClient();
1086
+ const result = await client.trafficStatus(project);
1087
+ const details = result.sources;
1088
+ if (opts.format === "json") {
1089
+ console.log(JSON.stringify(result, null, 2));
1090
+ return;
1091
+ } else if (opts.format === "jsonl") {
1092
+ emitJsonl(details.map((detail) => ({ project, ...detail })));
1093
+ return;
1094
+ }
1095
+ if (details.length === 0) {
1096
+ console.log(`No traffic sources connected for project "${project}".`);
1097
+ console.log("Run: canonry traffic connect cloud-run <project> --gcp-project <id> --service-account-key <path>");
1098
+ return;
1099
+ }
1100
+ for (const d of details) {
1101
+ console.log(`Source ${d.id} (${d.sourceType})`);
1102
+ console.log(` Display name: ${d.displayName}`);
1103
+ console.log(` Status: ${d.status}`);
1104
+ console.log(` Last synced: ${d.lastSyncedAt ?? "never"}`);
1105
+ if (d.lastError) console.log(` Last error: ${d.lastError}`);
1106
+ console.log(` 24h content: ${d.totals24h.crawlerContentHits} crawls`);
1107
+ console.log(` 24h infra: ${d.totals24h.crawlerInfraHits} sitemap/robots/asset fetches`);
1108
+ console.log(` 24h other: ${d.totals24h.crawlerSegments.other} fetches`);
1109
+ console.log(` 24h crawler: ${d.totals24h.crawlerHits} hits total`);
1110
+ console.log(` 24h AI referral: ${d.totals24h.aiReferralLandedHits} sessions (+${d.totals24h.aiReferralRedirectedHits} redirect hops excluded)`);
1111
+ console.log(` 24h samples: ${d.totals24h.sampleCount}`);
1112
+ if (d.latestRun) {
1113
+ console.log(` Latest run: ${d.latestRun.runId} (${d.latestRun.status})`);
1114
+ console.log(` Started: ${d.latestRun.startedAt}`);
1115
+ if (d.latestRun.finishedAt) console.log(` Finished: ${d.latestRun.finishedAt}`);
1116
+ if (d.latestRun.error) console.log(` Error: ${d.latestRun.error}`);
1117
+ } else {
1118
+ console.log(` Latest run: (none)`);
1119
+ }
1120
+ console.log("");
1121
+ }
1122
+ }
1123
+ function formatVerificationProvenance(event) {
1124
+ const parts = (event.verificationManifests ?? []).map(
1125
+ ({ manifestId, manifest, hits }) => `${manifest?.version ?? manifestId}\xD7${hits}`
1126
+ );
1127
+ const unattributedHits = event.verificationUnattributedHits ?? event.hits;
1128
+ if (unattributedHits > 0) {
1129
+ parts.push(`legacy/unattributed ${unattributedHits}`);
1130
+ }
1131
+ return `provenance ${parts.length > 0 ? parts.join(" \xB7 ") : "none"}`;
1132
+ }
1133
+ function formatEventLine(event) {
1134
+ switch (event.kind) {
1135
+ case TrafficEventKinds.crawler:
1136
+ return [
1137
+ event.tsHour,
1138
+ "crawler",
1139
+ event.botId,
1140
+ event.verificationStatus,
1141
+ formatVerificationProvenance(event),
1142
+ String(event.status),
1143
+ `${event.pathNormalized} [${event.pathClass}]`,
1144
+ `${event.hits} hits`
1145
+ ].join(" ");
1146
+ case TrafficEventKinds["ai-user-fetch"]:
1147
+ return [
1148
+ event.tsHour,
1149
+ "ai-user-fetch",
1150
+ event.botId,
1151
+ event.verificationStatus,
1152
+ formatVerificationProvenance(event),
1153
+ String(event.status),
1154
+ event.pathNormalized,
1155
+ `${event.hits} hits`
1156
+ ].join(" ");
1157
+ case TrafficEventKinds["ai-referral"]:
1158
+ return [
1159
+ event.tsHour,
1160
+ "ai-referral",
1161
+ event.product,
1162
+ event.evidenceType,
1163
+ event.sourceDomain,
1164
+ event.landingPathNormalized,
1165
+ `${event.hits} hits`,
1166
+ `(paid ${event.paidHits} \xB7 organic ${event.organicHits} \xB7 unclassified ${event.unknownHits})`
1167
+ ].join(" ");
1168
+ }
1169
+ }
1170
+ async function trafficSamples(project, opts) {
1171
+ const { format, sinceMinutes, ...input } = opts;
1172
+ if (sinceMinutes !== void 0) {
1173
+ if (!Number.isSafeInteger(sinceMinutes) || sinceMinutes <= 0 || !Number.isFinite(Date.now() - sinceMinutes * 6e4)) throw usageError("--since-minutes must be a positive integer");
1174
+ if (input.since) throw usageError("--since and --since-minutes cannot be combined");
1175
+ const end = input.until === void 0 ? Date.now() : Date.parse(input.until);
1176
+ if (!Number.isFinite(end) || !Number.isFinite(new Date(end - sinceMinutes * 6e4).getTime())) throw usageError("Invalid traffic sample time window");
1177
+ input.since = new Date(end - sinceMinutes * 6e4).toISOString();
1178
+ }
1179
+ const parsed = trafficSamplesQuerySchema.safeParse(input);
1180
+ if (!parsed.success) throw usageError(formatValidationIssues(parsed.error.issues), { details: { issues: parsed.error.issues.map(({ path: path2, message }) => ({ path: path2, message })) } });
1181
+ const result = await createApiClient().trafficListSamples(project, parsed.data);
1182
+ if (isMachineFormat(format)) {
1183
+ if (format === "jsonl") emitJsonl(result.samples.map((sample) => ({ project, windowStart: result.windowStart, windowEnd: result.windowEnd, ...sample })));
1184
+ else console.log(JSON.stringify(result, null, 2));
1185
+ return;
1186
+ }
1187
+ console.log(`Stored traffic samples for "${project}": ${result.samples.length} of ${result.totalRows} matching sample rows. Sampled tail, not visits; use traffic events for totals.`);
1188
+ console.log("Retention: 30 days. Caps: 100 per sync, 500 per backfill, 100 per source per push hour.");
1189
+ console.log("traffic status shows the last-24h sample count per source, including unknown samples. This selection excludes unknown unless requested.");
1190
+ for (const sample of result.samples) {
1191
+ const classifier = sample.classifier.aiReferral ?? sample.classifier.aiUserFetch ?? sample.classifier.crawler;
1192
+ console.log([sample.ts, sample.kind, sample.status ?? "-", sample.pathNormalized, sample.refererHost ?? "-", classifier?.product ?? "-", sample.userAgent ?? "-"].join(" "));
1193
+ }
1194
+ }
1195
+ async function trafficEvents(project, opts) {
1196
+ if (opts.kind && opts.kind !== "all" && opts.kind !== TrafficEventKinds.crawler && opts.kind !== TrafficEventKinds["ai-user-fetch"] && opts.kind !== TrafficEventKinds["ai-referral"]) {
1197
+ throw new CliError({
1198
+ code: "TRAFFIC_INVALID_KIND",
1199
+ message: `--kind must be one of: all, ${TrafficEventKinds.crawler}, ${TrafficEventKinds["ai-user-fetch"]}, ${TrafficEventKinds["ai-referral"]}`,
1200
+ displayMessage: `Error: --kind must be "all", "${TrafficEventKinds.crawler}", "${TrafficEventKinds["ai-user-fetch"]}", or "${TrafficEventKinds["ai-referral"]}"`,
1201
+ details: { project, kind: opts.kind }
1202
+ });
1203
+ }
1204
+ if (opts.granularity && opts.granularity !== TrafficSeriesGranularities.hour && opts.granularity !== TrafficSeriesGranularities.day) {
1205
+ throw new CliError({
1206
+ code: "TRAFFIC_INVALID_GRANULARITY",
1207
+ message: `--granularity must be one of: ${TrafficSeriesGranularities.hour}, ${TrafficSeriesGranularities.day}`,
1208
+ displayMessage: `Error: --granularity must be "${TrafficSeriesGranularities.hour}" or "${TrafficSeriesGranularities.day}"`,
1209
+ details: { project, granularity: opts.granularity }
1210
+ });
1211
+ }
1212
+ const params = {};
1213
+ if (opts.kind && opts.kind !== "all") params.kind = opts.kind;
1214
+ if (opts.source) params.sourceId = opts.source;
1215
+ if (opts.limit !== void 0) params.limit = opts.limit;
1216
+ if (opts.granularity) params.granularity = opts.granularity;
1217
+ if (opts.sinceMinutes !== void 0) {
1218
+ const since = new Date(Date.now() - opts.sinceMinutes * 6e4).toISOString();
1219
+ params.since = since;
1220
+ } else if (opts.since) {
1221
+ params.since = opts.since;
1222
+ }
1223
+ if (opts.until) params.until = opts.until;
1224
+ const client = createApiClient();
1225
+ const result = await client.trafficListEvents(project, params);
1226
+ if (opts.format === "json") {
1227
+ console.log(JSON.stringify(result, null, 2));
1228
+ return;
1229
+ } else if (opts.format === "jsonl") {
1230
+ emitJsonl(result.events.map((event) => ({
1231
+ project,
1232
+ windowStart: result.windowStart,
1233
+ windowEnd: result.windowEnd,
1234
+ ...event
1235
+ })));
1236
+ return;
1237
+ }
1238
+ console.log(`Traffic events for "${project}" ${result.windowStart} \u2192 ${result.windowEnd}`);
1239
+ console.log(` Content crawls (window): ${result.totals.crawlerContentHits}`);
1240
+ console.log(` Infra fetches (window): ${result.totals.crawlerInfraHits} (sitemap ${result.totals.crawlerSegments.sitemap} \xB7 robots ${result.totals.crawlerSegments.robots} \xB7 asset ${result.totals.crawlerSegments.asset})`);
1241
+ console.log(` Other fetches (window): ${result.totals.crawlerSegments.other}`);
1242
+ console.log(` Crawler hits total (window): ${result.totals.crawlerHits}`);
1243
+ console.log(` AI user-fetch hits (window): ${result.totals.aiUserFetchHits}`);
1244
+ console.log(` AI referral sessions (window): ${result.totals.aiReferralLandedHits} (+${result.totals.aiReferralRedirectedHits} redirect hops excluded)`);
1245
+ console.log(` paid: ${result.totals.aiReferralPaidHits}`);
1246
+ console.log(` organic: ${result.totals.aiReferralOrganicHits}`);
1247
+ console.log(` unclassified: ${result.totals.aiReferralUnknownHits} (ingested before paid/organic classification)`);
1248
+ console.log("");
1249
+ if (result.events.length === 0) {
1250
+ console.log("No events in this window.");
1251
+ return;
1252
+ }
1253
+ console.log(" TS_HOUR KIND IDENTITY EVIDENCE/STATUS PROVENANCE PATH COUNT");
1254
+ for (const event of result.events) {
1255
+ console.log(` ${formatEventLine(event)}`);
1256
+ }
1257
+ }
1258
+ async function trafficReferralAssessment(project, options) {
1259
+ const { format, ...query } = options;
1260
+ if (!query.startDate || !query.endDate) throw usageError("--start and --end are required for traffic referral-assessment.");
1261
+ const parsed = referralAssessmentQuerySchema.safeParse(query);
1262
+ if (!parsed.success) throw new CliError({ code: "TRAFFIC_INVALID_ASSESSMENT", message: formatValidationIssues(parsed.error.issues) });
1263
+ const result = await createApiClient().trafficReferralAssessment(project, parsed.data);
1264
+ if (isMachineFormat(format)) {
1265
+ console.log(JSON.stringify(result, null, 2));
1266
+ return;
1267
+ }
1268
+ console.log(`AI referral assessment for "${project}" \xB7 ${result.window.startDate} to ${result.window.endDate} UTC`);
1269
+ console.log(` Raw stored hits: ${result.totals.raw.total}`);
1270
+ console.log(` Countable stored hits: ${result.totals.countable.total}`);
1271
+ console.log(` Suspected burst hits: ${result.totals.suspected.total} (not confirmed automation)`);
1272
+ console.log(` Adjusted estimate: ${result.totals.adjustedEstimate.total} (countable minus candidate bursts)`);
1273
+ console.log(` Rule: ${result.rule.version}; threshold ${result.rule.burstThreshold}; ${result.rule.calibration}`);
1274
+ console.log(` Observed server/GA quotient: ${result.comparison.observedRatio ?? "unavailable"}; comparable coverage: unavailable`);
1275
+ console.log(` Evidence: ${result.evidence.returned} of ${result.evidence.total} candidate groups (source, product, normalized path, UTC hour)`);
1276
+ for (const burst of result.bursts) console.log(` ${burst.tsHour} ${burst.sourceId} ${burst.product} ${burst.landingPathNormalized} ${burst.counts.total}`);
1277
+ for (const caveat of result.caveats) console.log(` ${caveat}`);
1278
+ }
1279
+ export {
1280
+ DEFAULT_CLOUDFLARE_QUEUE_RETENTION_SECONDS,
1281
+ trafficActivate,
1282
+ trafficAnalytics,
1283
+ trafficBackfill,
1284
+ trafficConnectCloudRun,
1285
+ trafficConnectCloudflare,
1286
+ trafficConnectVercel,
1287
+ trafficConnectWordpress,
1288
+ trafficEvents,
1289
+ trafficReferralAssessment,
1290
+ trafficReset,
1291
+ trafficSamples,
1292
+ trafficSources,
1293
+ trafficStatus,
1294
+ trafficSync
1295
+ };