@canonry/canonry 7.104.4 → 7.105.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 (140) hide show
  1. package/assets/agent-workspace/skills/aero/SKILL.md +11 -0
  2. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +11 -2
  3. package/assets/assets/{AccessControls-hIgRxmCY.js → AccessControls-BL5Ohk1o.js} +1 -1
  4. package/assets/assets/{AgentSetupPage-BEYkXfMI.js → AgentSetupPage-DOlYQxIa.js} +1 -1
  5. package/assets/assets/{AuditHistoryPanel-B4RSWnDd.js → AuditHistoryPanel-YeKe0CdO.js} +1 -1
  6. package/assets/assets/{BacklinksPage-CU089NxY.js → BacklinksPage--cebdWId.js} +1 -1
  7. package/assets/assets/{ChartPrimitives-DfRYjnsb.js → ChartPrimitives-DXCNvCNq.js} +1 -1
  8. package/assets/assets/{HistoryPage-CtOK4bCH.js → HistoryPage-Bv5Nsm5B.js} +1 -1
  9. package/assets/assets/{MeasurementPropertyPage-C-XeLSL1.js → MeasurementPropertyPage-Czyfi0Cy.js} +1 -1
  10. package/assets/assets/{ProjectPage-HpOMuZBk.js → ProjectPage-DJe32kjK.js} +9 -9
  11. package/assets/assets/{RunsPage-CRnzj7dU.js → RunsPage-BBMqOkFs.js} +1 -1
  12. package/assets/assets/{ServerTrafficSection-x_7QecPB.js → ServerTrafficSection-DGWMEhEc.js} +1 -1
  13. package/assets/assets/{SettingsPage-BumPFoPz.js → SettingsPage-9PzZpqL2.js} +1 -1
  14. package/assets/assets/{ToneBadge-BoscSKWW.js → ToneBadge-DRmwaKRk.js} +2 -2
  15. package/assets/assets/{TrafficPage-CxEO_Y2c.js → TrafficPage-Cejn8Fnv.js} +1 -1
  16. package/assets/assets/{TrafficSourceDetailPage-D9me5kmv.js → TrafficSourceDetailPage-DIeCgXFX.js} +1 -1
  17. package/assets/assets/{account-context-n5iq1FxI.js → account-context-CfBDR6hl.js} +1 -1
  18. package/assets/assets/{agent-trust-copy-BWQkohiR.js → agent-trust-copy-DMeyA6SQ.js} +1 -1
  19. package/assets/assets/{card-CnZ3aU1G.js → card-CtxpcVrz.js} +1 -1
  20. package/assets/assets/{index-DPz1idfn.css → index-BfcVhcae.css} +1 -1
  21. package/assets/assets/{index-BEk3rfJu.js → index-C9zbuGlp.js} +3 -3
  22. package/assets/assets/{query-client-CTKEElDQ.js → query-client-HEvA-XRl.js} +1 -1
  23. package/assets/assets/{react-query-D-G5epGz.js → react-query-D-u-W_MC.js} +1 -1
  24. package/assets/assets/{react-sigma_core.esm.min-4Kr0Zt4p.js → react-sigma_core.esm.min-nHUsVjqN.js} +1 -1
  25. package/assets/assets/{server-traffic-Deh27adW.js → server-traffic-CiE8LDtb.js} +1 -1
  26. package/assets/assets/{service-Dur_GX4q.js → service-CpuZCGWk.js} +1 -1
  27. package/assets/index.html +9 -9
  28. package/dist/{ads-LPBLEQBU.js → ads-SDMYCM7U.js} +3 -3
  29. package/dist/{agent-NUQQRFIX.js → agent-KAJ7N4K5.js} +7 -7
  30. package/dist/{agent-ask-RLIEXI6J.js → agent-ask-VRBAA3LD.js} +3 -3
  31. package/dist/{agent-conversations-HXWBYGSK.js → agent-conversations-UJKZIBTJ.js} +3 -3
  32. package/dist/{agent-journeys-DZ4OK6RG.js → agent-journeys-ZEXWTKIX.js} +3 -3
  33. package/dist/{agent-memory-QASRDHY6.js → agent-memory-ZLNG67QP.js} +3 -3
  34. package/dist/{agent-providers-UNJBT65F.js → agent-providers-DC26H7L7.js} +3 -3
  35. package/dist/{agent-transcript-IYQDRVLL.js → agent-transcript-LQ7MD25B.js} +3 -3
  36. package/dist/{analytics-TGZAZQ4V.js → analytics-ECTVTHBL.js} +3 -3
  37. package/dist/{apply-OVSQL4ND.js → apply-PU5SMSQT.js} +3 -3
  38. package/dist/{backfill-QEYMNKWT.js → backfill-UOBJ74WV.js} +10 -10
  39. package/dist/{backlinks-TAEE5NW2.js → backlinks-5ACAELA4.js} +3 -3
  40. package/dist/{bing-Y47PPL2K.js → bing-EJAYJY2Q.js} +3 -3
  41. package/dist/{bootstrap-6SVPLI2X.js → bootstrap-67SLL4TQ.js} +10 -10
  42. package/dist/{cdp-AQQZBCSJ.js → cdp-RRK6SI5J.js} +7 -7
  43. package/dist/{chunk-MXCBG4Z7.js → chunk-237UH5XU.js} +1 -1
  44. package/dist/{chunk-2P2YNCJB.js → chunk-2NIALUNF.js} +1 -1
  45. package/dist/{chunk-VFT4AFA6.js → chunk-342SRLS4.js} +4 -4
  46. package/dist/{chunk-ZGAOBFAT.js → chunk-36E6ONH7.js} +1 -1
  47. package/dist/{chunk-WMZYHYKE.js → chunk-3YWBDKEM.js} +2 -2
  48. package/dist/{chunk-T52VRYI6.js → chunk-4RSE4WVE.js} +4 -4
  49. package/dist/{chunk-7X5YFLPM.js → chunk-4ZJ5OBHI.js} +2 -2
  50. package/dist/{chunk-VZXLMIPS.js → chunk-AP6NF7XZ.js} +3 -3
  51. package/dist/{chunk-FS65HPCW.js → chunk-CIRM6CYI.js} +2 -2
  52. package/dist/{chunk-FEHIXKYR.js → chunk-DNMJVN2G.js} +3 -3
  53. package/dist/{chunk-NWOPXLH3.js → chunk-DXHZAE7B.js} +3 -3
  54. package/dist/{chunk-MUBVE7E5.js → chunk-FX2WXFRS.js} +2 -2
  55. package/dist/{chunk-34ZFWATV.js → chunk-HOBBF66T.js} +1 -1
  56. package/dist/{chunk-5NU6BWCL.js → chunk-HUOJB576.js} +5 -5
  57. package/dist/{chunk-BNSSB6H4.js → chunk-IDSJ2UL7.js} +1 -1
  58. package/dist/{chunk-BDPFPPPQ.js → chunk-ITTJLJAV.js} +1 -1
  59. package/dist/{chunk-OBDOHDDJ.js → chunk-JCRR4R6U.js} +2 -2
  60. package/dist/{chunk-GOKYM7T5.js → chunk-KNDCEG3S.js} +923 -605
  61. package/dist/{chunk-7OGHD6Z2.js → chunk-KRMQHEHA.js} +22 -22
  62. package/dist/{chunk-VBNULTRM.js → chunk-KVBHT4RM.js} +1 -1
  63. package/dist/{chunk-ANAZ6ANA.js → chunk-KWZY4DGQ.js} +366 -366
  64. package/dist/{chunk-QZKQL65D.js → chunk-LOXYLU6K.js} +1 -1
  65. package/dist/{chunk-HM25YXM4.js → chunk-NF6H2HWJ.js} +7 -7
  66. package/dist/{chunk-CPLY2O4L.js → chunk-NW7CHK4V.js} +121 -4
  67. package/dist/{chunk-W6ORSOMS.js → chunk-QWVE4LB4.js} +1 -1
  68. package/dist/{chunk-2TFDE7HA.js → chunk-RMH7VXGG.js} +5 -5
  69. package/dist/{chunk-PQ6AORS2.js → chunk-T3NIHALJ.js} +4 -4
  70. package/dist/{chunk-TXH5BMVL.js → chunk-T45PRIHN.js} +3 -3
  71. package/dist/{chunk-T6TLIZEO.js → chunk-TBJKDTRW.js} +1 -1
  72. package/dist/{chunk-N5YFWTDQ.js → chunk-UPS2WHB3.js} +1 -1
  73. package/dist/{chunk-73SA4H5D.js → chunk-VTQMKA45.js} +1 -1
  74. package/dist/{chunk-HUH6676A.js → chunk-VZS2C7IA.js} +4 -4
  75. package/dist/{chunk-5KKU3YTF.js → chunk-XDCUJC4K.js} +4 -4
  76. package/dist/{chunk-O3HY3VSN.js → chunk-XZTCLR3G.js} +1 -1
  77. package/dist/{chunk-4PLVST2T.js → chunk-YO3SECAK.js} +2 -2
  78. package/dist/{chunk-2FWYWGIR.js → chunk-YW6J3STO.js} +1 -1
  79. package/dist/{chunk-KUNOMUUG.js → chunk-ZYG7V5RY.js} +7 -7
  80. package/dist/{citations-EPWMDINT.js → citations-F5X6YTXT.js} +4 -4
  81. package/dist/{cli-catalog-LOONVW4I.js → cli-catalog-3TK244WS.js} +3 -3
  82. package/dist/{cli-commands-3GFP4QFF.js → cli-commands-PFMEKY4J.js} +7 -7
  83. package/dist/cli.js +13 -13
  84. package/dist/{competitor-XUXFF3N5.js → competitor-3BLGH7MK.js} +3 -3
  85. package/dist/{content-X4VUI6Q4.js → content-7QRCYQT6.js} +3 -3
  86. package/dist/{dashboard-B5MO4JD6.js → dashboard-C42KGKG4.js} +6 -6
  87. package/dist/{demo-QTTEHPTG.js → demo-XYLOAE34.js} +1 -1
  88. package/dist/{demo-server-NQG5YAQE.js → demo-server-PTXOU2UU.js} +65 -15
  89. package/dist/{discover-Q53AI7AP.js → discover-LYRDQHZJ.js} +4 -4
  90. package/dist/{discover-eval-72A2EKS5.js → discover-eval-DPXWK35F.js} +3 -3
  91. package/dist/{doctor-PSJW22ME.js → doctor-57L3Q4O2.js} +3 -3
  92. package/dist/{evidence-BVP2S73D.js → evidence-K6K7BVTX.js} +3 -3
  93. package/dist/{export-cmd-3LZAJ24E.js → export-cmd-LIBMZHI5.js} +3 -3
  94. package/dist/{ga-VRCCYIOW.js → ga-U56VPNRX.js} +46 -5
  95. package/dist/{gbp-OK4CJ6JF.js → gbp-MRFDJ2HK.js} +3 -3
  96. package/dist/{google-GULK767N.js → google-QQDJNZ3O.js} +4 -4
  97. package/dist/{google-marketing-TQPEDQY6.js → google-marketing-MXFKQNQF.js} +1 -1
  98. package/dist/{health-cmd-IC5IQKBN.js → health-cmd-FECKLV5E.js} +4 -4
  99. package/dist/{history-EAEYLEVG.js → history-S3UJGH7B.js} +3 -3
  100. package/dist/index.d.ts +25 -25
  101. package/dist/index.js +26 -26
  102. package/dist/{init-SXOJJUNJ.js → init-X4WUARKM.js} +12 -12
  103. package/dist/{insights-ICTSKQD6.js → insights-2UAIY4EV.js} +3 -3
  104. package/dist/intelligence-service-64ZLE37W.js +16 -0
  105. package/dist/{journeys-H2BOW42B.js → journeys-44U2W4WQ.js} +3 -3
  106. package/dist/{keys-OTJZGBGX.js → keys-JKUNWJQN.js} +3 -3
  107. package/dist/{keyword-ZZ4SPADG.js → keyword-5W3PDFCZ.js} +3 -3
  108. package/dist/{logs-IH74KKBP.js → logs-67S2VOW2.js} +3 -3
  109. package/dist/{mcp-U736ZMVE.js → mcp-RBZEEULW.js} +4 -4
  110. package/dist/mcp.js +10 -10
  111. package/dist/{measurement-plan-EJ5H5S3X.js → measurement-plan-H2WHPS6M.js} +5 -5
  112. package/dist/{notify-PVTESANP.js → notify-5MHM43II.js} +3 -3
  113. package/dist/{organic-evidence-PGDCDE7I.js → organic-evidence-PT37WD5D.js} +3 -3
  114. package/dist/{overview-3QPRHIML.js → overview-YSGLVOQL.js} +5 -5
  115. package/dist/{project-FLF4NQYK.js → project-I7VQRW4I.js} +3 -3
  116. package/dist/{project-setup-HMIMB7LA.js → project-setup-ABNKGLKM.js} +3 -3
  117. package/dist/{query-WFNBO5IA.js → query-6HCKL366.js} +3 -3
  118. package/dist/{research-NOC77N5S.js → research-4D3GNHI6.js} +3 -3
  119. package/dist/{results-export-MQ372TJX.js → results-export-CHHMZU7K.js} +3 -3
  120. package/dist/{run-KQEZAMFC.js → run-TYIRQZD6.js} +5 -5
  121. package/dist/{schedule-RXJR7S5O.js → schedule-JLTS2OH4.js} +3 -3
  122. package/dist/{search-AVPIH3SH.js → search-LRBIRDUD.js} +3 -3
  123. package/dist/{serve-Z3WLVD46.js → serve-X7MZKZ3B.js} +27 -27
  124. package/dist/{session-HEV5XBJI.js → session-F3FYX2QK.js} +14 -14
  125. package/dist/{settings-FOPSQVXA.js → settings-K5SUV5Y4.js} +3 -3
  126. package/dist/{sitemaps-GOA3STCM.js → sitemaps-YWWBI67M.js} +3 -3
  127. package/dist/{skills-XJKTJ6LH.js → skills-ECQG3MBE.js} +2 -2
  128. package/dist/{snapshot-4W4FLLRV.js → snapshot-62BXAS6C.js} +3 -3
  129. package/dist/{src-VTBSLT3E.js → src-R53436JE.js} +2 -2
  130. package/dist/{status-DMP7OCRB.js → status-TNOLPP73.js} +5 -5
  131. package/dist/{technical-aeo-IBYKY4VO.js → technical-aeo-YDVU5TWC.js} +3 -3
  132. package/dist/{telemetry-PXSA7GSQ.js → telemetry-WBO4WDQB.js} +4 -4
  133. package/dist/{tools-B3B7I7OU.js → tools-BI3B6WLL.js} +11 -11
  134. package/dist/{traffic-USZLDNGC.js → traffic-CPSRCVU7.js} +5 -5
  135. package/dist/{trends-FT5WL6EZ.js → trends-TD6UGUYE.js} +3 -3
  136. package/dist/{users-C5QGTAEE.js → users-NPOXIJ3C.js} +3 -3
  137. package/dist/{visibility-stats-FJRKQAIB.js → visibility-stats-VHU4F3VL.js} +4 -4
  138. package/dist/{wordpress-DII4DF43.js → wordpress-OLPTUY5E.js} +3 -3
  139. package/package.json +1 -1
  140. package/dist/intelligence-service-MFMPHWQM.js +0 -16
@@ -19,14 +19,14 @@ import {
19
19
  normalizeTrafficPathPattern,
20
20
  sessionizeJourneyRequests,
21
21
  verifyRequestSignature
22
- } from "./chunk-O3HY3VSN.js";
22
+ } from "./chunk-XZTCLR3G.js";
23
23
  import {
24
24
  currentOutcomeAttribution,
25
25
  getRequestContext,
26
26
  registerRequestContext,
27
27
  requestAuditIdentity,
28
28
  sanitizeRequestContext
29
- } from "./chunk-N5YFWTDQ.js";
29
+ } from "./chunk-UPS2WHB3.js";
30
30
  import {
31
31
  RawEventSampleEventTypes,
32
32
  SentimentIdempotencyConflict,
@@ -190,7 +190,7 @@ import {
190
190
  userSessions,
191
191
  users,
192
192
  writeNegativeReviewMaxStars
193
- } from "./chunk-2P2YNCJB.js";
193
+ } from "./chunk-2NIALUNF.js";
194
194
  import {
195
195
  ADS_ACTIVATE_SCOPE,
196
196
  ADS_ACTIVATION_ABSOLUTE_MAX_ENTITIES,
@@ -432,6 +432,7 @@ import {
432
432
  SITE_HEALTH_SUBGRAPH_MAX_EDGES,
433
433
  SITE_HEALTH_SUBGRAPH_MAX_NODES,
434
434
  SKILL_MANIFEST_FILENAME,
435
+ SOCIAL_PLATFORM_RANKING_MIN_SESSIONS,
435
436
  SOURCE_BREAKDOWN_COUNT_UNITS,
436
437
  STORED_ONLY_HEADER,
437
438
  SchedulableRunKinds,
@@ -749,6 +750,7 @@ import {
749
750
  formatCanonryPluginVersionMismatch,
750
751
  formatIsoDate,
751
752
  formatIsoDateInTimeZone,
753
+ formatPerThousand,
752
754
  formatPercent,
753
755
  formatRunErrorOneLine,
754
756
  formatSignedPercent,
@@ -1354,7 +1356,7 @@ import {
1354
1356
  wordpressSchemaDeployResultDtoSchema,
1355
1357
  wordpressSchemaStatusResultDtoSchema,
1356
1358
  wordpressStatusDtoSchema
1357
- } from "./chunk-CPLY2O4L.js";
1359
+ } from "./chunk-NW7CHK4V.js";
1358
1360
 
1359
1361
  // ../api-routes/src/user-session.ts
1360
1362
  import crypto2 from "crypto";
@@ -35560,6 +35562,47 @@ function literalPathPrefixCondition(path8, prefix) {
35560
35562
 
35561
35563
  // ../api-routes/src/ga-measurement-analysis.ts
35562
35564
  import { and as and58, eq as eq68, gte as gte18, inArray as inArray36, lte as lte16, or as or12, sql as sql31 } from "drizzle-orm";
35565
+
35566
+ // ../api-routes/src/ga-lead-rate.ts
35567
+ function resolveLeadEvents(measurement, state) {
35568
+ const configuredLeadEvents = [...measurement.leadEventNames];
35569
+ const keyEventNames = countsKeyEvents(measurement) ? state?.keyEventNames ?? null : null;
35570
+ const countedEventNames = countedLeadEventNames(configuredLeadEvents, keyEventNames ?? []);
35571
+ const measuredEventSet = new Set(state?.leadEventNames ?? configuredLeadEvents);
35572
+ const reportedEventNames = countedEventNames.filter((name) => measuredEventSet.has(name));
35573
+ return { configuredLeadEvents, keyEventNames, countedEventNames, measuredEventSet, reportedEventNames };
35574
+ }
35575
+ function latestDate(rows) {
35576
+ let latest = null;
35577
+ for (const row of rows) {
35578
+ if (latest === null || row.date > latest) latest = row.date;
35579
+ }
35580
+ return latest;
35581
+ }
35582
+ function hasLeadDayWithoutSessions(acquisitionRows, leadRows) {
35583
+ const acquisitionDates = /* @__PURE__ */ new Set();
35584
+ for (const row of acquisitionRows) acquisitionDates.add(row.date);
35585
+ for (const row of leadRows) {
35586
+ if (!acquisitionDates.has(row.date)) return true;
35587
+ }
35588
+ return false;
35589
+ }
35590
+ function leadRateUnavailableReason(input) {
35591
+ if (!input.hasData) return AiEngineLeadRateUnavailableReasons["no-data"];
35592
+ if (input.acquisitionStatus !== "ready" || input.leadStatus !== "ready") {
35593
+ return AiEngineLeadRateUnavailableReasons["sync-not-ready"];
35594
+ }
35595
+ if (input.channelLeadsUnfiltered) return AiEngineLeadRateUnavailableReasons["channel-leads-unfiltered"];
35596
+ if (input.paidOnlyByLandingPage) return AiEngineLeadRateUnavailableReasons["paid-split-needs-landing-page"];
35597
+ if (input.latestLeadDate !== null && (input.latestAcquisitionDate === null || input.latestAcquisitionDate < input.latestLeadDate)) {
35598
+ return AiEngineLeadRateUnavailableReasons["sessions-behind-leads"];
35599
+ }
35600
+ if (input.leadDayWithoutSessions) return AiEngineLeadRateUnavailableReasons["sessions-missing-on-lead-days"];
35601
+ if (input.sessionsBeforeLeads) return AiEngineLeadRateUnavailableReasons["sessions-before-leads"];
35602
+ return null;
35603
+ }
35604
+
35605
+ // ../api-routes/src/ga-measurement-analysis.ts
35563
35606
  var UNKNOWN_LANDING_PAGE = "(not set)";
35564
35607
  function addDays(date, offset) {
35565
35608
  const value = /* @__PURE__ */ new Date(`${date}T00:00:00.000Z`);
@@ -35709,30 +35752,6 @@ function buildAiEngineLeads(input) {
35709
35752
  paid: classBlock(AiReferralTrafficClasses.paid)
35710
35753
  };
35711
35754
  }
35712
- function latestDate(rows) {
35713
- let latest = null;
35714
- for (const row of rows) {
35715
- if (latest === null || row.date > latest) latest = row.date;
35716
- }
35717
- return latest;
35718
- }
35719
- function hasLeadDayWithoutSessions(acquisitionRows, leadRows) {
35720
- const acquisitionDates = new Set(acquisitionRows.map((row) => row.date));
35721
- return leadRows.some((row) => !acquisitionDates.has(row.date));
35722
- }
35723
- function aiEngineLeadRateUnavailableReason(input) {
35724
- if (!input.hasData) return AiEngineLeadRateUnavailableReasons["no-data"];
35725
- if (input.acquisitionStatus !== "ready" || input.leadStatus !== "ready") {
35726
- return AiEngineLeadRateUnavailableReasons["sync-not-ready"];
35727
- }
35728
- if (input.channelLeadsUnfiltered) return AiEngineLeadRateUnavailableReasons["channel-leads-unfiltered"];
35729
- if (input.paidOnlyByLandingPage) return AiEngineLeadRateUnavailableReasons["paid-split-needs-landing-page"];
35730
- if (input.latestLeadDate !== null && (input.latestAcquisitionDate === null || input.latestAcquisitionDate < input.latestLeadDate)) {
35731
- return AiEngineLeadRateUnavailableReasons["sessions-behind-leads"];
35732
- }
35733
- if (input.leadDayWithoutSessions) return AiEngineLeadRateUnavailableReasons["sessions-missing-on-lead-days"];
35734
- return null;
35735
- }
35736
35755
  function engagementPeriods(periods, rows) {
35737
35756
  return periods.map((period2) => {
35738
35757
  const inPeriod = rows.filter((row) => row.date >= period2.startDate && row.date <= period2.endDate);
@@ -35861,12 +35880,14 @@ function buildGaMeasurementAnalysis(db, projectName, options = {}) {
35861
35880
  const acquisitionScope = scopedConditions(gaAcquisitionDaily.hostName, gaAcquisitionDaily.landingPageNormalized, gaAcquisitionDaily.landingPage);
35862
35881
  const leadLandingScope = scopedConditions(gaLeadEventsDaily.hostName, gaLeadEventsDaily.landingPageNormalized, gaLeadEventsDaily.landingPage);
35863
35882
  const state = db.select().from(gaMeasurementSyncStates).where(eq68(gaMeasurementSyncStates.projectId, project.id)).get();
35864
- const configuredLeadEvents = [...project.measurement.leadEventNames];
35865
35883
  const keyEventsEnabled = countsKeyEvents(project.measurement);
35866
- const keyEventNames = keyEventsEnabled ? state?.keyEventNames ?? null : null;
35867
- const countedEventNames = countedLeadEventNames(configuredLeadEvents, keyEventNames ?? []);
35868
- const measuredEventSet = new Set(state?.leadEventNames ?? configuredLeadEvents);
35869
- const reportedEventNames = countedEventNames.filter((name) => measuredEventSet.has(name));
35884
+ const {
35885
+ configuredLeadEvents,
35886
+ keyEventNames,
35887
+ countedEventNames,
35888
+ measuredEventSet,
35889
+ reportedEventNames
35890
+ } = resolveLeadEvents(project.measurement, state);
35870
35891
  const leadEventCondition = reportedEventNames.length > 0 ? inArray36(gaLeadEventsDaily.eventName, reportedEventNames) : null;
35871
35892
  const acquisitionAnchor = db.select({ date: sql31`max(${gaAcquisitionDaily.date})` }).from(gaAcquisitionDaily).where(and58(eq68(gaAcquisitionDaily.projectId, project.id), ...acquisitionScope)).get()?.date ?? null;
35872
35893
  const leadAnchor = leadEventCondition === null ? null : db.select({ date: sql31`max(${gaLeadEventsDaily.date})` }).from(gaLeadEventsDaily).where(and58(eq68(gaLeadEventsDaily.projectId, project.id), leadEventCondition, or12(
@@ -35971,7 +35992,7 @@ function buildGaMeasurementAnalysis(db, projectName, options = {}) {
35971
35992
  periods: hasAiEngineLeadData ? gaPeriods : [],
35972
35993
  leads: aiEngineRows.leads,
35973
35994
  sessions: aiEngineRows.sessions,
35974
- leadRateUnavailableReason: aiEngineLeadRateUnavailableReason({
35995
+ leadRateUnavailableReason: leadRateUnavailableReason({
35975
35996
  hasData: hasAiEngineLeadData,
35976
35997
  acquisitionStatus: state?.acquisitionStatus,
35977
35998
  leadStatus: state?.leadStatus,
@@ -44660,6 +44681,7 @@ var routeCatalog = [
44660
44681
  parameters: [nameParameter, googleTypeParameter],
44661
44682
  responses: {
44662
44683
  204: { description: "Google connection deleted." },
44684
+ 400: errorResponse("The connection belongs to another project that tracks the same domain; nothing was removed."),
44663
44685
  404: errorResponse("Project or connection not found.")
44664
44686
  }
44665
44687
  },
@@ -45090,6 +45112,7 @@ var routeCatalog = [
45090
45112
  parameters: [nameParameter],
45091
45113
  responses: {
45092
45114
  204: { description: "Disconnected." },
45115
+ 400: errorResponse("The connection belongs to another project that tracks the same domain; nothing was removed."),
45093
45116
  404: errorResponse("Project not found.")
45094
45117
  }
45095
45118
  },
@@ -56045,6 +56068,12 @@ async function googleRoutes(app, opts) {
56045
56068
  app.delete("/projects/:name/gbp/connection", connectionRoute(app, () => ({ integration: "gbp", action: "disconnect" }), async (request, reply, attempt) => {
56046
56069
  const project = resolveProject(app.db, request.params.name);
56047
56070
  const store = requireConnectionStore();
56071
+ const existing = store.getConnection(project.canonicalDomain, "gbp");
56072
+ if (existing?.createdByProjectId && existing.createdByProjectId !== project.id) {
56073
+ throw validationError(
56074
+ "This Google GBP connection is owned by a different project. Disconnect from the owning project instead."
56075
+ );
56076
+ }
56048
56077
  app.db.transaction((tx) => {
56049
56078
  clearGbpProjectData(tx, project.id);
56050
56079
  writeAuditLog(tx, {
@@ -65011,7 +65040,7 @@ async function cdpRoutes(app, opts) {
65011
65040
 
65012
65041
  // ../api-routes/src/ga.ts
65013
65042
  import crypto56 from "crypto";
65014
- import { eq as eq95, desc as desc43, and as and80, inArray as inArray45, sql as sql42 } from "drizzle-orm";
65043
+ import { eq as eq96, desc as desc43, and as and81, inArray as inArray46, sql as sql43 } from "drizzle-orm";
65015
65044
 
65016
65045
  // ../api-routes/src/ga-session-history.ts
65017
65046
  function buildSessionHistory(landingPageDays, dailyTotals) {
@@ -65174,17 +65203,299 @@ function findBiggestMover(current, prior) {
65174
65203
  return mover;
65175
65204
  }
65176
65205
 
65206
+ // ../api-routes/src/ga-social-platform-performance.ts
65207
+ import { and as and78, eq as eq93, inArray as inArray45, sql as sql41 } from "drizzle-orm";
65208
+ var SOCIAL_CHANNEL_GROUPS2 = /* @__PURE__ */ new Set(["Organic Social", "Paid Social"]);
65209
+ var CHART_SERIES_LIMIT2 = 5;
65210
+ function socialPlatformGroupFor(source, channelGroup) {
65211
+ const socialChannel = SOCIAL_CHANNEL_GROUPS2.has(channelGroup);
65212
+ const platform = socialPlatformForReferralSource(source, socialChannel ? {} : { minLabelLength: 2 });
65213
+ if (platform) return { key: platform, platform };
65214
+ if (socialChannel) return { key: `source:${source}`, platform: null };
65215
+ return null;
65216
+ }
65217
+ function groupLabel(group, source) {
65218
+ return group.platform ? socialPlatformLabel(group.platform) : source;
65219
+ }
65220
+ function trafficClassOf(row) {
65221
+ return classifyAiReferralTrafficClass({
65222
+ source: row.source,
65223
+ medium: row.medium,
65224
+ channelGroup: row.channelGroup,
65225
+ landingPage: null
65226
+ });
65227
+ }
65228
+ function conversionsPerThousand(conversions, sessions, available) {
65229
+ if (!available || conversions === null || sessions <= 0) return null;
65230
+ return Number((conversions / sessions * 1e3).toFixed(2));
65231
+ }
65232
+ function rateFields(conversions, sessions, available) {
65233
+ const perThousand = conversionsPerThousand(conversions, sessions, available);
65234
+ return {
65235
+ conversions,
65236
+ conversionsPerThousandSessions: perThousand,
65237
+ conversionsPerThousandSessionsDisplay: formatPerThousand(perThousand)
65238
+ };
65239
+ }
65240
+ function sourceKey(row) {
65241
+ return `${row.source}\0${row.medium}\0${row.channelGroup}`;
65242
+ }
65243
+ function compareCodeUnits2(left, right) {
65244
+ if (left < right) return -1;
65245
+ return left > right ? 1 : 0;
65246
+ }
65247
+ function buildSocialPlatformPerformance(input) {
65248
+ const minSessions = input.minSessions ?? SOCIAL_PLATFORM_RANKING_MIN_SESSIONS;
65249
+ const conversionsMeasured = input.conversionRows !== null;
65250
+ const rateAvailable = conversionsMeasured && input.conversionRateUnavailableReason === null;
65251
+ if (!input.hasAcquisitionRows) {
65252
+ return {
65253
+ status: "unavailable",
65254
+ unavailableReason: "sessions-not-synced",
65255
+ sessions: 0,
65256
+ sharePct: 0,
65257
+ sharePctDisplay: formatPercent(null),
65258
+ paidSessions: 0,
65259
+ paidShare: 0,
65260
+ conversions: null,
65261
+ conversionRateAvailable: false,
65262
+ conversionRateUnavailableReason: input.conversionRateUnavailableReason,
65263
+ countedEventNames: [...input.countedEventNames],
65264
+ minSessions,
65265
+ site: { sessions: input.siteSessions, ...rateFields(input.siteConversions, input.siteSessions ?? 0, false) },
65266
+ platforms: [],
65267
+ daily: buildStackedDailySeries([], { limit: CHART_SERIES_LIMIT2, otherLabel: "Other" })
65268
+ };
65269
+ }
65270
+ const platforms = /* @__PURE__ */ new Map();
65271
+ const accumulate = (row, side) => {
65272
+ const group = socialPlatformGroupFor(row.source, row.channelGroup);
65273
+ if (!group) return;
65274
+ let platform = platforms.get(group.key);
65275
+ if (!platform) {
65276
+ platform = {
65277
+ key: group.key,
65278
+ platform: group.platform,
65279
+ label: groupLabel(group, row.source),
65280
+ sessions: 0,
65281
+ paidSessions: 0,
65282
+ organicSessions: 0,
65283
+ conversions: 0,
65284
+ paidConversions: 0,
65285
+ organicConversions: 0,
65286
+ channelSessions: /* @__PURE__ */ new Map(),
65287
+ sources: /* @__PURE__ */ new Map()
65288
+ };
65289
+ platforms.set(group.key, platform);
65290
+ }
65291
+ const trafficClass = trafficClassOf(row);
65292
+ const key = sourceKey(row);
65293
+ let source = platform.sources.get(key);
65294
+ if (!source) {
65295
+ source = { source: row.source, medium: row.medium, channelGroup: row.channelGroup, trafficClass, sessions: 0, conversions: 0 };
65296
+ platform.sources.set(key, source);
65297
+ }
65298
+ const paid = trafficClass === AiReferralTrafficClasses.paid;
65299
+ if (side === "sessions") {
65300
+ source.sessions += row.value;
65301
+ platform.sessions += row.value;
65302
+ if (paid) platform.paidSessions += row.value;
65303
+ else platform.organicSessions += row.value;
65304
+ platform.channelSessions.set(row.channelGroup, (platform.channelSessions.get(row.channelGroup) ?? 0) + row.value);
65305
+ } else {
65306
+ source.conversions += row.value;
65307
+ platform.conversions += row.value;
65308
+ if (paid) platform.paidConversions += row.value;
65309
+ else platform.organicConversions += row.value;
65310
+ if (!platform.channelSessions.has(row.channelGroup)) platform.channelSessions.set(row.channelGroup, 0);
65311
+ }
65312
+ };
65313
+ for (const row of input.sessionRows) accumulate(row, "sessions");
65314
+ for (const row of input.conversionRows ?? []) accumulate(row, "conversions");
65315
+ const ordered = [...platforms.values()].sort((a, b) => b.sessions - a.sessions || compareCodeUnits2(a.label, b.label));
65316
+ const totalSessions = ordered.reduce((sum, platform) => sum + platform.sessions, 0);
65317
+ const paidSessions = ordered.reduce((sum, platform) => sum + platform.paidSessions, 0);
65318
+ const totalConversions = conversionsMeasured ? ordered.reduce((sum, platform) => sum + platform.conversions, 0) : null;
65319
+ const platformShares = breakdownShares(ordered.map((platform) => platform.sessions));
65320
+ const allSources = ordered.flatMap((platform) => [...platform.sources.values()]);
65321
+ const sourceShares = new Map(allSources.map((source, index) => [source, index]));
65322
+ const sourceShareValues = breakdownShares(allSources.map((source) => source.sessions));
65323
+ const conversionsOf = (value) => conversionsMeasured ? value : null;
65324
+ const classBlock = (sessions, conversions) => ({
65325
+ sessions,
65326
+ ...rateFields(conversionsOf(conversions), sessions, rateAvailable)
65327
+ });
65328
+ const rows = ordered.map((platform, index) => {
65329
+ const sources = [...platform.sources.values()].sort((a, b) => b.sessions - a.sessions || b.conversions - a.conversions || compareCodeUnits2(sourceKey(a), sourceKey(b))).map((source) => ({
65330
+ source: source.source,
65331
+ medium: source.medium,
65332
+ channelGroup: source.channelGroup,
65333
+ trafficClass: source.trafficClass,
65334
+ sessions: source.sessions,
65335
+ share: sourceShareValues[sourceShares.get(source)] ?? 0,
65336
+ ...rateFields(conversionsOf(source.conversions), source.sessions, rateAvailable)
65337
+ }));
65338
+ return {
65339
+ key: platform.key,
65340
+ platform: platform.platform,
65341
+ label: platform.label,
65342
+ sessions: platform.sessions,
65343
+ organicSessions: platform.organicSessions,
65344
+ paidSessions: platform.paidSessions,
65345
+ share: platformShares[index] ?? 0,
65346
+ ...rateFields(conversionsOf(platform.conversions), platform.sessions, rateAvailable),
65347
+ enoughSessions: platform.sessions >= minSessions,
65348
+ rank: null,
65349
+ paid: classBlock(platform.paidSessions, platform.paidConversions),
65350
+ organic: classBlock(platform.organicSessions, platform.organicConversions),
65351
+ channelGroups: [...platform.channelSessions.entries()].sort((a, b) => b[1] - a[1] || compareCodeUnits2(a[0], b[0])).map(([channelGroup]) => channelGroup),
65352
+ sources
65353
+ };
65354
+ });
65355
+ const ranked = rows.filter((row) => row.enoughSessions && row.conversionsPerThousandSessions !== null).sort((a, b) => b.conversionsPerThousandSessions - a.conversionsPerThousandSessions || (b.conversions ?? 0) - (a.conversions ?? 0) || b.sessions - a.sessions || compareCodeUnits2(a.label, b.label));
65356
+ ranked.forEach((row, index) => {
65357
+ row.rank = index + 1;
65358
+ });
65359
+ const labelByKey = new Map(rows.map((row) => [row.key, row.label]));
65360
+ const daily = buildStackedDailySeries(
65361
+ input.dailyRows.flatMap((row) => {
65362
+ const group = socialPlatformGroupFor(row.source, row.channelGroup);
65363
+ if (!group) return [];
65364
+ return [{ date: row.date, key: group.key, label: labelByKey.get(group.key) ?? groupLabel(group, row.source), sessions: row.sessions }];
65365
+ }),
65366
+ { limit: CHART_SERIES_LIMIT2, otherLabel: "Other" }
65367
+ );
65368
+ return {
65369
+ status: "ready",
65370
+ unavailableReason: null,
65371
+ sessions: totalSessions,
65372
+ sharePct: percentOf(totalSessions, input.totalSessions) ?? 0,
65373
+ sharePctDisplay: formatPercent(shareOf(totalSessions, input.totalSessions)),
65374
+ paidSessions,
65375
+ paidShare: shareOf(paidSessions, totalSessions) ?? 0,
65376
+ conversions: totalConversions,
65377
+ conversionRateAvailable: rateAvailable,
65378
+ conversionRateUnavailableReason: input.conversionRateUnavailableReason,
65379
+ countedEventNames: [...input.countedEventNames],
65380
+ minSessions,
65381
+ site: {
65382
+ sessions: input.siteSessions,
65383
+ ...rateFields(input.siteConversions, input.siteSessions ?? 0, rateAvailable)
65384
+ },
65385
+ platforms: rows,
65386
+ daily
65387
+ };
65388
+ }
65389
+ function loadSocialPlatformPerformance(db, input) {
65390
+ const acquisitionWhere = and78(eq93(gaAcquisitionDaily.projectId, input.projectId), ...input.dateConditions(gaAcquisitionDaily.date));
65391
+ const state = db.select().from(gaMeasurementSyncStates).where(eq93(gaMeasurementSyncStates.projectId, input.projectId)).get();
65392
+ const { countedEventNames, reportedEventNames } = resolveLeadEvents(input.measurement, state);
65393
+ const acquisitionDates = db.select({ date: gaAcquisitionDaily.date }).from(gaAcquisitionDaily).where(acquisitionWhere).groupBy(gaAcquisitionDaily.date).all();
65394
+ const platformSources = [...new Set(db.select({ source: gaAcquisitionDaily.source, channelGroup: gaAcquisitionDaily.channelGroup }).from(gaAcquisitionDaily).where(acquisitionWhere).groupBy(gaAcquisitionDaily.source, gaAcquisitionDaily.channelGroup).all().filter((row) => socialPlatformGroupFor(row.source, row.channelGroup) !== null).map((row) => row.source))];
65395
+ const readPlatformSessions = () => {
65396
+ const perLandingPage = db.select({
65397
+ date: gaAcquisitionDaily.date,
65398
+ channelGroup: gaAcquisitionDaily.channelGroup,
65399
+ source: gaAcquisitionDaily.source,
65400
+ medium: gaAcquisitionDaily.medium,
65401
+ sessions: sql41`MAX(${gaAcquisitionDaily.sessions})`.as("sessions")
65402
+ }).from(gaAcquisitionDaily).where(and78(acquisitionWhere, inArray45(gaAcquisitionDaily.source, platformSources))).groupBy(
65403
+ gaAcquisitionDaily.date,
65404
+ gaAcquisitionDaily.channelGroup,
65405
+ gaAcquisitionDaily.source,
65406
+ gaAcquisitionDaily.medium,
65407
+ gaAcquisitionDaily.landingPage
65408
+ ).as("per_landing_page");
65409
+ return db.select({
65410
+ date: perLandingPage.date,
65411
+ channelGroup: perLandingPage.channelGroup,
65412
+ source: perLandingPage.source,
65413
+ medium: perLandingPage.medium,
65414
+ sessions: sql41`SUM(${perLandingPage.sessions})`
65415
+ }).from(perLandingPage).groupBy(perLandingPage.date, perLandingPage.channelGroup, perLandingPage.source, perLandingPage.medium).all();
65416
+ };
65417
+ const dailyKeyRows = platformSources.length > 0 ? readPlatformSessions() : [];
65418
+ const sessionTotals = /* @__PURE__ */ new Map();
65419
+ const dailyRows = [];
65420
+ for (const row of dailyKeyRows) {
65421
+ if (socialPlatformGroupFor(row.source, row.channelGroup) === null) continue;
65422
+ const value = row.sessions ?? 0;
65423
+ const key = `${row.source}\0${row.medium}\0${row.channelGroup}`;
65424
+ const total = sessionTotals.get(key);
65425
+ if (total) total.value += value;
65426
+ else sessionTotals.set(key, { source: row.source, medium: row.medium, channelGroup: row.channelGroup, value });
65427
+ dailyRows.push({ date: row.date, source: row.source, channelGroup: row.channelGroup, sessions: value });
65428
+ }
65429
+ const sessionRows = [...sessionTotals.values()];
65430
+ const leadWhere = reportedEventNames.length > 0 ? and78(
65431
+ eq93(gaLeadEventsDaily.projectId, input.projectId),
65432
+ inArray45(gaLeadEventsDaily.eventName, reportedEventNames),
65433
+ ...input.dateConditions(gaLeadEventsDaily.date)
65434
+ ) : null;
65435
+ const hasLeadTimeline = reportedEventNames.length > 0 && (state?.leadSyncedAt != null || leadWhere !== null && db.select({ found: sql41`1` }).from(gaLeadEventsDaily).where(leadWhere).limit(1).get() !== void 0);
65436
+ const conversionRows = leadWhere && hasLeadTimeline ? db.select({
65437
+ source: gaLeadEventsDaily.source,
65438
+ medium: gaLeadEventsDaily.medium,
65439
+ channelGroup: gaLeadEventsDaily.channelGroup,
65440
+ value: sql41`SUM(${gaLeadEventsDaily.eventCount})`
65441
+ }).from(gaLeadEventsDaily).where(leadWhere).groupBy(gaLeadEventsDaily.source, gaLeadEventsDaily.medium, gaLeadEventsDaily.channelGroup).all().map((row) => ({ ...row, value: row.value ?? 0 })) : null;
65442
+ const leadDates = leadWhere && hasLeadTimeline ? db.selectDistinct({ date: gaLeadEventsDaily.date }).from(gaLeadEventsDaily).where(leadWhere).all() : [];
65443
+ const acquisitionDays = acquisitionDates.map((row) => row.date);
65444
+ const siteTotals = acquisitionDays.length > 0 ? db.select({
65445
+ days: sql41`COUNT(DISTINCT ${gaDailyTotals.date})`,
65446
+ sessions: sql41`SUM(${gaDailyTotals.sessions})`
65447
+ }).from(gaDailyTotals).where(and78(
65448
+ eq93(gaDailyTotals.projectId, input.projectId),
65449
+ ...input.dateConditions(gaDailyTotals.date),
65450
+ inArray45(gaDailyTotals.date, acquisitionDays)
65451
+ )).get() : void 0;
65452
+ const siteSessions = siteTotals && siteTotals.days === acquisitionDays.length ? siteTotals.sessions : null;
65453
+ const siteConversionsRow = leadWhere && hasLeadTimeline ? db.select({ conversions: sql41`SUM(${gaLeadEventsDaily.eventCount})` }).from(gaLeadEventsDaily).where(leadWhere).get() : null;
65454
+ const firstLeadReceipt = reportedEventNames.length > 0 ? db.select({ date: sql41`MIN(${gaSyncCoverage.date})` }).from(gaSyncCoverage).where(and78(eq93(gaSyncCoverage.projectId, input.projectId), eq93(gaSyncCoverage.component, "leads"))).get()?.date ?? null : null;
65455
+ const firstLeadRow = reportedEventNames.length > 0 ? db.select({ date: sql41`MIN(${gaLeadEventsDaily.date})` }).from(gaLeadEventsDaily).where(and78(eq93(gaLeadEventsDaily.projectId, input.projectId), inArray45(gaLeadEventsDaily.eventName, reportedEventNames))).get()?.date ?? null : null;
65456
+ const leadHistoryStart = [firstLeadReceipt, firstLeadRow].filter((date) => date !== null).sort()[0] ?? null;
65457
+ const firstAcquisitionDate = acquisitionDays.reduce(
65458
+ (first, date) => first === null || date < first ? date : first,
65459
+ null
65460
+ );
65461
+ const conversionRateUnavailableReason = leadRateUnavailableReason({
65462
+ hasData: conversionRows !== null && acquisitionDates.length > 0,
65463
+ acquisitionStatus: state?.acquisitionStatus ?? void 0,
65464
+ leadStatus: state?.leadStatus ?? void 0,
65465
+ // Every host and the whole site on both sides, so a channel-scoped lead
65466
+ // row (no landing page) is never narrowed differently from its sessions.
65467
+ channelLeadsUnfiltered: false,
65468
+ // Neither side reads the landing page (see `trafficClassOf`).
65469
+ paidOnlyByLandingPage: false,
65470
+ latestAcquisitionDate: latestDate(acquisitionDates),
65471
+ latestLeadDate: latestDate(leadDates),
65472
+ leadDayWithoutSessions: hasLeadDayWithoutSessions(acquisitionDates, leadDates),
65473
+ sessionsBeforeLeads: leadHistoryStart !== null && firstAcquisitionDate !== null && firstAcquisitionDate < leadHistoryStart
65474
+ });
65475
+ return buildSocialPlatformPerformance({
65476
+ sessionRows,
65477
+ conversionRows,
65478
+ dailyRows,
65479
+ hasAcquisitionRows: acquisitionDates.length > 0,
65480
+ siteSessions,
65481
+ siteConversions: conversionRows === null ? null : siteConversionsRow?.conversions ?? 0,
65482
+ totalSessions: input.totalSessions,
65483
+ countedEventNames: reportedEventNames.length > 0 ? reportedEventNames : countedEventNames,
65484
+ conversionRateUnavailableReason
65485
+ });
65486
+ }
65487
+
65177
65488
  // ../api-routes/src/ga-sync-coverage.ts
65178
- import { and as and78, eq as eq93, lt as lt19 } from "drizzle-orm";
65489
+ import { and as and79, eq as eq94, lt as lt19 } from "drizzle-orm";
65179
65490
  function planGaSyncCoverage(db, input, now) {
65180
65491
  const definition2 = input.definition ?? "v1";
65181
65492
  const refreshStart = shiftIsoCalendarDate(input.requested.endDate, -13);
65182
65493
  const reconcileAfter = new Date(Date.parse(now) - 30 * 864e5).toISOString();
65183
- const covered = new Set(db.select().from(gaSyncCoverage).where(and78(
65184
- eq93(gaSyncCoverage.projectId, input.projectId),
65185
- eq93(gaSyncCoverage.propertyId, input.propertyId),
65186
- eq93(gaSyncCoverage.component, input.component),
65187
- eq93(gaSyncCoverage.definition, definition2)
65494
+ const covered = new Set(db.select().from(gaSyncCoverage).where(and79(
65495
+ eq94(gaSyncCoverage.projectId, input.projectId),
65496
+ eq94(gaSyncCoverage.propertyId, input.propertyId),
65497
+ eq94(gaSyncCoverage.component, input.component),
65498
+ eq94(gaSyncCoverage.definition, definition2)
65188
65499
  )).all().filter((row) => row.settled && row.syncedAt > reconcileAfter).map((row) => row.date));
65189
65500
  const missing = calendarDateRange(input.requested.startDate, input.requested.endDate).filter((date) => date >= refreshStart || !covered.has(date));
65190
65501
  return {
@@ -65213,8 +65524,8 @@ function saveGaSyncCoverage(tx, plan, ranges, syncedAt, syncRunId) {
65213
65524
  }).run();
65214
65525
  }
65215
65526
  }
65216
- tx.delete(gaSyncCoverage).where(and78(
65217
- eq93(gaSyncCoverage.projectId, plan.projectId),
65527
+ tx.delete(gaSyncCoverage).where(and79(
65528
+ eq94(gaSyncCoverage.projectId, plan.projectId),
65218
65529
  lt19(gaSyncCoverage.date, shiftIsoCalendarDate(plan.requested.endDate, -362))
65219
65530
  )).run();
65220
65531
  }
@@ -65228,11 +65539,11 @@ async function fetchGaSyncRanges(plan, fetchRange) {
65228
65539
 
65229
65540
  // ../api-routes/src/ga-search-landing-pages.ts
65230
65541
  import crypto55 from "crypto";
65231
- import { and as and79, asc as asc25, count as count7, desc as desc42, eq as eq94, gte as gte24, lte as lte24, sql as sql41 } from "drizzle-orm";
65542
+ import { and as and80, asc as asc25, count as count7, desc as desc42, eq as eq95, gte as gte24, lte as lte24, sql as sql42 } from "drizzle-orm";
65232
65543
  function searchLandingWindowsToFetch(db, projectId, propertyId, timeZone, requestedAt) {
65233
- const state = db.select().from(gaMeasurementSyncStates).where(eq94(gaMeasurementSyncStates.projectId, projectId)).get();
65544
+ const state = db.select().from(gaMeasurementSyncStates).where(eq95(gaMeasurementSyncStates.projectId, projectId)).get();
65234
65545
  if (!timeZone || state?.searchLandingStatus !== "ready") return [...GA_SEARCH_LANDING_WINDOWS];
65235
- const stored = db.select().from(gaSearchLandingWindows).where(eq94(gaSearchLandingWindows.projectId, projectId)).all();
65546
+ const stored = db.select().from(gaSearchLandingWindows).where(eq95(gaSearchLandingWindows.projectId, projectId)).all();
65236
65547
  const now = Date.parse(requestedAt);
65237
65548
  const end = isoDateDaysBeforeInTimeZone(requestedAt, 1, timeZone);
65238
65549
  return GA_SEARCH_LANDING_WINDOWS.filter((window2) => {
@@ -65250,16 +65561,16 @@ function persistSearchLandingSnapshot(db, input) {
65250
65561
  throw new Error("Search landing snapshots changed during sync; retry to refresh the missing windows");
65251
65562
  }
65252
65563
  }
65253
- const otherProperty = tx.select({ propertyId: gaSearchLandingWindows.propertyId }).from(gaSearchLandingWindows).where(eq94(gaSearchLandingWindows.projectId, input.projectId)).all().some((row) => row.propertyId !== input.propertyId);
65564
+ const otherProperty = tx.select({ propertyId: gaSearchLandingWindows.propertyId }).from(gaSearchLandingWindows).where(eq95(gaSearchLandingWindows.projectId, input.projectId)).all().some((row) => row.propertyId !== input.propertyId);
65254
65565
  if (otherProperty) deleteSearchLandingRows(tx, input.projectId);
65255
65566
  for (const window2 of input.windows) {
65256
- tx.delete(gaSearchLandingPages).where(and79(
65257
- eq94(gaSearchLandingPages.projectId, input.projectId),
65258
- eq94(gaSearchLandingPages.windowKey, window2.window)
65567
+ tx.delete(gaSearchLandingPages).where(and80(
65568
+ eq95(gaSearchLandingPages.projectId, input.projectId),
65569
+ eq95(gaSearchLandingPages.windowKey, window2.window)
65259
65570
  )).run();
65260
- tx.delete(gaSearchLandingWindows).where(and79(
65261
- eq94(gaSearchLandingWindows.projectId, input.projectId),
65262
- eq94(gaSearchLandingWindows.windowKey, window2.window)
65571
+ tx.delete(gaSearchLandingWindows).where(and80(
65572
+ eq95(gaSearchLandingWindows.projectId, input.projectId),
65573
+ eq95(gaSearchLandingWindows.windowKey, window2.window)
65263
65574
  )).run();
65264
65575
  tx.insert(gaSearchLandingWindows).values({
65265
65576
  id: crypto55.randomUUID(),
@@ -65321,7 +65632,7 @@ function persistSearchLandingSnapshot(db, input) {
65321
65632
  }
65322
65633
  function persistSearchLandingFailure(db, projectId, propertyId, status, message, attemptedAt) {
65323
65634
  db.transaction((tx) => {
65324
- const storedProperties = tx.selectDistinct({ propertyId: gaSearchLandingWindows.propertyId }).from(gaSearchLandingWindows).where(eq94(gaSearchLandingWindows.projectId, projectId)).all();
65635
+ const storedProperties = tx.selectDistinct({ propertyId: gaSearchLandingWindows.propertyId }).from(gaSearchLandingWindows).where(eq95(gaSearchLandingWindows.projectId, projectId)).all();
65325
65636
  const otherProperty = storedProperties.some((stored) => stored.propertyId !== propertyId);
65326
65637
  if (otherProperty) deleteSearchLandingRows(tx, projectId);
65327
65638
  upsertSearchLandingState(tx, projectId, {
@@ -65333,8 +65644,8 @@ function persistSearchLandingFailure(db, projectId, propertyId, status, message,
65333
65644
  });
65334
65645
  }
65335
65646
  function deleteSearchLandingRows(db, projectId) {
65336
- db.delete(gaSearchLandingPages).where(eq94(gaSearchLandingPages.projectId, projectId)).run();
65337
- db.delete(gaSearchLandingWindows).where(eq94(gaSearchLandingWindows.projectId, projectId)).run();
65647
+ db.delete(gaSearchLandingPages).where(eq95(gaSearchLandingPages.projectId, projectId)).run();
65648
+ db.delete(gaSearchLandingWindows).where(eq95(gaSearchLandingWindows.projectId, projectId)).run();
65338
65649
  }
65339
65650
  function upsertSearchLandingState(db, projectId, fields, updatedAt) {
65340
65651
  db.insert(gaMeasurementSyncStates).values({ projectId, ...fields, updatedAt }).onConflictDoUpdate({
@@ -65366,11 +65677,11 @@ function buildGaSearchLandingPages(db, projectName, query2, connections) {
65366
65677
  throw validationError('"offset" must be a non-negative integer');
65367
65678
  }
65368
65679
  const project = resolveProject(db, projectName);
65369
- const storedWindow = db.select().from(gaSearchLandingWindows).where(and79(eq94(gaSearchLandingWindows.projectId, project.id), eq94(gaSearchLandingWindows.windowKey, window2))).get();
65680
+ const storedWindow = db.select().from(gaSearchLandingWindows).where(and80(eq95(gaSearchLandingWindows.projectId, project.id), eq95(gaSearchLandingWindows.windowKey, window2))).get();
65370
65681
  const otherProperty = storedWindow !== void 0 && storedWindow.propertyId !== resolveCurrentGa4PropertyId(connections, project.name, project.canonicalDomain);
65371
65682
  const stored = otherProperty ? void 0 : storedWindow;
65372
- const state = otherProperty ? void 0 : db.select().from(gaMeasurementSyncStates).where(eq94(gaMeasurementSyncStates.projectId, project.id)).get();
65373
- const pageScope = and79(eq94(gaSearchLandingPages.projectId, project.id), eq94(gaSearchLandingPages.windowKey, window2));
65683
+ const state = otherProperty ? void 0 : db.select().from(gaMeasurementSyncStates).where(eq95(gaMeasurementSyncStates.projectId, project.id)).get();
65684
+ const pageScope = and80(eq95(gaSearchLandingPages.projectId, project.id), eq95(gaSearchLandingPages.windowKey, window2));
65374
65685
  const totalRows = otherProperty ? 0 : db.select({ value: count7() }).from(gaSearchLandingPages).where(pageScope).get()?.value ?? 0;
65375
65686
  const rows = otherProperty ? [] : db.select().from(gaSearchLandingPages).where(pageScope).orderBy(desc42(gaSearchLandingPages.clicks), desc42(gaSearchLandingPages.impressions), asc25(gaSearchLandingPages.landingPage)).limit(limit).offset(offset).all();
65376
65687
  const total = stored ? toWireMetrics({
@@ -65409,8 +65720,8 @@ function buildGaSearchLandingPages(db, projectName, query2, connections) {
65409
65720
  function searchConsoleLinkFor(db, projectId, total, windowStart, windowEnd) {
65410
65721
  const stored = db.select({
65411
65722
  days: count7(),
65412
- impressions: sql41`sum(${gscDailyTotals.impressions})`
65413
- }).from(gscDailyTotals).where(and79(eq94(gscDailyTotals.projectId, projectId), gte24(gscDailyTotals.date, windowStart), lte24(gscDailyTotals.date, windowEnd))).get();
65723
+ impressions: sql42`sum(${gscDailyTotals.impressions})`
65724
+ }).from(gscDailyTotals).where(and80(eq95(gscDailyTotals.projectId, projectId), gte24(gscDailyTotals.date, windowStart), lte24(gscDailyTotals.date, windowEnd))).get();
65414
65725
  const searchConsoleImpressions = stored && stored.days > 0 ? Number(stored.impressions ?? 0) : null;
65415
65726
  if (gaSearchLandingHasSearchData(total)) return { state: "has-data", searchConsoleImpressions };
65416
65727
  if (searchConsoleImpressions === null) return { state: "unknown", searchConsoleImpressions };
@@ -65495,17 +65806,17 @@ function aiReferralMonthlySeries(input) {
65495
65806
  }
65496
65807
  function dateRangeConditions(column, range) {
65497
65808
  const conditions = [];
65498
- if (range.startDate) conditions.push(sql42`${column} >= ${range.startDate}`);
65499
- if (range.endDate) conditions.push(sql42`${column} <= ${range.endDate}`);
65809
+ if (range.startDate) conditions.push(sql43`${column} >= ${range.startDate}`);
65810
+ if (range.endDate) conditions.push(sql43`${column} <= ${range.endDate}`);
65500
65811
  return conditions;
65501
65812
  }
65502
- var SOCIAL_CHANNEL_GROUPS2 = /* @__PURE__ */ new Set(["Organic Social", "Paid Social"]);
65813
+ var SOCIAL_CHANNEL_GROUPS3 = /* @__PURE__ */ new Set(["Organic Social", "Paid Social"]);
65503
65814
  function buildChannelBreakdown(input) {
65504
65815
  const aiSessions = [...input.aiSessionsByChannelGroup.values()].reduce((sum, sessions) => sum + sessions, 0);
65505
65816
  const aiOrganicOverlap = Math.min(input.organicSessions, input.aiSessionsByChannelGroup.get("Organic Search") ?? 0);
65506
65817
  const aiSocialOverlap = Math.min(
65507
65818
  input.socialSessions,
65508
- [...input.aiSessionsByChannelGroup.entries()].filter(([channelGroup]) => SOCIAL_CHANNEL_GROUPS2.has(channelGroup)).reduce((sum, [, sessions]) => sum + sessions, 0)
65819
+ [...input.aiSessionsByChannelGroup.entries()].filter(([channelGroup]) => SOCIAL_CHANNEL_GROUPS3.has(channelGroup)).reduce((sum, [, sessions]) => sum + sessions, 0)
65509
65820
  );
65510
65821
  const aiDirectOverlap = Math.min(input.directSessions, input.aiSessionsByChannelGroup.get("Direct") ?? 0);
65511
65822
  const organicSessions = Math.max(0, input.organicSessions - aiOrganicOverlap);
@@ -65554,10 +65865,10 @@ function keepWinningDimensionRows(rows, groupKey) {
65554
65865
  function persistAcquisitionMeasurement(db, input) {
65555
65866
  const { startDate, endDate } = input.report;
65556
65867
  db.transaction((tx) => {
65557
- tx.delete(gaAcquisitionDaily).where(and80(
65558
- eq95(gaAcquisitionDaily.projectId, input.projectId),
65559
- sql42`${gaAcquisitionDaily.date} >= ${startDate}`,
65560
- sql42`${gaAcquisitionDaily.date} <= ${endDate}`
65868
+ tx.delete(gaAcquisitionDaily).where(and81(
65869
+ eq96(gaAcquisitionDaily.projectId, input.projectId),
65870
+ sql43`${gaAcquisitionDaily.date} >= ${startDate}`,
65871
+ sql43`${gaAcquisitionDaily.date} <= ${endDate}`
65561
65872
  )).run();
65562
65873
  for (const row of input.report.rows) {
65563
65874
  tx.insert(gaAcquisitionDaily).values({
@@ -65596,10 +65907,10 @@ function persistAcquisitionMeasurement(db, input) {
65596
65907
  function persistLeadMeasurement(db, input) {
65597
65908
  const { startDate, endDate } = input.report;
65598
65909
  db.transaction((tx) => {
65599
- tx.delete(gaLeadEventsDaily).where(and80(
65600
- eq95(gaLeadEventsDaily.projectId, input.projectId),
65601
- sql42`${gaLeadEventsDaily.date} >= ${startDate}`,
65602
- sql42`${gaLeadEventsDaily.date} <= ${endDate}`
65910
+ tx.delete(gaLeadEventsDaily).where(and81(
65911
+ eq96(gaLeadEventsDaily.projectId, input.projectId),
65912
+ sql43`${gaLeadEventsDaily.date} >= ${startDate}`,
65913
+ sql43`${gaLeadEventsDaily.date} <= ${endDate}`
65603
65914
  )).run();
65604
65915
  for (const row of input.report.rows) {
65605
65916
  tx.insert(gaLeadEventsDaily).values({
@@ -65643,8 +65954,8 @@ function persistLeadMeasurement(db, input) {
65643
65954
  }
65644
65955
  function resetLeadMeasurement(db, projectId, updatedAt) {
65645
65956
  db.transaction((tx) => {
65646
- tx.delete(gaLeadEventsDaily).where(eq95(gaLeadEventsDaily.projectId, projectId)).run();
65647
- tx.delete(gaSyncCoverage).where(and80(eq95(gaSyncCoverage.projectId, projectId), eq95(gaSyncCoverage.component, "leads"))).run();
65957
+ tx.delete(gaLeadEventsDaily).where(eq96(gaLeadEventsDaily.projectId, projectId)).run();
65958
+ tx.delete(gaSyncCoverage).where(and81(eq96(gaSyncCoverage.projectId, projectId), eq96(gaSyncCoverage.component, "leads"))).run();
65648
65959
  tx.insert(gaMeasurementSyncStates).values({ projectId, leadStatus: "never-synced", leadError: null, leadSyncedAt: null, leadAttributionScope: null, leadEventNames: null, updatedAt }).onConflictDoUpdate({
65649
65960
  target: gaMeasurementSyncStates.projectId,
65650
65961
  set: { leadStatus: "never-synced", leadError: null, leadSyncedAt: null, leadAttributionScope: null, leadEventNames: null, updatedAt }
@@ -65986,7 +66297,7 @@ async function ga4Routes(app, opts) {
65986
66297
  if (!connected2) {
65987
66298
  return { connected: false, propertyId: null, clientEmail: null, authMethod: null, lastSyncedAt: null };
65988
66299
  }
65989
- const latestSync = app.db.select({ syncedAt: gaTrafficSummaries.syncedAt }).from(gaTrafficSummaries).where(eq95(gaTrafficSummaries.projectId, project.id)).orderBy(desc43(gaTrafficSummaries.syncedAt)).limit(1).get();
66300
+ const latestSync = app.db.select({ syncedAt: gaTrafficSummaries.syncedAt }).from(gaTrafficSummaries).where(eq96(gaTrafficSummaries.projectId, project.id)).orderBy(desc43(gaTrafficSummaries.syncedAt)).limit(1).get();
65990
66301
  return {
65991
66302
  connected: true,
65992
66303
  propertyId: saConn?.propertyId ?? oauthConn?.propertyId ?? null,
@@ -66009,7 +66320,7 @@ async function ga4Routes(app, opts) {
66009
66320
  const syncAi = !only || only === "ai";
66010
66321
  const syncSocial = !only || only === "social";
66011
66322
  const syncSearchLanding = !only || only === "search-landing";
66012
- const measurementState = app.db.select().from(gaMeasurementSyncStates).where(eq95(gaMeasurementSyncStates.projectId, project.id)).get();
66323
+ const measurementState = app.db.select().from(gaMeasurementSyncStates).where(eq96(gaMeasurementSyncStates.projectId, project.id)).get();
66013
66324
  const acquisitionDays = measurementState?.acquisitionSyncedAt != null ? days : GA4_MAX_SYNC_DAYS;
66014
66325
  let leadDays = GA4_MAX_SYNC_DAYS;
66015
66326
  let leadEventNames = [];
@@ -66105,10 +66416,10 @@ async function ga4Routes(app, opts) {
66105
66416
  if (syncTraffic) {
66106
66417
  for (const { range } of trafficReports) {
66107
66418
  tx.delete(gaTrafficSnapshots).where(
66108
- and80(
66109
- eq95(gaTrafficSnapshots.projectId, project.id),
66110
- sql42`${gaTrafficSnapshots.date} >= ${range.startDate}`,
66111
- sql42`${gaTrafficSnapshots.date} <= ${range.endDate}`
66419
+ and81(
66420
+ eq96(gaTrafficSnapshots.projectId, project.id),
66421
+ sql43`${gaTrafficSnapshots.date} >= ${range.startDate}`,
66422
+ sql43`${gaTrafficSnapshots.date} <= ${range.endDate}`
66112
66423
  )
66113
66424
  ).run();
66114
66425
  }
@@ -66130,10 +66441,10 @@ async function ga4Routes(app, opts) {
66130
66441
  }
66131
66442
  for (const { report } of dailyReports) {
66132
66443
  tx.delete(gaDailyTotals).where(
66133
- and80(
66134
- eq95(gaDailyTotals.projectId, project.id),
66135
- sql42`${gaDailyTotals.date} >= ${report.startDate}`,
66136
- sql42`${gaDailyTotals.date} <= ${report.endDate}`
66444
+ and81(
66445
+ eq96(gaDailyTotals.projectId, project.id),
66446
+ sql43`${gaDailyTotals.date} >= ${report.startDate}`,
66447
+ sql43`${gaDailyTotals.date} <= ${report.endDate}`
66137
66448
  )
66138
66449
  ).run();
66139
66450
  }
@@ -66162,7 +66473,7 @@ async function ga4Routes(app, opts) {
66162
66473
  createdAt: now
66163
66474
  }).run();
66164
66475
  }
66165
- tx.delete(gaWindowMetrics).where(eq95(gaWindowMetrics.projectId, project.id)).run();
66476
+ tx.delete(gaWindowMetrics).where(eq96(gaWindowMetrics.projectId, project.id)).run();
66166
66477
  for (const windowMetric of windowMetrics) {
66167
66478
  for (const [period2, totals] of [
66168
66479
  [GaOverviewPeriods.current, windowMetric.current],
@@ -66194,10 +66505,10 @@ async function ga4Routes(app, opts) {
66194
66505
  if (syncAi) {
66195
66506
  for (const { range } of aiReports) {
66196
66507
  tx.delete(gaAiReferrals).where(
66197
- and80(
66198
- eq95(gaAiReferrals.projectId, project.id),
66199
- sql42`${gaAiReferrals.date} >= ${range.startDate}`,
66200
- sql42`${gaAiReferrals.date} <= ${range.endDate}`
66508
+ and81(
66509
+ eq96(gaAiReferrals.projectId, project.id),
66510
+ sql43`${gaAiReferrals.date} >= ${range.startDate}`,
66511
+ sql43`${gaAiReferrals.date} <= ${range.endDate}`
66201
66512
  )
66202
66513
  ).run();
66203
66514
  }
@@ -66228,10 +66539,10 @@ async function ga4Routes(app, opts) {
66228
66539
  if (syncSocial) {
66229
66540
  for (const { range } of socialReports) {
66230
66541
  tx.delete(gaSocialReferrals).where(
66231
- and80(
66232
- eq95(gaSocialReferrals.projectId, project.id),
66233
- sql42`${gaSocialReferrals.date} >= ${range.startDate}`,
66234
- sql42`${gaSocialReferrals.date} <= ${range.endDate}`
66542
+ and81(
66543
+ eq96(gaSocialReferrals.projectId, project.id),
66544
+ sql43`${gaSocialReferrals.date} >= ${range.startDate}`,
66545
+ sql43`${gaSocialReferrals.date} <= ${range.endDate}`
66235
66546
  )
66236
66547
  ).run();
66237
66548
  }
@@ -66251,7 +66562,7 @@ async function ga4Routes(app, opts) {
66251
66562
  }
66252
66563
  }
66253
66564
  if (syncSummary) {
66254
- tx.delete(gaTrafficSummaries).where(eq95(gaTrafficSummaries.projectId, project.id)).run();
66565
+ tx.delete(gaTrafficSummaries).where(eq96(gaTrafficSummaries.projectId, project.id)).run();
66255
66566
  tx.insert(gaTrafficSummaries).values({
66256
66567
  id: crypto56.randomUUID(),
66257
66568
  projectId: project.id,
@@ -66263,7 +66574,7 @@ async function ga4Routes(app, opts) {
66263
66574
  syncedAt: now,
66264
66575
  syncRunId: runId
66265
66576
  }).run();
66266
- tx.delete(gaTrafficWindowSummaries).where(eq95(gaTrafficWindowSummaries.projectId, project.id)).run();
66577
+ tx.delete(gaTrafficWindowSummaries).where(eq96(gaTrafficWindowSummaries.projectId, project.id)).run();
66267
66578
  for (const ws of windowSummaries) {
66268
66579
  tx.insert(gaTrafficWindowSummaries).values({
66269
66580
  id: crypto56.randomUUID(),
@@ -66415,7 +66726,7 @@ async function ga4Routes(app, opts) {
66415
66726
  return recordSearchLandingFailure("error", error);
66416
66727
  }
66417
66728
  })();
66418
- app.db.update(runs).set({ status: RunStatuses.completed, finishedAt: measurementNow }).where(eq95(runs.id, runId)).run();
66729
+ app.db.update(runs).set({ status: RunStatuses.completed, finishedAt: measurementNow }).where(eq96(runs.id, runId)).run();
66419
66730
  const syncedComponents = only ? [
66420
66731
  ...syncTraffic ? ["traffic"] : [],
66421
66732
  ...syncSummary ? ["summary"] : [],
@@ -66461,7 +66772,7 @@ async function ga4Routes(app, opts) {
66461
66772
  } catch (e) {
66462
66773
  const msg = describeError(e);
66463
66774
  gaLog("error", "sync.fetch-failed", { projectId: project.id, runId, error: msg });
66464
- app.db.update(runs).set({ status: RunStatuses.failed, error: msg, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq95(runs.id, runId)).run();
66775
+ app.db.update(runs).set({ status: RunStatuses.failed, error: msg, finishedAt: (/* @__PURE__ */ new Date()).toISOString() }).where(eq96(runs.id, runId)).run();
66465
66776
  outcome2.report({ status: OutcomeStatuses.failed, ...ga4SyncFailure(e, credentialsResolved, opts, project) });
66466
66777
  throw e;
66467
66778
  }
@@ -66479,9 +66790,9 @@ async function ga4Routes(app, opts) {
66479
66790
  totalDirectSessions: gaTrafficWindowSummaries.totalDirectSessions,
66480
66791
  totalUsers: gaTrafficWindowSummaries.totalUsers
66481
66792
  }).from(gaTrafficWindowSummaries).where(
66482
- and80(
66483
- eq95(gaTrafficWindowSummaries.projectId, project.id),
66484
- eq95(gaTrafficWindowSummaries.windowKey, range.window)
66793
+ and81(
66794
+ eq96(gaTrafficWindowSummaries.projectId, project.id),
66795
+ eq96(gaTrafficWindowSummaries.windowKey, range.window)
66485
66796
  )
66486
66797
  ).get() : null;
66487
66798
  const projectSummaryRow = app.db.select({
@@ -66490,11 +66801,11 @@ async function ga4Routes(app, opts) {
66490
66801
  totalSessions: gaTrafficSummaries.totalSessions,
66491
66802
  totalOrganicSessions: gaTrafficSummaries.totalOrganicSessions,
66492
66803
  totalUsers: gaTrafficSummaries.totalUsers
66493
- }).from(gaTrafficSummaries).where(eq95(gaTrafficSummaries.projectId, project.id)).get();
66804
+ }).from(gaTrafficSummaries).where(eq96(gaTrafficSummaries.projectId, project.id)).get();
66494
66805
  const retainedBounds = [
66495
- app.db.select({ min: sql42`MIN(${gaTrafficSnapshots.date})`, max: sql42`MAX(${gaTrafficSnapshots.date})` }).from(gaTrafficSnapshots).where(eq95(gaTrafficSnapshots.projectId, project.id)).get(),
66496
- app.db.select({ min: sql42`MIN(${gaAiReferrals.date})`, max: sql42`MAX(${gaAiReferrals.date})` }).from(gaAiReferrals).where(eq95(gaAiReferrals.projectId, project.id)).get(),
66497
- app.db.select({ min: sql42`MIN(${gaSocialReferrals.date})`, max: sql42`MAX(${gaSocialReferrals.date})` }).from(gaSocialReferrals).where(eq95(gaSocialReferrals.projectId, project.id)).get()
66806
+ app.db.select({ min: sql43`MIN(${gaTrafficSnapshots.date})`, max: sql43`MAX(${gaTrafficSnapshots.date})` }).from(gaTrafficSnapshots).where(eq96(gaTrafficSnapshots.projectId, project.id)).get(),
66807
+ app.db.select({ min: sql43`MIN(${gaAiReferrals.date})`, max: sql43`MAX(${gaAiReferrals.date})` }).from(gaAiReferrals).where(eq96(gaAiReferrals.projectId, project.id)).get(),
66808
+ app.db.select({ min: sql43`MIN(${gaSocialReferrals.date})`, max: sql43`MAX(${gaSocialReferrals.date})` }).from(gaSocialReferrals).where(eq96(gaSocialReferrals.projectId, project.id)).get()
66498
66809
  ];
66499
66810
  const retainedDates = retainedBounds.flatMap((bound) => [bound?.min, bound?.max]).filter((date) => Boolean(date));
66500
66811
  const projectSummaryCoversAll = Boolean(
@@ -66503,15 +66814,15 @@ async function ga4Routes(app, opts) {
66503
66814
  const denominatorRow = windowSummaryRow ?? (range.window === "all" && projectSummaryCoversAll ? projectSummaryRow : null);
66504
66815
  const denominatorPeriod = denominatorRow?.periodStart && denominatorRow.periodEnd ? { startDate: denominatorRow.periodStart, endDate: denominatorRow.periodEnd } : null;
66505
66816
  const measuredRange = denominatorPeriod ? { ...range, ...denominatorPeriod } : range;
66506
- const snapshotConditions = [eq95(gaTrafficSnapshots.projectId, project.id), ...dateRangeConditions(gaTrafficSnapshots.date, measuredRange)];
66507
- const aiConditions = [eq95(gaAiReferrals.projectId, project.id), ...dateRangeConditions(gaAiReferrals.date, measuredRange)];
66508
- const socialConditions = [eq95(gaSocialReferrals.projectId, project.id), ...dateRangeConditions(gaSocialReferrals.date, measuredRange)];
66817
+ const snapshotConditions = [eq96(gaTrafficSnapshots.projectId, project.id), ...dateRangeConditions(gaTrafficSnapshots.date, measuredRange)];
66818
+ const aiConditions = [eq96(gaAiReferrals.projectId, project.id), ...dateRangeConditions(gaAiReferrals.date, measuredRange)];
66819
+ const socialConditions = [eq96(gaSocialReferrals.projectId, project.id), ...dateRangeConditions(gaSocialReferrals.date, measuredRange)];
66509
66820
  const snapshotTotalsRow = !denominatorRow ? (() => {
66510
66821
  const summed = app.db.select({
66511
- totalSessions: sql42`COALESCE(SUM(${gaTrafficSnapshots.sessions}), 0)`,
66512
- totalOrganicSessions: sql42`COALESCE(SUM(${gaTrafficSnapshots.organicSessions}), 0)`,
66513
- totalUsers: sql42`COALESCE(SUM(${gaTrafficSnapshots.users}), 0)`
66514
- }).from(gaTrafficSnapshots).where(and80(...snapshotConditions)).get();
66822
+ totalSessions: sql43`COALESCE(SUM(${gaTrafficSnapshots.sessions}), 0)`,
66823
+ totalOrganicSessions: sql43`COALESCE(SUM(${gaTrafficSnapshots.organicSessions}), 0)`,
66824
+ totalUsers: sql43`COALESCE(SUM(${gaTrafficSnapshots.users}), 0)`
66825
+ }).from(gaTrafficSnapshots).where(and81(...snapshotConditions)).get();
66515
66826
  return {
66516
66827
  totalSessions: summed?.totalSessions ?? 0,
66517
66828
  totalOrganicSessions: summed?.totalOrganicSessions ?? 0,
@@ -66523,35 +66834,35 @@ async function ga4Routes(app, opts) {
66523
66834
  })() : null;
66524
66835
  const summaryRow = denominatorRow ?? snapshotTotalsRow;
66525
66836
  const directTotalRow = windowSummaryRow ? { totalDirectSessions: windowSummaryRow.totalDirectSessions } : app.db.select({
66526
- totalDirectSessions: sql42`COALESCE(SUM(${gaTrafficSnapshots.directSessions}), 0)`
66527
- }).from(gaTrafficSnapshots).where(and80(...snapshotConditions)).get();
66837
+ totalDirectSessions: sql43`COALESCE(SUM(${gaTrafficSnapshots.directSessions}), 0)`
66838
+ }).from(gaTrafficSnapshots).where(and81(...snapshotConditions)).get();
66528
66839
  const rows = app.db.select({
66529
- landingPage: sql42`COALESCE(${gaTrafficSnapshots.landingPageNormalized}, ${gaTrafficSnapshots.landingPage})`,
66530
- sessions: sql42`SUM(${gaTrafficSnapshots.sessions})`,
66531
- organicSessions: sql42`SUM(${gaTrafficSnapshots.organicSessions})`,
66532
- directSessions: sql42`COALESCE(SUM(${gaTrafficSnapshots.directSessions}), 0)`,
66533
- users: sql42`SUM(${gaTrafficSnapshots.users})`
66534
- }).from(gaTrafficSnapshots).where(and80(...snapshotConditions)).groupBy(sql42`COALESCE(${gaTrafficSnapshots.landingPageNormalized}, ${gaTrafficSnapshots.landingPage})`).orderBy(sql42`SUM(${gaTrafficSnapshots.sessions}) DESC`).limit(limit).all();
66840
+ landingPage: sql43`COALESCE(${gaTrafficSnapshots.landingPageNormalized}, ${gaTrafficSnapshots.landingPage})`,
66841
+ sessions: sql43`SUM(${gaTrafficSnapshots.sessions})`,
66842
+ organicSessions: sql43`SUM(${gaTrafficSnapshots.organicSessions})`,
66843
+ directSessions: sql43`COALESCE(SUM(${gaTrafficSnapshots.directSessions}), 0)`,
66844
+ users: sql43`SUM(${gaTrafficSnapshots.users})`
66845
+ }).from(gaTrafficSnapshots).where(and81(...snapshotConditions)).groupBy(sql43`COALESCE(${gaTrafficSnapshots.landingPageNormalized}, ${gaTrafficSnapshots.landingPage})`).orderBy(sql43`SUM(${gaTrafficSnapshots.sessions}) DESC`).limit(limit).all();
66535
66846
  const aiReferralRows = app.db.select({
66536
66847
  source: gaAiReferrals.source,
66537
66848
  medium: gaAiReferrals.medium,
66538
66849
  trafficClass: gaAiReferrals.trafficClass,
66539
66850
  sourceDimension: gaAiReferrals.sourceDimension,
66540
- sessions: sql42`SUM(${gaAiReferrals.sessions})`
66541
- }).from(gaAiReferrals).where(and80(...aiConditions)).groupBy(gaAiReferrals.source, gaAiReferrals.medium, gaAiReferrals.trafficClass, gaAiReferrals.sourceDimension).all();
66851
+ sessions: sql43`SUM(${gaAiReferrals.sessions})`
66852
+ }).from(gaAiReferrals).where(and81(...aiConditions)).groupBy(gaAiReferrals.source, gaAiReferrals.medium, gaAiReferrals.trafficClass, gaAiReferrals.sourceDimension).all();
66542
66853
  const aiReferralLandingPageRows = app.db.select({
66543
66854
  source: gaAiReferrals.source,
66544
66855
  medium: gaAiReferrals.medium,
66545
66856
  trafficClass: gaAiReferrals.trafficClass,
66546
66857
  sourceDimension: gaAiReferrals.sourceDimension,
66547
- landingPage: sql42`COALESCE(${gaAiReferrals.landingPageNormalized}, ${gaAiReferrals.landingPage})`,
66548
- sessions: sql42`SUM(${gaAiReferrals.sessions})`
66549
- }).from(gaAiReferrals).where(and80(...aiConditions)).groupBy(
66858
+ landingPage: sql43`COALESCE(${gaAiReferrals.landingPageNormalized}, ${gaAiReferrals.landingPage})`,
66859
+ sessions: sql43`SUM(${gaAiReferrals.sessions})`
66860
+ }).from(gaAiReferrals).where(and81(...aiConditions)).groupBy(
66550
66861
  gaAiReferrals.source,
66551
66862
  gaAiReferrals.medium,
66552
66863
  gaAiReferrals.trafficClass,
66553
66864
  gaAiReferrals.sourceDimension,
66554
- sql42`COALESCE(${gaAiReferrals.landingPageNormalized}, ${gaAiReferrals.landingPage})`
66865
+ sql43`COALESCE(${gaAiReferrals.landingPageNormalized}, ${gaAiReferrals.landingPage})`
66555
66866
  ).all();
66556
66867
  const aiRowsForTotals = app.db.select({
66557
66868
  date: gaAiReferrals.date,
@@ -66561,7 +66872,7 @@ async function ga4Routes(app, opts) {
66561
66872
  sourceDimension: gaAiReferrals.sourceDimension,
66562
66873
  channelGroup: gaAiReferrals.channelGroup,
66563
66874
  sessions: gaAiReferrals.sessions
66564
- }).from(gaAiReferrals).where(and80(...aiConditions)).all();
66875
+ }).from(gaAiReferrals).where(and81(...aiConditions)).all();
66565
66876
  const aiReferrals = keepWinningDimensionRows(aiReferralRows, (r) => r.source);
66566
66877
  const aiReferralLandingPages = keepWinningDimensionRows(
66567
66878
  aiReferralLandingPageRows,
@@ -66577,17 +66888,17 @@ async function ga4Routes(app, opts) {
66577
66888
  // is GA's COUNT DISTINCT at that grain, so summing over the window's
66578
66889
  // dates counts a returning visitor once per day they returned. Same
66579
66890
  // conclusion the AI-referral surfaces reached in 4.135.0.
66580
- sessions: sql42`SUM(${gaSocialReferrals.sessions})`
66581
- }).from(gaSocialReferrals).where(and80(...socialConditions)).groupBy(gaSocialReferrals.source, gaSocialReferrals.medium, gaSocialReferrals.channelGroup).orderBy(sql42`SUM(${gaSocialReferrals.sessions}) DESC`).all();
66891
+ sessions: sql43`SUM(${gaSocialReferrals.sessions})`
66892
+ }).from(gaSocialReferrals).where(and81(...socialConditions)).groupBy(gaSocialReferrals.source, gaSocialReferrals.medium, gaSocialReferrals.channelGroup).orderBy(sql43`SUM(${gaSocialReferrals.sessions}) DESC`).all();
66582
66893
  const socialDailyRows = app.db.select({
66583
66894
  date: gaSocialReferrals.date,
66584
66895
  source: gaSocialReferrals.source,
66585
- sessions: sql42`SUM(${gaSocialReferrals.sessions})`
66586
- }).from(gaSocialReferrals).where(and80(...socialConditions)).groupBy(gaSocialReferrals.date, gaSocialReferrals.source).all();
66896
+ sessions: sql43`SUM(${gaSocialReferrals.sessions})`
66897
+ }).from(gaSocialReferrals).where(and81(...socialConditions)).groupBy(gaSocialReferrals.date, gaSocialReferrals.source).all();
66587
66898
  const socialTotals = app.db.select({
66588
- sessions: sql42`SUM(${gaSocialReferrals.sessions})`
66589
- }).from(gaSocialReferrals).where(and80(...socialConditions)).get();
66590
- const latestSync = app.db.select({ syncedAt: gaTrafficSummaries.syncedAt }).from(gaTrafficSummaries).where(eq95(gaTrafficSummaries.projectId, project.id)).orderBy(desc43(gaTrafficSummaries.syncedAt)).limit(1).get();
66899
+ sessions: sql43`SUM(${gaSocialReferrals.sessions})`
66900
+ }).from(gaSocialReferrals).where(and81(...socialConditions)).get();
66901
+ const latestSync = app.db.select({ syncedAt: gaTrafficSummaries.syncedAt }).from(gaTrafficSummaries).where(eq96(gaTrafficSummaries.projectId, project.id)).orderBy(desc43(gaTrafficSummaries.syncedAt)).limit(1).get();
66591
66902
  const total = summaryRow?.totalSessions ?? 0;
66592
66903
  const totalDirectSessions = directTotalRow?.totalDirectSessions ?? 0;
66593
66904
  const totalOrganicSessions = summaryRow?.totalOrganicSessions ?? 0;
@@ -66615,6 +66926,12 @@ async function ga4Routes(app, opts) {
66615
66926
  channelGroup: r.channelGroup,
66616
66927
  sessions: r.sessions ?? 0
66617
66928
  })));
66929
+ const socialPlatformPerformance = loadSocialPlatformPerformance(app.db, {
66930
+ projectId: project.id,
66931
+ measurement: project.measurement,
66932
+ dateConditions: (column) => dateRangeConditions(column, measuredRange),
66933
+ totalSessions: total
66934
+ });
66618
66935
  return {
66619
66936
  totalSessions: total,
66620
66937
  totalOrganicSessions,
@@ -66665,6 +66982,7 @@ async function ga4Routes(app, opts) {
66665
66982
  source: r.source,
66666
66983
  sessions: r.sessions ?? 0
66667
66984
  }))),
66985
+ socialPlatformPerformance,
66668
66986
  socialSessions,
66669
66987
  ...paidSocialSummary(socialReferralDtos),
66670
66988
  channelBreakdown,
@@ -66709,26 +67027,26 @@ async function ga4Routes(app, opts) {
66709
67027
  const project = resolveProject(app.db, request.params.name);
66710
67028
  requireGa4Connection(opts, project.name, project.canonicalDomain);
66711
67029
  const range = resolveDateRange(request.query, WINDOW_SETS.gaTraffic);
66712
- const conditions = [eq95(gaAiReferrals.projectId, project.id), ...dateRangeConditions(gaAiReferrals.date, range)];
67030
+ const conditions = [eq96(gaAiReferrals.projectId, project.id), ...dateRangeConditions(gaAiReferrals.date, range)];
66713
67031
  const rows = app.db.select({
66714
67032
  date: gaAiReferrals.date,
66715
67033
  source: gaAiReferrals.source,
66716
67034
  medium: gaAiReferrals.medium,
66717
67035
  trafficClass: gaAiReferrals.trafficClass,
66718
- landingPage: sql42`COALESCE(${gaAiReferrals.landingPageNormalized}, ${gaAiReferrals.landingPage})`,
67036
+ landingPage: sql43`COALESCE(${gaAiReferrals.landingPageNormalized}, ${gaAiReferrals.landingPage})`,
66719
67037
  sourceDimension: gaAiReferrals.sourceDimension,
66720
67038
  // No `users`: ga-ai-referral-aggregation states the rule for this
66721
67039
  // table, that there is no grain at which the stored users column may be
66722
67040
  // added up. ga4AiReferralDtoSchema.users was deprecated for this in
66723
67041
  // 4.135.0; the history endpoint kept emitting one.
66724
- sessions: sql42`SUM(${gaAiReferrals.sessions})`
66725
- }).from(gaAiReferrals).where(and80(...conditions)).groupBy(
67042
+ sessions: sql43`SUM(${gaAiReferrals.sessions})`
67043
+ }).from(gaAiReferrals).where(and81(...conditions)).groupBy(
66726
67044
  gaAiReferrals.date,
66727
67045
  gaAiReferrals.source,
66728
67046
  gaAiReferrals.medium,
66729
67047
  gaAiReferrals.trafficClass,
66730
67048
  gaAiReferrals.sourceDimension,
66731
- sql42`COALESCE(${gaAiReferrals.landingPageNormalized}, ${gaAiReferrals.landingPage})`
67049
+ sql43`COALESCE(${gaAiReferrals.landingPageNormalized}, ${gaAiReferrals.landingPage})`
66732
67050
  ).orderBy(gaAiReferrals.date).all();
66733
67051
  return rows;
66734
67052
  });
@@ -66736,7 +67054,7 @@ async function ga4Routes(app, opts) {
66736
67054
  const project = resolveProject(app.db, request.params.name);
66737
67055
  requireGa4Connection(opts, project.name, project.canonicalDomain);
66738
67056
  const range = resolveDateRange(request.query, WINDOW_SETS.gaTraffic);
66739
- const conditions = [eq95(gaAiReferrals.projectId, project.id), ...dateRangeConditions(gaAiReferrals.date, range)];
67057
+ const conditions = [eq96(gaAiReferrals.projectId, project.id), ...dateRangeConditions(gaAiReferrals.date, range)];
66740
67058
  const rows = app.db.select({
66741
67059
  date: gaAiReferrals.date,
66742
67060
  source: gaAiReferrals.source,
@@ -66745,13 +67063,13 @@ async function ga4Routes(app, opts) {
66745
67063
  sourceDimension: gaAiReferrals.sourceDimension,
66746
67064
  channelGroup: gaAiReferrals.channelGroup,
66747
67065
  sessions: gaAiReferrals.sessions
66748
- }).from(gaAiReferrals).where(and80(...conditions)).all();
67066
+ }).from(gaAiReferrals).where(and81(...conditions)).all();
66749
67067
  const series = buildAiReferralDailySeries(rows);
66750
- const measuredDates = app.db.selectDistinct({ date: gaDailyTotals.date }).from(gaDailyTotals).where(and80(eq95(gaDailyTotals.projectId, project.id), ...dateRangeConditions(gaDailyTotals.date, range))).all().map((row) => row.date);
66751
- const firstAiDate = app.db.select({ date: sql42`MIN(${gaAiReferrals.date})` }).from(gaAiReferrals).where(eq95(gaAiReferrals.projectId, project.id)).get()?.date ?? null;
66752
- const firstReceipts = new Map(app.db.select({ component: gaSyncCoverage.component, date: sql42`MIN(${gaSyncCoverage.date})` }).from(gaSyncCoverage).where(and80(eq95(gaSyncCoverage.projectId, project.id), inArray45(gaSyncCoverage.component, ["ai", "traffic"]))).groupBy(gaSyncCoverage.component).all().map((row) => [row.component, row.date]));
67068
+ const measuredDates = app.db.selectDistinct({ date: gaDailyTotals.date }).from(gaDailyTotals).where(and81(eq96(gaDailyTotals.projectId, project.id), ...dateRangeConditions(gaDailyTotals.date, range))).all().map((row) => row.date);
67069
+ const firstAiDate = app.db.select({ date: sql43`MIN(${gaAiReferrals.date})` }).from(gaAiReferrals).where(eq96(gaAiReferrals.projectId, project.id)).get()?.date ?? null;
67070
+ const firstReceipts = new Map(app.db.select({ component: gaSyncCoverage.component, date: sql43`MIN(${gaSyncCoverage.date})` }).from(gaSyncCoverage).where(and81(eq96(gaSyncCoverage.projectId, project.id), inArray46(gaSyncCoverage.component, ["ai", "traffic"]))).groupBy(gaSyncCoverage.component).all().map((row) => [row.component, row.date]));
66753
67071
  const firstTrafficReceipt = firstReceipts.get("traffic") ?? null;
66754
- const firstTrafficDate = app.db.select({ date: sql42`MIN(${gaTrafficSnapshots.date})` }).from(gaTrafficSnapshots).where(eq95(gaTrafficSnapshots.projectId, project.id)).get()?.date ?? null;
67072
+ const firstTrafficDate = app.db.select({ date: sql43`MIN(${gaTrafficSnapshots.date})` }).from(gaTrafficSnapshots).where(eq96(gaTrafficSnapshots.projectId, project.id)).get()?.date ?? null;
66755
67073
  const trafficBeforeReceipts = firstTrafficDate !== null && (firstTrafficReceipt === null || firstTrafficDate < firstTrafficReceipt) ? firstTrafficDate : null;
66756
67074
  const aiCoverageStart = [firstReceipts.get("ai") ?? null, trafficBeforeReceipts, firstAiDate].filter((date) => date !== null).sort()[0] ?? null;
66757
67075
  const now = /* @__PURE__ */ new Date();
@@ -66765,7 +67083,7 @@ async function ga4Routes(app, opts) {
66765
67083
  const project = resolveProject(app.db, request.params.name);
66766
67084
  requireGa4Connection(opts, project.name, project.canonicalDomain);
66767
67085
  const range = resolveDateRange(request.query, WINDOW_SETS.gaTraffic);
66768
- const conditions = [eq95(gaSocialReferrals.projectId, project.id), ...dateRangeConditions(gaSocialReferrals.date, range)];
67086
+ const conditions = [eq96(gaSocialReferrals.projectId, project.id), ...dateRangeConditions(gaSocialReferrals.date, range)];
66769
67087
  const rows = app.db.select({
66770
67088
  date: gaSocialReferrals.date,
66771
67089
  source: gaSocialReferrals.source,
@@ -66773,7 +67091,7 @@ async function ga4Routes(app, opts) {
66773
67091
  channelGroup: gaSocialReferrals.channelGroup,
66774
67092
  sessions: gaSocialReferrals.sessions,
66775
67093
  users: gaSocialReferrals.users
66776
- }).from(gaSocialReferrals).where(and80(...conditions)).orderBy(gaSocialReferrals.date).all();
67094
+ }).from(gaSocialReferrals).where(and81(...conditions)).orderBy(gaSocialReferrals.date).all();
66777
67095
  return rows;
66778
67096
  });
66779
67097
  app.get("/projects/:name/ga/social-referral-trend", async (request, _reply) => {
@@ -66786,10 +67104,10 @@ async function ga4Routes(app, opts) {
66786
67104
  d.setDate(d.getDate() - n);
66787
67105
  return fmt(d);
66788
67106
  };
66789
- const sumSocial = (from, to) => app.db.select({ sessions: sql42`COALESCE(SUM(${gaSocialReferrals.sessions}), 0)` }).from(gaSocialReferrals).where(and80(
66790
- eq95(gaSocialReferrals.projectId, project.id),
66791
- sql42`${gaSocialReferrals.date} >= ${from}`,
66792
- sql42`${gaSocialReferrals.date} < ${to}`
67107
+ const sumSocial = (from, to) => app.db.select({ sessions: sql43`COALESCE(SUM(${gaSocialReferrals.sessions}), 0)` }).from(gaSocialReferrals).where(and81(
67108
+ eq96(gaSocialReferrals.projectId, project.id),
67109
+ sql43`${gaSocialReferrals.date} >= ${from}`,
67110
+ sql43`${gaSocialReferrals.date} < ${to}`
66793
67111
  )).get();
66794
67112
  const current7d = sumSocial(daysAgo(7), fmt(today));
66795
67113
  const prev7d = sumSocial(daysAgo(14), daysAgo(7));
@@ -66797,19 +67115,19 @@ async function ga4Routes(app, opts) {
66797
67115
  const prev30d = sumSocial(daysAgo(60), daysAgo(30));
66798
67116
  const sourceCurrent = app.db.select({
66799
67117
  source: gaSocialReferrals.source,
66800
- sessions: sql42`SUM(${gaSocialReferrals.sessions})`
66801
- }).from(gaSocialReferrals).where(and80(
66802
- eq95(gaSocialReferrals.projectId, project.id),
66803
- sql42`${gaSocialReferrals.date} >= ${daysAgo(7)}`,
66804
- sql42`${gaSocialReferrals.date} < ${fmt(today)}`
67118
+ sessions: sql43`SUM(${gaSocialReferrals.sessions})`
67119
+ }).from(gaSocialReferrals).where(and81(
67120
+ eq96(gaSocialReferrals.projectId, project.id),
67121
+ sql43`${gaSocialReferrals.date} >= ${daysAgo(7)}`,
67122
+ sql43`${gaSocialReferrals.date} < ${fmt(today)}`
66805
67123
  )).groupBy(gaSocialReferrals.source).all();
66806
67124
  const sourcePrev = app.db.select({
66807
67125
  source: gaSocialReferrals.source,
66808
- sessions: sql42`SUM(${gaSocialReferrals.sessions})`
66809
- }).from(gaSocialReferrals).where(and80(
66810
- eq95(gaSocialReferrals.projectId, project.id),
66811
- sql42`${gaSocialReferrals.date} >= ${daysAgo(14)}`,
66812
- sql42`${gaSocialReferrals.date} < ${daysAgo(7)}`
67126
+ sessions: sql43`SUM(${gaSocialReferrals.sessions})`
67127
+ }).from(gaSocialReferrals).where(and81(
67128
+ eq96(gaSocialReferrals.projectId, project.id),
67129
+ sql43`${gaSocialReferrals.date} >= ${daysAgo(14)}`,
67130
+ sql43`${gaSocialReferrals.date} < ${daysAgo(7)}`
66813
67131
  )).groupBy(gaSocialReferrals.source).all();
66814
67132
  const response = {
66815
67133
  socialSessions7d: current7d?.sessions ?? 0,
@@ -66832,16 +67150,16 @@ async function ga4Routes(app, opts) {
66832
67150
  d.setDate(d.getDate() - n);
66833
67151
  return fmt(d);
66834
67152
  };
66835
- const sumTotal = (from, to) => app.db.select({ sessions: sql42`COALESCE(SUM(${gaTrafficSnapshots.sessions}), 0)` }).from(gaTrafficSnapshots).where(and80(eq95(gaTrafficSnapshots.projectId, project.id), sql42`${gaTrafficSnapshots.date} >= ${from}`, sql42`${gaTrafficSnapshots.date} < ${to}`)).get();
66836
- const sumOrganic = (from, to) => app.db.select({ sessions: sql42`COALESCE(SUM(${gaTrafficSnapshots.organicSessions}), 0)` }).from(gaTrafficSnapshots).where(and80(eq95(gaTrafficSnapshots.projectId, project.id), sql42`${gaTrafficSnapshots.date} >= ${from}`, sql42`${gaTrafficSnapshots.date} < ${to}`)).get();
66837
- const sumDirect = (from, to) => app.db.select({ sessions: sql42`COALESCE(SUM(${gaTrafficSnapshots.directSessions}), 0)` }).from(gaTrafficSnapshots).where(and80(eq95(gaTrafficSnapshots.projectId, project.id), sql42`${gaTrafficSnapshots.date} >= ${from}`, sql42`${gaTrafficSnapshots.date} < ${to}`)).get();
66838
- const sumAi = (from, to) => app.db.select({ sessions: sql42`COALESCE(SUM(${gaAiReferrals.sessions}), 0)` }).from(gaAiReferrals).where(and80(
66839
- eq95(gaAiReferrals.projectId, project.id),
66840
- sql42`${gaAiReferrals.date} >= ${from}`,
66841
- sql42`${gaAiReferrals.date} < ${to}`,
66842
- eq95(gaAiReferrals.sourceDimension, "session")
67153
+ const sumTotal = (from, to) => app.db.select({ sessions: sql43`COALESCE(SUM(${gaTrafficSnapshots.sessions}), 0)` }).from(gaTrafficSnapshots).where(and81(eq96(gaTrafficSnapshots.projectId, project.id), sql43`${gaTrafficSnapshots.date} >= ${from}`, sql43`${gaTrafficSnapshots.date} < ${to}`)).get();
67154
+ const sumOrganic = (from, to) => app.db.select({ sessions: sql43`COALESCE(SUM(${gaTrafficSnapshots.organicSessions}), 0)` }).from(gaTrafficSnapshots).where(and81(eq96(gaTrafficSnapshots.projectId, project.id), sql43`${gaTrafficSnapshots.date} >= ${from}`, sql43`${gaTrafficSnapshots.date} < ${to}`)).get();
67155
+ const sumDirect = (from, to) => app.db.select({ sessions: sql43`COALESCE(SUM(${gaTrafficSnapshots.directSessions}), 0)` }).from(gaTrafficSnapshots).where(and81(eq96(gaTrafficSnapshots.projectId, project.id), sql43`${gaTrafficSnapshots.date} >= ${from}`, sql43`${gaTrafficSnapshots.date} < ${to}`)).get();
67156
+ const sumAi = (from, to) => app.db.select({ sessions: sql43`COALESCE(SUM(${gaAiReferrals.sessions}), 0)` }).from(gaAiReferrals).where(and81(
67157
+ eq96(gaAiReferrals.projectId, project.id),
67158
+ sql43`${gaAiReferrals.date} >= ${from}`,
67159
+ sql43`${gaAiReferrals.date} < ${to}`,
67160
+ eq96(gaAiReferrals.sourceDimension, "session")
66843
67161
  )).get();
66844
- const sumSocial = (from, to) => app.db.select({ sessions: sql42`COALESCE(SUM(${gaSocialReferrals.sessions}), 0)` }).from(gaSocialReferrals).where(and80(eq95(gaSocialReferrals.projectId, project.id), sql42`${gaSocialReferrals.date} >= ${from}`, sql42`${gaSocialReferrals.date} < ${to}`)).get();
67162
+ const sumSocial = (from, to) => app.db.select({ sessions: sql43`COALESCE(SUM(${gaSocialReferrals.sessions}), 0)` }).from(gaSocialReferrals).where(and81(eq96(gaSocialReferrals.projectId, project.id), sql43`${gaSocialReferrals.date} >= ${from}`, sql43`${gaSocialReferrals.date} < ${to}`)).get();
66845
67163
  const todayStr = fmt(today);
66846
67164
  const buildTrend = (sum) => {
66847
67165
  const c7 = sum(daysAgo(7), todayStr)?.sessions ?? 0;
@@ -66850,20 +67168,20 @@ async function ga4Routes(app, opts) {
66850
67168
  const p30 = sum(daysAgo(60), daysAgo(30))?.sessions ?? 0;
66851
67169
  return { sessions7d: c7, sessionsPrev7d: p7, trend7dPct: deltaPercent(c7, p7), sessions30d: c30, sessionsPrev30d: p30, trend30dPct: deltaPercent(c30, p30) };
66852
67170
  };
66853
- const aiSourceCurrent = app.db.select({ source: gaAiReferrals.source, sessions: sql42`COALESCE(SUM(${gaAiReferrals.sessions}), 0)` }).from(gaAiReferrals).where(and80(
66854
- eq95(gaAiReferrals.projectId, project.id),
66855
- sql42`${gaAiReferrals.date} >= ${daysAgo(7)}`,
66856
- sql42`${gaAiReferrals.date} < ${todayStr}`,
66857
- eq95(gaAiReferrals.sourceDimension, "session")
67171
+ const aiSourceCurrent = app.db.select({ source: gaAiReferrals.source, sessions: sql43`COALESCE(SUM(${gaAiReferrals.sessions}), 0)` }).from(gaAiReferrals).where(and81(
67172
+ eq96(gaAiReferrals.projectId, project.id),
67173
+ sql43`${gaAiReferrals.date} >= ${daysAgo(7)}`,
67174
+ sql43`${gaAiReferrals.date} < ${todayStr}`,
67175
+ eq96(gaAiReferrals.sourceDimension, "session")
66858
67176
  )).groupBy(gaAiReferrals.source).all();
66859
- const aiSourcePrev = app.db.select({ source: gaAiReferrals.source, sessions: sql42`COALESCE(SUM(${gaAiReferrals.sessions}), 0)` }).from(gaAiReferrals).where(and80(
66860
- eq95(gaAiReferrals.projectId, project.id),
66861
- sql42`${gaAiReferrals.date} >= ${daysAgo(14)}`,
66862
- sql42`${gaAiReferrals.date} < ${daysAgo(7)}`,
66863
- eq95(gaAiReferrals.sourceDimension, "session")
67177
+ const aiSourcePrev = app.db.select({ source: gaAiReferrals.source, sessions: sql43`COALESCE(SUM(${gaAiReferrals.sessions}), 0)` }).from(gaAiReferrals).where(and81(
67178
+ eq96(gaAiReferrals.projectId, project.id),
67179
+ sql43`${gaAiReferrals.date} >= ${daysAgo(14)}`,
67180
+ sql43`${gaAiReferrals.date} < ${daysAgo(7)}`,
67181
+ eq96(gaAiReferrals.sourceDimension, "session")
66864
67182
  )).groupBy(gaAiReferrals.source).all();
66865
- const socialSourceCurrent = app.db.select({ source: gaSocialReferrals.source, sessions: sql42`SUM(${gaSocialReferrals.sessions})` }).from(gaSocialReferrals).where(and80(eq95(gaSocialReferrals.projectId, project.id), sql42`${gaSocialReferrals.date} >= ${daysAgo(7)}`, sql42`${gaSocialReferrals.date} < ${todayStr}`)).groupBy(gaSocialReferrals.source).all();
66866
- const socialSourcePrev = app.db.select({ source: gaSocialReferrals.source, sessions: sql42`SUM(${gaSocialReferrals.sessions})` }).from(gaSocialReferrals).where(and80(eq95(gaSocialReferrals.projectId, project.id), sql42`${gaSocialReferrals.date} >= ${daysAgo(14)}`, sql42`${gaSocialReferrals.date} < ${daysAgo(7)}`)).groupBy(gaSocialReferrals.source).all();
67183
+ const socialSourceCurrent = app.db.select({ source: gaSocialReferrals.source, sessions: sql43`SUM(${gaSocialReferrals.sessions})` }).from(gaSocialReferrals).where(and81(eq96(gaSocialReferrals.projectId, project.id), sql43`${gaSocialReferrals.date} >= ${daysAgo(7)}`, sql43`${gaSocialReferrals.date} < ${todayStr}`)).groupBy(gaSocialReferrals.source).all();
67184
+ const socialSourcePrev = app.db.select({ source: gaSocialReferrals.source, sessions: sql43`SUM(${gaSocialReferrals.sessions})` }).from(gaSocialReferrals).where(and81(eq96(gaSocialReferrals.projectId, project.id), sql43`${gaSocialReferrals.date} >= ${daysAgo(14)}`, sql43`${gaSocialReferrals.date} < ${daysAgo(7)}`)).groupBy(gaSocialReferrals.source).all();
66867
67185
  const response = {
66868
67186
  total: buildTrend(sumTotal),
66869
67187
  organic: buildTrend(sumOrganic),
@@ -66879,16 +67197,16 @@ async function ga4Routes(app, opts) {
66879
67197
  const project = resolveProject(app.db, request.params.name);
66880
67198
  requireGa4Connection(opts, project.name, project.canonicalDomain);
66881
67199
  const window2 = parseGaOverviewWindow(request.query.window);
66882
- const periodRows = app.db.select().from(gaWindowMetrics).where(and80(eq95(gaWindowMetrics.projectId, project.id), eq95(gaWindowMetrics.windowKey, window2))).all();
67200
+ const periodRows = app.db.select().from(gaWindowMetrics).where(and81(eq96(gaWindowMetrics.projectId, project.id), eq96(gaWindowMetrics.windowKey, window2))).all();
66883
67201
  const current = periodRows.find((row) => row.period === GaOverviewPeriods.current) ?? null;
66884
67202
  const previous = periodRows.find((row) => row.period === GaOverviewPeriods.previous) ?? null;
66885
67203
  const fallback = gaOverviewComparisonRanges(window2);
66886
67204
  const from = previous?.startDate ?? fallback.previous.startDate;
66887
67205
  const to = current?.endDate ?? fallback.current.endDate;
66888
- const daily = app.db.select().from(gaDailyTotals).where(and80(
66889
- eq95(gaDailyTotals.projectId, project.id),
66890
- sql42`${gaDailyTotals.date} >= ${from}`,
66891
- sql42`${gaDailyTotals.date} <= ${to}`
67206
+ const daily = app.db.select().from(gaDailyTotals).where(and81(
67207
+ eq96(gaDailyTotals.projectId, project.id),
67208
+ sql43`${gaDailyTotals.date} >= ${from}`,
67209
+ sql43`${gaDailyTotals.date} <= ${to}`
66892
67210
  )).all();
66893
67211
  return buildGaOverview({ window: window2, current, previous, daily, fallback });
66894
67212
  });
@@ -66896,15 +67214,15 @@ async function ga4Routes(app, opts) {
66896
67214
  const project = resolveProject(app.db, request.params.name);
66897
67215
  requireGa4Connection(opts, project.name, project.canonicalDomain);
66898
67216
  const range = resolveDateRange(request.query, WINDOW_SETS.gaTraffic);
66899
- const conditions = [eq95(gaTrafficSnapshots.projectId, project.id), ...dateRangeConditions(gaTrafficSnapshots.date, range)];
67217
+ const conditions = [eq96(gaTrafficSnapshots.projectId, project.id), ...dateRangeConditions(gaTrafficSnapshots.date, range)];
66900
67218
  const rows = app.db.select({
66901
67219
  date: gaTrafficSnapshots.date,
66902
- sessions: sql42`SUM(${gaTrafficSnapshots.sessions})`,
66903
- organicSessions: sql42`SUM(${gaTrafficSnapshots.organicSessions})`,
66904
- users: sql42`SUM(${gaTrafficSnapshots.users})`
66905
- }).from(gaTrafficSnapshots).where(and80(...conditions)).groupBy(gaTrafficSnapshots.date).orderBy(gaTrafficSnapshots.date).all();
66906
- const totalConditions = [eq95(gaDailyTotals.projectId, project.id), ...dateRangeConditions(gaDailyTotals.date, range)];
66907
- const totals = app.db.select({ date: gaDailyTotals.date, users: gaDailyTotals.users }).from(gaDailyTotals).where(and80(...totalConditions)).all();
67220
+ sessions: sql43`SUM(${gaTrafficSnapshots.sessions})`,
67221
+ organicSessions: sql43`SUM(${gaTrafficSnapshots.organicSessions})`,
67222
+ users: sql43`SUM(${gaTrafficSnapshots.users})`
67223
+ }).from(gaTrafficSnapshots).where(and81(...conditions)).groupBy(gaTrafficSnapshots.date).orderBy(gaTrafficSnapshots.date).all();
67224
+ const totalConditions = [eq96(gaDailyTotals.projectId, project.id), ...dateRangeConditions(gaDailyTotals.date, range)];
67225
+ const totals = app.db.select({ date: gaDailyTotals.date, users: gaDailyTotals.users }).from(gaDailyTotals).where(and81(...totalConditions)).all();
66908
67226
  return buildSessionHistory(
66909
67227
  rows.map((r) => ({
66910
67228
  date: r.date,
@@ -66919,11 +67237,11 @@ async function ga4Routes(app, opts) {
66919
67237
  const project = resolveProject(app.db, request.params.name);
66920
67238
  requireGa4Connection(opts, project.name, project.canonicalDomain);
66921
67239
  const trafficPages = app.db.select({
66922
- landingPage: sql42`COALESCE(${gaTrafficSnapshots.landingPageNormalized}, ${gaTrafficSnapshots.landingPage})`,
66923
- sessions: sql42`SUM(${gaTrafficSnapshots.sessions})`,
66924
- organicSessions: sql42`SUM(${gaTrafficSnapshots.organicSessions})`,
66925
- users: sql42`SUM(${gaTrafficSnapshots.users})`
66926
- }).from(gaTrafficSnapshots).where(eq95(gaTrafficSnapshots.projectId, project.id)).groupBy(sql42`COALESCE(${gaTrafficSnapshots.landingPageNormalized}, ${gaTrafficSnapshots.landingPage})`).orderBy(sql42`SUM(${gaTrafficSnapshots.sessions}) DESC`).all();
67240
+ landingPage: sql43`COALESCE(${gaTrafficSnapshots.landingPageNormalized}, ${gaTrafficSnapshots.landingPage})`,
67241
+ sessions: sql43`SUM(${gaTrafficSnapshots.sessions})`,
67242
+ organicSessions: sql43`SUM(${gaTrafficSnapshots.organicSessions})`,
67243
+ users: sql43`SUM(${gaTrafficSnapshots.users})`
67244
+ }).from(gaTrafficSnapshots).where(eq96(gaTrafficSnapshots.projectId, project.id)).groupBy(sql43`COALESCE(${gaTrafficSnapshots.landingPageNormalized}, ${gaTrafficSnapshots.landingPage})`).orderBy(sql43`SUM(${gaTrafficSnapshots.sessions}) DESC`).all();
66927
67245
  return {
66928
67246
  pages: trafficPages.map((r) => ({
66929
67247
  landingPage: r.landingPage,
@@ -66936,7 +67254,7 @@ async function ga4Routes(app, opts) {
66936
67254
  }
66937
67255
 
66938
67256
  // ../api-routes/src/ga-acquisition.ts
66939
- import { and as and81, asc as asc26, count as count8, desc as desc44, eq as eq96, gte as gte25, lte as lte25, sql as sql43 } from "drizzle-orm";
67257
+ import { and as and82, asc as asc26, count as count8, desc as desc44, eq as eq97, gte as gte25, lte as lte25, sql as sql44 } from "drizzle-orm";
66940
67258
  async function gaAcquisitionRoutes(app) {
66941
67259
  app.get("/projects/:name/ga/acquisition", async (request) => {
66942
67260
  const project = resolveProject(app.db, request.params.name);
@@ -66950,7 +67268,7 @@ async function gaAcquisitionRoutes(app) {
66950
67268
  const groupBy = query2.groupBy === void 0 ? [...gaAcquisitionDimensionSchema.options] : [...new Set(query2.groupBy.split(",").map((key) => gaAcquisitionDimensionSchema.parse(key.trim())))];
66951
67269
  const limit = query2.limit ?? 100;
66952
67270
  const offset = query2.offset ?? 0;
66953
- const landingPage = sql43`coalesce(${gaAcquisitionDaily.landingPageNormalized}, ${gaAcquisitionDaily.landingPage})`;
67271
+ const landingPage = sql44`coalesce(${gaAcquisitionDaily.landingPageNormalized}, ${gaAcquisitionDaily.landingPage})`;
66954
67272
  const dimensions = {
66955
67273
  date: gaAcquisitionDaily.date,
66956
67274
  channelGroup: gaAcquisitionDaily.channelGroup,
@@ -66959,23 +67277,23 @@ async function gaAcquisitionRoutes(app) {
66959
67277
  hostName: gaAcquisitionDaily.hostName,
66960
67278
  landingPage
66961
67279
  };
66962
- const windowFilters = [eq96(gaAcquisitionDaily.projectId, project.id)];
67280
+ const windowFilters = [eq97(gaAcquisitionDaily.projectId, project.id)];
66963
67281
  if (range.startDate) windowFilters.push(gte25(gaAcquisitionDaily.date, range.startDate));
66964
67282
  if (range.endDate) windowFilters.push(lte25(gaAcquisitionDaily.date, range.endDate));
66965
67283
  const filters = [...windowFilters];
66966
- if (query2.channel !== void 0) filters.push(sql43`lower(${gaAcquisitionDaily.channelGroup}) = lower(${query2.channel})`);
66967
- if (query2.hostName !== void 0) filters.push(sql43`lower(${gaAcquisitionDaily.hostName}) = lower(${query2.hostName})`);
66968
- if (query2.source !== void 0) filters.push(eq96(gaAcquisitionDaily.source, query2.source));
66969
- if (query2.medium !== void 0) filters.push(eq96(gaAcquisitionDaily.medium, query2.medium));
67284
+ if (query2.channel !== void 0) filters.push(sql44`lower(${gaAcquisitionDaily.channelGroup}) = lower(${query2.channel})`);
67285
+ if (query2.hostName !== void 0) filters.push(sql44`lower(${gaAcquisitionDaily.hostName}) = lower(${query2.hostName})`);
67286
+ if (query2.source !== void 0) filters.push(eq97(gaAcquisitionDaily.source, query2.source));
67287
+ if (query2.medium !== void 0) filters.push(eq97(gaAcquisitionDaily.medium, query2.medium));
66970
67288
  const selectedLandingPage = query2.landingPage === void 0 ? void 0 : normalizeUrlPath(query2.landingPage) ?? query2.landingPage;
66971
- if (selectedLandingPage !== void 0) filters.push(sql43`${landingPage} = ${selectedLandingPage}`);
67289
+ if (selectedLandingPage !== void 0) filters.push(sql44`${landingPage} = ${selectedLandingPage}`);
66972
67290
  const pathPrefix = normalizePathPrefix(query2.pathPrefix);
66973
67291
  if (pathPrefix && pathPrefix !== "/") {
66974
- const pathname = sql43`case when instr(${landingPage}, '?') = 0 then ${landingPage} else substr(${landingPage}, 1, instr(${landingPage}, '?') - 1) end`;
67292
+ const pathname = sql44`case when instr(${landingPage}, '?') = 0 then ${landingPage} else substr(${landingPage}, 1, instr(${landingPage}, '?') - 1) end`;
66975
67293
  filters.push(literalPathPrefixCondition(pathname, pathPrefix));
66976
67294
  }
66977
- const where = and81(...filters);
66978
- const sessions = sql43`coalesce(sum(${gaAcquisitionDaily.sessions}), 0)`.mapWith(Number);
67295
+ const where = and82(...filters);
67296
+ const sessions = sql44`coalesce(sum(${gaAcquisitionDaily.sessions}), 0)`.mapWith(Number);
66979
67297
  const selected = Object.fromEntries(groupBy.map((key) => [key, dimensions[key]]));
66980
67298
  const grouped = app.db.select({ ...selected, sessions }).from(gaAcquisitionDaily).where(where).groupBy(...groupBy.map((key) => dimensions[key]));
66981
67299
  const totalRows = app.db.select({ total: count8() }).from(grouped.as("grouped_acquisition")).get().total;
@@ -66986,9 +67304,9 @@ async function gaAcquisitionRoutes(app) {
66986
67304
  ...groupBy.filter((key) => key !== GaAcquisitionDimensions.date).map((key) => asc26(dimensions[key]))
66987
67305
  ];
66988
67306
  const rows = grouped.orderBy(...order).limit(limit).offset(offset).all();
66989
- const coverage = app.db.select({ earliestDate: sql43`min(${gaAcquisitionDaily.date})`, latestDate: sql43`max(${gaAcquisitionDaily.date})` }).from(gaAcquisitionDaily).where(eq96(gaAcquisitionDaily.projectId, project.id)).get();
66990
- const channelGroups = app.db.selectDistinct({ channel: gaAcquisitionDaily.channelGroup }).from(gaAcquisitionDaily).where(and81(...windowFilters)).orderBy(asc26(gaAcquisitionDaily.channelGroup)).all().map((row) => row.channel);
66991
- const state = app.db.select().from(gaMeasurementSyncStates).where(eq96(gaMeasurementSyncStates.projectId, project.id)).get();
67307
+ const coverage = app.db.select({ earliestDate: sql44`min(${gaAcquisitionDaily.date})`, latestDate: sql44`max(${gaAcquisitionDaily.date})` }).from(gaAcquisitionDaily).where(eq97(gaAcquisitionDaily.projectId, project.id)).get();
67308
+ const channelGroups = app.db.selectDistinct({ channel: gaAcquisitionDaily.channelGroup }).from(gaAcquisitionDaily).where(and82(...windowFilters)).orderBy(asc26(gaAcquisitionDaily.channelGroup)).all().map((row) => row.channel);
67309
+ const state = app.db.select().from(gaMeasurementSyncStates).where(eq97(gaMeasurementSyncStates.projectId, project.id)).get();
66992
67310
  const response = {
66993
67311
  source: "ga4-acquisition",
66994
67312
  status: state?.acquisitionStatus ?? "never-synced",
@@ -68720,7 +69038,7 @@ async function wordpressRoutes(app, opts) {
68720
69038
 
68721
69039
  // ../api-routes/src/backlinks.ts
68722
69040
  import crypto58 from "crypto";
68723
- import { and as and84, asc as asc27, desc as desc45, eq as eq98, sql as sql44 } from "drizzle-orm";
69041
+ import { and as and85, asc as asc27, desc as desc45, eq as eq99, sql as sql45 } from "drizzle-orm";
68724
69042
 
68725
69043
  // ../integration-commoncrawl/src/constants.ts
68726
69044
  import os2 from "os";
@@ -69057,7 +69375,7 @@ async function queryBacklinks(opts) {
69057
69375
  const reversed = opts.targets.map(reverseDomain);
69058
69376
  const targetList = reversed.map(quote).join(", ");
69059
69377
  const limitClause = opts.limitPerTarget ? `QUALIFY row_number() OVER (PARTITION BY t.target_rev_domain ORDER BY v.num_hosts DESC) <= ${Math.floor(opts.limitPerTarget)}` : "";
69060
- const sql50 = `
69378
+ const sql51 = `
69061
69379
  WITH vertices AS (
69062
69380
  SELECT * FROM read_csv(
69063
69381
  ${quote(opts.vertexPath)},
@@ -69093,7 +69411,7 @@ async function queryBacklinks(opts) {
69093
69411
  const conn = await instance.connect();
69094
69412
  let rows;
69095
69413
  try {
69096
- const reader = await conn.runAndReadAll(sql50);
69414
+ const reader = await conn.runAndReadAll(sql51);
69097
69415
  rows = reader.getRowObjects();
69098
69416
  } finally {
69099
69417
  conn.disconnectSync?.();
@@ -69170,7 +69488,7 @@ function pruneCachedRelease(release, opts = {}) {
69170
69488
  }
69171
69489
 
69172
69490
  // ../api-routes/src/backlinks-filter.ts
69173
- import { and as and82, ne as ne15, notLike } from "drizzle-orm";
69491
+ import { and as and83, ne as ne15, notLike } from "drizzle-orm";
69174
69492
  var BACKLINK_FILTER_PATTERNS = [
69175
69493
  "*.google.com",
69176
69494
  "*.googleusercontent.com",
@@ -69193,23 +69511,23 @@ function backlinkCrawlerExclusionClause() {
69193
69511
  conditions.push(ne15(backlinkDomains.linkingDomain, pattern));
69194
69512
  }
69195
69513
  }
69196
- const combined = and82(...conditions);
69514
+ const combined = and83(...conditions);
69197
69515
  if (!combined) throw new Error("BACKLINK_FILTER_PATTERNS is unexpectedly empty");
69198
69516
  return combined;
69199
69517
  }
69200
69518
 
69201
69519
  // ../api-routes/src/backlinks-source-state.ts
69202
- import { and as and83, eq as eq97, isNotNull as isNotNull9, or as or18 } from "drizzle-orm";
69520
+ import { and as and84, eq as eq98, isNotNull as isNotNull9, or as or18 } from "drizzle-orm";
69203
69521
  function readCommonCrawlSourceState(db, projectId) {
69204
69522
  const completedReleases = db.select({ status: ccReleaseSyncs.status }).from(ccReleaseSyncs).where(or18(
69205
- eq97(ccReleaseSyncs.status, CcReleaseSyncStatuses.ready),
69523
+ eq98(ccReleaseSyncs.status, CcReleaseSyncStatuses.ready),
69206
69524
  isNotNull9(ccReleaseSyncs.queryFinishedAt)
69207
69525
  )).all();
69208
69526
  const hasReadyRelease = completedReleases.length > 0;
69209
69527
  const hasCurrentReadyRelease = completedReleases.some((release) => release.status === CcReleaseSyncStatuses.ready);
69210
- const hasProjectData = db.select({ id: backlinkSummaries.id }).from(backlinkSummaries).where(and83(
69211
- eq97(backlinkSummaries.projectId, projectId),
69212
- eq97(backlinkSummaries.source, BacklinkSources.commoncrawl)
69528
+ const hasProjectData = db.select({ id: backlinkSummaries.id }).from(backlinkSummaries).where(and84(
69529
+ eq98(backlinkSummaries.projectId, projectId),
69530
+ eq98(backlinkSummaries.source, BacklinkSources.commoncrawl)
69213
69531
  )).limit(1).get() !== void 0;
69214
69532
  return { hasReadyRelease, hasCurrentReadyRelease, hasProjectData, connected: hasReadyRelease && hasProjectData };
69215
69533
  }
@@ -69280,11 +69598,11 @@ function mapRunRow(row) {
69280
69598
  }
69281
69599
  function latestSummaryForProject(db, projectId, source, release) {
69282
69600
  const conditions = [
69283
- eq98(backlinkSummaries.projectId, projectId),
69284
- eq98(backlinkSummaries.source, source)
69601
+ eq99(backlinkSummaries.projectId, projectId),
69602
+ eq99(backlinkSummaries.source, source)
69285
69603
  ];
69286
- if (release) conditions.push(eq98(backlinkSummaries.release, release));
69287
- const rows = db.select().from(backlinkSummaries).where(and84(...conditions)).orderBy(desc45(backlinkSummaries.queriedAt)).all();
69604
+ if (release) conditions.push(eq99(backlinkSummaries.release, release));
69605
+ const rows = db.select().from(backlinkSummaries).where(and85(...conditions)).orderBy(desc45(backlinkSummaries.queriedAt)).all();
69288
69606
  return rows.reduce((latest, row) => {
69289
69607
  if (!latest) return row;
69290
69608
  const newer = isValidReleaseId(row.release) && isValidReleaseId(latest.release) && compareReleaseIds(row.release, latest.release) > 0;
@@ -69297,19 +69615,19 @@ function parseExcludeCrawlers(value) {
69297
69615
  return lower === "1" || lower === "true" || lower === "yes";
69298
69616
  }
69299
69617
  function computeFilteredSummary(db, base) {
69300
- const baseDomainCondition = and84(
69301
- eq98(backlinkDomains.projectId, base.projectId),
69302
- eq98(backlinkDomains.source, base.source),
69303
- eq98(backlinkDomains.release, base.release)
69618
+ const baseDomainCondition = and85(
69619
+ eq99(backlinkDomains.projectId, base.projectId),
69620
+ eq99(backlinkDomains.source, base.source),
69621
+ eq99(backlinkDomains.release, base.release)
69304
69622
  );
69305
- const filteredCondition = and84(baseDomainCondition, backlinkCrawlerExclusionClause());
69623
+ const filteredCondition = and85(baseDomainCondition, backlinkCrawlerExclusionClause());
69306
69624
  const unfilteredAgg = db.select({
69307
- count: sql44`count(*)`,
69308
- total: sql44`coalesce(sum(${backlinkDomains.numHosts}), 0)`
69625
+ count: sql45`count(*)`,
69626
+ total: sql45`coalesce(sum(${backlinkDomains.numHosts}), 0)`
69309
69627
  }).from(backlinkDomains).where(baseDomainCondition).get();
69310
69628
  const filteredAgg = db.select({
69311
- count: sql44`count(*)`,
69312
- total: sql44`coalesce(sum(${backlinkDomains.numHosts}), 0)`
69629
+ count: sql45`count(*)`,
69630
+ total: sql45`coalesce(sum(${backlinkDomains.numHosts}), 0)`
69313
69631
  }).from(backlinkDomains).where(filteredCondition).get();
69314
69632
  const top10Rows = db.select({ numHosts: backlinkDomains.numHosts }).from(backlinkDomains).where(filteredCondition).orderBy(desc45(backlinkDomains.numHosts)).limit(10).all();
69315
69633
  const totalLinkingDomains = Number(filteredAgg?.count ?? 0);
@@ -69332,8 +69650,8 @@ function computeFilteredSummary(db, base) {
69332
69650
  };
69333
69651
  }
69334
69652
  function computeFilteredReleaseTotals(db, projectId, source) {
69335
- const kept = sql44`case when ${backlinkCrawlerExclusionClause()} then 1 else 0 end`;
69336
- const rows = db.all(sql44`
69653
+ const kept = sql45`case when ${backlinkCrawlerExclusionClause()} then 1 else 0 end`;
69654
+ const rows = db.all(sql45`
69337
69655
  SELECT release,
69338
69656
  COUNT(*) AS domain_rows,
69339
69657
  SUM(kept) AS linking_domains,
@@ -69343,7 +69661,7 @@ function computeFilteredReleaseTotals(db, projectId, source) {
69343
69661
  SELECT ${backlinkDomains.release} AS release, ${backlinkDomains.numHosts} AS num_hosts, ${kept} AS kept,
69344
69662
  ROW_NUMBER() OVER (PARTITION BY ${backlinkDomains.release}, ${kept} ORDER BY ${backlinkDomains.numHosts} DESC) AS kept_rank
69345
69663
  FROM ${backlinkDomains}
69346
- WHERE ${and84(eq98(backlinkDomains.projectId, projectId), eq98(backlinkDomains.source, source))}
69664
+ WHERE ${and85(eq99(backlinkDomains.projectId, projectId), eq99(backlinkDomains.source, source))}
69347
69665
  )
69348
69666
  GROUP BY release`);
69349
69667
  return new Map(rows.map((row) => {
@@ -69357,13 +69675,13 @@ function computeFilteredReleaseTotals(db, projectId, source) {
69357
69675
  }));
69358
69676
  }
69359
69677
  function buildSourceAvailability(db, projectId, source, connected2, excludeCrawlers) {
69360
- const summary3 = db.select().from(backlinkSummaries).where(and84(eq98(backlinkSummaries.projectId, projectId), eq98(backlinkSummaries.source, source))).orderBy(desc45(backlinkSummaries.queriedAt)).limit(1).get();
69678
+ const summary3 = db.select().from(backlinkSummaries).where(and85(eq99(backlinkSummaries.projectId, projectId), eq99(backlinkSummaries.source, source))).orderBy(desc45(backlinkSummaries.queriedAt)).limit(1).get();
69361
69679
  let totalLinkingDomains = summary3?.totalLinkingDomains ?? 0;
69362
69680
  if (summary3 && excludeCrawlers) {
69363
- const filtered = db.select({ count: sql44`count(*)` }).from(backlinkDomains).where(and84(
69364
- eq98(backlinkDomains.projectId, projectId),
69365
- eq98(backlinkDomains.source, source),
69366
- eq98(backlinkDomains.release, summary3.release),
69681
+ const filtered = db.select({ count: sql45`count(*)` }).from(backlinkDomains).where(and85(
69682
+ eq99(backlinkDomains.projectId, projectId),
69683
+ eq99(backlinkDomains.source, source),
69684
+ eq99(backlinkDomains.release, summary3.release),
69367
69685
  backlinkCrawlerExclusionClause()
69368
69686
  )).get();
69369
69687
  totalLinkingDomains = Number(filtered?.count ?? 0);
@@ -69433,7 +69751,7 @@ async function backlinksRoutes(app, opts) {
69433
69751
  "@duckdb/node-api is not installed. Run `canonry backlinks install` to enable the backlinks feature."
69434
69752
  );
69435
69753
  }
69436
- const existing = app.db.select().from(ccReleaseSyncs).where(eq98(ccReleaseSyncs.release, release)).get();
69754
+ const existing = app.db.select().from(ccReleaseSyncs).where(eq99(ccReleaseSyncs.release, release)).get();
69437
69755
  const now = (/* @__PURE__ */ new Date()).toISOString();
69438
69756
  if (existing) {
69439
69757
  if (NON_TERMINAL_SYNC_STATUSES.has(existing.status)) {
@@ -69444,9 +69762,9 @@ async function backlinksRoutes(app, opts) {
69444
69762
  phaseDetail: null,
69445
69763
  error: null,
69446
69764
  updatedAt: now
69447
- }).where(eq98(ccReleaseSyncs.id, existing.id)).run();
69765
+ }).where(eq99(ccReleaseSyncs.id, existing.id)).run();
69448
69766
  opts.onReleaseSyncRequested(existing.id, release);
69449
- const refreshed = app.db.select().from(ccReleaseSyncs).where(eq98(ccReleaseSyncs.id, existing.id)).get();
69767
+ const refreshed = app.db.select().from(ccReleaseSyncs).where(eq99(ccReleaseSyncs.id, existing.id)).get();
69450
69768
  return reply.status(200).send(mapSyncRow(refreshed));
69451
69769
  }
69452
69770
  const id = crypto58.randomUUID();
@@ -69458,7 +69776,7 @@ async function backlinksRoutes(app, opts) {
69458
69776
  updatedAt: now
69459
69777
  }).run();
69460
69778
  opts.onReleaseSyncRequested(id, release);
69461
- const inserted = app.db.select().from(ccReleaseSyncs).where(eq98(ccReleaseSyncs.id, id)).get();
69779
+ const inserted = app.db.select().from(ccReleaseSyncs).where(eq99(ccReleaseSyncs.id, id)).get();
69462
69780
  return reply.status(201).send(mapSyncRow(inserted));
69463
69781
  });
69464
69782
  app.get("/backlinks/syncs/latest", async (_request, reply) => {
@@ -69516,7 +69834,7 @@ async function backlinksRoutes(app, opts) {
69516
69834
  createdAt: now
69517
69835
  }).run();
69518
69836
  opts.onBacklinkExtractRequested(runId, project.id, release);
69519
- const run = app.db.select().from(runs).where(eq98(runs.id, runId)).get();
69837
+ const run = app.db.select().from(runs).where(eq99(runs.id, runId)).get();
69520
69838
  return reply.status(201).send(mapRunRow(run));
69521
69839
  });
69522
69840
  app.get(
@@ -69542,13 +69860,13 @@ async function backlinksRoutes(app, opts) {
69542
69860
  const limit = Math.min(Math.max(parseInt(request.query.limit ?? "50", 10) || 50, 1), 500);
69543
69861
  const offset = Math.max(parseInt(request.query.offset ?? "0", 10) || 0, 0);
69544
69862
  const excludeCrawlers = parseExcludeCrawlers(request.query.excludeCrawlers);
69545
- const baseDomainCondition = and84(
69546
- eq98(backlinkDomains.projectId, project.id),
69547
- eq98(backlinkDomains.source, source),
69548
- eq98(backlinkDomains.release, targetRelease)
69863
+ const baseDomainCondition = and85(
69864
+ eq99(backlinkDomains.projectId, project.id),
69865
+ eq99(backlinkDomains.source, source),
69866
+ eq99(backlinkDomains.release, targetRelease)
69549
69867
  );
69550
- const domainCondition = excludeCrawlers ? and84(baseDomainCondition, backlinkCrawlerExclusionClause()) : baseDomainCondition;
69551
- const totalRow = app.db.select({ count: sql44`count(*)` }).from(backlinkDomains).where(domainCondition).get();
69868
+ const domainCondition = excludeCrawlers ? and85(baseDomainCondition, backlinkCrawlerExclusionClause()) : baseDomainCondition;
69869
+ const totalRow = app.db.select({ count: sql45`count(*)` }).from(backlinkDomains).where(domainCondition).get();
69552
69870
  const rows = app.db.select({
69553
69871
  linkingDomain: backlinkDomains.linkingDomain,
69554
69872
  numHosts: backlinkDomains.numHosts,
@@ -69571,7 +69889,7 @@ async function backlinksRoutes(app, opts) {
69571
69889
  async (request, reply) => {
69572
69890
  const project = resolveProject(app.db, request.params.name);
69573
69891
  const source = parseSourceParam(request.query.source);
69574
- const rows = app.db.select().from(backlinkSummaries).where(and84(eq98(backlinkSummaries.projectId, project.id), eq98(backlinkSummaries.source, source))).orderBy(asc27(backlinkSummaries.queriedAt)).all();
69892
+ const rows = app.db.select().from(backlinkSummaries).where(and85(eq99(backlinkSummaries.projectId, project.id), eq99(backlinkSummaries.source, source))).orderBy(asc27(backlinkSummaries.queriedAt)).all();
69575
69893
  const response = rows.map((r) => ({
69576
69894
  release: r.release,
69577
69895
  totalLinkingDomains: r.totalLinkingDomains,
@@ -69598,7 +69916,7 @@ async function backlinksRoutes(app, opts) {
69598
69916
  import crypto60 from "crypto";
69599
69917
  import { isIP as isIP3 } from "net";
69600
69918
  import { isDeepStrictEqual } from "util";
69601
- import { and as and86, desc as desc46, eq as eq100, gt as gt8, gte as gte26, inArray as inArray46, lt as lt20, lte as lte27, sql as sql45 } from "drizzle-orm";
69919
+ import { and as and87, desc as desc46, eq as eq101, gt as gt8, gte as gte26, inArray as inArray47, lt as lt20, lte as lte27, sql as sql46 } from "drizzle-orm";
69602
69920
 
69603
69921
  // ../api-routes/src/traffic-limits.ts
69604
69922
  var VERCEL_MAX_SYNC_WINDOW_MS = 24 * 60 * 6e4;
@@ -70941,7 +71259,7 @@ async function ackCloudflareQueueMessages(client, options) {
70941
71259
  }
70942
71260
 
70943
71261
  // ../api-routes/src/traffic-sync-lease.ts
70944
- import { and as and85, eq as eq99, isNull as isNull17, lte as lte26, or as or19 } from "drizzle-orm";
71262
+ import { and as and86, eq as eq100, isNull as isNull17, lte as lte26, or as or19 } from "drizzle-orm";
70945
71263
  function leaseExpiresAt(now, ttlMs) {
70946
71264
  const nowMs = Date.parse(now);
70947
71265
  if (!Number.isFinite(nowMs)) throw new RangeError("Traffic sync lease now must be an ISO instant");
@@ -70954,12 +71272,12 @@ function tryClaimTrafficSyncLease(input) {
70954
71272
  const changed = tx.update(trafficSources).set({
70955
71273
  syncLeaseOwner: input.owner,
70956
71274
  syncLeaseExpiresAt: expiresAt
70957
- }).where(and85(
70958
- eq99(trafficSources.id, input.sourceId),
71275
+ }).where(and86(
71276
+ eq100(trafficSources.id, input.sourceId),
70959
71277
  or19(
70960
71278
  isNull17(trafficSources.syncLeaseOwner),
70961
71279
  lte26(trafficSources.syncLeaseExpiresAt, input.now),
70962
- eq99(trafficSources.syncLeaseOwner, input.owner)
71280
+ eq100(trafficSources.syncLeaseOwner, input.owner)
70963
71281
  )
70964
71282
  )).run();
70965
71283
  return changed.changes === 1;
@@ -70970,9 +71288,9 @@ function releaseTrafficSyncLease(input) {
70970
71288
  const changed = tx.update(trafficSources).set({
70971
71289
  syncLeaseOwner: null,
70972
71290
  syncLeaseExpiresAt: null
70973
- }).where(and85(
70974
- eq99(trafficSources.id, input.sourceId),
70975
- eq99(trafficSources.syncLeaseOwner, input.owner)
71291
+ }).where(and86(
71292
+ eq100(trafficSources.id, input.sourceId),
71293
+ eq100(trafficSources.syncLeaseOwner, input.owner)
70976
71294
  )).run();
70977
71295
  return changed.changes === 1;
70978
71296
  }, { behavior: "immediate" });
@@ -71046,14 +71364,14 @@ async function loadQueueReceiptPolicy(db, sourceId, readRetentionSeconds, warn2)
71046
71364
  if (liveTtlMs === null) return { ttlMsAt: () => CLOUDFLARE_QUEUE_RECEIPT_TTL_MS };
71047
71365
  const ttlMs = liveTtlMs;
71048
71366
  const now = (/* @__PURE__ */ new Date()).toISOString();
71049
- const alive = and86(eq100(trafficEventReceipts.sourceId, sourceId), gt8(trafficEventReceipts.expiresAt, now));
71050
- const lifetimeMs = sql45`(julianday(${trafficEventReceipts.expiresAt}) - julianday(${trafficEventReceipts.receivedAt})) * ${DAY_MS5}`;
71051
- const shortest = db.select({ ms: sql45`min(${lifetimeMs})` }).from(trafficEventReceipts).where(alive).get()?.ms ?? null;
71367
+ const alive = and87(eq101(trafficEventReceipts.sourceId, sourceId), gt8(trafficEventReceipts.expiresAt, now));
71368
+ const lifetimeMs = sql46`(julianday(${trafficEventReceipts.expiresAt}) - julianday(${trafficEventReceipts.receivedAt})) * ${DAY_MS5}`;
71369
+ const shortest = db.select({ ms: sql46`min(${lifetimeMs})` }).from(trafficEventReceipts).where(alive).get()?.ms ?? null;
71052
71370
  if (shortest !== null && shortest < ttlMs - 1e3) {
71053
- const extended = sql45`strftime('%Y-%m-%dT%H:%M:%fZ', julianday(${trafficEventReceipts.receivedAt}) + ${ttlMs / DAY_MS5})`;
71054
- db.update(trafficEventReceipts).set({ expiresAt: extended }).where(and86(alive, lt20(trafficEventReceipts.expiresAt, extended))).run();
71371
+ const extended = sql46`strftime('%Y-%m-%dT%H:%M:%fZ', julianday(${trafficEventReceipts.receivedAt}) + ${ttlMs / DAY_MS5})`;
71372
+ db.update(trafficEventReceipts).set({ expiresAt: extended }).where(and87(alive, lt20(trafficEventReceipts.expiresAt, extended))).run();
71055
71373
  }
71056
- const floorExpiry = db.select({ at: sql45`max(${trafficEventReceipts.expiresAt})` }).from(trafficEventReceipts).where(and86(alive, sql45`${lifetimeMs} < ${CLOUDFLARE_QUEUE_RECEIPT_TTL_MS - 1e3}`)).get()?.at ?? null;
71374
+ const floorExpiry = db.select({ at: sql46`max(${trafficEventReceipts.expiresAt})` }).from(trafficEventReceipts).where(and87(alive, sql46`${lifetimeMs} < ${CLOUDFLARE_QUEUE_RECEIPT_TTL_MS - 1e3}`)).get()?.at ?? null;
71057
71375
  const floorMs = floorExpiry ? Date.parse(floorExpiry) : 0;
71058
71376
  return { ttlMsAt: (receivedAt) => Math.max(ttlMs, floorMs - Date.parse(receivedAt)) };
71059
71377
  }
@@ -71108,7 +71426,7 @@ function cloudflareIngestRateLimitKey(request, store, db) {
71108
71426
  const authenticated = authenticateCloudflareIngest(request, store);
71109
71427
  const params = request.params;
71110
71428
  if (authenticated && typeof params.name === "string" && authenticated.credential.projectName === params.name) {
71111
- const source = db.select().from(trafficSources).where(eq100(trafficSources.id, authenticated.credential.sourceId)).get();
71429
+ const source = db.select().from(trafficSources).where(eq101(trafficSources.id, authenticated.credential.sourceId)).get();
71112
71430
  if (source && source.sourceType === TrafficSourceTypes.cloudflare && source.status === TrafficSourceStatuses.connected && parseDirectPushCloudflareSourceConfig(source.configJson) && timingSafeEqualHex(authenticated.bearerHash, source.ingestTokenHash)) {
71113
71431
  return `cloudflare-source:${authenticated.credential.sourceId}`;
71114
71432
  }
@@ -71187,7 +71505,7 @@ var SERIES_BUCKET_LENGTH = {
71187
71505
  };
71188
71506
  function seriesBucketSql(tsHour, granularity) {
71189
71507
  const length = SERIES_BUCKET_LENGTH[granularity];
71190
- return length === null ? tsHour : sql45`substr(${tsHour}, 1, ${sql45.raw(String(length))})`;
71508
+ return length === null ? tsHour : sql46`substr(${tsHour}, 1, ${sql46.raw(String(length))})`;
71191
71509
  }
71192
71510
  function seriesBucketOf(iso2, granularity) {
71193
71511
  const length = SERIES_BUCKET_LENGTH[granularity];
@@ -71279,7 +71597,7 @@ function crawlerVerificationProvenance(db, projectId, events) {
71279
71597
  manifestId: crawlerVerificationManifestsHourly.manifestId,
71280
71598
  manifest: crawlerVerificationManifestsHourly.manifestJson,
71281
71599
  hits: crawlerVerificationManifestsHourly.hits
71282
- }).from(crawlerVerificationManifestsHourly).where(sql45`(
71600
+ }).from(crawlerVerificationManifestsHourly).where(sql46`(
71283
71601
  ${crawlerVerificationManifestsHourly.projectId},
71284
71602
  ${crawlerVerificationManifestsHourly.sourceId},
71285
71603
  ${crawlerVerificationManifestsHourly.tsHour},
@@ -71313,7 +71631,7 @@ function aiUserFetchVerificationProvenance(db, projectId, events) {
71313
71631
  manifestId: aiUserFetchVerificationManifestsHourly.manifestId,
71314
71632
  manifest: aiUserFetchVerificationManifestsHourly.manifestJson,
71315
71633
  hits: aiUserFetchVerificationManifestsHourly.hits
71316
- }).from(aiUserFetchVerificationManifestsHourly).where(sql45`(
71634
+ }).from(aiUserFetchVerificationManifestsHourly).where(sql46`(
71317
71635
  ${aiUserFetchVerificationManifestsHourly.projectId},
71318
71636
  ${aiUserFetchVerificationManifestsHourly.sourceId},
71319
71637
  ${aiUserFetchVerificationManifestsHourly.tsHour},
@@ -71368,7 +71686,7 @@ async function defaultResolveAccessToken(record3) {
71368
71686
  );
71369
71687
  }
71370
71688
  function hasConnectedTrafficSourceSibling(db, projectId, sourceId) {
71371
- return db.select().from(trafficSources).where(eq100(trafficSources.projectId, projectId)).all().some((row) => row.id !== sourceId && row.status === TrafficSourceStatuses.connected);
71689
+ return db.select().from(trafficSources).where(eq101(trafficSources.projectId, projectId)).all().some((row) => row.id !== sourceId && row.status === TrafficSourceStatuses.connected);
71372
71690
  }
71373
71691
  function isAuthoritativeTrafficSource(db, source) {
71374
71692
  return (source.status === TrafficSourceStatuses.connected || source.status === TrafficSourceStatuses.error) && !hasConnectedTrafficSourceSibling(db, source.projectId, source.id);
@@ -71395,13 +71713,13 @@ function wordpressBaseUrlIdentity(value) {
71395
71713
  }
71396
71714
  }
71397
71715
  function bindTrafficSyncSchedule(tx, projectId, sourceId, now, createIfMissing = true) {
71398
- const schedule = tx.select().from(schedules).where(and86(
71399
- eq100(schedules.projectId, projectId),
71400
- eq100(schedules.kind, SchedulableRunKinds["traffic-sync"])
71716
+ const schedule = tx.select().from(schedules).where(and87(
71717
+ eq101(schedules.projectId, projectId),
71718
+ eq101(schedules.kind, SchedulableRunKinds["traffic-sync"])
71401
71719
  )).get();
71402
71720
  if (schedule) {
71403
71721
  if (schedule.sourceId === sourceId) return { changed: false, created: false };
71404
- tx.update(schedules).set({ sourceId, updatedAt: nextScheduleUpdatedAt(schedule.updatedAt, Date.parse(now)) }).where(eq100(schedules.id, schedule.id)).run();
71722
+ tx.update(schedules).set({ sourceId, updatedAt: nextScheduleUpdatedAt(schedule.updatedAt, Date.parse(now)) }).where(eq101(schedules.id, schedule.id)).run();
71405
71723
  return { changed: true, created: false };
71406
71724
  }
71407
71725
  if (!createIfMissing) return { changed: false, created: false };
@@ -71443,7 +71761,7 @@ async function runBackfillTask(options) {
71443
71761
  };
71444
71762
  const renewLease2 = setInterval(() => {
71445
71763
  try {
71446
- const latest = app.db.select().from(trafficSources).where(eq100(trafficSources.id, sourceRow2.id)).get();
71764
+ const latest = app.db.select().from(trafficSources).where(eq101(trafficSources.id, sourceRow2.id)).get();
71447
71765
  if (!latest || !isAuthoritativeTrafficSource(app.db, latest) || !isSameTrafficSourceGeneration(latest, sourceRow2)) {
71448
71766
  clearInterval(renewLease2);
71449
71767
  stopped.abort();
@@ -71491,10 +71809,10 @@ async function runBackfillTaskHoldingLease(options, signal) {
71491
71809
  const failedAt = (/* @__PURE__ */ new Date()).toISOString();
71492
71810
  try {
71493
71811
  app.db.transaction((tx) => {
71494
- tx.update(runs).set({ status: RunStatuses.failed, error: msg, finishedAt: failedAt }).where(eq100(runs.id, runId)).run();
71495
- const latestSource = tx.select().from(trafficSources).where(eq100(trafficSources.id, sourceRow2.id)).get();
71812
+ tx.update(runs).set({ status: RunStatuses.failed, error: msg, finishedAt: failedAt }).where(eq101(runs.id, runId)).run();
71813
+ const latestSource = tx.select().from(trafficSources).where(eq101(trafficSources.id, sourceRow2.id)).get();
71496
71814
  if (!preserveSourceState && latestSource && isAuthoritativeTrafficSource(tx, latestSource) && isSameBackfillSource(latestSource, sourceRow2, leaseOwner)) {
71497
- tx.update(trafficSources).set({ status: TrafficSourceStatuses.error, lastError: msg, updatedAt: failedAt }).where(eq100(trafficSources.id, sourceRow2.id)).run();
71815
+ tx.update(trafficSources).set({ status: TrafficSourceStatuses.error, lastError: msg, updatedAt: failedAt }).where(eq101(trafficSources.id, sourceRow2.id)).run();
71498
71816
  }
71499
71817
  });
71500
71818
  } catch {
@@ -71526,7 +71844,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
71526
71844
  let emptyOutcome;
71527
71845
  try {
71528
71846
  const completed = app.db.transaction((tx) => {
71529
- const latestSource = tx.select().from(trafficSources).where(eq100(trafficSources.id, sourceRow2.id)).get();
71847
+ const latestSource = tx.select().from(trafficSources).where(eq101(trafficSources.id, sourceRow2.id)).get();
71530
71848
  const stillAuthoritative = latestSource && isAuthoritativeTrafficSource(tx, latestSource) && isSameBackfillSource(latestSource, sourceRow2, leaseOwner);
71531
71849
  if (stillAuthoritative) {
71532
71850
  enforceRawEventSampleRetention(tx, sourceRow2.id, finishedAt2);
@@ -71535,7 +71853,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
71535
71853
  status: RunStatuses.failed,
71536
71854
  error: "Traffic source was deactivated or reconfigured during backfill",
71537
71855
  finishedAt: finishedAt2
71538
- }).where(eq100(runs.id, runId)).run();
71856
+ }).where(eq101(runs.id, runId)).run();
71539
71857
  return Boolean(stillAuthoritative);
71540
71858
  });
71541
71859
  emptyOutcome = completed ? { status: OutcomeStatuses.skipped, reasonCode: OutcomeReasonCodes.NO_DATA } : { status: OutcomeStatuses.failed, reasonCode: OutcomeReasonCodes.NOT_CONNECTED };
@@ -71567,13 +71885,13 @@ async function runBackfillTaskHoldingLease(options, signal) {
71567
71885
  const nextLastSyncedAt = Math.max(currentLastSyncedMs, windowEnd.getTime()) === windowEnd.getTime() ? windowEndIso : sourceRow2.lastSyncedAt;
71568
71886
  try {
71569
71887
  const commitOutcome = app.db.transaction((tx) => {
71570
- const latestSource = tx.select().from(trafficSources).where(eq100(trafficSources.id, sourceRow2.id)).get();
71888
+ const latestSource = tx.select().from(trafficSources).where(eq101(trafficSources.id, sourceRow2.id)).get();
71571
71889
  if (latestSource?.sourceType === TrafficSourceTypes.wordpress) {
71572
71890
  tx.update(runs).set({
71573
71891
  status: RunStatuses.failed,
71574
71892
  error: "Generic WordPress replace backfill is unavailable because retained coverage is unproven.",
71575
71893
  finishedAt
71576
- }).where(eq100(runs.id, runId)).run();
71894
+ }).where(eq101(runs.id, runId)).run();
71577
71895
  return "wordpress-backfill-unsupported";
71578
71896
  }
71579
71897
  if (!latestSource || !isAuthoritativeTrafficSource(tx, latestSource) || !isSameBackfillSource(latestSource, sourceRow2, leaseOwner)) {
@@ -71581,7 +71899,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
71581
71899
  status: RunStatuses.failed,
71582
71900
  error: "Traffic source was deactivated or reconfigured during backfill",
71583
71901
  finishedAt
71584
- }).where(eq100(runs.id, runId)).run();
71902
+ }).where(eq101(runs.id, runId)).run();
71585
71903
  return "source-inactive";
71586
71904
  }
71587
71905
  const rawSampleCutoff = enforceRawEventSampleRetention(
@@ -71590,37 +71908,37 @@ async function runBackfillTaskHoldingLease(options, signal) {
71590
71908
  finishedAt
71591
71909
  );
71592
71910
  tx.delete(crawlerEventsHourly).where(
71593
- and86(
71594
- eq100(crawlerEventsHourly.sourceId, sourceRow2.id),
71911
+ and87(
71912
+ eq101(crawlerEventsHourly.sourceId, sourceRow2.id),
71595
71913
  gte26(crawlerEventsHourly.tsHour, windowStartIso),
71596
71914
  lte27(crawlerEventsHourly.tsHour, windowEndIso)
71597
71915
  )
71598
71916
  ).run();
71599
71917
  tx.delete(aiUserFetchEventsHourly).where(
71600
- and86(
71601
- eq100(aiUserFetchEventsHourly.sourceId, sourceRow2.id),
71918
+ and87(
71919
+ eq101(aiUserFetchEventsHourly.sourceId, sourceRow2.id),
71602
71920
  gte26(aiUserFetchEventsHourly.tsHour, windowStartIso),
71603
71921
  lte27(aiUserFetchEventsHourly.tsHour, windowEndIso)
71604
71922
  )
71605
71923
  ).run();
71606
71924
  clearLikelyFakeAgentHits(tx, { sourceId: sourceRow2.id, windowStart: windowStartIso, windowEnd: windowEndIso });
71607
71925
  tx.delete(aiReferralEventsHourly).where(
71608
- and86(
71609
- eq100(aiReferralEventsHourly.sourceId, sourceRow2.id),
71926
+ and87(
71927
+ eq101(aiReferralEventsHourly.sourceId, sourceRow2.id),
71610
71928
  gte26(aiReferralEventsHourly.tsHour, windowStartIso),
71611
71929
  lte27(aiReferralEventsHourly.tsHour, windowEndIso)
71612
71930
  )
71613
71931
  ).run();
71614
71932
  tx.delete(rawEventSamples).where(
71615
- and86(
71616
- eq100(rawEventSamples.sourceId, sourceRow2.id),
71933
+ and87(
71934
+ eq101(rawEventSamples.sourceId, sourceRow2.id),
71617
71935
  gte26(rawEventSamples.ts, windowStartIso),
71618
71936
  lte27(rawEventSamples.ts, windowEndIso)
71619
71937
  )
71620
71938
  ).run();
71621
71939
  tx.delete(unrecognizedAgentEventsHourly).where(
71622
- and86(
71623
- eq100(unrecognizedAgentEventsHourly.sourceId, sourceRow2.id),
71940
+ and87(
71941
+ eq101(unrecognizedAgentEventsHourly.sourceId, sourceRow2.id),
71624
71942
  gte26(unrecognizedAgentEventsHourly.tsHour, windowStartIso),
71625
71943
  lte27(unrecognizedAgentEventsHourly.tsHour, windowEndIso)
71626
71944
  )
@@ -71651,7 +71969,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
71651
71969
  crawlerEventsHourly.status
71652
71970
  ],
71653
71971
  set: {
71654
- hits: sql45`${crawlerEventsHourly.hits} + ${bucket.hits}`,
71972
+ hits: sql46`${crawlerEventsHourly.hits} + ${bucket.hits}`,
71655
71973
  sampledUserAgent: bucket.sampledUserAgent,
71656
71974
  updatedAt: finishedAt
71657
71975
  }
@@ -71682,7 +72000,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
71682
72000
  crawlerVerificationManifestsHourly.manifestId
71683
72001
  ],
71684
72002
  set: {
71685
- hits: sql45`${crawlerVerificationManifestsHourly.hits} + ${bucket.hits}`,
72003
+ hits: sql46`${crawlerVerificationManifestsHourly.hits} + ${bucket.hits}`,
71686
72004
  manifestJson: bucket.verificationManifest,
71687
72005
  updatedAt: finishedAt
71688
72006
  }
@@ -71715,7 +72033,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
71715
72033
  aiUserFetchEventsHourly.status
71716
72034
  ],
71717
72035
  set: {
71718
- hits: sql45`${aiUserFetchEventsHourly.hits} + ${bucket.hits}`,
72036
+ hits: sql46`${aiUserFetchEventsHourly.hits} + ${bucket.hits}`,
71719
72037
  sampledUserAgent: bucket.sampledUserAgent,
71720
72038
  updatedAt: finishedAt
71721
72039
  }
@@ -71746,7 +72064,7 @@ async function runBackfillTaskHoldingLease(options, signal) {
71746
72064
  aiUserFetchVerificationManifestsHourly.manifestId
71747
72065
  ],
71748
72066
  set: {
71749
- hits: sql45`${aiUserFetchVerificationManifestsHourly.hits} + ${bucket.hits}`,
72067
+ hits: sql46`${aiUserFetchVerificationManifestsHourly.hits} + ${bucket.hits}`,
71750
72068
  manifestJson: bucket.verificationManifest,
71751
72069
  updatedAt: finishedAt
71752
72070
  }
@@ -71823,13 +72141,13 @@ async function runBackfillTaskHoldingLease(options, signal) {
71823
72141
  const skipRecovered = sourceRow2.sourceType !== TrafficSourceTypes.wordpress && Number.isFinite(recordedSkipMs) && windowStart.getTime() <= recordedSkipMs;
71824
72142
  let olderCountUntil = latestSource.aiReferralOlderCountUntil;
71825
72143
  if (olderCountUntil !== null) {
71826
- const ruleChange = tx.get(sql45`
72144
+ const ruleChange = tx.get(sql46`
71827
72145
  SELECT strftime('%Y-%m-%dT%H:%M:%fZ', applied_at) AS appliedAt
71828
72146
  FROM _migrations WHERE version = 207
71829
72147
  `);
71830
72148
  if (ruleChange?.appliedAt) {
71831
- const olderReferral = tx.select({ sourceId: aiReferralEventsHourly.sourceId }).from(aiReferralEventsHourly).where(and86(
71832
- eq100(aiReferralEventsHourly.sourceId, sourceRow2.id),
72149
+ const olderReferral = tx.select({ sourceId: aiReferralEventsHourly.sourceId }).from(aiReferralEventsHourly).where(and87(
72150
+ eq101(aiReferralEventsHourly.sourceId, sourceRow2.id),
71833
72151
  lt20(aiReferralEventsHourly.createdAt, ruleChange.appliedAt)
71834
72152
  )).limit(1).get();
71835
72153
  if (!olderReferral) olderCountUntil = null;
@@ -71850,8 +72168,8 @@ async function runBackfillTaskHoldingLease(options, signal) {
71850
72168
  aiUserFetchOlderCountUntil: userFetchOlderCountUntil,
71851
72169
  ...skipRecovered ? { skippedThroughAt: null } : {},
71852
72170
  updatedAt: finishedAt
71853
- }).where(eq100(trafficSources.id, sourceRow2.id)).run();
71854
- tx.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(eq100(runs.id, runId)).run();
72171
+ }).where(eq101(trafficSources.id, sourceRow2.id)).run();
72172
+ tx.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(eq101(runs.id, runId)).run();
71855
72173
  return "committed";
71856
72174
  });
71857
72175
  reportBackfill(commitOutcome === "committed" ? {
@@ -72025,7 +72343,7 @@ async function trafficRoutes(app, opts) {
72025
72343
  };
72026
72344
  const fallbackName = displayName ?? `Cloud Run \xB7 ${gcpProjectId}${serviceName ? ` / ${serviceName}` : ""}`;
72027
72345
  const { sourceRow: sourceRow2, scheduleChanged } = app.db.transaction((tx) => {
72028
- const activeSource = tx.select().from(trafficSources).where(eq100(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes["cloud-run"] && row.status !== TrafficSourceStatuses.archived);
72346
+ const activeSource = tx.select().from(trafficSources).where(eq101(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes["cloud-run"] && row.status !== TrafficSourceStatuses.archived);
72029
72347
  const sourceId = activeSource?.id ?? crypto60.randomUUID();
72030
72348
  const sourceStatus = trafficConnectStatus(tx, project.id, activeSource);
72031
72349
  if (activeSource) {
@@ -72035,7 +72353,7 @@ async function trafficRoutes(app, opts) {
72035
72353
  lastError: null,
72036
72354
  configJson: config,
72037
72355
  updatedAt: now
72038
- }).where(eq100(trafficSources.id, sourceId)).run();
72356
+ }).where(eq101(trafficSources.id, sourceId)).run();
72039
72357
  } else {
72040
72358
  tx.insert(trafficSources).values({
72041
72359
  id: sourceId,
@@ -72061,7 +72379,7 @@ async function trafficRoutes(app, opts) {
72061
72379
  entityId: sourceId
72062
72380
  });
72063
72381
  return {
72064
- sourceRow: tx.select().from(trafficSources).where(eq100(trafficSources.id, sourceId)).get(),
72382
+ sourceRow: tx.select().from(trafficSources).where(eq101(trafficSources.id, sourceId)).get(),
72065
72383
  scheduleChanged: scheduleBinding.changed
72066
72384
  };
72067
72385
  }, { behavior: "immediate" });
@@ -72116,7 +72434,7 @@ async function trafficRoutes(app, opts) {
72116
72434
  const config = { baseUrl, username };
72117
72435
  const fallbackName = displayName ?? `WordPress \xB7 ${new URL(baseUrl).host}`;
72118
72436
  const { sourceRow: sourceRow2, scheduleChanged } = app.db.transaction((tx) => {
72119
- const activeSource = tx.select().from(trafficSources).where(eq100(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes.wordpress && row.status !== TrafficSourceStatuses.archived);
72437
+ const activeSource = tx.select().from(trafficSources).where(eq101(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes.wordpress && row.status !== TrafficSourceStatuses.archived);
72120
72438
  const endpointChanged = activeSource !== void 0 && wordpressBaseUrlIdentity(activeSource.configJson.baseUrl) !== wordpressBaseUrlIdentity(baseUrl);
72121
72439
  const sourceId = endpointChanged ? crypto60.randomUUID() : activeSource?.id ?? crypto60.randomUUID();
72122
72440
  const sourceStatus = trafficConnectStatus(tx, project.id, activeSource);
@@ -72127,14 +72445,14 @@ async function trafficRoutes(app, opts) {
72127
72445
  lastError: null,
72128
72446
  configJson: config,
72129
72447
  updatedAt: now
72130
- }).where(eq100(trafficSources.id, sourceId)).run();
72448
+ }).where(eq101(trafficSources.id, sourceId)).run();
72131
72449
  } else {
72132
72450
  if (activeSource) {
72133
72451
  tx.update(trafficSources).set({
72134
72452
  status: TrafficSourceStatuses.archived,
72135
72453
  archivedAt: now,
72136
72454
  updatedAt: now
72137
- }).where(eq100(trafficSources.id, activeSource.id)).run();
72455
+ }).where(eq101(trafficSources.id, activeSource.id)).run();
72138
72456
  }
72139
72457
  tx.insert(trafficSources).values({
72140
72458
  id: sourceId,
@@ -72160,7 +72478,7 @@ async function trafficRoutes(app, opts) {
72160
72478
  entityId: sourceId
72161
72479
  });
72162
72480
  return {
72163
- sourceRow: tx.select().from(trafficSources).where(eq100(trafficSources.id, sourceId)).get(),
72481
+ sourceRow: tx.select().from(trafficSources).where(eq101(trafficSources.id, sourceId)).get(),
72164
72482
  scheduleChanged: scheduleBinding.changed
72165
72483
  };
72166
72484
  }, { behavior: "immediate" });
@@ -72217,7 +72535,7 @@ async function trafficRoutes(app, opts) {
72217
72535
  const config = { projectId, teamId, environment };
72218
72536
  const fallbackName = displayName ?? `Vercel \xB7 ${projectId}`;
72219
72537
  const { sourceRow: sourceRow2, scheduleChanged } = app.db.transaction((tx) => {
72220
- const activeSource = tx.select().from(trafficSources).where(eq100(trafficSources.projectId, project.id)).all().find((row2) => row2.sourceType === TrafficSourceTypes.vercel && row2.status !== TrafficSourceStatuses.archived);
72538
+ const activeSource = tx.select().from(trafficSources).where(eq101(trafficSources.projectId, project.id)).all().find((row2) => row2.sourceType === TrafficSourceTypes.vercel && row2.status !== TrafficSourceStatuses.archived);
72221
72539
  const sourceStatus = trafficConnectStatus(tx, project.id, activeSource);
72222
72540
  let row;
72223
72541
  if (activeSource) {
@@ -72227,8 +72545,8 @@ async function trafficRoutes(app, opts) {
72227
72545
  lastError: null,
72228
72546
  configJson: config,
72229
72547
  updatedAt: now
72230
- }).where(eq100(trafficSources.id, activeSource.id)).run();
72231
- row = tx.select().from(trafficSources).where(eq100(trafficSources.id, activeSource.id)).get();
72548
+ }).where(eq101(trafficSources.id, activeSource.id)).run();
72549
+ row = tx.select().from(trafficSources).where(eq101(trafficSources.id, activeSource.id)).get();
72232
72550
  } else {
72233
72551
  const newId = crypto60.randomUUID();
72234
72552
  tx.insert(trafficSources).values({
@@ -72253,7 +72571,7 @@ async function trafficRoutes(app, opts) {
72253
72571
  createdAt: now,
72254
72572
  updatedAt: now
72255
72573
  }).run();
72256
- row = tx.select().from(trafficSources).where(eq100(trafficSources.id, newId)).get();
72574
+ row = tx.select().from(trafficSources).where(eq101(trafficSources.id, newId)).get();
72257
72575
  }
72258
72576
  const scheduleBinding = sourceStatus === TrafficSourceStatuses.connected ? bindTrafficSyncSchedule(tx, project.id, row.id, now) : { changed: false, created: false };
72259
72577
  writeAuditLog(tx, {
@@ -72297,7 +72615,7 @@ async function trafficRoutes(app, opts) {
72297
72615
  const { displayName: displayName2, zoneId: zoneId2, accountId: accountId2, queueId, queueName, retentionSeconds, apiToken } = parsed.data;
72298
72616
  const workerRouteHost2 = resolveCloudflareWorkerRouteHost(project.canonicalDomain);
72299
72617
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
72300
- const cloudflareSources = app.db.select().from(trafficSources).where(eq100(trafficSources.projectId, project.id)).all().filter((row) => row.sourceType === TrafficSourceTypes.cloudflare && row.status !== TrafficSourceStatuses.archived);
72618
+ const cloudflareSources = app.db.select().from(trafficSources).where(eq101(trafficSources.projectId, project.id)).all().filter((row) => row.sourceType === TrafficSourceTypes.cloudflare && row.status !== TrafficSourceStatuses.archived);
72301
72619
  const sameModeSource = cloudflareSources.find((row) => parseQueuePullCloudflareSourceConfig(row.configJson));
72302
72620
  if (sameModeSource) attempt.update({ action: "reauth" });
72303
72621
  const sourceId2 = sameModeSource?.id ?? crypto60.randomUUID();
@@ -72351,7 +72669,7 @@ async function trafficRoutes(app, opts) {
72351
72669
  let scheduleChanged = false;
72352
72670
  try {
72353
72671
  const result = app.db.transaction((tx) => {
72354
- const currentSameModeSource = tx.select().from(trafficSources).where(eq100(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes.cloudflare && row.status !== TrafficSourceStatuses.archived && parseQueuePullCloudflareSourceConfig(row.configJson) !== null);
72672
+ const currentSameModeSource = tx.select().from(trafficSources).where(eq101(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes.cloudflare && row.status !== TrafficSourceStatuses.archived && parseQueuePullCloudflareSourceConfig(row.configJson) !== null);
72355
72673
  if ((currentSameModeSource?.id ?? null) !== (sameModeSource?.id ?? null)) {
72356
72674
  throw operationInProgress("Cloudflare Queue source changed during connect; retry");
72357
72675
  }
@@ -72369,7 +72687,7 @@ async function trafficRoutes(app, opts) {
72369
72687
  queueBacklogObservedAt: null
72370
72688
  } : {},
72371
72689
  updatedAt: now2
72372
- }).where(eq100(trafficSources.id, sourceId2)).run();
72690
+ }).where(eq101(trafficSources.id, sourceId2)).run();
72373
72691
  } else {
72374
72692
  tx.insert(trafficSources).values({
72375
72693
  id: sourceId2,
@@ -72389,7 +72707,7 @@ async function trafficRoutes(app, opts) {
72389
72707
  }
72390
72708
  const changed = status === TrafficSourceStatuses.connected ? bindTrafficSyncSchedule(tx, project.id, sourceId2, now2).changed : false;
72391
72709
  return {
72392
- row: tx.select().from(trafficSources).where(eq100(trafficSources.id, sourceId2)).get(),
72710
+ row: tx.select().from(trafficSources).where(eq101(trafficSources.id, sourceId2)).get(),
72393
72711
  scheduleChanged: changed
72394
72712
  };
72395
72713
  }, { behavior: "immediate" });
@@ -72439,7 +72757,7 @@ async function trafficRoutes(app, opts) {
72439
72757
  const { deliveryMode, displayName, zoneId, accountId } = parsed.data;
72440
72758
  const workerRouteHost = resolveCloudflareWorkerRouteHost(project.canonicalDomain);
72441
72759
  const now = (/* @__PURE__ */ new Date()).toISOString();
72442
- const activeSource = app.db.select().from(trafficSources).where(eq100(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes.cloudflare && row.status !== TrafficSourceStatuses.archived && parseDirectPushCloudflareSourceConfig(row.configJson) !== null);
72760
+ const activeSource = app.db.select().from(trafficSources).where(eq101(trafficSources.projectId, project.id)).all().find((row) => row.sourceType === TrafficSourceTypes.cloudflare && row.status !== TrafficSourceStatuses.archived && parseDirectPushCloudflareSourceConfig(row.configJson) !== null);
72443
72761
  if (activeSource) attempt.update({ action: "reauth" });
72444
72762
  const sourceId = activeSource?.id ?? crypto60.randomUUID();
72445
72763
  const parsedActiveConfig = activeSource ? parseDirectPushCloudflareSourceConfig(activeSource.configJson) : null;
@@ -72507,7 +72825,7 @@ async function trafficRoutes(app, opts) {
72507
72825
  let scheduleRemoved = false;
72508
72826
  try {
72509
72827
  const result = app.db.transaction((tx) => {
72510
- const currentActiveSource = tx.select().from(trafficSources).where(eq100(trafficSources.projectId, project.id)).all().find((row2) => row2.sourceType === TrafficSourceTypes.cloudflare && row2.status !== TrafficSourceStatuses.archived && parseDirectPushCloudflareSourceConfig(row2.configJson) !== null);
72828
+ const currentActiveSource = tx.select().from(trafficSources).where(eq101(trafficSources.projectId, project.id)).all().find((row2) => row2.sourceType === TrafficSourceTypes.cloudflare && row2.status !== TrafficSourceStatuses.archived && parseDirectPushCloudflareSourceConfig(row2.configJson) !== null);
72511
72829
  if ((currentActiveSource?.id ?? null) !== (activeSource?.id ?? null)) {
72512
72830
  throw operationInProgress("Cloudflare direct-push source changed during connect; retry");
72513
72831
  }
@@ -72521,8 +72839,8 @@ async function trafficRoutes(app, opts) {
72521
72839
  configJson: config,
72522
72840
  ingestTokenHash,
72523
72841
  updatedAt: now
72524
- }).where(eq100(trafficSources.id, currentActiveSource.id)).run();
72525
- row = tx.select().from(trafficSources).where(eq100(trafficSources.id, currentActiveSource.id)).get();
72842
+ }).where(eq101(trafficSources.id, currentActiveSource.id)).run();
72843
+ row = tx.select().from(trafficSources).where(eq101(trafficSources.id, currentActiveSource.id)).get();
72526
72844
  } else {
72527
72845
  tx.insert(trafficSources).values({
72528
72846
  id: sourceId,
@@ -72542,16 +72860,16 @@ async function trafficRoutes(app, opts) {
72542
72860
  createdAt: now,
72543
72861
  updatedAt: now
72544
72862
  }).run();
72545
- row = tx.select().from(trafficSources).where(eq100(trafficSources.id, sourceId)).get();
72863
+ row = tx.select().from(trafficSources).where(eq101(trafficSources.id, sourceId)).get();
72546
72864
  }
72547
72865
  let removed = false;
72548
72866
  if (row.status === TrafficSourceStatuses.connected) {
72549
- const schedule = tx.select().from(schedules).where(and86(
72550
- eq100(schedules.projectId, project.id),
72551
- eq100(schedules.kind, SchedulableRunKinds["traffic-sync"])
72867
+ const schedule = tx.select().from(schedules).where(and87(
72868
+ eq101(schedules.projectId, project.id),
72869
+ eq101(schedules.kind, SchedulableRunKinds["traffic-sync"])
72552
72870
  )).get();
72553
72871
  if (schedule) {
72554
- tx.delete(schedules).where(eq100(schedules.id, schedule.id)).run();
72872
+ tx.delete(schedules).where(eq101(schedules.id, schedule.id)).run();
72555
72873
  removed = true;
72556
72874
  }
72557
72875
  }
@@ -72607,47 +72925,47 @@ async function trafficRoutes(app, opts) {
72607
72925
  };
72608
72926
  }));
72609
72927
  app.post("/projects/:name/traffic/sources/:id/activate", connectionRoute(app, (request) => {
72610
- const source = app.db.select({ sourceType: trafficSources.sourceType }).from(trafficSources).where(eq100(trafficSources.id, request.params.id)).get();
72928
+ const source = app.db.select({ sourceType: trafficSources.sourceType }).from(trafficSources).where(eq101(trafficSources.id, request.params.id)).get();
72611
72929
  const integration = source ? TRAFFIC_SOURCE_INTEGRATIONS[source.sourceType] : void 0;
72612
72930
  return integration ? { integration, action: "select" } : void 0;
72613
72931
  }, async (request) => {
72614
72932
  const project = resolveProject(app.db, request.params.name);
72615
72933
  const now = (/* @__PURE__ */ new Date()).toISOString();
72616
72934
  const result = app.db.transaction((tx) => {
72617
- const target = tx.select().from(trafficSources).where(eq100(trafficSources.id, request.params.id)).get();
72935
+ const target = tx.select().from(trafficSources).where(eq101(trafficSources.id, request.params.id)).get();
72618
72936
  if (!target || target.projectId !== project.id || target.status === TrafficSourceStatuses.archived) {
72619
72937
  throw notFound("Traffic source", request.params.id);
72620
72938
  }
72621
72939
  const { usesPullSchedule } = validateTrafficSourceCredential(target, project.name);
72622
- const siblings = tx.select().from(trafficSources).where(eq100(trafficSources.projectId, project.id)).all();
72940
+ const siblings = tx.select().from(trafficSources).where(eq101(trafficSources.projectId, project.id)).all();
72623
72941
  for (const sibling of siblings) {
72624
72942
  if (sibling.id === target.id || sibling.status === TrafficSourceStatuses.archived) continue;
72625
72943
  tx.update(trafficSources).set({
72626
72944
  status: TrafficSourceStatuses.paused,
72627
72945
  updatedAt: now
72628
- }).where(eq100(trafficSources.id, sibling.id)).run();
72946
+ }).where(eq101(trafficSources.id, sibling.id)).run();
72629
72947
  }
72630
72948
  tx.update(trafficSources).set({
72631
72949
  status: TrafficSourceStatuses.connected,
72632
72950
  lastError: null,
72633
72951
  archivedAt: null,
72634
72952
  updatedAt: now
72635
- }).where(eq100(trafficSources.id, target.id)).run();
72953
+ }).where(eq101(trafficSources.id, target.id)).run();
72636
72954
  let scheduleAction = null;
72637
72955
  if (usesPullSchedule) {
72638
72956
  bindTrafficSyncSchedule(tx, project.id, target.id, now);
72639
72957
  scheduleAction = "upsert";
72640
72958
  } else {
72641
- const schedule = tx.select().from(schedules).where(and86(
72642
- eq100(schedules.projectId, project.id),
72643
- eq100(schedules.kind, SchedulableRunKinds["traffic-sync"])
72959
+ const schedule = tx.select().from(schedules).where(and87(
72960
+ eq101(schedules.projectId, project.id),
72961
+ eq101(schedules.kind, SchedulableRunKinds["traffic-sync"])
72644
72962
  )).get();
72645
72963
  if (schedule) {
72646
- tx.delete(schedules).where(eq100(schedules.id, schedule.id)).run();
72964
+ tx.delete(schedules).where(eq101(schedules.id, schedule.id)).run();
72647
72965
  scheduleAction = "delete";
72648
72966
  }
72649
72967
  }
72650
- const source = tx.select().from(trafficSources).where(eq100(trafficSources.id, target.id)).get();
72968
+ const source = tx.select().from(trafficSources).where(eq101(trafficSources.id, target.id)).get();
72651
72969
  writeAuditLog(tx, {
72652
72970
  projectId: project.id,
72653
72971
  actor: "api",
@@ -72715,7 +73033,7 @@ async function trafficRoutes(app, opts) {
72715
73033
  }
72716
73034
  const { bearerHash, credential } = authenticated;
72717
73035
  const sourceId = credential.sourceId;
72718
- const sourceRow2 = app.db.select().from(trafficSources).where(eq100(trafficSources.id, sourceId)).get();
73036
+ const sourceRow2 = app.db.select().from(trafficSources).where(eq101(trafficSources.id, sourceId)).get();
72719
73037
  if (!sourceRow2 || sourceRow2.sourceType !== TrafficSourceTypes.cloudflare || sourceRow2.status !== TrafficSourceStatuses.connected || !parseDirectPushCloudflareSourceConfig(sourceRow2.configJson) || !timingSafeEqualHex(bearerHash, sourceRow2.ingestTokenHash)) {
72720
73038
  throw authRequired();
72721
73039
  }
@@ -72795,7 +73113,7 @@ async function trafficRoutes(app, opts) {
72795
73113
  });
72796
73114
  app.post("/projects/:name/traffic/sources/:id/sync", async (request) => {
72797
73115
  const project = resolveProject(app.db, request.params.name);
72798
- const initialSourceRow = app.db.select().from(trafficSources).where(eq100(trafficSources.id, request.params.id)).get();
73116
+ const initialSourceRow = app.db.select().from(trafficSources).where(eq101(trafficSources.id, request.params.id)).get();
72799
73117
  if (!initialSourceRow || initialSourceRow.projectId !== project.id) {
72800
73118
  throw notFound("Traffic source", request.params.id);
72801
73119
  }
@@ -72869,7 +73187,7 @@ async function trafficRoutes(app, opts) {
72869
73187
  });
72870
73188
  const finishSync = (status, error, stopReason) => {
72871
73189
  const queueDrain = drainSummary(stopReason);
72872
- app.db.update(runs).set({ status, finishedAt: committedAt, syncSummary: queueDrain, ...error ? { error } : {} }).where(eq100(runs.id, runId)).run();
73190
+ app.db.update(runs).set({ status, finishedAt: committedAt, syncSummary: queueDrain, ...error ? { error } : {} }).where(eq101(runs.id, runId)).run();
72873
73191
  writeAuditLog(app.db, {
72874
73192
  projectId: project.id,
72875
73193
  actor: "api",
@@ -73046,7 +73364,7 @@ async function trafficRoutes(app, opts) {
73046
73364
  now: (/* @__PURE__ */ new Date()).toISOString(),
73047
73365
  ttlMs: CLOUDFLARE_QUEUE_SYNC_LEASE_TTL_MS
73048
73366
  })) throw new Error("Queue sync lease was lost before acknowledgement");
73049
- const latestSource = app.db.select().from(trafficSources).where(eq100(trafficSources.id, sourceRow2.id)).get();
73367
+ const latestSource = app.db.select().from(trafficSources).where(eq101(trafficSources.id, sourceRow2.id)).get();
73050
73368
  if (!latestSource || latestSource.projectId !== project.id || latestSource.status !== TrafficSourceStatuses.connected || latestSource.syncLeaseOwner !== leaseOwner || !isDeepStrictEqual(latestSource.configJson, sourceRow2.configJson)) {
73051
73369
  throw validationError("Cloudflare Queue source was reconfigured before acknowledgement");
73052
73370
  }
@@ -73136,13 +73454,13 @@ async function trafficRoutes(app, opts) {
73136
73454
  error: safeError,
73137
73455
  finishedAt: failedAt,
73138
73456
  syncSummary: drainSummary(CloudflareQueueDrainStopReasons.error)
73139
- }).where(eq100(runs.id, runId)).run();
73140
- const latestSource = tx.select().from(trafficSources).where(eq100(trafficSources.id, sourceRow2.id)).get();
73457
+ }).where(eq101(runs.id, runId)).run();
73458
+ const latestSource = tx.select().from(trafficSources).where(eq101(trafficSources.id, sourceRow2.id)).get();
73141
73459
  if (latestSource && latestSource.status === TrafficSourceStatuses.connected && latestSource.syncLeaseOwner === leaseOwner && isDeepStrictEqual(latestSource.configJson, sourceRow2.configJson)) {
73142
- tx.update(trafficSources).set({ lastError: safeError, updatedAt: failedAt }).where(and86(
73143
- eq100(trafficSources.id, sourceRow2.id),
73144
- eq100(trafficSources.status, TrafficSourceStatuses.connected),
73145
- eq100(trafficSources.syncLeaseOwner, leaseOwner)
73460
+ tx.update(trafficSources).set({ lastError: safeError, updatedAt: failedAt }).where(and87(
73461
+ eq101(trafficSources.id, sourceRow2.id),
73462
+ eq101(trafficSources.status, TrafficSourceStatuses.connected),
73463
+ eq101(trafficSources.syncLeaseOwner, leaseOwner)
73146
73464
  )).run();
73147
73465
  }
73148
73466
  });
@@ -73161,7 +73479,7 @@ async function trafficRoutes(app, opts) {
73161
73479
  `Sync for source type "${sourceRow2.sourceType}" is not implemented yet \u2014 only cloud-run, wordpress, and vercel are supported in v1.`
73162
73480
  );
73163
73481
  }
73164
- const hasConnectedSibling = sourceRow2.status === TrafficSourceStatuses.error && app.db.select().from(trafficSources).where(eq100(trafficSources.projectId, project.id)).all().some((row) => row.id !== sourceRow2.id && row.status === TrafficSourceStatuses.connected);
73482
+ const hasConnectedSibling = sourceRow2.status === TrafficSourceStatuses.error && app.db.select().from(trafficSources).where(eq101(trafficSources.projectId, project.id)).all().some((row) => row.id !== sourceRow2.id && row.status === TrafficSourceStatuses.connected);
73165
73483
  if (sourceRow2.status === TrafficSourceStatuses.paused || sourceRow2.status === TrafficSourceStatuses.archived || hasConnectedSibling) {
73166
73484
  throw validationError("Traffic source must be active before it can sync");
73167
73485
  }
@@ -73198,10 +73516,10 @@ async function trafficRoutes(app, opts) {
73198
73516
  const markFailed = (msg, errorCode2) => {
73199
73517
  const failedAt = (/* @__PURE__ */ new Date()).toISOString();
73200
73518
  app.db.transaction((tx) => {
73201
- tx.update(runs).set({ status: RunStatuses.failed, error: msg, finishedAt: failedAt }).where(eq100(runs.id, runId)).run();
73202
- const latestSource = tx.select().from(trafficSources).where(eq100(trafficSources.id, sourceRow2.id)).get();
73519
+ tx.update(runs).set({ status: RunStatuses.failed, error: msg, finishedAt: failedAt }).where(eq101(runs.id, runId)).run();
73520
+ const latestSource = tx.select().from(trafficSources).where(eq101(trafficSources.id, sourceRow2.id)).get();
73203
73521
  if (latestSource?.status === TrafficSourceStatuses.connected && isSameTrafficSourceGeneration(latestSource, sourceRow2) && latestSource.syncLeaseOwner === syncLeaseOwner) {
73204
- tx.update(trafficSources).set({ status: TrafficSourceStatuses.error, lastError: msg, updatedAt: failedAt }).where(eq100(trafficSources.id, sourceRow2.id)).run();
73522
+ tx.update(trafficSources).set({ status: TrafficSourceStatuses.error, lastError: msg, updatedAt: failedAt }).where(eq101(trafficSources.id, sourceRow2.id)).run();
73205
73523
  }
73206
73524
  });
73207
73525
  try {
@@ -73295,7 +73613,7 @@ async function trafficRoutes(app, opts) {
73295
73613
  }
73296
73614
  const credential = credentialStore.getConnection(project.name);
73297
73615
  if (!credential) {
73298
- app.db.delete(runs).where(eq100(runs.id, runId)).run();
73616
+ app.db.delete(runs).where(eq101(runs.id, runId)).run();
73299
73617
  throw validationError(
73300
73618
  `No WordPress credential found for project "${project.name}". Run "canonry traffic connect wordpress" first.`
73301
73619
  );
@@ -73329,14 +73647,14 @@ async function trafficRoutes(app, opts) {
73329
73647
  const windowEndIso2 = windowEnd.toISOString();
73330
73648
  const reservedAt = (/* @__PURE__ */ new Date()).toISOString();
73331
73649
  const reservedSource = app.db.transaction((tx) => {
73332
- const latestSource = tx.select().from(trafficSources).where(eq100(trafficSources.id, sourceRow2.id)).get();
73650
+ const latestSource = tx.select().from(trafficSources).where(eq101(trafficSources.id, sourceRow2.id)).get();
73333
73651
  if (!latestSource || !isAuthoritativeTrafficSource(tx, latestSource) || !isSameTrafficSourceGeneration(latestSource, sourceRow2) || latestSource.syncLeaseOwner !== syncLeaseOwner || latestSource.lastCursor || latestSource.wordpressPendingUntil) return void 0;
73334
73652
  tx.update(trafficSources).set({
73335
73653
  lastSyncedAt: windowStartIso2,
73336
73654
  wordpressPendingUntil: windowEndIso2,
73337
73655
  updatedAt: reservedAt
73338
- }).where(eq100(trafficSources.id, sourceRow2.id)).run();
73339
- return tx.select().from(trafficSources).where(eq100(trafficSources.id, sourceRow2.id)).get();
73656
+ }).where(eq101(trafficSources.id, sourceRow2.id)).run();
73657
+ return tx.select().from(trafficSources).where(eq101(trafficSources.id, sourceRow2.id)).get();
73340
73658
  }, { behavior: "immediate" });
73341
73659
  if (!reservedSource) {
73342
73660
  const message = "Traffic source changed while reserving the WordPress sync window; retry the sync.";
@@ -73396,12 +73714,12 @@ async function trafficRoutes(app, opts) {
73396
73714
  auditAction = "traffic.vercel.synced";
73397
73715
  const credentialStore = opts.vercelTrafficCredentialStore;
73398
73716
  if (!credentialStore) {
73399
- app.db.delete(runs).where(eq100(runs.id, runId)).run();
73717
+ app.db.delete(runs).where(eq101(runs.id, runId)).run();
73400
73718
  throw validationError("Vercel traffic credential storage is not configured for this deployment");
73401
73719
  }
73402
73720
  const credential = credentialStore.getConnection(project.name);
73403
73721
  if (!credential) {
73404
- app.db.delete(runs).where(eq100(runs.id, runId)).run();
73722
+ app.db.delete(runs).where(eq101(runs.id, runId)).run();
73405
73723
  throw validationError(
73406
73724
  `No Vercel credential found for project "${project.name}". Run "canonry traffic connect vercel" first.`
73407
73725
  );
@@ -73419,7 +73737,7 @@ async function trafficRoutes(app, opts) {
73419
73737
  if (cappedStartMs > clampedStartMs) {
73420
73738
  const previousSkip = sourceRow2.skippedThroughAt ? Date.parse(sourceRow2.skippedThroughAt) : Number.NaN;
73421
73739
  const skippedThrough = Number.isFinite(previousSkip) ? new Date(Math.max(previousSkip, cappedStartMs)) : new Date(cappedStartMs);
73422
- app.db.update(trafficSources).set({ skippedThroughAt: skippedThrough.toISOString() }).where(eq100(trafficSources.id, sourceRow2.id)).run();
73740
+ app.db.update(trafficSources).set({ skippedThroughAt: skippedThrough.toISOString() }).where(eq101(trafficSources.id, sourceRow2.id)).run();
73423
73741
  request.log.warn(
73424
73742
  {
73425
73743
  sourceId: sourceRow2.id,
@@ -73514,15 +73832,15 @@ async function trafficRoutes(app, opts) {
73514
73832
  throw providerError(`WordPress sync failed: ${msg}`);
73515
73833
  }
73516
73834
  const commitOutcome = app.db.transaction((tx) => {
73517
- const latestRow = tx.select().from(trafficSources).where(eq100(trafficSources.id, sourceRow2.id)).get();
73518
- const latestHasConnectedSibling = tx.select().from(trafficSources).where(eq100(trafficSources.projectId, project.id)).all().some((row) => row.id !== sourceRow2.id && row.status === TrafficSourceStatuses.connected);
73835
+ const latestRow = tx.select().from(trafficSources).where(eq101(trafficSources.id, sourceRow2.id)).get();
73836
+ const latestHasConnectedSibling = tx.select().from(trafficSources).where(eq101(trafficSources.projectId, project.id)).all().some((row) => row.id !== sourceRow2.id && row.status === TrafficSourceStatuses.connected);
73519
73837
  if (!latestRow || latestRow.status !== TrafficSourceStatuses.connected && latestRow.status !== TrafficSourceStatuses.error || latestHasConnectedSibling || latestRow.syncLeaseOwner !== syncLeaseOwner || !isSameTrafficSourceGeneration(latestRow, sourceRow2)) {
73520
73838
  const abortedAt = (/* @__PURE__ */ new Date()).toISOString();
73521
73839
  tx.update(runs).set({
73522
73840
  status: RunStatuses.failed,
73523
73841
  error: "Traffic source was deactivated or reconfigured during sync",
73524
73842
  finishedAt: abortedAt
73525
- }).where(eq100(runs.id, runId)).run();
73843
+ }).where(eq101(runs.id, runId)).run();
73526
73844
  return "source-inactive";
73527
73845
  }
73528
73846
  const previousIds = latestRow.lastEventIds ?? [];
@@ -73587,7 +73905,7 @@ async function trafficRoutes(app, opts) {
73587
73905
  crawlerEventsHourly.status
73588
73906
  ],
73589
73907
  set: {
73590
- hits: sql45`${crawlerEventsHourly.hits} + ${bucket.hits}`,
73908
+ hits: sql46`${crawlerEventsHourly.hits} + ${bucket.hits}`,
73591
73909
  sampledUserAgent: bucket.sampledUserAgent,
73592
73910
  updatedAt: finishedAt
73593
73911
  }
@@ -73618,7 +73936,7 @@ async function trafficRoutes(app, opts) {
73618
73936
  crawlerVerificationManifestsHourly.manifestId
73619
73937
  ],
73620
73938
  set: {
73621
- hits: sql45`${crawlerVerificationManifestsHourly.hits} + ${bucket.hits}`,
73939
+ hits: sql46`${crawlerVerificationManifestsHourly.hits} + ${bucket.hits}`,
73622
73940
  manifestJson: bucket.verificationManifest,
73623
73941
  updatedAt: finishedAt
73624
73942
  }
@@ -73652,7 +73970,7 @@ async function trafficRoutes(app, opts) {
73652
73970
  aiUserFetchEventsHourly.status
73653
73971
  ],
73654
73972
  set: {
73655
- hits: sql45`${aiUserFetchEventsHourly.hits} + ${bucket.hits}`,
73973
+ hits: sql46`${aiUserFetchEventsHourly.hits} + ${bucket.hits}`,
73656
73974
  sampledUserAgent: bucket.sampledUserAgent,
73657
73975
  updatedAt: finishedAt
73658
73976
  }
@@ -73683,7 +74001,7 @@ async function trafficRoutes(app, opts) {
73683
74001
  aiUserFetchVerificationManifestsHourly.manifestId
73684
74002
  ],
73685
74003
  set: {
73686
- hits: sql45`${aiUserFetchVerificationManifestsHourly.hits} + ${bucket.hits}`,
74004
+ hits: sql46`${aiUserFetchVerificationManifestsHourly.hits} + ${bucket.hits}`,
73687
74005
  manifestJson: bucket.verificationManifest,
73688
74006
  updatedAt: finishedAt
73689
74007
  }
@@ -73725,9 +74043,9 @@ async function trafficRoutes(app, opts) {
73725
74043
  // colliding bucket adds its paid and organic arrivals to the ones
73726
74044
  // already there rather than overwriting a single label.
73727
74045
  set: {
73728
- sessionsOrHits: sql45`${aiReferralEventsHourly.sessionsOrHits} + ${bucket.hits}`,
73729
- paidSessionsOrHits: sql45`${aiReferralEventsHourly.paidSessionsOrHits} + ${bucket.paidHits}`,
73730
- organicSessionsOrHits: sql45`${aiReferralEventsHourly.organicSessionsOrHits} + ${bucket.organicHits}`,
74046
+ sessionsOrHits: sql46`${aiReferralEventsHourly.sessionsOrHits} + ${bucket.hits}`,
74047
+ paidSessionsOrHits: sql46`${aiReferralEventsHourly.paidSessionsOrHits} + ${bucket.paidHits}`,
74048
+ organicSessionsOrHits: sql46`${aiReferralEventsHourly.organicSessionsOrHits} + ${bucket.organicHits}`,
73731
74049
  updatedAt: finishedAt
73732
74050
  }
73733
74051
  }).run();
@@ -73809,8 +74127,8 @@ async function trafficRoutes(app, opts) {
73809
74127
  sourceUpdate.lastCursor = nextCursor ?? null;
73810
74128
  sourceUpdate.wordpressPendingUntil = nextCursor ? windowEnd.toISOString() : null;
73811
74129
  }
73812
- tx.update(trafficSources).set(sourceUpdate).where(eq100(trafficSources.id, sourceRow2.id)).run();
73813
- tx.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(eq100(runs.id, runId)).run();
74130
+ tx.update(trafficSources).set(sourceUpdate).where(eq101(trafficSources.id, sourceRow2.id)).run();
74131
+ tx.update(runs).set({ status: RunStatuses.completed, finishedAt }).where(eq101(runs.id, runId)).run();
73814
74132
  return "committed";
73815
74133
  }, { behavior: "immediate" });
73816
74134
  if (commitOutcome === "source-inactive") {
@@ -73881,7 +74199,7 @@ async function trafficRoutes(app, opts) {
73881
74199
  });
73882
74200
  app.post("/projects/:name/traffic/sources/:id/backfill", async (request) => withFeatureOutcome(app, { feature: "server_traffic", operation: "backfill" }, async (recordOutcome) => {
73883
74201
  const project = resolveProject(app.db, request.params.name);
73884
- const sourceRow2 = app.db.select().from(trafficSources).where(eq100(trafficSources.id, request.params.id)).get();
74202
+ const sourceRow2 = app.db.select().from(trafficSources).where(eq101(trafficSources.id, request.params.id)).get();
73885
74203
  if (!sourceRow2 || sourceRow2.projectId !== project.id) {
73886
74204
  throw notFound("Traffic source", request.params.id);
73887
74205
  }
@@ -74006,7 +74324,7 @@ async function trafficRoutes(app, opts) {
74006
74324
  }
74007
74325
  try {
74008
74326
  app.db.transaction((tx) => {
74009
- const latestSource = tx.select().from(trafficSources).where(eq100(trafficSources.id, sourceRow2.id)).get();
74327
+ const latestSource = tx.select().from(trafficSources).where(eq101(trafficSources.id, sourceRow2.id)).get();
74010
74328
  if (!latestSource || !isAuthoritativeTrafficSource(tx, latestSource) || !isSameTrafficSourceGeneration(latestSource, sourceRow2)) {
74011
74329
  throw validationError("Traffic source must remain active and unchanged before it can backfill");
74012
74330
  }
@@ -74054,10 +74372,10 @@ async function trafficRoutes(app, opts) {
74054
74372
  function buildSourceDetail(projectId, row, since) {
74055
74373
  const crawlerPathRows = app.db.select({
74056
74374
  pathNormalized: crawlerEventsHourly.pathNormalized,
74057
- hits: sql45`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`
74375
+ hits: sql46`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`
74058
74376
  }).from(crawlerEventsHourly).where(
74059
- and86(
74060
- eq100(crawlerEventsHourly.sourceId, row.id),
74377
+ and87(
74378
+ eq101(crawlerEventsHourly.sourceId, row.id),
74061
74379
  gte26(crawlerEventsHourly.tsHour, since)
74062
74380
  )
74063
74381
  ).groupBy(crawlerEventsHourly.pathNormalized).all();
@@ -74065,39 +74383,39 @@ async function trafficRoutes(app, opts) {
74065
74383
  crawlerPathRows.map((r) => ({ pathNormalized: r.pathNormalized, hits: Number(r.hits) }))
74066
74384
  );
74067
74385
  const crawlerTotal = crawlerSegments.content + crawlerSegments.sitemap + crawlerSegments.robots + crawlerSegments.asset + crawlerSegments.other;
74068
- const aiUserFetchTotals = app.db.select({ total: sql45`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
74069
- and86(
74070
- eq100(aiUserFetchEventsHourly.sourceId, row.id),
74386
+ const aiUserFetchTotals = app.db.select({ total: sql46`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
74387
+ and87(
74388
+ eq101(aiUserFetchEventsHourly.sourceId, row.id),
74071
74389
  gte26(aiUserFetchEventsHourly.tsHour, since)
74072
74390
  )
74073
74391
  ).get();
74074
- const likelyFakeTotals = app.db.select({ total: sql45`COALESCE(SUM(${aiUserFetchLikelyFakeHourly.hits}), 0)` }).from(aiUserFetchLikelyFakeHourly).where(
74075
- and86(
74076
- eq100(aiUserFetchLikelyFakeHourly.sourceId, row.id),
74392
+ const likelyFakeTotals = app.db.select({ total: sql46`COALESCE(SUM(${aiUserFetchLikelyFakeHourly.hits}), 0)` }).from(aiUserFetchLikelyFakeHourly).where(
74393
+ and87(
74394
+ eq101(aiUserFetchLikelyFakeHourly.sourceId, row.id),
74077
74395
  gte26(aiUserFetchLikelyFakeHourly.tsHour, since)
74078
74396
  )
74079
74397
  ).get();
74080
74398
  const aiTotals = app.db.select({
74081
- total: sql45`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)`,
74082
- nonhop: sql45`COALESCE(SUM(CASE WHEN ${referralLandedCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`,
74083
- landed: sql45`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`
74399
+ total: sql46`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)`,
74400
+ nonhop: sql46`COALESCE(SUM(CASE WHEN ${referralLandedCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`,
74401
+ landed: sql46`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`
74084
74402
  }).from(aiReferralEventsHourly).where(
74085
- and86(
74086
- eq100(aiReferralEventsHourly.sourceId, row.id),
74403
+ and87(
74404
+ eq101(aiReferralEventsHourly.sourceId, row.id),
74087
74405
  gte26(aiReferralEventsHourly.tsHour, since)
74088
74406
  )
74089
74407
  ).get();
74090
- const sampleTotals = app.db.select({ total: sql45`COUNT(*)` }).from(rawEventSamples).where(
74091
- and86(
74092
- eq100(rawEventSamples.sourceId, row.id),
74408
+ const sampleTotals = app.db.select({ total: sql46`COUNT(*)` }).from(rawEventSamples).where(
74409
+ and87(
74410
+ eq101(rawEventSamples.sourceId, row.id),
74093
74411
  gte26(rawEventSamples.ts, since)
74094
74412
  )
74095
74413
  ).get();
74096
74414
  const latestRun2 = app.db.select().from(runs).where(
74097
- and86(
74098
- eq100(runs.projectId, projectId),
74099
- eq100(runs.kind, RunKinds["traffic-sync"]),
74100
- eq100(runs.sourceId, row.id)
74415
+ and87(
74416
+ eq101(runs.projectId, projectId),
74417
+ eq101(runs.kind, RunKinds["traffic-sync"]),
74418
+ eq101(runs.sourceId, row.id)
74101
74419
  )
74102
74420
  ).orderBy(desc46(runs.startedAt)).limit(1).get();
74103
74421
  return {
@@ -74135,7 +74453,7 @@ async function trafficRoutes(app, opts) {
74135
74453
  const now = (/* @__PURE__ */ new Date()).toISOString();
74136
74454
  let updatedRow;
74137
74455
  app.db.transaction((tx) => {
74138
- const sourceRow2 = tx.select().from(trafficSources).where(and86(eq100(trafficSources.projectId, project.id), eq100(trafficSources.id, request.params.id))).get();
74456
+ const sourceRow2 = tx.select().from(trafficSources).where(and87(eq101(trafficSources.projectId, project.id), eq101(trafficSources.id, request.params.id))).get();
74139
74457
  if (!sourceRow2) {
74140
74458
  throw notFound("traffic source", request.params.id);
74141
74459
  }
@@ -74149,7 +74467,7 @@ async function trafficRoutes(app, opts) {
74149
74467
  `Traffic source "${sourceRow2.id}" is staged. Activate it explicitly instead of resetting it.`
74150
74468
  );
74151
74469
  }
74152
- const hasConnectedSibling = tx.select().from(trafficSources).where(eq100(trafficSources.projectId, project.id)).all().some((row) => row.id !== sourceRow2.id && row.status === TrafficSourceStatuses.connected);
74470
+ const hasConnectedSibling = tx.select().from(trafficSources).where(eq101(trafficSources.projectId, project.id)).all().some((row) => row.id !== sourceRow2.id && row.status === TrafficSourceStatuses.connected);
74153
74471
  if (hasConnectedSibling) {
74154
74472
  throw validationError(
74155
74473
  `Traffic source "${sourceRow2.id}" is not authoritative. Activate it explicitly instead of resetting it.`
@@ -74166,7 +74484,7 @@ async function trafficRoutes(app, opts) {
74166
74484
  status: TrafficSourceStatuses.connected,
74167
74485
  lastError: null,
74168
74486
  updatedAt: now
74169
- }).where(eq100(trafficSources.id, sourceRow2.id)).run();
74487
+ }).where(eq101(trafficSources.id, sourceRow2.id)).run();
74170
74488
  writeAuditLog(tx, auditFromRequest(request, {
74171
74489
  projectId: project.id,
74172
74490
  actor: "api",
@@ -74174,7 +74492,7 @@ async function trafficRoutes(app, opts) {
74174
74492
  entityType: "traffic_source",
74175
74493
  entityId: sourceRow2.id
74176
74494
  }));
74177
- updatedRow = tx.select().from(trafficSources).where(eq100(trafficSources.id, sourceRow2.id)).get();
74495
+ updatedRow = tx.select().from(trafficSources).where(eq101(trafficSources.id, sourceRow2.id)).get();
74178
74496
  });
74179
74497
  return buildSourceDetail(project.id, updatedRow, new Date(Date.now() - 24 * 60 * 6e4).toISOString());
74180
74498
  }));
@@ -74186,7 +74504,7 @@ async function trafficRoutes(app, opts) {
74186
74504
  }
74187
74505
  let updatedRow;
74188
74506
  app.db.transaction((tx) => {
74189
- const sourceRow2 = tx.select().from(trafficSources).where(and86(eq100(trafficSources.projectId, project.id), eq100(trafficSources.id, request.params.id))).get();
74507
+ const sourceRow2 = tx.select().from(trafficSources).where(and87(eq101(trafficSources.projectId, project.id), eq101(trafficSources.id, request.params.id))).get();
74190
74508
  if (!sourceRow2) {
74191
74509
  throw notFound("traffic source", request.params.id);
74192
74510
  }
@@ -74199,7 +74517,7 @@ async function trafficRoutes(app, opts) {
74199
74517
  );
74200
74518
  }
74201
74519
  const now = (/* @__PURE__ */ new Date()).toISOString();
74202
- tx.update(trafficSources).set({ skippedThroughAt: null, updatedAt: now }).where(eq100(trafficSources.id, sourceRow2.id)).run();
74520
+ tx.update(trafficSources).set({ skippedThroughAt: null, updatedAt: now }).where(eq101(trafficSources.id, sourceRow2.id)).run();
74203
74521
  writeAuditLog(tx, auditFromRequest(request, {
74204
74522
  projectId: project.id,
74205
74523
  actor: "api",
@@ -74208,20 +74526,20 @@ async function trafficRoutes(app, opts) {
74208
74526
  entityId: sourceRow2.id,
74209
74527
  diff: { skippedThroughAt: sourceRow2.skippedThroughAt, sourceType: sourceRow2.sourceType }
74210
74528
  }));
74211
- updatedRow = tx.select().from(trafficSources).where(eq100(trafficSources.id, sourceRow2.id)).get();
74529
+ updatedRow = tx.select().from(trafficSources).where(eq101(trafficSources.id, sourceRow2.id)).get();
74212
74530
  });
74213
74531
  return buildSourceDetail(project.id, updatedRow, new Date(Date.now() - 24 * 60 * 6e4).toISOString());
74214
74532
  });
74215
74533
  app.get("/projects/:name/traffic/sources", async (request) => {
74216
74534
  const project = resolveProject(app.db, request.params.name);
74217
- const rows = app.db.select().from(trafficSources).where(eq100(trafficSources.projectId, project.id)).orderBy(desc46(trafficSources.createdAt)).all();
74535
+ const rows = app.db.select().from(trafficSources).where(eq101(trafficSources.projectId, project.id)).orderBy(desc46(trafficSources.createdAt)).all();
74218
74536
  const sources = rows.filter((row) => row.status !== TrafficSourceStatuses.archived).map(rowToDto);
74219
74537
  const response = { sources };
74220
74538
  return response;
74221
74539
  });
74222
74540
  app.get("/projects/:name/traffic/status", async (request) => {
74223
74541
  const project = resolveProject(app.db, request.params.name);
74224
- const rows = app.db.select().from(trafficSources).where(eq100(trafficSources.projectId, project.id)).orderBy(desc46(trafficSources.createdAt)).all();
74542
+ const rows = app.db.select().from(trafficSources).where(eq101(trafficSources.projectId, project.id)).orderBy(desc46(trafficSources.createdAt)).all();
74225
74543
  const since = new Date(Date.now() - 24 * 60 * 6e4).toISOString();
74226
74544
  const sources = rows.filter((row) => row.status !== TrafficSourceStatuses.archived).map((row) => buildSourceDetail(project.id, row, since));
74227
74545
  const response = { sources };
@@ -74231,7 +74549,7 @@ async function trafficRoutes(app, opts) {
74231
74549
  "/projects/:name/traffic/sources/:id",
74232
74550
  async (request) => {
74233
74551
  const project = resolveProject(app.db, request.params.name);
74234
- const row = app.db.select().from(trafficSources).where(eq100(trafficSources.id, request.params.id)).get();
74552
+ const row = app.db.select().from(trafficSources).where(eq101(trafficSources.id, request.params.id)).get();
74235
74553
  if (!row || row.projectId !== project.id) {
74236
74554
  throw notFound("Traffic source", request.params.id);
74237
74555
  }
@@ -74300,16 +74618,16 @@ async function trafficRoutes(app, opts) {
74300
74618
  const seriesByBucket = /* @__PURE__ */ new Map();
74301
74619
  if (kinds.has(TrafficEventKinds.crawler)) {
74302
74620
  const crawlerFilters = [
74303
- eq100(crawlerEventsHourly.projectId, project.id),
74621
+ eq101(crawlerEventsHourly.projectId, project.id),
74304
74622
  gte26(crawlerEventsHourly.tsHour, sinceIso),
74305
74623
  lte27(crawlerEventsHourly.tsHour, untilIso)
74306
74624
  ];
74307
- if (sourceIdParam) crawlerFilters.push(eq100(crawlerEventsHourly.sourceId, sourceIdParam));
74308
- const crawlerWhere = and86(...crawlerFilters);
74625
+ if (sourceIdParam) crawlerFilters.push(eq101(crawlerEventsHourly.sourceId, sourceIdParam));
74626
+ const crawlerWhere = and87(...crawlerFilters);
74309
74627
  const pathTotals = app.db.select({
74310
74628
  pathNormalized: crawlerEventsHourly.pathNormalized,
74311
- hits: sql45`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`,
74312
- rows: sql45`COUNT(*)`
74629
+ hits: sql46`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`,
74630
+ rows: sql46`COUNT(*)`
74313
74631
  }).from(crawlerEventsHourly).where(crawlerWhere).groupBy(crawlerEventsHourly.pathNormalized).all();
74314
74632
  crawlerSegments = segmentCrawlerHits(
74315
74633
  pathTotals.map((r) => ({ pathNormalized: r.pathNormalized, hits: Number(r.hits) }))
@@ -74328,12 +74646,12 @@ async function trafficRoutes(app, opts) {
74328
74646
  const listed = useContentList ? contentPaths : infraPaths;
74329
74647
  const IN_LIST_CAP = 2e4;
74330
74648
  const listFitsInSql = listed.length <= IN_LIST_CAP;
74331
- const contentExpr = listed.length === 0 ? useContentList ? sql45`0` : sql45`${crawlerEventsHourly.hits}` : useContentList ? sql45`CASE WHEN ${inArray46(crawlerEventsHourly.pathNormalized, listed)} THEN ${crawlerEventsHourly.hits} ELSE 0 END` : sql45`CASE WHEN ${inArray46(crawlerEventsHourly.pathNormalized, listed)} THEN 0 ELSE ${crawlerEventsHourly.hits} END`;
74649
+ const contentExpr = listed.length === 0 ? useContentList ? sql46`0` : sql46`${crawlerEventsHourly.hits}` : useContentList ? sql46`CASE WHEN ${inArray47(crawlerEventsHourly.pathNormalized, listed)} THEN ${crawlerEventsHourly.hits} ELSE 0 END` : sql46`CASE WHEN ${inArray47(crawlerEventsHourly.pathNormalized, listed)} THEN 0 ELSE ${crawlerEventsHourly.hits} END`;
74332
74650
  if (listFitsInSql) {
74333
74651
  const crawlerSeries = app.db.select({
74334
74652
  bucket: crawlerSeriesBucket,
74335
- hits: sql45`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`,
74336
- content: sql45`COALESCE(SUM(${contentExpr}), 0)`
74653
+ hits: sql46`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`,
74654
+ content: sql46`COALESCE(SUM(${contentExpr}), 0)`
74337
74655
  }).from(crawlerEventsHourly).where(crawlerWhere).groupBy(crawlerSeriesBucket).all();
74338
74656
  for (const row of crawlerSeries) {
74339
74657
  const point = trafficSeriesPoint(seriesByBucket, String(row.bucket));
@@ -74345,7 +74663,7 @@ async function trafficRoutes(app, opts) {
74345
74663
  const grouped = app.db.select({
74346
74664
  bucket: crawlerSeriesBucket,
74347
74665
  pathNormalized: crawlerEventsHourly.pathNormalized,
74348
- hits: sql45`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`
74666
+ hits: sql46`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)`
74349
74667
  }).from(crawlerEventsHourly).where(crawlerWhere).groupBy(crawlerSeriesBucket, crawlerEventsHourly.pathNormalized).all();
74350
74668
  for (const row of grouped) {
74351
74669
  const point = trafficSeriesPoint(seriesByBucket, String(row.bucket));
@@ -74375,22 +74693,22 @@ async function trafficRoutes(app, opts) {
74375
74693
  }
74376
74694
  if (kinds.has(TrafficEventKinds["ai-user-fetch"])) {
74377
74695
  const userFetchFilters = [
74378
- eq100(aiUserFetchEventsHourly.projectId, project.id),
74696
+ eq101(aiUserFetchEventsHourly.projectId, project.id),
74379
74697
  gte26(aiUserFetchEventsHourly.tsHour, sinceIso),
74380
74698
  lte27(aiUserFetchEventsHourly.tsHour, untilIso)
74381
74699
  ];
74382
- if (sourceIdParam) userFetchFilters.push(eq100(aiUserFetchEventsHourly.sourceId, sourceIdParam));
74383
- const userFetchWhere = and86(...userFetchFilters);
74700
+ if (sourceIdParam) userFetchFilters.push(eq101(aiUserFetchEventsHourly.sourceId, sourceIdParam));
74701
+ const userFetchWhere = and87(...userFetchFilters);
74384
74702
  const total = app.db.select({
74385
- total: sql45`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)`,
74386
- rows: sql45`COUNT(*)`
74703
+ total: sql46`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)`,
74704
+ rows: sql46`COUNT(*)`
74387
74705
  }).from(aiUserFetchEventsHourly).where(userFetchWhere).get();
74388
74706
  aiUserFetchTotal = Number(total?.total ?? 0);
74389
74707
  totalEventRows += Number(total?.rows ?? 0);
74390
74708
  const userFetchSeriesBucket = seriesBucketSql(aiUserFetchEventsHourly.tsHour, granularity);
74391
74709
  const userFetchSeries = app.db.select({
74392
74710
  bucket: userFetchSeriesBucket,
74393
- hits: sql45`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)`
74711
+ hits: sql46`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)`
74394
74712
  }).from(aiUserFetchEventsHourly).where(userFetchWhere).groupBy(userFetchSeriesBucket).all();
74395
74713
  for (const row of userFetchSeries) {
74396
74714
  trafficSeriesPoint(seriesByBucket, row.bucket).aiUserFetchHits = Number(row.hits);
@@ -74414,19 +74732,19 @@ async function trafficRoutes(app, opts) {
74414
74732
  }
74415
74733
  if (kinds.has(TrafficEventKinds["ai-referral"])) {
74416
74734
  const aiFilters = [
74417
- eq100(aiReferralEventsHourly.projectId, project.id),
74735
+ eq101(aiReferralEventsHourly.projectId, project.id),
74418
74736
  gte26(aiReferralEventsHourly.tsHour, sinceIso),
74419
74737
  lte27(aiReferralEventsHourly.tsHour, untilIso)
74420
74738
  ];
74421
- if (sourceIdParam) aiFilters.push(eq100(aiReferralEventsHourly.sourceId, sourceIdParam));
74422
- const aiWhere = and86(...aiFilters);
74739
+ if (sourceIdParam) aiFilters.push(eq101(aiReferralEventsHourly.sourceId, sourceIdParam));
74740
+ const aiWhere = and87(...aiFilters);
74423
74741
  const total = app.db.select({
74424
- total: sql45`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)`,
74425
- nonhop: sql45`COALESCE(SUM(CASE WHEN ${referralLandedCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`,
74426
- landed: sql45`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`,
74427
- paid: sql45`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.paidSessionsOrHits} ELSE 0 END), 0)`,
74428
- organic: sql45`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.organicSessionsOrHits} ELSE 0 END), 0)`,
74429
- rows: sql45`COUNT(*)`
74742
+ total: sql46`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)`,
74743
+ nonhop: sql46`COALESCE(SUM(CASE WHEN ${referralLandedCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`,
74744
+ landed: sql46`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`,
74745
+ paid: sql46`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.paidSessionsOrHits} ELSE 0 END), 0)`,
74746
+ organic: sql46`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.organicSessionsOrHits} ELSE 0 END), 0)`,
74747
+ rows: sql46`COUNT(*)`
74430
74748
  }).from(aiReferralEventsHourly).where(aiWhere).get();
74431
74749
  aiReferralTotalHits = Number(total?.total ?? 0);
74432
74750
  aiReferralNonHopHits = Number(total?.nonhop ?? 0);
@@ -74440,8 +74758,8 @@ async function trafficRoutes(app, opts) {
74440
74758
  const referralSeriesBucket = seriesBucketSql(aiReferralEventsHourly.tsHour, granularity);
74441
74759
  const referralSeries = app.db.select({
74442
74760
  bucket: referralSeriesBucket,
74443
- hits: sql45`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)`,
74444
- landed: sql45`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`
74761
+ hits: sql46`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)`,
74762
+ landed: sql46`COALESCE(SUM(CASE WHEN ${countableReferralCondition()} THEN ${aiReferralEventsHourly.sessionsOrHits} ELSE 0 END), 0)`
74445
74763
  }).from(aiReferralEventsHourly).where(aiWhere).groupBy(referralSeriesBucket).all();
74446
74764
  for (const row of referralSeries) {
74447
74765
  const point = trafficSeriesPoint(seriesByBucket, row.bucket);
@@ -74494,11 +74812,11 @@ async function trafficRoutes(app, opts) {
74494
74812
  windowEnd: untilIso,
74495
74813
  series: (() => {
74496
74814
  const points = completeTrafficSeries(since, until, granularity, seriesByBucket);
74497
- const coverageScope = (col, srcCol) => sourceIdParam ? and86(eq100(col, project.id), eq100(srcCol, sourceIdParam)) : eq100(col, project.id);
74815
+ const coverageScope = (col, srcCol) => sourceIdParam ? and87(eq101(col, project.id), eq101(srcCol, sourceIdParam)) : eq101(col, project.id);
74498
74816
  const firsts = [
74499
- app.db.select({ v: sql45`MIN(${crawlerEventsHourly.tsHour})` }).from(crawlerEventsHourly).where(coverageScope(crawlerEventsHourly.projectId, crawlerEventsHourly.sourceId)).get()?.v,
74500
- app.db.select({ v: sql45`MIN(${aiUserFetchEventsHourly.tsHour})` }).from(aiUserFetchEventsHourly).where(coverageScope(aiUserFetchEventsHourly.projectId, aiUserFetchEventsHourly.sourceId)).get()?.v,
74501
- app.db.select({ v: sql45`MIN(${aiReferralEventsHourly.tsHour})` }).from(aiReferralEventsHourly).where(coverageScope(aiReferralEventsHourly.projectId, aiReferralEventsHourly.sourceId)).get()?.v
74817
+ app.db.select({ v: sql46`MIN(${crawlerEventsHourly.tsHour})` }).from(crawlerEventsHourly).where(coverageScope(crawlerEventsHourly.projectId, crawlerEventsHourly.sourceId)).get()?.v,
74818
+ app.db.select({ v: sql46`MIN(${aiUserFetchEventsHourly.tsHour})` }).from(aiUserFetchEventsHourly).where(coverageScope(aiUserFetchEventsHourly.projectId, aiUserFetchEventsHourly.sourceId)).get()?.v,
74819
+ app.db.select({ v: sql46`MIN(${aiReferralEventsHourly.tsHour})` }).from(aiReferralEventsHourly).where(coverageScope(aiReferralEventsHourly.projectId, aiReferralEventsHourly.sourceId)).get()?.v
74502
74820
  ].filter((v) => typeof v === "string" && v.length > 0);
74503
74821
  const referralCountingChangedAt = aiReferralOlderCountUntil(app.db, { projectId: project.id, sourceId: sourceIdParam });
74504
74822
  const referralCountingChangedMs = referralCountingChangedAt === null ? null : Date.parse(referralCountingChangedAt);
@@ -74588,7 +74906,7 @@ async function trafficRoutes(app, opts) {
74588
74906
  }
74589
74907
 
74590
74908
  // ../api-routes/src/doctor/checks/report-sweeps.ts
74591
- import { and as and87, asc as asc28, eq as eq101, gte as gte27, lte as lte28 } from "drizzle-orm";
74909
+ import { and as and88, asc as asc28, eq as eq102, gte as gte27, lte as lte28 } from "drizzle-orm";
74592
74910
 
74593
74911
  // ../api-routes/src/visibility-attribution.ts
74594
74912
  function buildQueryAttribution2(projectQueries) {
@@ -74622,11 +74940,11 @@ function inspectSweep(ctx, run) {
74622
74940
  answerMentioned: querySnapshots.answerMentioned,
74623
74941
  answerText: querySnapshots.answerText,
74624
74942
  measurementExecutionId: querySnapshots.measurementExecutionId
74625
- }).from(querySnapshots).where(eq101(querySnapshots.runId, run.id)).all();
74943
+ }).from(querySnapshots).where(eq102(querySnapshots.runId, run.id)).all();
74626
74944
  if (snapshots.length === 0) return { detail: { ...base, complete: false, reason: "no-answers" } };
74627
74945
  try {
74628
74946
  if (run.measurementPlanVersionId) {
74629
- const version = ctx.db.select().from(measurementPlanVersions).where(and87(eq101(measurementPlanVersions.projectId, ctx.project.id), eq101(measurementPlanVersions.id, run.measurementPlanVersionId))).get();
74947
+ const version = ctx.db.select().from(measurementPlanVersions).where(and88(eq102(measurementPlanVersions.projectId, ctx.project.id), eq102(measurementPlanVersions.id, run.measurementPlanVersionId))).get();
74630
74948
  if (!version) return { detail: { ...base, complete: false, reason: "missing-plan" } };
74631
74949
  const plan = parseStoredMeasurementPlanAnyVersion(version.canonicalJson);
74632
74950
  const manifest = measurementRunExpectedSlots(run, plan);
@@ -74658,10 +74976,10 @@ function inspectSweep(ctx, run) {
74658
74976
  };
74659
74977
  return unbound ? { detail } : { detail, coverage: slotCoverage(expected2, answered3) };
74660
74978
  }
74661
- const stored = ctx.db.select().from(simpleMeasurementDefinitions).where(eq101(simpleMeasurementDefinitions.runId, run.id)).get();
74979
+ const stored = ctx.db.select().from(simpleMeasurementDefinitions).where(eq102(simpleMeasurementDefinitions.runId, run.id)).get();
74662
74980
  const frozen = stored ? simpleMeasurementDefinitionSchema.parse(stored.definition) : null;
74663
- const project = ctx.db.select().from(projects).where(eq101(projects.id, ctx.project.id)).get();
74664
- const basket = frozen ? frozen.queries.map((query2) => ({ id: query2.queryId, query: query2.queryText })) : ctx.db.select({ id: queries.id, query: queries.query }).from(queries).where(eq101(queries.projectId, project.id)).all();
74981
+ const project = ctx.db.select().from(projects).where(eq102(projects.id, ctx.project.id)).get();
74982
+ const basket = frozen ? frozen.queries.map((query2) => ({ id: query2.queryId, query: query2.queryText })) : ctx.db.select({ id: queries.id, query: queries.query }).from(queries).where(eq102(queries.projectId, project.id)).all();
74665
74983
  const providers = frozen ? frozen.engines.map((engine) => engine.provider) : project.providers.length > 0 ? project.providers : [...new Set(snapshots.map((snapshot) => snapshot.provider))];
74666
74984
  const attribution = buildQueryAttribution2(basket);
74667
74985
  const expected = new Set(basket.flatMap((query2) => providers.map((provider) => JSON.stringify([query2.id, provider.trim().toLowerCase()]))));
@@ -74710,7 +75028,7 @@ var reportSweepsCheck = {
74710
75028
  const graded = gradedReportMonths(reportMonths, now);
74711
75029
  const months = reportMonths.map((month) => {
74712
75030
  const bounds = calendarMonthBounds(month);
74713
- const monthRuns = ctx.db.select().from(runs).where(and87(eq101(runs.projectId, ctx.project.id), eq101(runs.kind, RunKinds["answer-visibility"]), notProbeRun(), gte27(runs.createdAt, bounds.since), lte28(runs.createdAt, bounds.until))).orderBy(asc28(runs.createdAt), asc28(runs.id)).all();
75031
+ const monthRuns = ctx.db.select().from(runs).where(and88(eq102(runs.projectId, ctx.project.id), eq102(runs.kind, RunKinds["answer-visibility"]), notProbeRun(), gte27(runs.createdAt, bounds.since), lte28(runs.createdAt, bounds.until))).orderBy(asc28(runs.createdAt), asc28(runs.id)).all();
74714
75032
  const evidence = monthRuns.map((run) => inspectSweep(ctx, run));
74715
75033
  return {
74716
75034
  month,
@@ -74733,7 +75051,7 @@ var reportSweepsCheck = {
74733
75051
  };
74734
75052
 
74735
75053
  // ../api-routes/src/doctor/checks/report-models.ts
74736
- import { and as and88, eq as eq102, gte as gte28, inArray as inArray47, lte as lte29 } from "drizzle-orm";
75054
+ import { and as and89, eq as eq103, gte as gte28, inArray as inArray48, lte as lte29 } from "drizzle-orm";
74737
75055
  var reportModelsCheck = {
74738
75056
  id: "report.models",
74739
75057
  category: CheckCategories.providers,
@@ -74748,7 +75066,7 @@ var reportModelsCheck = {
74748
75066
  const months = reportMonths.flatMap((month) => {
74749
75067
  const bounds = calendarMonthBounds(month);
74750
75068
  const previous = new Date(Date.parse(bounds.since) - 1).toISOString().slice(0, 7);
74751
- const observations = ctx.db.select({ provider: querySnapshots.provider, model: querySnapshots.model, at: runs.createdAt }).from(querySnapshots).innerJoin(runs, eq102(runs.id, querySnapshots.runId)).where(and88(eq102(runs.projectId, ctx.project.id), eq102(runs.kind, RunKinds["answer-visibility"]), inArray47(runs.status, [RunStatuses.completed, RunStatuses.partial]), notProbeRun(), gte28(runs.createdAt, bounds.since), lte29(runs.createdAt, bounds.until))).all();
75069
+ const observations = ctx.db.select({ provider: querySnapshots.provider, model: querySnapshots.model, at: runs.createdAt }).from(querySnapshots).innerJoin(runs, eq103(runs.id, querySnapshots.runId)).where(and89(eq103(runs.projectId, ctx.project.id), eq103(runs.kind, RunKinds["answer-visibility"]), inArray48(runs.status, [RunStatuses.completed, RunStatuses.partial]), notProbeRun(), gte28(runs.createdAt, bounds.since), lte29(runs.createdAt, bounds.until))).all();
74752
75070
  return readVisibilityContinuity(ctx.db, ctx.project.name, { from: previous, to: month }).map(({ frame, continuity: continuity2 }) => ({
74753
75071
  month,
74754
75072
  previousMonth: previous,
@@ -74789,7 +75107,7 @@ var reportModelsCheck = {
74789
75107
  };
74790
75108
 
74791
75109
  // ../api-routes/src/doctor/checks/report-daily-data.ts
74792
- import { eq as eq103 } from "drizzle-orm";
75110
+ import { eq as eq104 } from "drizzle-orm";
74793
75111
  var REPORTING_LAG_DAYS = 3;
74794
75112
  function dateSpan(dates) {
74795
75113
  const sorted = [...dates].sort();
@@ -74798,31 +75116,31 @@ function dateSpan(dates) {
74798
75116
  function latestSyncRange(ctx, source) {
74799
75117
  const projectId = ctx.project.id;
74800
75118
  if (source === "ga") {
74801
- const rows2 = ctx.db.select({ date: gaDailyTotals.date, syncedAt: gaDailyTotals.syncedAt }).from(gaDailyTotals).where(eq103(gaDailyTotals.projectId, projectId)).all();
75119
+ const rows2 = ctx.db.select({ date: gaDailyTotals.date, syncedAt: gaDailyTotals.syncedAt }).from(gaDailyTotals).where(eq104(gaDailyTotals.projectId, projectId)).all();
74802
75120
  const latest2 = rows2.reduce((max2, row) => max2 === null || row.syncedAt > max2 ? row.syncedAt : max2, null);
74803
- const summary3 = ctx.db.select({ start: gaTrafficSummaries.periodStart, end: gaTrafficSummaries.periodEnd, syncedAt: gaTrafficSummaries.syncedAt }).from(gaTrafficSummaries).where(eq103(gaTrafficSummaries.projectId, projectId)).get();
75121
+ const summary3 = ctx.db.select({ start: gaTrafficSummaries.periodStart, end: gaTrafficSummaries.periodEnd, syncedAt: gaTrafficSummaries.syncedAt }).from(gaTrafficSummaries).where(eq104(gaTrafficSummaries.projectId, projectId)).get();
74804
75122
  if (summary3 && (latest2 === null || summary3.syncedAt >= latest2)) return { start: summary3.start, end: summary3.end, syncedAt: summary3.syncedAt };
74805
75123
  const span2 = dateSpan(rows2.filter((row) => row.syncedAt === latest2).map((row) => row.date));
74806
75124
  return span2 && latest2 !== null ? { ...span2, syncedAt: latest2 } : null;
74807
75125
  }
74808
- const rows = ctx.db.select({ date: gscDailyTotals.date, createdAt: gscDailyTotals.createdAt }).from(gscDailyTotals).where(eq103(gscDailyTotals.projectId, projectId)).all();
75126
+ const rows = ctx.db.select({ date: gscDailyTotals.date, createdAt: gscDailyTotals.createdAt }).from(gscDailyTotals).where(eq104(gscDailyTotals.projectId, projectId)).all();
74809
75127
  const latest = rows.reduce((max2, row) => max2 === null || row.createdAt > max2 ? row.createdAt : max2, null);
74810
75128
  const span = dateSpan(rows.filter((row) => row.createdAt === latest).map((row) => row.date));
74811
75129
  if (!span || latest === null) return null;
74812
- const watermark = ctx.db.select({ through: gscDataWatermarks.syncedThroughDate, updatedAt: gscDataWatermarks.updatedAt }).from(gscDataWatermarks).where(eq103(gscDataWatermarks.projectId, projectId)).get();
75130
+ const watermark = ctx.db.select({ through: gscDataWatermarks.syncedThroughDate, updatedAt: gscDataWatermarks.updatedAt }).from(gscDataWatermarks).where(eq104(gscDataWatermarks.projectId, projectId)).get();
74813
75131
  return watermark?.through && watermark.updatedAt === latest && watermark.through > span.end ? { start: span.start, end: watermark.through, syncedAt: latest } : { ...span, syncedAt: latest };
74814
75132
  }
74815
75133
  function dailyCoverage(ctx, month, source) {
74816
75134
  const project = ctx.project;
74817
75135
  const connection = source === "ga" ? ctx.ga4CredentialStore?.getConnection(project.name) ?? ctx.googleConnectionStore?.getConnection(project.canonicalDomain, "ga4") : ctx.googleConnectionStore?.getConnection(project.canonicalDomain, "gsc");
74818
- const stored = source === "ga" ? ctx.db.select({ date: gaDailyTotals.date, count: gaDailyTotals.sessions }).from(gaDailyTotals).where(eq103(gaDailyTotals.projectId, project.id)).all() : ctx.db.select({ date: gscDailyTotals.date, count: gscDailyTotals.impressions }).from(gscDailyTotals).where(eq103(gscDailyTotals.projectId, project.id)).all();
75136
+ const stored = source === "ga" ? ctx.db.select({ date: gaDailyTotals.date, count: gaDailyTotals.sessions }).from(gaDailyTotals).where(eq104(gaDailyTotals.projectId, project.id)).all() : ctx.db.select({ date: gscDailyTotals.date, count: gscDailyTotals.impressions }).from(gscDailyTotals).where(eq104(gscDailyTotals.projectId, project.id)).all();
74819
75137
  if (!connection && stored.length === 0) return null;
74820
75138
  const bounds = calendarMonthBounds(month);
74821
75139
  const start = bounds.since.slice(0, 10);
74822
75140
  const end = bounds.until.slice(0, 10);
74823
75141
  const timeZone = source === "gsc" ? "America/Los_Angeles" : "UTC";
74824
75142
  const matureThrough = isoDateDaysBeforeInTimeZone((/* @__PURE__ */ new Date()).toISOString(), REPORTING_LAG_DAYS, timeZone);
74825
- const created = ctx.db.select({ date: projects.createdAt }).from(projects).where(eq103(projects.id, project.id)).get().date.slice(0, 10);
75143
+ const created = ctx.db.select({ date: projects.createdAt }).from(projects).where(eq104(projects.id, project.id)).get().date.slice(0, 10);
74826
75144
  const connectedAt = connection?.createdAt?.slice(0, 10) ?? created;
74827
75145
  const onboardingDate = [connectedAt, ...stored.map((row) => row.date)].sort()[0];
74828
75146
  const byDate = new Map(stored.map((row) => [row.date, row.count]));
@@ -74904,7 +75222,7 @@ var reportDailyDataCheck = {
74904
75222
  };
74905
75223
 
74906
75224
  // ../api-routes/src/doctor/checks/referral-assessment.ts
74907
- import { and as and89, eq as eq104, ne as ne16 } from "drizzle-orm";
75225
+ import { and as and90, eq as eq105, ne as ne16 } from "drizzle-orm";
74908
75226
  var REFERRAL_ASSESSMENT_CHECKS = [{
74909
75227
  id: "report.ai-referral-bursts",
74910
75228
  category: CheckCategories.integrations,
@@ -74913,7 +75231,7 @@ var REFERRAL_ASSESSMENT_CHECKS = [{
74913
75231
  notificationPolicy: CheckNotificationPolicies.silent,
74914
75232
  run: (ctx) => {
74915
75233
  if (!ctx.project) return { status: CheckStatuses.skipped, code: "report.ai-referral-bursts.no-project", summary: "Select a project to inspect referral evidence." };
74916
- const configured = ctx.db.select({ id: trafficSources.id }).from(trafficSources).where(and89(eq104(trafficSources.projectId, ctx.project.id), ne16(trafficSources.status, TrafficSourceStatuses.archived))).get();
75234
+ const configured = ctx.db.select({ id: trafficSources.id }).from(trafficSources).where(and90(eq105(trafficSources.projectId, ctx.project.id), ne16(trafficSources.status, TrafficSourceStatuses.archived))).get();
74917
75235
  if (!configured) {
74918
75236
  return { status: CheckStatuses.skipped, code: "report.ai-referral-bursts.not-configured", summary: "No non-archived server traffic source is configured for this project." };
74919
75237
  }
@@ -75325,18 +75643,18 @@ var BACKLINKS_CHECKS = [
75325
75643
  ];
75326
75644
 
75327
75645
  // ../api-routes/src/doctor/checks/bing-auth.ts
75328
- import { and as and90, desc as desc47, eq as eq105, inArray as inArray48 } from "drizzle-orm";
75646
+ import { and as and91, desc as desc47, eq as eq106, inArray as inArray49 } from "drizzle-orm";
75329
75647
  var BING_CONNECTION_ENTITY = "bing_connection";
75330
75648
  var BING_CONNECTED_ACTION = "bing.connected";
75331
75649
  var BING_DISCONNECTED_ACTION = "bing.disconnected";
75332
75650
  function lostBingConnection(ctx, project) {
75333
75651
  const hasRow = (row) => row !== void 0;
75334
- const storedData = hasRow(ctx.db.select({ id: bingCoverageSnapshots.id }).from(bingCoverageSnapshots).where(eq105(bingCoverageSnapshots.projectId, project.id)).limit(1).get()) || hasRow(ctx.db.select({ id: bingUrlInspections.id }).from(bingUrlInspections).where(eq105(bingUrlInspections.projectId, project.id)).limit(1).get()) || hasRow(ctx.db.select({ id: bingKeywordStats.id }).from(bingKeywordStats).where(eq105(bingKeywordStats.projectId, project.id)).limit(1).get()) || hasRow(ctx.db.select({ id: bingTrafficDaily.id }).from(bingTrafficDaily).where(eq105(bingTrafficDaily.projectId, project.id)).limit(1).get());
75652
+ const storedData = hasRow(ctx.db.select({ id: bingCoverageSnapshots.id }).from(bingCoverageSnapshots).where(eq106(bingCoverageSnapshots.projectId, project.id)).limit(1).get()) || hasRow(ctx.db.select({ id: bingUrlInspections.id }).from(bingUrlInspections).where(eq106(bingUrlInspections.projectId, project.id)).limit(1).get()) || hasRow(ctx.db.select({ id: bingKeywordStats.id }).from(bingKeywordStats).where(eq106(bingKeywordStats.projectId, project.id)).limit(1).get()) || hasRow(ctx.db.select({ id: bingTrafficDaily.id }).from(bingTrafficDaily).where(eq106(bingTrafficDaily.projectId, project.id)).limit(1).get());
75335
75653
  if (!storedData) return false;
75336
- const lastChange = ctx.db.select({ action: auditLog.action }).from(auditLog).where(and90(
75337
- eq105(auditLog.entityType, BING_CONNECTION_ENTITY),
75338
- eq105(auditLog.entityId, project.canonicalDomain),
75339
- inArray48(auditLog.action, [BING_CONNECTED_ACTION, BING_DISCONNECTED_ACTION])
75654
+ const lastChange = ctx.db.select({ action: auditLog.action }).from(auditLog).where(and91(
75655
+ eq106(auditLog.entityType, BING_CONNECTION_ENTITY),
75656
+ eq106(auditLog.entityId, project.canonicalDomain),
75657
+ inArray49(auditLog.action, [BING_CONNECTED_ACTION, BING_DISCONNECTED_ACTION])
75340
75658
  )).orderBy(desc47(auditLog.createdAt)).limit(1).get();
75341
75659
  return lastChange?.action !== BING_DISCONNECTED_ACTION;
75342
75660
  }
@@ -75494,7 +75812,7 @@ var BING_AUTH_CHECKS = [
75494
75812
  ];
75495
75813
 
75496
75814
  // ../api-routes/src/doctor/checks/content.ts
75497
- import { eq as eq106 } from "drizzle-orm";
75815
+ import { eq as eq107 } from "drizzle-orm";
75498
75816
  var WINNABILITY_COVERAGE_WARN_THRESHOLD = 0.8;
75499
75817
  var UNCLASSIFIED_DOMAIN_SAMPLE_LIMIT = 10;
75500
75818
  function skippedNoProject2() {
@@ -75507,7 +75825,7 @@ function skippedNoProject2() {
75507
75825
  }
75508
75826
  function loadProject(ctx) {
75509
75827
  if (!ctx.project) return null;
75510
- return ctx.db.select().from(projects).where(eq106(projects.id, ctx.project.id)).get() ?? null;
75828
+ return ctx.db.select().from(projects).where(eq107(projects.id, ctx.project.id)).get() ?? null;
75511
75829
  }
75512
75830
  var winnabilityCoverageCheck = {
75513
75831
  id: "content.winnability.coverage",
@@ -75600,7 +75918,7 @@ var CONTENT_CHECK_BY_ID = Object.fromEntries(
75600
75918
  );
75601
75919
 
75602
75920
  // ../api-routes/src/doctor/checks/ads.ts
75603
- import { eq as eq107 } from "drizzle-orm";
75921
+ import { eq as eq108 } from "drizzle-orm";
75604
75922
  var ADS_RECENT_SYNC_WARN_DAYS = 7;
75605
75923
  var ADS_RECENT_SYNC_FAIL_DAYS = 30;
75606
75924
  var adsConnectionCheck = {
@@ -75617,7 +75935,7 @@ var adsConnectionCheck = {
75617
75935
  remediation: null
75618
75936
  };
75619
75937
  }
75620
- const row = ctx.db.select().from(adsConnections).where(eq107(adsConnections.projectId, ctx.project.id)).get();
75938
+ const row = ctx.db.select().from(adsConnections).where(eq108(adsConnections.projectId, ctx.project.id)).get();
75621
75939
  if (!row) {
75622
75940
  return {
75623
75941
  status: CheckStatuses.skipped,
@@ -75667,7 +75985,7 @@ var adsRecentSyncCheck = {
75667
75985
  remediation: null
75668
75986
  };
75669
75987
  }
75670
- const row = ctx.db.select().from(adsConnections).where(eq107(adsConnections.projectId, ctx.project.id)).get();
75988
+ const row = ctx.db.select().from(adsConnections).where(eq108(adsConnections.projectId, ctx.project.id)).get();
75671
75989
  if (!row) {
75672
75990
  return {
75673
75991
  status: CheckStatuses.skipped,
@@ -75882,7 +76200,7 @@ var ga4ConnectionCheck = {
75882
76200
  var GA_AUTH_CHECKS = [ga4ConnectionCheck];
75883
76201
 
75884
76202
  // ../api-routes/src/doctor/checks/data-freshness.ts
75885
- import { and as and91, desc as desc48, eq as eq108, inArray as inArray49 } from "drizzle-orm";
76203
+ import { and as and92, desc as desc48, eq as eq109, inArray as inArray50 } from "drizzle-orm";
75886
76204
  var GA_DATA_AGING_DAYS = 3;
75887
76205
  var GA_DATA_STALE_DAYS = 5;
75888
76206
  var GSC_DATA_AGING_DAYS = 5;
@@ -75912,7 +76230,7 @@ function skipped(code, summary3) {
75912
76230
  return { status: CheckStatuses.skipped, code, summary: summary3, remediation: null };
75913
76231
  }
75914
76232
  function lastSyncAgeDays(ctx, kinds) {
75915
- const row = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(and91(eq108(runs.projectId, ctx.project.id), inArray49(runs.kind, kinds), eq108(runs.status, "completed"))).orderBy(desc48(runs.createdAt)).limit(1).get();
76233
+ const row = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(and92(eq109(runs.projectId, ctx.project.id), inArray50(runs.kind, kinds), eq109(runs.status, "completed"))).orderBy(desc48(runs.createdAt)).limit(1).get();
75916
76234
  if (!row?.createdAt) return null;
75917
76235
  const age = Math.floor((Date.now() - Date.parse(row.createdAt)) / DAY_MS6);
75918
76236
  return Number.isFinite(age) ? age : null;
@@ -76014,7 +76332,7 @@ var gaRecentDataCheck = {
76014
76332
  const connection = gaConnected(ctx);
76015
76333
  if (connection === "store-unavailable") return skipped("ga.data.store-unavailable", "No GA4 credential store configured for this deployment.");
76016
76334
  if (connection === "not-connected") return skipped("ga.data.not-connected", "GA4 is not connected for this project.");
76017
- const newest = ctx.db.select({ date: gaDailyTotals.date }).from(gaDailyTotals).where(eq108(gaDailyTotals.projectId, ctx.project.id)).orderBy(desc48(gaDailyTotals.date)).limit(1).get();
76335
+ const newest = ctx.db.select({ date: gaDailyTotals.date }).from(gaDailyTotals).where(eq109(gaDailyTotals.projectId, ctx.project.id)).orderBy(desc48(gaDailyTotals.date)).limit(1).get();
76018
76336
  return grade(ctx, GA_SPEC, newest?.date);
76019
76337
  }
76020
76338
  };
@@ -76029,16 +76347,16 @@ var gscRecentDataCheck = {
76029
76347
  if (!ctx.googleConnectionStore.getConnection(ctx.project.canonicalDomain, "gsc")) {
76030
76348
  return skipped("gsc.data.not-connected", "Search Console is not connected for this project.");
76031
76349
  }
76032
- const watermark = ctx.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq108(gscDataWatermarks.projectId, ctx.project.id)).get();
76350
+ const watermark = ctx.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq109(gscDataWatermarks.projectId, ctx.project.id)).get();
76033
76351
  if (watermark?.dataThroughDate) return grade(ctx, GSC_SPEC, watermark.dataThroughDate);
76034
- const newest = ctx.db.select({ date: gscDailyTotals.date }).from(gscDailyTotals).where(eq108(gscDailyTotals.projectId, ctx.project.id)).orderBy(desc48(gscDailyTotals.date)).limit(1).get();
76352
+ const newest = ctx.db.select({ date: gscDailyTotals.date }).from(gscDailyTotals).where(eq109(gscDailyTotals.projectId, ctx.project.id)).orderBy(desc48(gscDailyTotals.date)).limit(1).get();
76035
76353
  return grade(ctx, GSC_SPEC, newest?.date);
76036
76354
  }
76037
76355
  };
76038
76356
  var DATA_FRESHNESS_CHECKS = [gaRecentDataCheck, gscRecentDataCheck];
76039
76357
 
76040
76358
  // ../api-routes/src/doctor/checks/seo-refresh.ts
76041
- import { and as and92, asc as asc29, desc as desc49, eq as eq109, gt as gt9, inArray as inArray50, sql as sql46 } from "drizzle-orm";
76359
+ import { and as and93, asc as asc29, desc as desc49, eq as eq110, gt as gt9, inArray as inArray51, sql as sql47 } from "drizzle-orm";
76042
76360
  var GRACE_DAYS = 2;
76043
76361
  var DAY_MS7 = 24 * 60 * 60 * 1e3;
76044
76362
  var FIRING_SPAN_MS = 6e4;
@@ -76047,7 +76365,7 @@ function skipped2(code, summary3) {
76047
76365
  return { status: CheckStatuses.skipped, code, summary: summary3, remediation: null };
76048
76366
  }
76049
76367
  function seoSyncRuns(projectId) {
76050
- return and92(eq109(runs.projectId, projectId), eq109(runs.kind, RunKinds["seo-sync"]));
76368
+ return and93(eq110(runs.projectId, projectId), eq110(runs.kind, RunKinds["seo-sync"]));
76051
76369
  }
76052
76370
  function scheduleTiming(schedule) {
76053
76371
  if (!schedule.recurrence) return { cronExpr: schedule.cronExpr, timezone: schedule.timezone, recurrence: null };
@@ -76055,22 +76373,22 @@ function scheduleTiming(schedule) {
76055
76373
  return recurrence ? { cronExpr: schedule.cronExpr, timezone: schedule.timezone, recurrence } : null;
76056
76374
  }
76057
76375
  function latestFiring(ctx, projectId, enabledSince) {
76058
- const scheduled = and92(seoSyncRuns(projectId), eq109(runs.trigger, RunTriggers.scheduled), gt9(runs.createdAt, enabledSince));
76376
+ const scheduled = and93(seoSyncRuns(projectId), eq110(runs.trigger, RunTriggers.scheduled), gt9(runs.createdAt, enabledSince));
76059
76377
  const newest = ctx.db.select({ createdAt: runs.createdAt }).from(runs).where(scheduled).orderBy(desc49(runs.createdAt)).limit(1).get();
76060
76378
  if (!newest) return [];
76061
76379
  const newestMs = Date.parse(newest.createdAt);
76062
76380
  const after = Number.isFinite(newestMs) ? new Date(newestMs - FIRING_SPAN_MS).toISOString() : newest.createdAt;
76063
- return ctx.db.select({ id: runs.id, status: runs.status, error: runs.error, createdAt: runs.createdAt }).from(runs).where(and92(scheduled, gt9(runs.createdAt, after))).orderBy(asc29(runs.createdAt), asc29(runs.id)).all();
76381
+ return ctx.db.select({ id: runs.id, status: runs.status, error: runs.error, createdAt: runs.createdAt }).from(runs).where(and93(scheduled, gt9(runs.createdAt, after))).orderBy(asc29(runs.createdAt), asc29(runs.id)).all();
76064
76382
  }
76065
76383
  function lastCompleted(ctx, projectId) {
76066
- const at = sql46`coalesce(${runs.finishedAt}, ${runs.createdAt})`;
76067
- return ctx.db.select({ id: runs.id, at }).from(runs).where(and92(seoSyncRuns(projectId), eq109(runs.status, RunStatuses.completed))).orderBy(desc49(at)).limit(1).get() ?? null;
76384
+ const at = sql47`coalesce(${runs.finishedAt}, ${runs.createdAt})`;
76385
+ return ctx.db.select({ id: runs.id, at }).from(runs).where(and93(seoSyncRuns(projectId), eq110(runs.status, RunStatuses.completed))).orderBy(desc49(at)).limit(1).get() ?? null;
76068
76386
  }
76069
76387
  function isIncomplete(run) {
76070
76388
  return run.status === RunStatuses.failed || run.status === RunStatuses.partial;
76071
76389
  }
76072
76390
  function runProfiles(ctx, firing) {
76073
- const jobs = firing.length === 0 ? [] : ctx.db.select({ runId: seoJobs.runId, profileId: seoJobs.profileId }).from(seoJobs).where(inArray50(seoJobs.runId, firing.map((run) => run.id))).all();
76391
+ const jobs = firing.length === 0 ? [] : ctx.db.select({ runId: seoJobs.runId, profileId: seoJobs.profileId }).from(seoJobs).where(inArray51(seoJobs.runId, firing.map((run) => run.id))).all();
76074
76392
  const byRun = new Map(jobs.flatMap((job) => job.runId ? [[job.runId, job.profileId]] : []));
76075
76393
  return new Map(firing.map((run) => [run.id, byRun.get(run.id) ?? skippedRefreshProfile(run.error)]));
76076
76394
  }
@@ -76078,7 +76396,7 @@ function unsettledRuns(ctx, projectId, firing, profiles) {
76078
76396
  const incomplete = firing.filter(isIncomplete);
76079
76397
  const firedAt = firing[firing.length - 1]?.createdAt;
76080
76398
  if (incomplete.length === 0 || !firedAt) return incomplete;
76081
- const refreshed = new Set(ctx.db.select({ profileId: seoJobs.profileId }).from(runs).innerJoin(seoJobs, eq109(seoJobs.runId, runs.id)).where(and92(seoSyncRuns(projectId), eq109(runs.status, RunStatuses.completed), gt9(runs.createdAt, firedAt))).all().map((row) => row.profileId));
76399
+ const refreshed = new Set(ctx.db.select({ profileId: seoJobs.profileId }).from(runs).innerJoin(seoJobs, eq110(seoJobs.runId, runs.id)).where(and93(seoSyncRuns(projectId), eq110(runs.status, RunStatuses.completed), gt9(runs.createdAt, firedAt))).all().map((row) => row.profileId));
76082
76400
  return incomplete.filter((run) => {
76083
76401
  const profile = profiles.get(run.id) ?? null;
76084
76402
  return profile === null ? refreshed.size === 0 : !refreshed.has(profile);
@@ -76088,7 +76406,7 @@ var COUNT_LIST = new Intl.ListFormat("en", { style: "long", type: "conjunction"
76088
76406
  function refreshReason(ctx, run) {
76089
76407
  const stored = parseRunError(run.error);
76090
76408
  if (stored) return formatRunErrorOneLine(stored);
76091
- const tasks = currentSeoTasks(ctx.db.select({ id: seoTasks.id, retryOf: seoTasks.retryOf, status: seoTasks.status, error: seoTasks.error, request: seoTasks.request }).from(seoTasks).innerJoin(seoJobs, eq109(seoTasks.jobId, seoJobs.id)).where(eq109(seoJobs.runId, run.id)).all());
76409
+ const tasks = currentSeoTasks(ctx.db.select({ id: seoTasks.id, retryOf: seoTasks.retryOf, status: seoTasks.status, error: seoTasks.error, request: seoTasks.request }).from(seoTasks).innerJoin(seoJobs, eq110(seoTasks.jobId, seoJobs.id)).where(eq110(seoJobs.runId, run.id)).all());
76092
76410
  const failed = tasks.filter((task) => task.status === SeoRunStatuses.failed || task.status === SeoRunStatuses["reconciliation-required"]);
76093
76411
  const partial = tasks.filter((task) => task.status === SeoRunStatuses.partial).length;
76094
76412
  const cancelled = tasks.filter((task) => task.status === SeoRunStatuses.cancelled).length;
@@ -76108,7 +76426,7 @@ function refreshReason(ctx, run) {
76108
76426
  return `Of ${tasks.length} ${unit}, ${COUNT_LIST.format(counts2)}.${errors ? ` ${errors}` : ""}`;
76109
76427
  }
76110
76428
  function gradeSeoRefresh(ctx, project) {
76111
- const schedule = ctx.db.select().from(schedules).where(and92(eq109(schedules.projectId, project.id), eq109(schedules.kind, SchedulableRunKinds["seo-sync"]))).get();
76429
+ const schedule = ctx.db.select().from(schedules).where(and93(eq110(schedules.projectId, project.id), eq110(schedules.kind, SchedulableRunKinds["seo-sync"]))).get();
76112
76430
  if (!schedule) return skipped2("seo.data.not-scheduled", "No SEO refresh schedule is set for this project.");
76113
76431
  if (!schedule.enabled) return skipped2("seo.data.not-scheduled", "The SEO refresh schedule is disabled.");
76114
76432
  const name = project.name;
@@ -76180,7 +76498,7 @@ function gradeSeoRefresh(ctx, project) {
76180
76498
  };
76181
76499
  }
76182
76500
  if (now >= Date.parse(deadlineAt)) {
76183
- const active = ctx.db.select({ id: runs.id, createdAt: runs.createdAt }).from(runs).where(and92(seoSyncRuns(project.id), inArray50(runs.status, [RunStatuses.queued, RunStatuses.running]))).orderBy(asc29(runs.createdAt)).limit(1).get();
76501
+ const active = ctx.db.select({ id: runs.id, createdAt: runs.createdAt }).from(runs).where(and93(seoSyncRuns(project.id), inArray51(runs.status, [RunStatuses.queued, RunStatuses.running]))).orderBy(asc29(runs.createdAt)).limit(1).get();
76184
76502
  const since = last ? `No SEO refresh has completed since ${day(last.at)}.` : "No SEO refresh has completed since the schedule was enabled.";
76185
76503
  const missed = last ? `The scheduled refresh due ${day(dueAt)} did not complete within ${GRACE_DAYS} days.` : `Its first refresh, due ${day(dueAt)}, did not complete within ${GRACE_DAYS} days.`;
76186
76504
  return {
@@ -76490,7 +76808,7 @@ var siteReachabilityCheck = {
76490
76808
  var SITE_REACHABILITY_CHECKS = [siteReachabilityCheck];
76491
76809
 
76492
76810
  // ../api-routes/src/doctor/checks/api-hosts.ts
76493
- import { eq as eq111 } from "drizzle-orm";
76811
+ import { eq as eq112 } from "drizzle-orm";
76494
76812
 
76495
76813
  // ../api-routes/src/api-host-probe.ts
76496
76814
  import dns4 from "dns/promises";
@@ -76596,7 +76914,7 @@ async function probeApiHost(host, options = {}) {
76596
76914
  }
76597
76915
 
76598
76916
  // ../api-routes/src/doctor/checks/integration-sync.ts
76599
- import { and as and93, count as count9, desc as desc50, eq as eq110, gte as gte29, gt as gt10, inArray as inArray51, isNull as isNull18, notInArray as notInArray3, or as or20 } from "drizzle-orm";
76917
+ import { and as and94, count as count9, desc as desc50, eq as eq111, gte as gte29, gt as gt10, inArray as inArray52, isNull as isNull18, notInArray as notInArray3, or as or20 } from "drizzle-orm";
76600
76918
  var SYNC_FAILURE_WINDOW = 3;
76601
76919
  var SUMMARY_ERROR_LIMIT = 300;
76602
76920
  var FINISHED_STATUSES = [RunStatuses.completed, RunStatuses.partial, RunStatuses.failed];
@@ -76623,7 +76941,7 @@ function gscConnection(ctx, project) {
76623
76941
  function gbpConnection(ctx, project) {
76624
76942
  if (!ctx.googleConnectionStore) return { state: "store-unavailable" };
76625
76943
  if (!ctx.googleConnectionStore.getConnection(project.canonicalDomain, "gbp")) return { state: "not-connected" };
76626
- const selected = ctx.db.select({ locationName: gbpLocations.locationName }).from(gbpLocations).where(and93(eq110(gbpLocations.projectId, project.id), eq110(gbpLocations.selected, true))).limit(1).get();
76944
+ const selected = ctx.db.select({ locationName: gbpLocations.locationName }).from(gbpLocations).where(and94(eq111(gbpLocations.projectId, project.id), eq111(gbpLocations.selected, true))).limit(1).get();
76627
76945
  return selected ? CONNECTED : { state: "no-selected-locations" };
76628
76946
  }
76629
76947
  function gaConnection(ctx, project) {
@@ -76696,16 +77014,16 @@ function latestErrorText(raw) {
76696
77014
  return parsed ? formatRunErrorOneLine(parsed) : "no error was recorded";
76697
77015
  }
76698
77016
  function readSyncRunState(db, projectId, kind, options = {}) {
76699
- const scope = and93(
76700
- eq110(runs.projectId, projectId),
76701
- eq110(runs.kind, kind),
76702
- ...options.sourceId ? [eq110(runs.sourceId, options.sourceId)] : [],
77017
+ const scope = and94(
77018
+ eq111(runs.projectId, projectId),
77019
+ eq111(runs.kind, kind),
77020
+ ...options.sourceId ? [eq111(runs.sourceId, options.sourceId)] : [],
76703
77021
  ...options.nothingToSyncErrors?.length ? [or20(isNull18(runs.error), notInArray3(runs.error, [...options.nothingToSyncErrors]))] : []
76704
77022
  );
76705
- const graded = options.since ? and93(scope, gte29(runs.createdAt, options.since)) : scope;
76706
- const recent = db.select({ id: runs.id, status: runs.status, trigger: runs.trigger, error: runs.error, createdAt: runs.createdAt }).from(runs).where(and93(graded, inArray51(runs.status, FINISHED_STATUSES))).orderBy(desc50(runs.createdAt)).limit(SYNC_FAILURE_WINDOW).all();
76707
- const lastSuccess = db.select({ createdAt: runs.createdAt, finishedAt: runs.finishedAt }).from(runs).where(and93(graded, inArray51(runs.status, SUCCESS_STATUSES))).orderBy(desc50(runs.createdAt)).limit(1).get();
76708
- const failureCount = db.select({ count: count9() }).from(runs).where(and93(lastSuccess ? and93(graded, gt10(runs.createdAt, lastSuccess.createdAt)) : graded, eq110(runs.status, RunStatuses.failed))).get();
77023
+ const graded = options.since ? and94(scope, gte29(runs.createdAt, options.since)) : scope;
77024
+ const recent = db.select({ id: runs.id, status: runs.status, trigger: runs.trigger, error: runs.error, createdAt: runs.createdAt }).from(runs).where(and94(graded, inArray52(runs.status, FINISHED_STATUSES))).orderBy(desc50(runs.createdAt)).limit(SYNC_FAILURE_WINDOW).all();
77025
+ const lastSuccess = db.select({ createdAt: runs.createdAt, finishedAt: runs.finishedAt }).from(runs).where(and94(graded, inArray52(runs.status, SUCCESS_STATUSES))).orderBy(desc50(runs.createdAt)).limit(1).get();
77026
+ const failureCount = db.select({ count: count9() }).from(runs).where(and94(lastSuccess ? and94(graded, gt10(runs.createdAt, lastSuccess.createdAt)) : graded, eq111(runs.status, RunStatuses.failed))).get();
76709
77027
  const failuresSinceSuccess = Number(failureCount?.count ?? 0);
76710
77028
  const latest = recent[0];
76711
77029
  return {
@@ -76802,7 +77120,7 @@ function connectionFor(prefix, ctx, project) {
76802
77120
  if (prefix === "google-ads") return googleMarketingConnection("googleAds")(ctx);
76803
77121
  if (prefix === "gtm") return googleMarketingConnection("gtm")(ctx);
76804
77122
  if (prefix === "bing") return ctx.bingConnectionStore?.getConnection(project.canonicalDomain) ? { state: "connected", since: null } : { state: "not-connected" };
76805
- return ctx.db.select({ id: adsConnections.id }).from(adsConnections).where(eq111(adsConnections.projectId, project.id)).limit(1).get() ? { state: "connected", since: null } : { state: "not-connected" };
77123
+ return ctx.db.select({ id: adsConnections.id }).from(adsConnections).where(eq112(adsConnections.projectId, project.id)).limit(1).get() ? { state: "connected", since: null } : { state: "not-connected" };
76806
77124
  }
76807
77125
  function syncCommand(prefix) {
76808
77126
  if (prefix === "gsc") return "google sync";
@@ -76847,7 +77165,7 @@ function definition(prefix) {
76847
77165
  var API_HOST_CHECKS = Object.keys(API_HOST_TABLE).map(definition);
76848
77166
 
76849
77167
  // ../api-routes/src/doctor/checks/gbp-auth.ts
76850
- import { and as and94, eq as eq112 } from "drizzle-orm";
77168
+ import { and as and95, eq as eq113 } from "drizzle-orm";
76851
77169
  var RECENT_SYNC_WARN_DAYS = 4;
76852
77170
  var RECENT_SYNC_FAIL_DAYS = 30;
76853
77171
  function skippedNoProject3() {
@@ -76867,7 +77185,7 @@ function storeUnavailable() {
76867
77185
  };
76868
77186
  }
76869
77187
  function hasSelectedLocation(ctx, projectId) {
76870
- return !!ctx.db.select({ id: gbpLocations.id }).from(gbpLocations).where(and94(eq112(gbpLocations.projectId, projectId), eq112(gbpLocations.selected, true))).limit(1).get();
77188
+ return !!ctx.db.select({ id: gbpLocations.id }).from(gbpLocations).where(and95(eq113(gbpLocations.projectId, projectId), eq113(gbpLocations.selected, true))).limit(1).get();
76871
77189
  }
76872
77190
  async function resolveGbpToken(ctx) {
76873
77191
  if (!ctx.project) return { ok: false, output: skippedNoProject3() };
@@ -77127,7 +77445,7 @@ var recentSyncCheck = {
77127
77445
  title: "GBP recent sync",
77128
77446
  run: (ctx) => {
77129
77447
  if (!ctx.project) return skippedNoProject3();
77130
- const selected = ctx.db.select({ locationName: gbpLocations.locationName, syncedAt: gbpLocations.syncedAt }).from(gbpLocations).where(and94(eq112(gbpLocations.projectId, ctx.project.id), eq112(gbpLocations.selected, true))).all();
77448
+ const selected = ctx.db.select({ locationName: gbpLocations.locationName, syncedAt: gbpLocations.syncedAt }).from(gbpLocations).where(and95(eq113(gbpLocations.projectId, ctx.project.id), eq113(gbpLocations.selected, true))).all();
77131
77449
  if (selected.length === 0) {
77132
77450
  return {
77133
77451
  status: CheckStatuses.skipped,
@@ -77187,7 +77505,7 @@ var GBP_AUTH_CHECK_BY_ID = Object.fromEntries(
77187
77505
  );
77188
77506
 
77189
77507
  // ../api-routes/src/doctor/checks/places.ts
77190
- import { eq as eq113 } from "drizzle-orm";
77508
+ import { eq as eq114 } from "drizzle-orm";
77191
77509
  var apiKeyCheck = {
77192
77510
  id: "gbp.places.api-key",
77193
77511
  category: CheckCategories.auth,
@@ -77232,7 +77550,7 @@ var apiKeyCheck = {
77232
77550
  details: { tier: cfg.tier }
77233
77551
  };
77234
77552
  }
77235
- const rows = ctx.db.select({ placeId: gbpLocations.placeId, selected: gbpLocations.selected }).from(gbpLocations).where(eq113(gbpLocations.projectId, ctx.project.id)).all();
77553
+ const rows = ctx.db.select({ placeId: gbpLocations.placeId, selected: gbpLocations.selected }).from(gbpLocations).where(eq114(gbpLocations.projectId, ctx.project.id)).all();
77236
77554
  const selected = rows.filter((r) => r.selected);
77237
77555
  const locationsWithPlaceId = selected.filter((r) => Boolean(r.placeId)).length;
77238
77556
  const details = {
@@ -77265,7 +77583,7 @@ var PLACES_CHECK_BY_ID = Object.fromEntries(
77265
77583
  );
77266
77584
 
77267
77585
  // ../api-routes/src/doctor/checks/gbp-reviews.ts
77268
- import { and as and95, desc as desc51, eq as eq114, gte as gte30, inArray as inArray52, sql as sql47 } from "drizzle-orm";
77586
+ import { and as and96, desc as desc51, eq as eq115, gte as gte30, inArray as inArray53, sql as sql48 } from "drizzle-orm";
77269
77587
  var REVIEW_EVENTS = /* @__PURE__ */ new Set(["review.negative", "review.rating-dropped"]);
77270
77588
  var V4_ACCESS_REMEDIATION = "Business Profile reviews use the legacy My Business API (mybusiness.googleapis.com), which Google enables per Cloud project only on request; the API Library and `gcloud services enable` cannot turn it on. Open the enable link in the API access approval email as the approved account, or reply to the access-request thread asking Google to enable mybusiness.googleapis.com for your project number, then run `canonry gbp sync`.";
77271
77589
  var reviewsAccessCheck = {
@@ -77293,7 +77611,7 @@ var reviewsAccessCheck = {
77293
77611
  reviewsAccess: gbpLocations.reviewsAccess,
77294
77612
  reviewsAccessReason: gbpLocations.reviewsAccessReason,
77295
77613
  reviewsCheckedAt: gbpLocations.reviewsCheckedAt
77296
- }).from(gbpLocations).where(and95(eq114(gbpLocations.projectId, project.id), eq114(gbpLocations.selected, true))).all();
77614
+ }).from(gbpLocations).where(and96(eq115(gbpLocations.projectId, project.id), eq115(gbpLocations.selected, true))).all();
77297
77615
  if (locations.length === 0) {
77298
77616
  return {
77299
77617
  status: CheckStatuses.skipped,
@@ -77313,7 +77631,7 @@ var reviewsAccessCheck = {
77313
77631
  const places = ctx.getPlacesConfig?.();
77314
77632
  const placesFallback = places !== void 0 && places.tier === "atmosphere" && Boolean(places.apiKey);
77315
77633
  const v4Worked = new Set(
77316
- ctx.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and95(eq114(gbpReviewRatings.projectId, project.id), eq114(gbpReviewRatings.origin, "gbp"))).all().map((row) => row.locationName)
77634
+ ctx.db.select({ locationName: gbpReviewRatings.locationName }).from(gbpReviewRatings).where(and96(eq115(gbpReviewRatings.projectId, project.id), eq115(gbpReviewRatings.origin, "gbp"))).all().map((row) => row.locationName)
77317
77635
  );
77318
77636
  const coverageOf = (loc) => {
77319
77637
  if (businessProfileReviewsCover(loc.reviewsAccess ?? null, v4Worked.has(loc.locationName))) return "full";
@@ -77347,7 +77665,7 @@ var reviewsAccessCheck = {
77347
77665
  none > 0 ? `${none} have no review source` : null
77348
77666
  ].filter((part) => part !== null);
77349
77667
  const summary3 = `Business Profile reviews are not available${why}. ${parts.join("; ")}.`;
77350
- const subscribed = ctx.db.select({ config: notifications.config, enabled: notifications.enabled }).from(notifications).where(eq114(notifications.projectId, project.id)).all().some((n) => n.enabled && (n.config.events ?? []).some((event) => REVIEW_EVENTS.has(event)));
77668
+ const subscribed = ctx.db.select({ config: notifications.config, enabled: notifications.enabled }).from(notifications).where(eq115(notifications.projectId, project.id)).all().some((n) => n.enabled && (n.config.events ?? []).some((event) => REVIEW_EVENTS.has(event)));
77351
77669
  const placesHint = placesFallback ? "" : " For partial coverage meanwhile, set a Places API key (`GOOGLE_PLACES_API_KEY` or `places.apiKey`) with `places.tier: atmosphere`.";
77352
77670
  if (none > 0 && subscribed) {
77353
77671
  return {
@@ -77378,7 +77696,7 @@ var reviewDeliveryCheck = {
77378
77696
  return { status: CheckStatuses.skipped, code: "gbp.reviews.delivery.no-project", summary: "Project context required.", remediation: null };
77379
77697
  }
77380
77698
  const since = new Date(Date.now() - UNDELIVERED_ATTENTION_DAYS * 864e5).toISOString();
77381
- const lastTouched = sql47`coalesce(${reviewWebhookDeliveries.attemptedAt}, ${reviewWebhookDeliveries.createdAt})`;
77699
+ const lastTouched = sql48`coalesce(${reviewWebhookDeliveries.attemptedAt}, ${reviewWebhookDeliveries.createdAt})`;
77382
77700
  const rows = ctx.db.select({
77383
77701
  id: reviewWebhookDeliveries.id,
77384
77702
  notificationId: reviewWebhookDeliveries.notificationId,
@@ -77386,9 +77704,9 @@ var reviewDeliveryCheck = {
77386
77704
  attempts: reviewWebhookDeliveries.attempts,
77387
77705
  lastTouched,
77388
77706
  payload: reviewWebhookDeliveries.payload
77389
- }).from(reviewWebhookDeliveries).where(and95(
77390
- eq114(reviewWebhookDeliveries.projectId, ctx.project.id),
77391
- inArray52(reviewWebhookDeliveries.state, [ReviewDeliveryStates.Uncertain, ReviewDeliveryStates.Failed]),
77707
+ }).from(reviewWebhookDeliveries).where(and96(
77708
+ eq115(reviewWebhookDeliveries.projectId, ctx.project.id),
77709
+ inArray53(reviewWebhookDeliveries.state, [ReviewDeliveryStates.Uncertain, ReviewDeliveryStates.Failed]),
77392
77710
  gte30(lastTouched, since)
77393
77711
  )).orderBy(desc51(lastTouched)).all();
77394
77712
  if (rows.length === 0) {
@@ -77399,7 +77717,7 @@ var reviewDeliveryCheck = {
77399
77717
  remediation: null
77400
77718
  };
77401
77719
  }
77402
- const destinations = new Map(ctx.db.select({ id: notifications.id, config: notifications.config }).from(notifications).where(eq114(notifications.projectId, ctx.project.id)).all().map((row) => [row.id, redactNotificationUrl(row.config.url).urlDisplay]));
77720
+ const destinations = new Map(ctx.db.select({ id: notifications.id, config: notifications.config }).from(notifications).where(eq115(notifications.projectId, ctx.project.id)).all().map((row) => [row.id, redactNotificationUrl(row.config.url).urlDisplay]));
77403
77721
  const deliveries = rows.map((row) => {
77404
77722
  const review = row.payload.reviews[0];
77405
77723
  return {
@@ -77973,7 +78291,7 @@ var RUNTIME_STATE_CHECKS = [
77973
78291
  ];
77974
78292
 
77975
78293
  // ../api-routes/src/doctor/checks/traffic-source.ts
77976
- import { and as and96, desc as desc52, eq as eq115, gte as gte31, inArray as inArray53, isNotNull as isNotNull10, ne as ne17, sql as sql48 } from "drizzle-orm";
78294
+ import { and as and97, desc as desc52, eq as eq116, gte as gte31, inArray as inArray54, isNotNull as isNotNull10, ne as ne17, sql as sql49 } from "drizzle-orm";
77977
78295
  var RECENT_DATA_WARN_DAYS = 7;
77978
78296
  var RECENT_DATA_FAIL_DAYS = 30;
77979
78297
  function isCloudflareDirectPush(source) {
@@ -78012,8 +78330,8 @@ function skippedNoProject5() {
78012
78330
  function loadProbes(ctx) {
78013
78331
  if (!ctx.project) return [];
78014
78332
  const rows = ctx.db.select().from(trafficSources).where(
78015
- and96(
78016
- eq115(trafficSources.projectId, ctx.project.id),
78333
+ and97(
78334
+ eq116(trafficSources.projectId, ctx.project.id),
78017
78335
  ne17(trafficSources.status, TrafficSourceStatuses.archived)
78018
78336
  )
78019
78337
  ).all();
@@ -78150,28 +78468,28 @@ var recentDataCheck = {
78150
78468
  const warnCutoff = new Date(now.getTime() - RECENT_DATA_WARN_DAYS * 24 * 60 * 6e4).toISOString();
78151
78469
  const failCutoff = new Date(now.getTime() - RECENT_DATA_FAIL_DAYS * 24 * 60 * 6e4).toISOString();
78152
78470
  const recentCrawlers = Number(
78153
- ctx.db.select({ total: sql48`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)` }).from(crawlerEventsHourly).where(
78154
- and96(
78155
- eq115(crawlerEventsHourly.projectId, ctx.project.id),
78156
- inArray53(crawlerEventsHourly.sourceId, activeSourceIds),
78471
+ ctx.db.select({ total: sql49`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)` }).from(crawlerEventsHourly).where(
78472
+ and97(
78473
+ eq116(crawlerEventsHourly.projectId, ctx.project.id),
78474
+ inArray54(crawlerEventsHourly.sourceId, activeSourceIds),
78157
78475
  gte31(crawlerEventsHourly.tsHour, warnCutoff)
78158
78476
  )
78159
78477
  ).get()?.total ?? 0
78160
78478
  );
78161
78479
  const recentReferrals = Number(
78162
- ctx.db.select({ total: sql48`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)` }).from(aiReferralEventsHourly).where(
78163
- and96(
78164
- eq115(aiReferralEventsHourly.projectId, ctx.project.id),
78165
- inArray53(aiReferralEventsHourly.sourceId, activeSourceIds),
78480
+ ctx.db.select({ total: sql49`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)` }).from(aiReferralEventsHourly).where(
78481
+ and97(
78482
+ eq116(aiReferralEventsHourly.projectId, ctx.project.id),
78483
+ inArray54(aiReferralEventsHourly.sourceId, activeSourceIds),
78166
78484
  gte31(aiReferralEventsHourly.tsHour, warnCutoff)
78167
78485
  )
78168
78486
  ).get()?.total ?? 0
78169
78487
  );
78170
78488
  const recentUserFetches = Number(
78171
- ctx.db.select({ total: sql48`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
78172
- and96(
78173
- eq115(aiUserFetchEventsHourly.projectId, ctx.project.id),
78174
- inArray53(aiUserFetchEventsHourly.sourceId, activeSourceIds),
78489
+ ctx.db.select({ total: sql49`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
78490
+ and97(
78491
+ eq116(aiUserFetchEventsHourly.projectId, ctx.project.id),
78492
+ inArray54(aiUserFetchEventsHourly.sourceId, activeSourceIds),
78175
78493
  gte31(aiUserFetchEventsHourly.tsHour, warnCutoff)
78176
78494
  )
78177
78495
  ).get()?.total ?? 0
@@ -78194,28 +78512,28 @@ var recentDataCheck = {
78194
78512
  };
78195
78513
  }
78196
78514
  const olderCrawlers = Number(
78197
- ctx.db.select({ total: sql48`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)` }).from(crawlerEventsHourly).where(
78198
- and96(
78199
- eq115(crawlerEventsHourly.projectId, ctx.project.id),
78200
- inArray53(crawlerEventsHourly.sourceId, activeSourceIds),
78515
+ ctx.db.select({ total: sql49`COALESCE(SUM(${crawlerEventsHourly.hits}), 0)` }).from(crawlerEventsHourly).where(
78516
+ and97(
78517
+ eq116(crawlerEventsHourly.projectId, ctx.project.id),
78518
+ inArray54(crawlerEventsHourly.sourceId, activeSourceIds),
78201
78519
  gte31(crawlerEventsHourly.tsHour, failCutoff)
78202
78520
  )
78203
78521
  ).get()?.total ?? 0
78204
78522
  );
78205
78523
  const olderReferrals = Number(
78206
- ctx.db.select({ total: sql48`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)` }).from(aiReferralEventsHourly).where(
78207
- and96(
78208
- eq115(aiReferralEventsHourly.projectId, ctx.project.id),
78209
- inArray53(aiReferralEventsHourly.sourceId, activeSourceIds),
78524
+ ctx.db.select({ total: sql49`COALESCE(SUM(${aiReferralEventsHourly.sessionsOrHits}), 0)` }).from(aiReferralEventsHourly).where(
78525
+ and97(
78526
+ eq116(aiReferralEventsHourly.projectId, ctx.project.id),
78527
+ inArray54(aiReferralEventsHourly.sourceId, activeSourceIds),
78210
78528
  gte31(aiReferralEventsHourly.tsHour, failCutoff)
78211
78529
  )
78212
78530
  ).get()?.total ?? 0
78213
78531
  );
78214
78532
  const olderUserFetches = Number(
78215
- ctx.db.select({ total: sql48`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
78216
- and96(
78217
- eq115(aiUserFetchEventsHourly.projectId, ctx.project.id),
78218
- inArray53(aiUserFetchEventsHourly.sourceId, activeSourceIds),
78533
+ ctx.db.select({ total: sql49`COALESCE(SUM(${aiUserFetchEventsHourly.hits}), 0)` }).from(aiUserFetchEventsHourly).where(
78534
+ and97(
78535
+ eq116(aiUserFetchEventsHourly.projectId, ctx.project.id),
78536
+ inArray54(aiUserFetchEventsHourly.sourceId, activeSourceIds),
78219
78537
  gte31(aiUserFetchEventsHourly.tsHour, failCutoff)
78220
78538
  )
78221
78539
  ).get()?.total ?? 0
@@ -78541,10 +78859,10 @@ var syncLagCheck = {
78541
78859
  }
78542
78860
  };
78543
78861
  function lastQueueStopReason(ctx, sourceId) {
78544
- const row = ctx.db.select({ syncSummary: runs.syncSummary }).from(runs).where(and96(
78545
- eq115(runs.projectId, ctx.project.id),
78546
- eq115(runs.kind, RunKinds["traffic-sync"]),
78547
- eq115(runs.sourceId, sourceId),
78862
+ const row = ctx.db.select({ syncSummary: runs.syncSummary }).from(runs).where(and97(
78863
+ eq116(runs.projectId, ctx.project.id),
78864
+ eq116(runs.kind, RunKinds["traffic-sync"]),
78865
+ eq116(runs.sourceId, sourceId),
78548
78866
  isNotNull10(runs.syncSummary)
78549
78867
  )).orderBy(desc52(runs.createdAt)).limit(1).get();
78550
78868
  return row?.syncSummary?.type === "cloudflare-queue" ? row.syncSummary.stopReason : null;
@@ -79344,7 +79662,7 @@ async function doctorRoutes(app, opts) {
79344
79662
  }
79345
79663
 
79346
79664
  // ../api-routes/src/status.ts
79347
- import { and as and97, desc as desc53, eq as eq116, isNull as isNull19 } from "drizzle-orm";
79665
+ import { and as and98, desc as desc53, eq as eq117, isNull as isNull19 } from "drizzle-orm";
79348
79666
  function ageDays(iso2) {
79349
79667
  if (!iso2) return null;
79350
79668
  const ms = Date.now() - Date.parse(iso2);
@@ -79394,7 +79712,7 @@ function makeRow(integration, label, runKind, state, staleAfterDays, dataThrough
79394
79712
  };
79395
79713
  }
79396
79714
  function latestDate2(db, table, projectId) {
79397
- const row = db.select({ date: table.date }).from(table).where(eq116(table.projectId, projectId)).orderBy(desc53(table.date)).limit(1).get();
79715
+ const row = db.select({ date: table.date }).from(table).where(eq117(table.projectId, projectId)).orderBy(desc53(table.date)).limit(1).get();
79398
79716
  return row?.date ?? null;
79399
79717
  }
79400
79718
  function projectRows(opts, project) {
@@ -79409,7 +79727,7 @@ function projectRows(opts, project) {
79409
79727
  const rows = [];
79410
79728
  const gsc = gscConnection(ctx, info);
79411
79729
  if (connected(gsc)) {
79412
- const watermarkRow = opts.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq116(gscDataWatermarks.projectId, project.id)).limit(1).get();
79730
+ const watermarkRow = opts.db.select({ dataThroughDate: gscDataWatermarks.dataThroughDate }).from(gscDataWatermarks).where(eq117(gscDataWatermarks.projectId, project.id)).limit(1).get();
79413
79731
  const state = readSyncRunState(opts.db, project.id, RunKinds["gsc-sync"], { since: gsc.since });
79414
79732
  const dataThrough = watermarkRow?.dataThroughDate ?? latestDate2(opts.db, gscDailyTotals, project.id);
79415
79733
  rows.push(makeRow("gsc", "Search Console", RunKinds["gsc-sync"], state, SYNC_IDLE_DAYS, dataThrough, null, ["gsc.sync.recent-failures"], GSC_DATA_AGING_DAYS));
@@ -79425,12 +79743,12 @@ function projectRows(opts, project) {
79425
79743
  rows.push(makeRow("bing", "Bing Webmaster Tools", RunKinds["bing-inspect-sitemap"], readSyncRunState(opts.db, project.id, RunKinds["bing-inspect-sitemap"]), null));
79426
79744
  rows.push(makeRow("bing-search", "Bing search data", RunKinds["bing-sync"], readSyncRunState(opts.db, project.id, RunKinds["bing-sync"]), SYNC_IDLE_DAYS, latestDate2(opts.db, bingTrafficDaily, project.id), null, ["bing.sync.recent-failures"], BING_DATA_AGING_DAYS));
79427
79745
  }
79428
- const ads = opts.db.select({ id: adsConnections.id, lastSyncedAt: adsConnections.lastSyncedAt }).from(adsConnections).where(eq116(adsConnections.projectId, project.id)).limit(1).get();
79746
+ const ads = opts.db.select({ id: adsConnections.id, lastSyncedAt: adsConnections.lastSyncedAt }).from(adsConnections).where(eq117(adsConnections.projectId, project.id)).limit(1).get();
79429
79747
  if (ads) rows.push(makeRow("ads", "OpenAI Ads", RunKinds["ads-sync"], readSyncRunState(opts.db, project.id, RunKinds["ads-sync"]), ADS_RECENT_SYNC_WARN_DAYS, null, null, ["ads.data.recent-sync"], ADS_RECENT_SYNC_WARN_DAYS, ads.lastSyncedAt));
79430
79748
  const marketing = opts.getGoogleMarketingDoctorInput?.(ctx);
79431
79749
  if (marketing?.googleAds) rows.push(makeRow("google-ads", "Google Ads", RunKinds["google-ads-sync"], readSyncRunState(opts.db, project.id, RunKinds["google-ads-sync"]), FRESH_SNAPSHOT_WARN_DAYS, null, null, ["google-ads.sync.recent-failures"], FRESH_SNAPSHOT_WARN_DAYS, marketing.googleAds.latestSnapshotAt));
79432
79750
  if (marketing?.gtm) rows.push(makeRow("gtm", "Google Tag Manager", RunKinds["gtm-sync"], readSyncRunState(opts.db, project.id, RunKinds["gtm-sync"]), FRESH_SNAPSHOT_WARN_DAYS, null, null, ["gtm.sync.recent-failures"], FRESH_SNAPSHOT_WARN_DAYS, marketing.gtm.latestSnapshotAt));
79433
- const sources = opts.db.select().from(trafficSources).where(and97(eq116(trafficSources.projectId, project.id), isNull19(trafficSources.archivedAt))).all();
79751
+ const sources = opts.db.select().from(trafficSources).where(and98(eq117(trafficSources.projectId, project.id), isNull19(trafficSources.archivedAt))).all();
79434
79752
  for (const source of sources) {
79435
79753
  const row = makeRow("traffic", source.displayName, RunKinds["traffic-sync"], readSyncRunState(opts.db, project.id, RunKinds["traffic-sync"], { sourceId: source.id }), null, null, source.id, ["traffic.source.sync-lag", "traffic.source.recent-data"]);
79436
79754
  const lag = source.lastSyncedAt ? Date.now() - Date.parse(source.lastSyncedAt) : Number.POSITIVE_INFINITY;
@@ -79442,7 +79760,7 @@ function projectRows(opts, project) {
79442
79760
  }
79443
79761
  function projectStatus(opts, project) {
79444
79762
  const integrations = projectRows(opts, project);
79445
- const healthRow = opts.db.select().from(doctorHealthState).where(eq116(doctorHealthState.projectId, project.id)).limit(1).get();
79763
+ const healthRow = opts.db.select().from(doctorHealthState).where(eq117(doctorHealthState.projectId, project.id)).limit(1).get();
79446
79764
  const health = healthRow ? { status: healthRow.status, code: healthRow.code, summary: healthRow.summary, checkedAt: healthRow.checkedAt, notifiedAt: healthRow.notifiedAt } : null;
79447
79765
  const rank = { ok: 0, "never-synced": 1, warning: 2, stale: 3, failing: 4 };
79448
79766
  const healthState = health?.status === "fail" ? "failing" : health?.status === "warn" ? "warning" : "ok";
@@ -79462,7 +79780,7 @@ async function statusRoutes(app, opts) {
79462
79780
  if (request.query.problems === "true") result.projects = result.projects.map((item2) => ({ ...item2, integrations: item2.integrations.filter((row) => row.state !== "ok") }));
79463
79781
  return instanceStatusDtoSchema.parse(result);
79464
79782
  }
79465
- const projectsRows = (scopedId ? opts.db.select().from(projects).where(eq116(projects.id, scopedId)) : opts.db.select().from(projects)).all();
79783
+ const projectsRows = (scopedId ? opts.db.select().from(projects).where(eq117(projects.id, scopedId)) : opts.db.select().from(projects)).all();
79466
79784
  const output = { generatedAt: (/* @__PURE__ */ new Date()).toISOString(), ...opts.getMcpHealth ? { mcp: opts.getMcpHealth() } : {}, summary: { projects: projectsRows.length, ok: 0, failing: 0, warning: 0, stale: 0, neverSynced: 0 }, projects: projectsRows.map((project) => projectStatus(opts, project)) };
79467
79785
  for (const project of output.projects) {
79468
79786
  const key = project.state === "never-synced" ? "neverSynced" : project.state;
@@ -79475,7 +79793,7 @@ async function statusRoutes(app, opts) {
79475
79793
 
79476
79794
  // ../api-routes/src/discovery/routes.ts
79477
79795
  import crypto62 from "crypto";
79478
- import { and as and98, desc as desc54, eq as eq117, gte as gte32, inArray as inArray54, isNull as isNull20, or as or21 } from "drizzle-orm";
79796
+ import { and as and99, desc as desc54, eq as eq118, gte as gte32, inArray as inArray55, isNull as isNull20, or as or21 } from "drizzle-orm";
79479
79797
  var MAX_INFLIGHT_DISCOVERY_AGE_MS = 2 * 60 * 60 * 1e3;
79480
79798
  async function discoveryRoutes(app, opts) {
79481
79799
  app.post("/projects/:name/discover/run", async (request, reply) => {
@@ -79509,13 +79827,13 @@ async function discoveryRoutes(app, opts) {
79509
79827
  const now = (/* @__PURE__ */ new Date()).toISOString();
79510
79828
  const ageFloorIso = new Date(Date.now() - MAX_INFLIGHT_DISCOVERY_AGE_MS).toISOString();
79511
79829
  const decision = app.db.transaction((tx) => {
79512
- const existing = tx.select({ id: discoverySessions.id, runId: discoverySessions.runId }).from(discoverySessions).where(and98(
79513
- eq117(discoverySessions.projectId, project.id),
79514
- eq117(discoverySessions.icpDescription, icpDescription),
79830
+ const existing = tx.select({ id: discoverySessions.id, runId: discoverySessions.runId }).from(discoverySessions).where(and99(
79831
+ eq118(discoverySessions.projectId, project.id),
79832
+ eq118(discoverySessions.icpDescription, icpDescription),
79515
79833
  // Buyer is part of session identity: it changes the seed prompt's
79516
79834
  // semantics, so a request with a different (or no) buyer must start
79517
79835
  // its own session, never adopt another buyer's probes.
79518
- parsed.data.buyerDescription == null ? isNull20(discoverySessions.buyerDescription) : eq117(discoverySessions.buyerDescription, parsed.data.buyerDescription),
79836
+ parsed.data.buyerDescription == null ? isNull20(discoverySessions.buyerDescription) : eq118(discoverySessions.buyerDescription, parsed.data.buyerDescription),
79519
79837
  // Locations are identity too: a different service-area subset seeds
79520
79838
  // and probes a different geo, so it must never reuse another geo's
79521
79839
  // session. resolveLocations is deterministic (project-config order),
@@ -79525,12 +79843,12 @@ async function discoveryRoutes(app, opts) {
79525
79843
  // locations a NULL row's subset is unknowable, so it conservatively
79526
79844
  // never reuses — a one-time, bounded (2h window) non-reuse after
79527
79845
  // upgrade, never a wrong reuse.
79528
- locations.length === 0 ? or21(isNull20(discoverySessions.locations), eq117(discoverySessions.locations, locations)) : eq117(discoverySessions.locations, locations),
79846
+ locations.length === 0 ? or21(isNull20(discoverySessions.locations), eq118(discoverySessions.locations, locations)) : eq118(discoverySessions.locations, locations),
79529
79847
  // Seed provider set is identity: a different phrasing distribution
79530
79848
  // must never reuse another set's session. Null (= Gemini-only
79531
79849
  // default, including explicit ['gemini']) matches legacy rows.
79532
- seedProviders == null ? isNull20(discoverySessions.seedProviders) : eq117(discoverySessions.seedProviders, seedProviders),
79533
- inArray54(discoverySessions.status, [
79850
+ seedProviders == null ? isNull20(discoverySessions.seedProviders) : eq118(discoverySessions.seedProviders, seedProviders),
79851
+ inArray55(discoverySessions.status, [
79534
79852
  DiscoverySessionStatuses.queued,
79535
79853
  DiscoverySessionStatuses.seeding,
79536
79854
  DiscoverySessionStatuses.probing
@@ -79605,7 +79923,7 @@ async function discoveryRoutes(app, opts) {
79605
79923
  const project = resolveProject(app.db, request.params.name);
79606
79924
  const parsedLimit = parseInt(request.query.limit ?? "", 10);
79607
79925
  const limit = Number.isNaN(parsedLimit) || parsedLimit <= 0 ? 50 : parsedLimit;
79608
- const rows = app.db.select().from(discoverySessions).where(eq117(discoverySessions.projectId, project.id)).orderBy(desc54(discoverySessions.createdAt)).limit(limit).all();
79926
+ const rows = app.db.select().from(discoverySessions).where(eq118(discoverySessions.projectId, project.id)).orderBy(desc54(discoverySessions.createdAt)).limit(limit).all();
79609
79927
  return reply.send(rows.map(serializeSession));
79610
79928
  }
79611
79929
  );
@@ -79613,11 +79931,11 @@ async function discoveryRoutes(app, opts) {
79613
79931
  "/projects/:name/discover/sessions/:id",
79614
79932
  async (request, reply) => {
79615
79933
  const project = resolveProject(app.db, request.params.name);
79616
- const session = app.db.select().from(discoverySessions).where(eq117(discoverySessions.id, request.params.id)).get();
79934
+ const session = app.db.select().from(discoverySessions).where(eq118(discoverySessions.id, request.params.id)).get();
79617
79935
  if (!session || session.projectId !== project.id) {
79618
79936
  throw notFound("Discovery session", request.params.id);
79619
79937
  }
79620
- const probeRows = app.db.select().from(discoveryProbes).where(eq117(discoveryProbes.sessionId, session.id)).all();
79938
+ const probeRows = app.db.select().from(discoveryProbes).where(eq118(discoveryProbes.sessionId, session.id)).all();
79621
79939
  const detail = {
79622
79940
  ...serializeSession(session),
79623
79941
  probes: probeRows.map(serializeProbe)
@@ -79629,7 +79947,7 @@ async function discoveryRoutes(app, opts) {
79629
79947
  "/projects/:name/discover/sessions/:id/harvest",
79630
79948
  async (request, reply) => {
79631
79949
  const project = resolveProject(app.db, request.params.name);
79632
- const session = app.db.select().from(discoverySessions).where(eq117(discoverySessions.id, request.params.id)).get();
79950
+ const session = app.db.select().from(discoverySessions).where(eq118(discoverySessions.id, request.params.id)).get();
79633
79951
  if (!session || session.projectId !== project.id) {
79634
79952
  throw notFound("Discovery session", request.params.id);
79635
79953
  }
@@ -79637,7 +79955,7 @@ async function discoveryRoutes(app, opts) {
79637
79955
  const minProbeHits = Number.isNaN(parsedFloor) || parsedFloor < 1 ? 1 : parsedFloor;
79638
79956
  const applyAnchor = request.query.anchor !== "false";
79639
79957
  const provider = session.seedProvider ?? "gemini";
79640
- const probeRows = app.db.select().from(discoveryProbes).where(eq117(discoveryProbes.sessionId, session.id)).all();
79958
+ const probeRows = app.db.select().from(discoveryProbes).where(eq118(discoveryProbes.sessionId, session.id)).all();
79641
79959
  const extract = opts.harvestSearchQueries;
79642
79960
  const probesWithQueries = probeRows.map((row) => {
79643
79961
  if (!extract || !row.rawResponse) return { searchQueries: [] };
@@ -79648,7 +79966,7 @@ async function discoveryRoutes(app, opts) {
79648
79966
  return { searchQueries: [] };
79649
79967
  }
79650
79968
  });
79651
- const trackedQueries = app.db.select({ query: queries.query }).from(queries).where(eq117(queries.projectId, project.id)).all().map((r) => r.query);
79969
+ const trackedQueries = app.db.select({ query: queries.query }).from(queries).where(eq118(queries.projectId, project.id)).all().map((r) => r.query);
79652
79970
  const anchorTerms = buildHarvestAnchorTerms(
79653
79971
  [session.icpDescription ?? "", ...trackedQueries],
79654
79972
  effectiveDomains(project)
@@ -79695,11 +80013,11 @@ async function discoveryRoutes(app, opts) {
79695
80013
  "/projects/:name/discover/sessions/:id/promote",
79696
80014
  async (request, reply) => {
79697
80015
  const project = resolveProject(app.db, request.params.name);
79698
- const session = app.db.select().from(discoverySessions).where(eq117(discoverySessions.id, request.params.id)).get();
80016
+ const session = app.db.select().from(discoverySessions).where(eq118(discoverySessions.id, request.params.id)).get();
79699
80017
  if (!session || session.projectId !== project.id) {
79700
80018
  throw notFound("Discovery session", request.params.id);
79701
80019
  }
79702
- const probeRows = app.db.select().from(discoveryProbes).where(eq117(discoveryProbes.sessionId, session.id)).all();
80020
+ const probeRows = app.db.select().from(discoveryProbes).where(eq118(discoveryProbes.sessionId, session.id)).all();
79703
80021
  const cited = /* @__PURE__ */ new Set();
79704
80022
  const aspirational = /* @__PURE__ */ new Set();
79705
80023
  const wasted = /* @__PURE__ */ new Set();
@@ -79734,7 +80052,7 @@ async function discoveryRoutes(app, opts) {
79734
80052
  );
79735
80053
  app.post("/projects/:name/discover/sessions/:id/promote", async (request, reply) => {
79736
80054
  const project = resolveProject(app.db, request.params.name);
79737
- const session = app.db.select().from(discoverySessions).where(eq117(discoverySessions.id, request.params.id)).get();
80055
+ const session = app.db.select().from(discoverySessions).where(eq118(discoverySessions.id, request.params.id)).get();
79738
80056
  if (!session || session.projectId !== project.id) {
79739
80057
  throw notFound("Discovery session", request.params.id);
79740
80058
  }
@@ -79757,7 +80075,7 @@ async function discoveryRoutes(app, opts) {
79757
80075
  const bucketSet = new Set(buckets);
79758
80076
  const includeCompetitors = parsed.data.includeCompetitors ?? true;
79759
80077
  const competitorTypes = parsed.data.competitorTypes ?? DEFAULT_DISCOVERY_PROMOTE_COMPETITOR_TYPES;
79760
- const probeRows = app.db.select().from(discoveryProbes).where(eq117(discoveryProbes.sessionId, session.id)).all();
80078
+ const probeRows = app.db.select().from(discoveryProbes).where(eq118(discoveryProbes.sessionId, session.id)).all();
79761
80079
  const candidateQueries = /* @__PURE__ */ new Set();
79762
80080
  for (const probe of probeRows) {
79763
80081
  if (!probe.bucket) continue;
@@ -79765,7 +80083,7 @@ async function discoveryRoutes(app, opts) {
79765
80083
  if (bucket.success && bucketSet.has(bucket.data)) candidateQueries.add(probe.query);
79766
80084
  }
79767
80085
  const existingQueries = new Set(
79768
- app.db.select({ query: queries.query }).from(queries).where(eq117(queries.projectId, project.id)).all().map((r) => r.query.toLowerCase())
80086
+ app.db.select({ query: queries.query }).from(queries).where(eq118(queries.projectId, project.id)).all().map((r) => r.query.toLowerCase())
79769
80087
  );
79770
80088
  const promotedQueries = [];
79771
80089
  const skippedQueries = [];
@@ -79979,7 +80297,7 @@ function planCompetitorPromotion(input) {
79979
80297
 
79980
80298
  // ../api-routes/src/discovery/orchestrate.ts
79981
80299
  import crypto63 from "crypto";
79982
- import { eq as eq118 } from "drizzle-orm";
80300
+ import { eq as eq119 } from "drizzle-orm";
79983
80301
  var DEFAULT_MAX_PROBES = 100;
79984
80302
  var ABSOLUTE_MAX_PROBES = 500;
79985
80303
  function classifyProbeBucket(input) {
@@ -80065,7 +80383,7 @@ async function executeDiscovery(opts) {
80065
80383
  status: DiscoverySessionStatuses.seeding,
80066
80384
  dedupThreshold,
80067
80385
  startedAt
80068
- }).where(eq118(discoverySessions.id, opts.sessionId)).run();
80386
+ }).where(eq119(discoverySessions.id, opts.sessionId)).run();
80069
80387
  const seedResult = await opts.deps.seed({
80070
80388
  project: opts.project,
80071
80389
  icpDescription: opts.icpDescription,
@@ -80126,7 +80444,7 @@ async function executeDiscovery(opts) {
80126
80444
  dedupBandPairFraction: dedupStats.bandPairFraction,
80127
80445
  dedupPairsTotal: dedupStats.pairsTotal,
80128
80446
  warning
80129
- }).where(eq118(discoverySessions.id, opts.sessionId)).run();
80447
+ }).where(eq119(discoverySessions.id, opts.sessionId)).run();
80130
80448
  const probeLocation = opts.locations?.[0];
80131
80449
  const probeResults = await mapWithConcurrency(
80132
80450
  probedCanonicals,
@@ -80180,7 +80498,7 @@ async function executeDiscovery(opts) {
80180
80498
  wastedCount: buckets["wasted-surface"],
80181
80499
  competitorMap,
80182
80500
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
80183
- }).where(eq118(discoverySessions.id, opts.sessionId)).run();
80501
+ }).where(eq119(discoverySessions.id, opts.sessionId)).run();
80184
80502
  upsertDomainClassifications(opts.db, opts.project.id, opts.sessionId, competitorMap);
80185
80503
  return {
80186
80504
  buckets,
@@ -80220,7 +80538,7 @@ function markSessionFailed(db, sessionId, error) {
80220
80538
  status: DiscoverySessionStatuses.failed,
80221
80539
  error,
80222
80540
  finishedAt: (/* @__PURE__ */ new Date()).toISOString()
80223
- }).where(eq118(discoverySessions.id, sessionId)).run();
80541
+ }).where(eq119(discoverySessions.id, sessionId)).run();
80224
80542
  }
80225
80543
  function dedupeStrings(input) {
80226
80544
  const seen2 = /* @__PURE__ */ new Set();
@@ -80237,7 +80555,7 @@ function dedupeStrings(input) {
80237
80555
  }
80238
80556
 
80239
80557
  // ../api-routes/src/trends.ts
80240
- import { and as and99, asc as asc30, eq as eq119 } from "drizzle-orm";
80558
+ import { and as and100, asc as asc30, eq as eq120 } from "drizzle-orm";
80241
80559
  function parseSurface(value) {
80242
80560
  const parsed = trendSurfaceSchema.safeParse(value);
80243
80561
  if (!parsed.success) {
@@ -80293,8 +80611,8 @@ async function trendsRoutes(app) {
80293
80611
  function readSurface(app, projectId, surface) {
80294
80612
  switch (surface) {
80295
80613
  case TrendSurfaces["index-coverage"]: {
80296
- const google = app.db.select({ date: gscCoverageSnapshots.date, indexed: gscCoverageSnapshots.indexed, notIndexed: gscCoverageSnapshots.notIndexed }).from(gscCoverageSnapshots).where(eq119(gscCoverageSnapshots.projectId, projectId)).orderBy(asc30(gscCoverageSnapshots.date)).all();
80297
- const bing = app.db.select({ date: bingCoverageSnapshots.date, indexed: bingCoverageSnapshots.indexed, notIndexed: bingCoverageSnapshots.notIndexed }).from(bingCoverageSnapshots).where(eq119(bingCoverageSnapshots.projectId, projectId)).orderBy(asc30(bingCoverageSnapshots.date)).all();
80614
+ const google = app.db.select({ date: gscCoverageSnapshots.date, indexed: gscCoverageSnapshots.indexed, notIndexed: gscCoverageSnapshots.notIndexed }).from(gscCoverageSnapshots).where(eq120(gscCoverageSnapshots.projectId, projectId)).orderBy(asc30(gscCoverageSnapshots.date)).all();
80615
+ const bing = app.db.select({ date: bingCoverageSnapshots.date, indexed: bingCoverageSnapshots.indexed, notIndexed: bingCoverageSnapshots.notIndexed }).from(bingCoverageSnapshots).where(eq120(bingCoverageSnapshots.projectId, projectId)).orderBy(asc30(bingCoverageSnapshots.date)).all();
80298
80616
  const coverage = (key, label, rows) => ({
80299
80617
  key,
80300
80618
  label,
@@ -80306,7 +80624,7 @@ function readSurface(app, projectId, surface) {
80306
80624
  return [coverage("google", "Google", google), coverage("bing", "Bing", bing)];
80307
80625
  }
80308
80626
  case TrendSurfaces["site-health"]: {
80309
- const rows = app.db.select({ auditedAt: siteAuditSnapshots.auditedAt, aggregateScore: siteAuditSnapshots.aggregateScore, pagesAudited: siteAuditSnapshots.pagesAudited }).from(siteAuditSnapshots).innerJoin(runs, eq119(siteAuditSnapshots.runId, runs.id)).where(and99(...surfaceableSiteAuditFilters(projectId))).orderBy(asc30(siteAuditSnapshots.auditedAt)).all();
80627
+ const rows = app.db.select({ auditedAt: siteAuditSnapshots.auditedAt, aggregateScore: siteAuditSnapshots.aggregateScore, pagesAudited: siteAuditSnapshots.pagesAudited }).from(siteAuditSnapshots).innerJoin(runs, eq120(siteAuditSnapshots.runId, runs.id)).where(and100(...surfaceableSiteAuditFilters(projectId))).orderBy(asc30(siteAuditSnapshots.auditedAt)).all();
80310
80628
  return [{
80311
80629
  key: "site-health",
80312
80630
  label: "Agent Readiness",
@@ -80318,7 +80636,7 @@ function readSurface(app, projectId, surface) {
80318
80636
  }
80319
80637
  case TrendSurfaces.backlinks: {
80320
80638
  const totals = computeFilteredReleaseTotals(app.db, projectId, BacklinkSources.commoncrawl);
80321
- const rows = app.db.select({ release: backlinkSummaries.release, totalLinkingDomains: backlinkSummaries.totalLinkingDomains, queriedAt: backlinkSummaries.queriedAt }).from(backlinkSummaries).where(and99(eq119(backlinkSummaries.projectId, projectId), eq119(backlinkSummaries.source, BacklinkSources.commoncrawl))).all().sort((a, b) => compareReleaseIds(a.release, b.release)).map((row) => {
80639
+ const rows = app.db.select({ release: backlinkSummaries.release, totalLinkingDomains: backlinkSummaries.totalLinkingDomains, queriedAt: backlinkSummaries.queriedAt }).from(backlinkSummaries).where(and100(eq120(backlinkSummaries.projectId, projectId), eq120(backlinkSummaries.source, BacklinkSources.commoncrawl))).all().sort((a, b) => compareReleaseIds(a.release, b.release)).map((row) => {
80322
80640
  const filtered = totals.get(row.release);
80323
80641
  const known = (filtered?.domainRows ?? 0) > 0 || row.totalLinkingDomains === 0;
80324
80642
  const windowEnd = releaseWindowEndMonth(row.release);
@@ -80348,7 +80666,7 @@ function readSurface(app, projectId, surface) {
80348
80666
  // ../api-routes/src/research.ts
80349
80667
  import crypto64 from "crypto";
80350
80668
  import { z as z7 } from "zod";
80351
- import { and as and100, count as count10, desc as desc55, eq as eq120, gte as gte33, lt as lt21, or as or22, sql as sql49 } from "drizzle-orm";
80669
+ import { and as and101, count as count10, desc as desc55, eq as eq121, gte as gte33, lt as lt21, or as or22, sql as sql50 } from "drizzle-orm";
80352
80670
  var sameLocation = (a, b) => a.label === b.label && a.city === b.city && a.region === b.region && a.country === b.country && a.timezone === b.timezone;
80353
80671
  var BATCH_RECEIPT_PREFIX = "__canonry_research_batch__:";
80354
80672
  async function researchRoutes(app, opts) {
@@ -80367,7 +80685,7 @@ async function researchRoutes(app, opts) {
80367
80685
  const input = parsed.data;
80368
80686
  if (input.idempotencyKey?.startsWith(BATCH_RECEIPT_PREFIX)) throw validationError("This idempotency key prefix is reserved for internal research batch receipts.");
80369
80687
  const requestHash2 = directResearchRequestHash(input);
80370
- const existingReceipt = input.idempotencyKey ? app.db.select().from(researchRuns).where(and100(eq120(researchRuns.projectId, project.id), eq120(researchRuns.idempotencyKey, input.idempotencyKey))).get() : void 0;
80688
+ const existingReceipt = input.idempotencyKey ? app.db.select().from(researchRuns).where(and101(eq121(researchRuns.projectId, project.id), eq121(researchRuns.idempotencyKey, input.idempotencyKey))).get() : void 0;
80371
80689
  if (existingReceipt) {
80372
80690
  assertSameDirectResearchRequest(existingReceipt, input, requestHash2);
80373
80691
  const result2 = getDetail(app, project.id, existingReceipt.id);
@@ -80402,7 +80720,7 @@ async function researchRoutes(app, opts) {
80402
80720
  const initiatedBy = researchPrincipal(request);
80403
80721
  const decision = app.db.transaction((tx) => {
80404
80722
  if (input.idempotencyKey) {
80405
- const existing = tx.select().from(researchRuns).where(and100(eq120(researchRuns.projectId, project.id), eq120(researchRuns.idempotencyKey, input.idempotencyKey))).get();
80723
+ const existing = tx.select().from(researchRuns).where(and101(eq121(researchRuns.projectId, project.id), eq121(researchRuns.idempotencyKey, input.idempotencyKey))).get();
80406
80724
  if (existing) {
80407
80725
  assertSameDirectResearchRequest(existing, input, requestHash2);
80408
80726
  return { reused: true, id: existing.id, shouldDispatch: existing.status === ResearchRunStatuses.queued };
@@ -80410,11 +80728,11 @@ async function researchRoutes(app, opts) {
80410
80728
  }
80411
80729
  if (initiatedBy?.limited) {
80412
80730
  const { start, end, date } = utcDayBounds(now);
80413
- const used = tx.select({ value: count10() }).from(researchRuns).where(and100(
80414
- eq120(researchRuns.projectId, project.id),
80731
+ const used = tx.select({ value: count10() }).from(researchRuns).where(and101(
80732
+ eq121(researchRuns.projectId, project.id),
80415
80733
  gte33(researchRuns.createdAt, start),
80416
80734
  lt21(researchRuns.createdAt, end),
80417
- sql49`(json_extract(${researchRuns.initiatedBy}, '$.role') = ${UserRoles.viewer} OR json_extract(${researchRuns.initiatedBy}, '$.limited') = 1)`
80735
+ sql50`(json_extract(${researchRuns.initiatedBy}, '$.role') = ${UserRoles.viewer} OR json_extract(${researchRuns.initiatedBy}, '$.limited') = 1)`
80418
80736
  )).get()?.value ?? 0;
80419
80737
  if (used >= viewerDailyRunLimit) {
80420
80738
  throw researchDailyLimitExceeded(project.name, viewerDailyRunLimit, date);
@@ -80442,15 +80760,15 @@ async function researchRoutes(app, opts) {
80442
80760
  if (input.idempotencyKey.startsWith(BATCH_RECEIPT_PREFIX)) throw validationError("This idempotency key prefix is reserved for internal research batch receipts.");
80443
80761
  const requestHash2 = researchBatchRequestHash(input);
80444
80762
  const receiptKeys = input.runs.map((_run, index) => batchChildReceiptKey(input.idempotencyKey, index));
80445
- const firstReceipt = app.db.select().from(researchRuns).where(and100(
80446
- eq120(researchRuns.projectId, project.id),
80447
- eq120(researchRuns.idempotencyKey, receiptKeys[0])
80763
+ const firstReceipt = app.db.select().from(researchRuns).where(and101(
80764
+ eq121(researchRuns.projectId, project.id),
80765
+ eq121(researchRuns.idempotencyKey, receiptKeys[0])
80448
80766
  )).get();
80449
80767
  if (firstReceipt) {
80450
80768
  if (firstReceipt.requestHash !== requestHash2) throw alreadyExists("Research batch idempotency key", input.idempotencyKey);
80451
- const saved = receiptKeys.map((key) => app.db.select().from(researchRuns).where(and100(
80452
- eq120(researchRuns.projectId, project.id),
80453
- eq120(researchRuns.idempotencyKey, key)
80769
+ const saved = receiptKeys.map((key) => app.db.select().from(researchRuns).where(and101(
80770
+ eq121(researchRuns.projectId, project.id),
80771
+ eq121(researchRuns.idempotencyKey, key)
80454
80772
  )).get());
80455
80773
  if (saved.some((row) => !row || row.requestHash !== requestHash2)) throw alreadyExists("Research batch idempotency key", input.idempotencyKey);
80456
80774
  const runs3 = saved.map((row) => getDetail(app, project.id, row.id));
@@ -80466,11 +80784,11 @@ async function researchRoutes(app, opts) {
80466
80784
  const decision = app.db.transaction((tx) => {
80467
80785
  if (initiatedBy?.limited) {
80468
80786
  const { start, end, date } = utcDayBounds(now);
80469
- const used = tx.select({ value: count10() }).from(researchRuns).where(and100(
80470
- eq120(researchRuns.projectId, project.id),
80787
+ const used = tx.select({ value: count10() }).from(researchRuns).where(and101(
80788
+ eq121(researchRuns.projectId, project.id),
80471
80789
  gte33(researchRuns.createdAt, start),
80472
80790
  lt21(researchRuns.createdAt, end),
80473
- sql49`(json_extract(${researchRuns.initiatedBy}, '$.role') = ${UserRoles.viewer} OR json_extract(${researchRuns.initiatedBy}, '$.limited') = 1)`
80791
+ sql50`(json_extract(${researchRuns.initiatedBy}, '$.role') = ${UserRoles.viewer} OR json_extract(${researchRuns.initiatedBy}, '$.limited') = 1)`
80474
80792
  )).get()?.value ?? 0;
80475
80793
  if (used + prepared.length > viewerDailyRunLimit) throw researchDailyLimitExceeded(project.name, viewerDailyRunLimit, date);
80476
80794
  }
@@ -80521,9 +80839,9 @@ async function researchRoutes(app, opts) {
80521
80839
  const requested = Number.parseInt(request.query.limit ?? "", 10);
80522
80840
  const limit = Number.isInteger(requested) && requested > 0 ? Math.min(requested, 100) : 20;
80523
80841
  const cursor = request.query.cursor ? parseResearchCursor(request.query.cursor, project.id) : null;
80524
- const rows = app.db.select().from(researchRuns).where(and100(
80525
- eq120(researchRuns.projectId, project.id),
80526
- cursor ? or22(lt21(researchRuns.createdAt, cursor.createdAt), and100(eq120(researchRuns.createdAt, cursor.createdAt), lt21(researchRuns.id, cursor.id))) : void 0
80842
+ const rows = app.db.select().from(researchRuns).where(and101(
80843
+ eq121(researchRuns.projectId, project.id),
80844
+ cursor ? or22(lt21(researchRuns.createdAt, cursor.createdAt), and101(eq121(researchRuns.createdAt, cursor.createdAt), lt21(researchRuns.id, cursor.id))) : void 0
80527
80845
  )).orderBy(desc55(researchRuns.createdAt), desc55(researchRuns.id)).limit(limit + 1).all();
80528
80846
  const runs2 = rows.slice(0, limit).map(serializeRun);
80529
80847
  const last = runs2.at(-1);
@@ -80673,9 +80991,9 @@ function resolveStoredResearchTemplate(stored, selection, idempotencyKey) {
80673
80991
  return stored;
80674
80992
  }
80675
80993
  function resolveResearchTemplate(app, projectId, selection, scope, location) {
80676
- const savedTemplate = app.db.select().from(measurementQueryTemplates).where(and100(
80677
- eq120(measurementQueryTemplates.projectId, projectId),
80678
- eq120(measurementQueryTemplates.id, selection.templateId)
80994
+ const savedTemplate = app.db.select().from(measurementQueryTemplates).where(and101(
80995
+ eq121(measurementQueryTemplates.projectId, projectId),
80996
+ eq121(measurementQueryTemplates.id, selection.templateId)
80679
80997
  )).get();
80680
80998
  if (!savedTemplate) throw validationError("Unknown or stale research template. Reload the selected template and try again.");
80681
80999
  const templateVersion = savedTemplate.updatedAt;
@@ -80684,7 +81002,7 @@ function resolveResearchTemplate(app, projectId, selection, scope, location) {
80684
81002
  }
80685
81003
  const bindingLocation = selection.bindingLocation === void 0 ? location : selection.bindingLocation;
80686
81004
  if (bindingLocation) {
80687
- const project = app.db.select({ locations: projects.locations }).from(projects).where(eq120(projects.id, projectId)).get();
81005
+ const project = app.db.select({ locations: projects.locations }).from(projects).where(eq121(projects.id, projectId)).get();
80688
81006
  if (!project.locations.some((item2) => sameLocation(item2, bindingLocation))) throw validationError("Research template binding location must match a configured project location.");
80689
81007
  }
80690
81008
  const { bindings, output } = expandResearchTemplate(savedTemplate, scope, bindingLocation);
@@ -80697,9 +81015,9 @@ function classifyResearchQueries(project, plan, queries2) {
80697
81015
  return queries2.map((query2) => classifier?.classify(query2) ?? null);
80698
81016
  }
80699
81017
  function getDetail(app, projectId, id) {
80700
- const row = app.db.select().from(researchRuns).where(and100(eq120(researchRuns.id, id), eq120(researchRuns.projectId, projectId))).get();
81018
+ const row = app.db.select().from(researchRuns).where(and101(eq121(researchRuns.id, id), eq121(researchRuns.projectId, projectId))).get();
80701
81019
  if (!row) throw notFound("Research run", id);
80702
- const queries2 = app.db.select().from(researchRunQueries).where(eq120(researchRunQueries.researchRunId, id)).orderBy(researchRunQueries.position).all().map((query2) => serializeQuery(query2, row.provider));
81020
+ const queries2 = app.db.select().from(researchRunQueries).where(eq121(researchRunQueries.researchRunId, id)).orderBy(researchRunQueries.position).all().map((query2) => serializeQuery(query2, row.provider));
80703
81021
  return { ...serializeRun(row), queries: queries2 };
80704
81022
  }
80705
81023
  function serializeRun(row) {
@@ -80760,7 +81078,7 @@ function utcDayBounds(now) {
80760
81078
 
80761
81079
  // ../api-routes/src/simple-measurement-definitions.ts
80762
81080
  import crypto65 from "crypto";
80763
- import { and as and101, eq as eq121 } from "drizzle-orm";
81081
+ import { and as and102, eq as eq122 } from "drizzle-orm";
80764
81082
  function captureSimpleMeasurementDefinition(db, input) {
80765
81083
  return db.transaction((tx) => {
80766
81084
  const run = tx.select({
@@ -80768,7 +81086,7 @@ function captureSimpleMeasurementDefinition(db, input) {
80768
81086
  trigger: runs.trigger,
80769
81087
  status: runs.status,
80770
81088
  measurementPlanVersionId: runs.measurementPlanVersionId
80771
- }).from(runs).where(and101(eq121(runs.projectId, input.projectId), eq121(runs.id, input.runId))).get();
81089
+ }).from(runs).where(and102(eq122(runs.projectId, input.projectId), eq122(runs.id, input.runId))).get();
80772
81090
  if (!run) throw notFound("Run", input.runId);
80773
81091
  if (run.kind !== RunKinds["answer-visibility"] || run.trigger === RunTriggers.probe || run.measurementPlanVersionId !== null) {
80774
81092
  return null;
@@ -80789,7 +81107,7 @@ function captureSimpleMeasurementDefinition(db, input) {
80789
81107
  throw validationError("Qualified aliases must be a sorted subset of the captured aliases.");
80790
81108
  }
80791
81109
  }
80792
- const existing = tx.select().from(simpleMeasurementDefinitions).where(and101(eq121(simpleMeasurementDefinitions.projectId, input.projectId), eq121(simpleMeasurementDefinitions.runId, input.runId))).get();
81110
+ const existing = tx.select().from(simpleMeasurementDefinitions).where(and102(eq122(simpleMeasurementDefinitions.projectId, input.projectId), eq122(simpleMeasurementDefinitions.runId, input.runId))).get();
80793
81111
  if (existing) {
80794
81112
  const frozen = simpleMeasurementDefinitionSchema.parse(existing.definition);
80795
81113
  const { qualifiedAliases: _liveQualifiedAliases, ...liveIdentity } = definition2.identity;
@@ -80815,15 +81133,15 @@ function captureSimpleMeasurementDefinition(db, input) {
80815
81133
  if (run.status !== RunStatuses.running) {
80816
81134
  throw validationError("Only a running run can capture a new measurement definition.");
80817
81135
  }
80818
- if (tx.select({ id: querySnapshots.id }).from(querySnapshots).where(eq121(querySnapshots.runId, input.runId)).limit(1).get()) {
81136
+ if (tx.select({ id: querySnapshots.id }).from(querySnapshots).where(eq122(querySnapshots.runId, input.runId)).limit(1).get()) {
80819
81137
  throw validationError("This run already has stored answers. Its measurement definition cannot be inferred afterward.");
80820
81138
  }
80821
- const projectQueryIds = new Set(tx.select({ id: queries.id }).from(queries).where(eq121(queries.projectId, input.projectId)).all().map((query2) => query2.id));
81139
+ const projectQueryIds = new Set(tx.select({ id: queries.id }).from(queries).where(eq122(queries.projectId, input.projectId)).all().map((query2) => query2.id));
80822
81140
  if (definition2.queries.some((query2) => !projectQueryIds.has(query2.queryId))) {
80823
81141
  throw validationError("Every captured query must belong to the run project.");
80824
81142
  }
80825
81143
  if (definition2.competitors !== void 0) {
80826
- const liveCompetitorDomains = new Set(tx.select({ domain: competitors.domain }).from(competitors).where(eq121(competitors.projectId, input.projectId)).orderBy(competitors.domain).all().map((competitor) => competitor.domain));
81144
+ const liveCompetitorDomains = new Set(tx.select({ domain: competitors.domain }).from(competitors).where(eq122(competitors.projectId, input.projectId)).orderBy(competitors.domain).all().map((competitor) => competitor.domain));
80827
81145
  const capturedDomains = new Set(definition2.competitors.map((competitor) => competitor.domain));
80828
81146
  if (liveCompetitorDomains.size !== capturedDomains.size || [...liveCompetitorDomains].some((domain) => !capturedDomains.has(domain))) {
80829
81147
  throw validationError("Captured competitors must exactly match the project competitors dispatched for this run.");