seo 0.17.7 → 0.17.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,137 +1,138 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __seoCreateRequire } from 'node:module'; const require = __seoCreateRequire(import.meta.url);
3
- import{$ as e,$n as t,$t as n,A as r,An as i,At as a,B as o,Bn as s,Bt as c,C as l,Cn as u,Cr as d,D as f,Dn as p,Dr as ee,Dt as m,E as te,En as h,Er as g,Et as ne,F as re,Fn as ie,Ft as ae,G as oe,Gn as se,Gt as ce,H as le,Hn as ue,Ht as de,I as fe,In as pe,It as me,J as he,Jn as ge,Jt as _e,K as ve,Kn as ye,Kt as be,L as xe,Ln as Se,Lt as Ce,M as we,Mn as Te,Mt as Ee,N as De,Nn as Oe,Nt as ke,O as Ae,On as je,Ot as Me,P as Ne,Pn as Pe,Pt as Fe,Q as Ie,Qn as Le,Qt as Re,R as ze,Rn as Be,Rt as Ve,S as He,Sn as Ue,Sr as We,St as Ge,T as Ke,Tn as qe,Tr as Je,Tt as Ye,U as Xe,Un as Ze,Ut as Qe,V as $e,Vn as et,Vt as tt,W as nt,Wn as rt,Wt as it,X as at,Xn as ot,Xt as st,Y as ct,Yn as lt,Yt as ut,Z as dt,Zn as ft,Zt as pt,_ as mt,_n as ht,_r as gt,_t,a as vt,an as yt,ar as bt,at as xt,b as St,bn as Ct,br as wt,bt as Tt,c as Et,cn as Dt,cr as Ot,ct as kt,d as At,dn as jt,dr as Mt,dt as Nt,en as Pt,er as Ft,et as It,f as Lt,fn as Rt,fr as zt,ft as Bt,g as Vt,gn as Ht,gr as Ut,gt as Wt,h as Gt,hn as Kt,hr as qt,ht as Jt,i as Yt,in as Xt,ir as Zt,it as Qt,j as $t,jn as en,jt as tn,k as nn,kn as rn,kt as an,l as on,ln as sn,lr as cn,lt as ln,m as un,mn as dn,mr as fn,mt as pn,nn as mn,nr as hn,nt as gn,o as _n,on as vn,or as yn,ot as bn,p as xn,pn as Sn,pr as Cn,pt as wn,q as Tn,qn as En,qt as Dn,rn as On,rr as kn,rt as An,sn as jn,sr as Mn,st as Nn,t as Pn,tn as Fn,tr as In,tt as Ln,u as Rn,un as zn,ur as Bn,ut as Vn,v as Hn,vn as Un,vr as Wn,vt as Gn,w as Kn,wn as qn,wr as Jn,wt as Yn,x as Xn,xn as Zn,xr as Qn,xt as $n,y as er,yn as tr,yr as nr,yt as rr,z as ir,zn as ar,zt as or}from"./dist--XpKpLek.js";import{randomBytes as sr}from"node:crypto";import{arch as cr,homedir as lr,platform as ur}from"node:os";import{basename as dr,dirname as _,join as v,posix as fr,relative as pr,resolve as mr,sep as hr,win32 as gr}from"node:path";import{constants as _r,copyFileSync as vr,createWriteStream as yr,existsSync as y,mkdirSync as br,readFileSync as xr,readdirSync as Sr,realpathSync as Cr,renameSync as wr,rmSync as Tr,statSync as Er,writeFileSync as Dr}from"node:fs";import{fileURLToPath as Or}from"node:url";import{cp as kr,mkdir as Ar,open as jr,readFile as b,readdir as Mr,rename as Nr,stat as Pr,writeFile as Fr}from"node:fs/promises";import{isDeepStrictEqual as Ir,stripVTControlCharacters as Lr}from"node:util";import{spawn as Rr,spawnSync as zr}from"node:child_process";import{defineCommand as x,runCommand as Br,runMain as Vr}from"citty";import{cancel as Hr,confirm as Ur,intro as Wr,isCancel as Gr,log as Kr,multiselect as qr,note as S,outro as C,password as Jr,select as Yr,text as Xr}from"@clack/prompts";import Zr from"picocolors";import Qr from"string-width";import $r from"cli-table3";import{finished as ei}from"node:stream/promises";import{applyEdits as ti,modify as ni,parse as ri,printParseErrorCode as ii}from"jsonc-parser";import ai from"update-notifier";const w={summary:/* @__PURE__ */ `workflow.site.generated_at.summary.attribution.confidence.classification.updates_matched.known_confounders.page_segment_status.page_segment_eligible_rows.page_segment_returned_rows.page_segment_limited_rows.page_segment_result_limit.page_segment_source_row_limit.page_segment_source_possibly_truncated.page_segment_warnings.query_segment_status.query_segment_eligible_rows.query_segment_returned_rows.query_segment_limited_rows.query_segment_result_limit.query_segment_source_row_limit.query_segment_source_possibly_truncated.query_segment_warnings.device_segment_status.device_segment_eligible_rows.device_segment_returned_rows.device_segment_limited_rows.device_segment_result_limit.device_segment_source_row_limit.device_segment_source_possibly_truncated.device_segment_warnings.country_segment_status.country_segment_eligible_rows.country_segment_returned_rows.country_segment_limited_rows.country_segment_result_limit.country_segment_source_row_limit.country_segment_source_possibly_truncated.country_segment_warnings`.split(`.`),steps:[`rank`,`tool`,`status`,`summary`],actions:[`rank`,`title`,`confidence`,`action`],findings:[`dimension`,`data_status`,`eligible_rows`,`returned_rows`,`limited_rows`,`result_limit`,`unmatched_rows`,`summary`,`winner_key`,`winner_click_delta`,`winner_impression_delta`,`winner_position_delta`,`loser_key`,`loser_click_delta`,`loser_impression_delta`,`loser_position_delta`],templates:[`rank`,`direction`,`template`,`confidence`,`url_count`,`click_delta`,`impression_delta`,`movement_share`,`movement_share_scope`,`confidence_scope`,`eligible_rows`,`returned_rows`,`limited_rows`,`result_limit`,`source_possibly_truncated`,`common_terms`,`sample_urls`,`summary`],evidence:[`rank`,`evidence`],confounders:[`rank`,`source`,`title`,`date`,`scope`,`target`,`description`],segment:[`rank`,`dimension`,`data_status`,`evidence_scope`,`key`,`before_clicks`,`after_clicks`,`click_delta`,`before_impressions`,`after_impressions`,`impression_delta`,`before_position`,`after_position`,`position_delta`],unmatchedSegment:[`rank`,`dimension`,`data_status`,`key`,`retained_in`,`clicks`,`impressions`,`position`,`reason`]};function oi(e,t){return[...e.output.segments[t].winners,...e.output.segments[t].losers].map((n,r)=>({rank:r+1,dimension:t,data_status:e.output.segments[t].dataStatus,evidence_scope:n.evidenceScope,key:n.key,before_clicks:n.beforeClicks,after_clicks:n.afterClicks,click_delta:n.clickDelta,before_impressions:n.beforeImpressions,after_impressions:n.afterImpressions,impression_delta:n.impressionDelta,before_position:n.beforePosition,after_position:n.afterPosition,position_delta:n.positionDelta}))}function si(e,t){return e.output.segments[t].unmatchedSegments.map((n,r)=>({rank:r+1,dimension:t,data_status:e.output.segments[t].dataStatus,key:n.key,retained_in:n.retainedIn,clicks:n.clicks,impressions:n.impressions,position:n.position,reason:n.reason}))}function ci(e){return[{filename:`postmortem-summary.csv`,headers:[...w.summary],rows:[{workflow:e.workflow,site:e.site,generated_at:e.generatedAt,summary:e.summary,attribution:e.output.update.attribution,confidence:e.output.update.confidence,classification:e.output.update.classification,updates_matched:e.output.update.overlappingUpdates.length,known_confounders:e.output.update.confounders.length,page_segment_status:e.output.segments.page.dataStatus,page_segment_eligible_rows:e.output.segments.page.coverage.eligibleRows,page_segment_returned_rows:e.output.segments.page.coverage.returnedRows,page_segment_limited_rows:e.output.segments.page.coverage.limitedRows,page_segment_result_limit:e.output.segments.page.coverage.resultLimit,page_segment_source_row_limit:e.output.segments.page.coverage.sourceRowLimit,page_segment_source_possibly_truncated:e.output.segments.page.coverage.sourcePossiblyTruncated,page_segment_warnings:e.output.segments.page.warnings.join(`; `),query_segment_status:e.output.segments.query.dataStatus,query_segment_eligible_rows:e.output.segments.query.coverage.eligibleRows,query_segment_returned_rows:e.output.segments.query.coverage.returnedRows,query_segment_limited_rows:e.output.segments.query.coverage.limitedRows,query_segment_result_limit:e.output.segments.query.coverage.resultLimit,query_segment_source_row_limit:e.output.segments.query.coverage.sourceRowLimit,query_segment_source_possibly_truncated:e.output.segments.query.coverage.sourcePossiblyTruncated,query_segment_warnings:e.output.segments.query.warnings.join(`; `),device_segment_status:e.output.segments.device.dataStatus,device_segment_eligible_rows:e.output.segments.device.coverage.eligibleRows,device_segment_returned_rows:e.output.segments.device.coverage.returnedRows,device_segment_limited_rows:e.output.segments.device.coverage.limitedRows,device_segment_result_limit:e.output.segments.device.coverage.resultLimit,device_segment_source_row_limit:e.output.segments.device.coverage.sourceRowLimit,device_segment_source_possibly_truncated:e.output.segments.device.coverage.sourcePossiblyTruncated,device_segment_warnings:e.output.segments.device.warnings.join(`; `),country_segment_status:e.output.segments.country.dataStatus,country_segment_eligible_rows:e.output.segments.country.coverage.eligibleRows,country_segment_returned_rows:e.output.segments.country.coverage.returnedRows,country_segment_limited_rows:e.output.segments.country.coverage.limitedRows,country_segment_result_limit:e.output.segments.country.coverage.resultLimit,country_segment_source_row_limit:e.output.segments.country.coverage.sourceRowLimit,country_segment_source_possibly_truncated:e.output.segments.country.coverage.sourcePossiblyTruncated,country_segment_warnings:e.output.segments.country.warnings.join(`; `)}]},{filename:`workflow-steps.csv`,headers:[...w.steps],rows:e.steps.map((e,t)=>({rank:t+1,tool:e.tool,status:e.status,summary:e.summary}))},{filename:`workflow-actions.csv`,headers:[...w.actions],rows:e.actions.map((e,t)=>({rank:t+1,title:e.title,confidence:e.confidence,action:e.action}))},{filename:`postmortem-findings.csv`,headers:[...w.findings],rows:e.output.insights.map(e=>({dimension:e.dimension,data_status:e.dataStatus,eligible_rows:e.coverage.eligibleRows,returned_rows:e.coverage.returnedRows,limited_rows:e.coverage.limitedRows,result_limit:e.coverage.resultLimit,unmatched_rows:e.unmatchedRows,summary:e.summary,winner_key:e.winner?.key,winner_click_delta:e.winner?.clickDelta,winner_impression_delta:e.winner?.impressionDelta,winner_position_delta:e.winner?.positionDelta,loser_key:e.loser?.key,loser_click_delta:e.loser?.clickDelta,loser_impression_delta:e.loser?.impressionDelta,loser_position_delta:e.loser?.positionDelta}))},{filename:`postmortem-template-movement.csv`,headers:[...w.templates],rows:e.output.templateMovement.map((e,t)=>({rank:t+1,direction:e.direction,template:e.signature,confidence:e.confidence,url_count:e.urlCount,click_delta:e.clickDelta,impression_delta:e.impressionDelta,movement_share:e.movementShare,movement_share_scope:e.movementShareScope,confidence_scope:e.confidenceScope,eligible_rows:e.segmentCoverage.eligibleRows,returned_rows:e.segmentCoverage.returnedRows,limited_rows:e.segmentCoverage.limitedRows,result_limit:e.segmentCoverage.resultLimit,source_possibly_truncated:e.segmentCoverage.sourcePossiblyTruncated,common_terms:e.commonTerms.join(`; `),sample_urls:e.sampleUrls.join(`; `),summary:e.summary}))},{filename:`postmortem-update-evidence.csv`,headers:[...w.evidence],rows:e.output.update.evidence.map((e,t)=>({rank:t+1,evidence:e}))},{filename:`postmortem-confounders.csv`,headers:[...w.confounders],rows:e.output.update.confounders.map((e,t)=>({rank:t+1,source:e.source,title:e.title,date:e.date,scope:e.scope,target:e.target,description:e.description}))},...[`page`,`query`,`device`,`country`].map(t=>({filename:`postmortem-segment-${t}.csv`,headers:[...w.segment],rows:oi(e,t)})),...[`page`,`query`,`device`,`country`].map(t=>({filename:`postmortem-segment-${t}-unmatched.csv`,headers:[...w.unmatchedSegment],rows:si(e,t)}))]}function li(e){return y(e)?Sr(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.log`)).map(t=>{let n=v(e,t.name),r=Er(n);return{path:n,size:r.size,modifiedAt:r.mtimeMs}}):[]}function ui(e,t){let n=_(e),r=dr(e,`.log`),i=0;for(;;){let e=v(n,`${r}.${t}${i?`-${i}`:``}.log`);if(!y(e))return e;i+=1}}function di(e={}){let t=e.directory??gt().logDir,n=e.now??Date.now(),r=e.maxFileBytes??8388608,i=e.maxTotalBytes??67108864,a=e.maxAgeMs??12096e5;br(t,{recursive:!0,mode:448});let o=0,s=0;for(let e of li(t))e.size<=r||(wr(e.path,ui(e.path,n)),o+=1);for(let e of li(t))e.modifiedAt>=n-a||(Tr(e.path,{force:!0}),s+=1);let c=li(t).sort((e,t)=>e.modifiedAt-t.modifiedAt||(e.path<t.path?-1:+(e.path>t.path))),l=c.reduce((e,t)=>e+t.size,0);for(let e of c){if(l<=i)break;Tr(e.path,{force:!0}),l-=e.size,s+=1}return{rotated:o,removed:s,sizeBytes:l}}function fi(e){let t=e-Date.now();if(t<=0)return`expired`;let n=Math.round(t/6e4);if(n<60)return`in ${n}m`;let r=Math.floor(n/60),i=n%60;return i?`in ${r}h ${i}m`:`in ${r}h`}function pi(e,t){return{type:`boolean`,default:!0,description:e,negativeDescription:t}}function T(e){return typeof e==`string`?e:void 0}function E(e){return typeof e==`boolean`?e:void 0}function mi(e){let t=T(e.rendering);if(t!==void 0&&t!==`auto`&&t!==`on`&&t!==`off`)throw new d(`INVALID_INPUT`,`--rendering must be auto, on, or off.`);if(E(e.js)===!0&&t&&t!==`on`)throw new d(`INVALID_INPUT`,`Use either --js or --rendering on, not both with different modes.`);return t??(E(e.js)?`on`:`auto`)}function D(e,t){let n=E(e[t]);if(n===!1)return!0;if(n===!0)return!1;let r=E(e[hi(t)]);if(r===!1)return!0;if(r===!0)return!1;if(E(e[`no-${t}`])===!0||E(e[`no${gi(t)}`])===!0)return!0}function hi(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function gi(e){let t=hi(e);return t?`${t[0]?.toUpperCase()}${t.slice(1)}`:``}function O(e){if(typeof e==`number`)return e;if(typeof e!=`string`||!e.trim())return;let t=Number(e);return Number.isFinite(t)?t:void 0}function k(e,t){if(e===void 0||e===``)return;let n=O(e);if(n===void 0)throw new d(`INVALID_INPUT`,`${t} must be a number.`);return n}function A(e){if(typeof e!=`string`)return;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t.length?t:void 0}function _i(e){return A(e)??[]}function vi(e){let t={concurrency:O(e[`fetch-concurrency`]),intervalCap:O(e[`fetch-interval-cap`]),intervalMs:O(e[`fetch-interval-ms`])};return Object.values(t).some(e=>e!==void 0)?t:void 0}function j(e){return e.json===!0}async function yi(e,t){let n=T(e),r=T(t);if(n&&r)throw Error(`Use either --body or --body-file, not both.`);if(!n&&!r)return;let i=n??await b(r??``,`utf8`),a=JSON.parse(i);if(!a||typeof a!=`object`||Array.isArray(a))throw Error(`JSON body must be an object.`);return a}function M(e){if(e)return e;throw new d(`INVALID_INPUT`,"No site given. Pass --site with a domain, URL or sc-domain: property. Run `seo sites` to list your Search Console properties.")}async function bi(e,t={}){let n=M(e),r=(await u(t.refresh,t.account)).map(e=>e.siteUrl),i=nr(r,n);if(!i)throw new d(`PROPERTY_NOT_FOUND`,`This Google login has no Search Console property for ${n}. Run \`seo sites\` to list the properties it can read.`);return i}function xi(e){if(e)return e;throw new d(`INVALID_INPUT`,"No Google Analytics property given. Pass --property with the numeric property id. Run `seo analytics google properties` to list them.")}function Si(e){if(typeof e==`number`)return Number.isFinite(e)?Math.round(e):void 0;if(!e)return;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:void 0}function Ci(e={}){let t=e.env??process.env,n=Si(e.columns)??Si(e.streamColumns)??Si(t.COLUMNS)??80;return Math.min(200,Math.max(40,n))}function N(e={}){let t=e.env??process.env,n=e.isTTY??!!process.stdout.isTTY,r=e.color??!!(n&&t.NO_COLOR===void 0);return{columns:Ci({...e,env:t,streamColumns:e.streamColumns??process.stdout.columns}),colors:Zr.createColors(r),hasColor:r,isInteractive:n&&!t.CI}}function P(e){return Qr(Lr(e))}function wi(e,t){let n=[],r=``;for(let i of e)r&&P(`${r}${i}`)>t?(n.push(r),r=i):r+=i;return r&&n.push(r),n}function Ti(e,t){if(!e)return[``];let n=e.trim().split(/\s+/u),r=[],i=``;for(let e of n){let n=P(e)>t?wi(e,t):[e];for(let e of n)i?P(`${i} ${e}`)<=t?i+=` ${e}`:(r.push(i),i=e):i=e}return i&&r.push(i),r.length>0?r:[``]}function F(e,t){let n=Math.max(1,t);return e.replaceAll(`\r
3
+ import{$ as e,$n as t,$t as n,A as r,An as i,Ar as a,At as o,B as s,Bn as c,Bt as l,C as u,Cn as d,Cr as f,Ct as ee,D as p,Dn as te,Dr as m,Dt as h,E as ne,En as re,Er as ie,Et as ae,F as oe,Fn as se,Ft as ce,G as le,Gn as ue,Gt as de,H as fe,Hn as pe,Ht as me,I as he,In as ge,It as _e,J as ve,Jn as ye,Jt as be,K as xe,Kn as Se,Kt as Ce,L as we,Ln as Te,Lt as Ee,M as De,Mn as Oe,Mr as ke,Mt as Ae,N as je,Nn as Me,Nt as Ne,O as Pe,On as Fe,Or as g,P as Ie,Pn as Le,Pt as Re,Q as ze,Qn as Be,Qt as Ve,R as He,Rn as Ue,Rt as We,S as Ge,Sn as Ke,Sr as qe,St as Je,T as Ye,Tn as Xe,Tr as Ze,Tt as Qe,U as $e,Un as et,Ut as tt,V as nt,Vn as rt,Vt as it,W as at,Wn as ot,Wt as st,X as ct,Xn as lt,Xt as ut,Y as dt,Yn as ft,Yt as pt,Z as mt,Zn as ht,Zt as gt,_ as _t,_n as vt,_r as yt,_t as bt,a as xt,an as St,ar as Ct,at as wt,b as Tt,bn as Et,br as Dt,bt as Ot,c as kt,cn as At,cr as jt,ct as Mt,d as Nt,dn as Pt,dr as Ft,dt as It,en as Lt,er as Rt,et as zt,f as Bt,fn as Vt,fr as Ht,ft as Ut,g as Wt,gn as Gt,gr as Kt,gt as qt,h as Jt,hn as Yt,hr as Xt,ht as Zt,i as Qt,in as $t,ir as en,it as tn,j as nn,jn as rn,jr as an,jt as on,k as sn,kn as cn,kr as ln,kt as un,l as dn,ln as fn,lr as pn,lt as mn,m as hn,mn as gn,mr as _n,mt as vn,nn as yn,nr as bn,nt as xn,o as Sn,on as Cn,or as wn,ot as Tn,p as En,pn as Dn,pr as On,pt as kn,q as An,qn as jn,qt as Mn,rn as Nn,rr as Pn,rt as Fn,sn as In,sr as Ln,st as Rn,t as zn,tn as Bn,tr as Vn,tt as Hn,u as Un,un as Wn,ur as Gn,ut as Kn,v as qn,vn as Jn,vr as Yn,vt as Xn,w as Zn,wn as Qn,wr as $n,wt as er,x as tr,xn as nr,xr as rr,xt as ir,y as ar,yn as or,yr as sr,yt as cr,z as lr,zn as ur,zt as dr}from"./dist-DiyyBCYL.js";import{randomBytes as fr}from"node:crypto";import{arch as pr,homedir as mr,platform as hr}from"node:os";import{basename as gr,dirname as _r,join as _,posix as vr,relative as yr,resolve as br,sep as xr,win32 as Sr}from"node:path";import{constants as Cr,copyFileSync as wr,createWriteStream as Tr,existsSync as v,mkdirSync as Er,readFileSync as Dr,readdirSync as Or,realpathSync as kr,renameSync as Ar,rmSync as jr,statSync as Mr,writeFileSync as Nr}from"node:fs";import{fileURLToPath as Pr}from"node:url";import{cp as Fr,mkdir as Ir,open as Lr,readFile as y,readdir as Rr,rename as zr,stat as Br,writeFile as Vr}from"node:fs/promises";import{isDeepStrictEqual as Hr,stripVTControlCharacters as Ur}from"node:util";import{spawn as Wr,spawnSync as Gr}from"node:child_process";import{defineCommand as b,runCommand as Kr,runMain as qr}from"citty";import{cancel as Jr,confirm as Yr,intro as Xr,isCancel as Zr,log as Qr,multiselect as $r,note as x,outro as S,password as ei,select as ti,text as ni}from"@clack/prompts";import ri from"picocolors";import ii from"string-width";import ai from"cli-table3";import{finished as oi}from"node:stream/promises";import{applyEdits as si,modify as ci,parse as li,printParseErrorCode as ui}from"jsonc-parser";import di from"update-notifier";const C={summary:/* @__PURE__ */ `workflow.site.generated_at.summary.attribution.confidence.classification.updates_matched.known_confounders.page_segment_status.page_segment_eligible_rows.page_segment_returned_rows.page_segment_limited_rows.page_segment_result_limit.page_segment_source_row_limit.page_segment_source_possibly_truncated.page_segment_warnings.query_segment_status.query_segment_eligible_rows.query_segment_returned_rows.query_segment_limited_rows.query_segment_result_limit.query_segment_source_row_limit.query_segment_source_possibly_truncated.query_segment_warnings.device_segment_status.device_segment_eligible_rows.device_segment_returned_rows.device_segment_limited_rows.device_segment_result_limit.device_segment_source_row_limit.device_segment_source_possibly_truncated.device_segment_warnings.country_segment_status.country_segment_eligible_rows.country_segment_returned_rows.country_segment_limited_rows.country_segment_result_limit.country_segment_source_row_limit.country_segment_source_possibly_truncated.country_segment_warnings`.split(`.`),steps:[`rank`,`tool`,`status`,`summary`],actions:[`rank`,`title`,`confidence`,`action`],findings:[`dimension`,`data_status`,`eligible_rows`,`returned_rows`,`limited_rows`,`result_limit`,`unmatched_rows`,`summary`,`winner_key`,`winner_click_delta`,`winner_impression_delta`,`winner_position_delta`,`loser_key`,`loser_click_delta`,`loser_impression_delta`,`loser_position_delta`],templates:[`rank`,`direction`,`template`,`confidence`,`url_count`,`click_delta`,`impression_delta`,`movement_share`,`movement_share_scope`,`confidence_scope`,`eligible_rows`,`returned_rows`,`limited_rows`,`result_limit`,`source_possibly_truncated`,`common_terms`,`sample_urls`,`summary`],evidence:[`rank`,`evidence`],confounders:[`rank`,`source`,`title`,`date`,`scope`,`target`,`description`],segment:[`rank`,`dimension`,`data_status`,`evidence_scope`,`key`,`before_clicks`,`after_clicks`,`click_delta`,`before_impressions`,`after_impressions`,`impression_delta`,`before_position`,`after_position`,`position_delta`],unmatchedSegment:[`rank`,`dimension`,`data_status`,`key`,`retained_in`,`clicks`,`impressions`,`position`,`reason`]};function fi(e,t){return[...e.output.segments[t].winners,...e.output.segments[t].losers].map((n,r)=>({rank:r+1,dimension:t,data_status:e.output.segments[t].dataStatus,evidence_scope:n.evidenceScope,key:n.key,before_clicks:n.beforeClicks,after_clicks:n.afterClicks,click_delta:n.clickDelta,before_impressions:n.beforeImpressions,after_impressions:n.afterImpressions,impression_delta:n.impressionDelta,before_position:n.beforePosition,after_position:n.afterPosition,position_delta:n.positionDelta}))}function pi(e,t){return e.output.segments[t].unmatchedSegments.map((n,r)=>({rank:r+1,dimension:t,data_status:e.output.segments[t].dataStatus,key:n.key,retained_in:n.retainedIn,clicks:n.clicks,impressions:n.impressions,position:n.position,reason:n.reason}))}function mi(e){return[{filename:`postmortem-summary.csv`,headers:[...C.summary],rows:[{workflow:e.workflow,site:e.site,generated_at:e.generatedAt,summary:e.summary,attribution:e.output.update.attribution,confidence:e.output.update.confidence,classification:e.output.update.classification,updates_matched:e.output.update.overlappingUpdates.length,known_confounders:e.output.update.confounders.length,page_segment_status:e.output.segments.page.dataStatus,page_segment_eligible_rows:e.output.segments.page.coverage.eligibleRows,page_segment_returned_rows:e.output.segments.page.coverage.returnedRows,page_segment_limited_rows:e.output.segments.page.coverage.limitedRows,page_segment_result_limit:e.output.segments.page.coverage.resultLimit,page_segment_source_row_limit:e.output.segments.page.coverage.sourceRowLimit,page_segment_source_possibly_truncated:e.output.segments.page.coverage.sourcePossiblyTruncated,page_segment_warnings:e.output.segments.page.warnings.join(`; `),query_segment_status:e.output.segments.query.dataStatus,query_segment_eligible_rows:e.output.segments.query.coverage.eligibleRows,query_segment_returned_rows:e.output.segments.query.coverage.returnedRows,query_segment_limited_rows:e.output.segments.query.coverage.limitedRows,query_segment_result_limit:e.output.segments.query.coverage.resultLimit,query_segment_source_row_limit:e.output.segments.query.coverage.sourceRowLimit,query_segment_source_possibly_truncated:e.output.segments.query.coverage.sourcePossiblyTruncated,query_segment_warnings:e.output.segments.query.warnings.join(`; `),device_segment_status:e.output.segments.device.dataStatus,device_segment_eligible_rows:e.output.segments.device.coverage.eligibleRows,device_segment_returned_rows:e.output.segments.device.coverage.returnedRows,device_segment_limited_rows:e.output.segments.device.coverage.limitedRows,device_segment_result_limit:e.output.segments.device.coverage.resultLimit,device_segment_source_row_limit:e.output.segments.device.coverage.sourceRowLimit,device_segment_source_possibly_truncated:e.output.segments.device.coverage.sourcePossiblyTruncated,device_segment_warnings:e.output.segments.device.warnings.join(`; `),country_segment_status:e.output.segments.country.dataStatus,country_segment_eligible_rows:e.output.segments.country.coverage.eligibleRows,country_segment_returned_rows:e.output.segments.country.coverage.returnedRows,country_segment_limited_rows:e.output.segments.country.coverage.limitedRows,country_segment_result_limit:e.output.segments.country.coverage.resultLimit,country_segment_source_row_limit:e.output.segments.country.coverage.sourceRowLimit,country_segment_source_possibly_truncated:e.output.segments.country.coverage.sourcePossiblyTruncated,country_segment_warnings:e.output.segments.country.warnings.join(`; `)}]},{filename:`workflow-steps.csv`,headers:[...C.steps],rows:e.steps.map((e,t)=>({rank:t+1,tool:e.tool,status:e.status,summary:e.summary}))},{filename:`workflow-actions.csv`,headers:[...C.actions],rows:e.actions.map((e,t)=>({rank:t+1,title:e.title,confidence:e.confidence,action:e.action}))},{filename:`postmortem-findings.csv`,headers:[...C.findings],rows:e.output.insights.map(e=>({dimension:e.dimension,data_status:e.dataStatus,eligible_rows:e.coverage.eligibleRows,returned_rows:e.coverage.returnedRows,limited_rows:e.coverage.limitedRows,result_limit:e.coverage.resultLimit,unmatched_rows:e.unmatchedRows,summary:e.summary,winner_key:e.winner?.key,winner_click_delta:e.winner?.clickDelta,winner_impression_delta:e.winner?.impressionDelta,winner_position_delta:e.winner?.positionDelta,loser_key:e.loser?.key,loser_click_delta:e.loser?.clickDelta,loser_impression_delta:e.loser?.impressionDelta,loser_position_delta:e.loser?.positionDelta}))},{filename:`postmortem-template-movement.csv`,headers:[...C.templates],rows:e.output.templateMovement.map((e,t)=>({rank:t+1,direction:e.direction,template:e.signature,confidence:e.confidence,url_count:e.urlCount,click_delta:e.clickDelta,impression_delta:e.impressionDelta,movement_share:e.movementShare,movement_share_scope:e.movementShareScope,confidence_scope:e.confidenceScope,eligible_rows:e.segmentCoverage.eligibleRows,returned_rows:e.segmentCoverage.returnedRows,limited_rows:e.segmentCoverage.limitedRows,result_limit:e.segmentCoverage.resultLimit,source_possibly_truncated:e.segmentCoverage.sourcePossiblyTruncated,common_terms:e.commonTerms.join(`; `),sample_urls:e.sampleUrls.join(`; `),summary:e.summary}))},{filename:`postmortem-update-evidence.csv`,headers:[...C.evidence],rows:e.output.update.evidence.map((e,t)=>({rank:t+1,evidence:e}))},{filename:`postmortem-confounders.csv`,headers:[...C.confounders],rows:e.output.update.confounders.map((e,t)=>({rank:t+1,source:e.source,title:e.title,date:e.date,scope:e.scope,target:e.target,description:e.description}))},...[`page`,`query`,`device`,`country`].map(t=>({filename:`postmortem-segment-${t}.csv`,headers:[...C.segment],rows:fi(e,t)})),...[`page`,`query`,`device`,`country`].map(t=>({filename:`postmortem-segment-${t}-unmatched.csv`,headers:[...C.unmatchedSegment],rows:pi(e,t)}))]}function hi(e){return v(e)?Or(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.log`)).map(t=>{let n=_(e,t.name),r=Mr(n);return{path:n,size:r.size,modifiedAt:r.mtimeMs}}):[]}function gi(e,t){let n=_r(e),r=gr(e,`.log`),i=0;for(;;){let e=_(n,`${r}.${t}${i?`-${i}`:``}.log`);if(!v(e))return e;i+=1}}function _i(e={}){let t=e.directory??qe().logDir,n=e.now??Date.now(),r=e.maxFileBytes??8388608,i=e.maxTotalBytes??67108864,a=e.maxAgeMs??12096e5;Er(t,{recursive:!0,mode:448});let o=0,s=0;for(let e of hi(t))e.size<=r||(Ar(e.path,gi(e.path,n)),o+=1);for(let e of hi(t))e.modifiedAt>=n-a||(jr(e.path,{force:!0}),s+=1);let c=hi(t).sort((e,t)=>e.modifiedAt-t.modifiedAt||(e.path<t.path?-1:+(e.path>t.path))),l=c.reduce((e,t)=>e+t.size,0);for(let e of c){if(l<=i)break;jr(e.path,{force:!0}),l-=e.size,s+=1}return{rotated:o,removed:s,sizeBytes:l}}function vi(e){let t=e-Date.now();if(t<=0)return`expired`;let n=Math.round(t/6e4);if(n<60)return`in ${n}m`;let r=Math.floor(n/60),i=n%60;return i?`in ${r}h ${i}m`:`in ${r}h`}function yi(e,t){return{type:`boolean`,default:!0,description:e,negativeDescription:t}}function w(e){return typeof e==`string`?e:void 0}function T(e){return typeof e==`boolean`?e:void 0}function bi(e){let t=w(e.rendering);if(t!==void 0&&t!==`auto`&&t!==`on`&&t!==`off`)throw new g(`INVALID_INPUT`,`--rendering must be auto, on, or off.`);if(T(e.js)===!0&&t&&t!==`on`)throw new g(`INVALID_INPUT`,`Use either --js or --rendering on, not both with different modes.`);return t??(T(e.js)?`on`:`auto`)}function E(e,t){let n=T(e[t]);if(n===!1)return!0;if(n===!0)return!1;let r=T(e[xi(t)]);if(r===!1)return!0;if(r===!0)return!1;if(T(e[`no-${t}`])===!0||T(e[`no${Si(t)}`])===!0)return!0}function xi(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function Si(e){let t=xi(e);return t?`${t[0]?.toUpperCase()}${t.slice(1)}`:``}function D(e){if(typeof e==`number`)return e;if(typeof e!=`string`||!e.trim())return;let t=Number(e);return Number.isFinite(t)?t:void 0}function O(e,t){if(e===void 0||e===``)return;let n=D(e);if(n===void 0)throw new g(`INVALID_INPUT`,`${t} must be a number.`);return n}function k(e){if(typeof e!=`string`)return;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t.length?t:void 0}function Ci(e){return k(e)??[]}function wi(e){let t={concurrency:D(e[`fetch-concurrency`]),intervalCap:D(e[`fetch-interval-cap`]),intervalMs:D(e[`fetch-interval-ms`])};return Object.values(t).some(e=>e!==void 0)?t:void 0}function A(e){return e.json===!0}async function Ti(e,t){let n=w(e),r=w(t);if(n&&r)throw Error(`Use either --body or --body-file, not both.`);if(!n&&!r)return;let i=n??await y(r??``,`utf8`),a=JSON.parse(i);if(!a||typeof a!=`object`||Array.isArray(a))throw Error(`JSON body must be an object.`);return a}function j(e){if(e)return e;throw new g(`INVALID_INPUT`,"No site given. Pass --site with a domain, URL or sc-domain: property. Run `seo sites` to list your Search Console properties.")}async function Ei(e,t={}){let n=j(e),r=(await Fe(t.refresh,t.account)).map(e=>e.siteUrl),i=$n(r,n);if(!i)throw new g(`PROPERTY_NOT_FOUND`,`This Google login has no Search Console property for ${n}. Run \`seo sites\` to list the properties it can read.`);return i}function Di(e){if(e)return e;throw new g(`INVALID_INPUT`,"No Google Analytics property given. Pass --property with the numeric property id. Run `seo analytics google properties` to list them.")}function Oi(e){if(typeof e==`number`)return Number.isFinite(e)?Math.round(e):void 0;if(!e)return;let t=Number.parseInt(e,10);return Number.isFinite(t)?t:void 0}function ki(e={}){let t=e.env??process.env,n=Oi(e.columns)??Oi(e.streamColumns)??Oi(t.COLUMNS)??80;return Math.min(200,Math.max(40,n))}function M(e={}){let t=e.env??process.env,n=e.isTTY??!!process.stdout.isTTY,r=e.color??!!(n&&t.NO_COLOR===void 0);return{columns:ki({...e,env:t,streamColumns:e.streamColumns??process.stdout.columns}),colors:ri.createColors(r),hasColor:r,isInteractive:n&&!t.CI}}function N(e){return ii(Ur(e))}function Ai(e,t){let n=[],r=``;for(let i of e)r&&N(`${r}${i}`)>t?(n.push(r),r=i):r+=i;return r&&n.push(r),n}function ji(e,t){if(!e)return[``];let n=e.trim().split(/\s+/u),r=[],i=``;for(let e of n){let n=N(e)>t?Ai(e,t):[e];for(let e of n)i?N(`${i} ${e}`)<=t?i+=` ${e}`:(r.push(i),i=e):i=e}return i&&r.push(i),r.length>0?r:[``]}function P(e,t){let n=Math.max(1,t);return e.replaceAll(`\r
4
4
  `,`
5
5
  `).split(`
6
- `).flatMap(e=>Ti(e,n))}function Ei(e,t){if(P(e)<=t)return e;let n=Math.max(1,t-P(`...`)),r=``;for(let t of e){if(P(`${r}${t}`)>n)break;r+=t}return`${r}...`}const Di={top:``,"top-mid":``,"top-left":``,"top-right":``,bottom:``,"bottom-mid":``,"bottom-left":``,"bottom-right":``,left:``,"left-mid":``,mid:``,"mid-mid":``,right:``,"right-mid":``,middle:``};function Oi(e){return e===void 0?``:String(e)}function ki(e,t){return e.map((e,n)=>{let r=t.map(e=>Oi(e[n]));return Math.min(42,Math.max(P(e),...r.map(P),4))})}function Ai(e,t,n){return e.length===0||e.length>4||!e.map((e,n)=>t.every(e=>/^-?(?:\d+(?:\.\d+)?|\d+(?:\.\d+)?%)$/u.test(Oi(e[n]).trim()))).some(Boolean)?!1:ki(e,t).reduce((e,t)=>e+t+2,0)<=n.columns}function ji(e,t,n){if(!/(?:status|state|assessment|data|allowed)/iu.test(e))return t;let r=t.trim().toLowerCase();return[`pass`,`passed`,`completed`,`allowed`,`yes`].includes(r)?n.colors.green(t):[`warn`,`warning`,`review`,`partial`].includes(r)?n.colors.yellow(t):[`fail`,`failed`,`blocked`,`no`].includes(r)?n.colors.red(t):[`unknown`,`unavailable`].includes(r)?n.colors.blue(t):t}function Mi(e,t,n){let r=ki(e,t).map(e=>e+2),i=new $r({chars:Di,colWidths:r,head:e.map(e=>n.colors.bold(e)),style:{border:[],head:[],"padding-left":0,"padding-right":2},wordWrap:!1});for(let a of t)i.push(e.map((e,t)=>F(ji(e,Oi(a[t]),n),Math.max(1,(r[t]??3)-2)).join(`
7
- `)));return i.toString()}function Ni(e,t,n,r){let i=r.columns-n-2;return i<24?[r.colors.dim(e),...F(t,r.columns-2).map(e=>` ${e}`)]:F(t,i).map((t,i)=>{let a=i===0?e.padEnd(n):``.padEnd(n);return`${r.colors.dim(a)}${` `.repeat(2)}${t}`})}function Pi(e,t,n,r={}){let i=Math.min(28,Math.max(...e.map(e=>P(e)),0)),a=r.rowNumbers??!1,o=String(t.length).length;return t.map((t,r)=>{let s=[];a&&s.push(n.colors.bold(String(r+1).padStart(o,`0`)));for(let[r,a]of e.entries())s.push(...Ni(a,ji(a,Oi(t[r]),n),i,n));return s.join(`
6
+ `).flatMap(e=>ji(e,n))}function Mi(e,t){if(N(e)<=t)return e;let n=Math.max(1,t-N(`...`)),r=``;for(let t of e){if(N(`${r}${t}`)>n)break;r+=t}return`${r}...`}const Ni={top:``,"top-mid":``,"top-left":``,"top-right":``,bottom:``,"bottom-mid":``,"bottom-left":``,"bottom-right":``,left:``,"left-mid":``,mid:``,"mid-mid":``,right:``,"right-mid":``,middle:``};function Pi(e){return e===void 0?``:String(e)}function Fi(e,t){return e.map((e,n)=>{let r=t.map(e=>Pi(e[n]));return Math.min(42,Math.max(N(e),...r.map(N),4))})}function Ii(e,t,n){return e.length===0||e.length>4||!e.map((e,n)=>t.every(e=>/^-?(?:\d+(?:\.\d+)?|\d+(?:\.\d+)?%)$/u.test(Pi(e[n]).trim()))).some(Boolean)?!1:Fi(e,t).reduce((e,t)=>e+t+2,0)<=n.columns}function Li(e,t,n){if(!/(?:status|state|assessment|data|allowed)/iu.test(e))return t;let r=t.trim().toLowerCase();return[`pass`,`passed`,`completed`,`allowed`,`yes`].includes(r)?n.colors.green(t):[`warn`,`warning`,`review`,`partial`].includes(r)?n.colors.yellow(t):[`fail`,`failed`,`blocked`,`no`].includes(r)?n.colors.red(t):[`unknown`,`unavailable`].includes(r)?n.colors.blue(t):t}function Ri(e,t,n){let r=Fi(e,t).map(e=>e+2),i=new ai({chars:Ni,colWidths:r,head:e.map(e=>n.colors.bold(e)),style:{border:[],head:[],"padding-left":0,"padding-right":2},wordWrap:!1});for(let a of t)i.push(e.map((e,t)=>P(Li(e,Pi(a[t]),n),Math.max(1,(r[t]??3)-2)).join(`
7
+ `)));return i.toString()}function zi(e,t,n,r){let i=r.columns-n-2;return i<24?[r.colors.dim(e),...P(t,r.columns-2).map(e=>` ${e}`)]:P(t,i).map((t,i)=>{let a=i===0?e.padEnd(n):``.padEnd(n);return`${r.colors.dim(a)}${` `.repeat(2)}${t}`})}function Bi(e,t,n,r={}){let i=Math.min(28,Math.max(...e.map(e=>N(e)),0)),a=r.rowNumbers??!1,o=String(t.length).length;return t.map((t,r)=>{let s=[];a&&s.push(n.colors.bold(String(r+1).padStart(o,`0`)));for(let[r,a]of e.entries())s.push(...zi(a,Li(a,Pi(t[r]),n),i,n));return s.join(`
8
8
  `)}).join(`
9
9
 
10
- `)}function Fi(e,t,n,r={}){return t.length===0?n.colors.dim(`No results.`):r.layout===`table`||r.layout!==`records`&&Ai(e,t,n)?Mi(e,t,n):Pi(e,t,n,r)}function Ii(e,t){if(e.length===0)return``;let n=Math.min(28,Math.max(...e.map(([e])=>P(e))));return e.flatMap(([e,r])=>{let i=Ni(e,r,n,t);return i.length>0&&(i[0]=(i[0]??``).replace(e,t.colors.bold(e))),i}).join(`
11
- `)}function Li(e,t){let n=[t.colors.bold(e.title)];return e.body&&n.push(...F(e.body,t.columns)),e.command&&n.push(t.colors.cyan(Ei(e.command,t.columns))),n.join(`
12
- `)}function Ri(e,t){return e===`pass`?t.colors.green:e===`warning`?t.colors.yellow:e===`fail`?t.colors.red:e===`unknown`?t.colors.blue:e===`info`?t.colors.cyan:t.colors.dim}function zi(e){return e===`warning`?`WARN`:e===`notApplicable`?`N/A`:e.toUpperCase()}function Bi(e,t,n){let r=` `.repeat(t);return F(e,Math.max(1,n-t)).map(e=>`${r}${e}`)}function Vi(e,t){let n=Ri(e.status,t)(`[${zi(e.status)}]`.padEnd(10)),r=Math.max(1,t.columns-10),i=F(e.title,r).map((e,r)=>`${r===0?n:` `.repeat(10)}${t.colors.bold(e)}`);i.push(...Bi(e.explanation,10,t.columns));for(let n of e.evidence??[]){let e=F(n,Math.max(1,t.columns-20));i.push(...e.map((e,n)=>`${` `.repeat(10)}${n===0?`${t.colors.dim(`Evidence`)} `:` `}${e}`))}if(e.fix){let n=F(e.fix,Math.max(1,t.columns-15));i.push(...n.map((e,n)=>`${` `.repeat(10)}${n===0?`${t.colors.cyan(t.colors.bold(`Fix`))} `:` `}${e}`))}return i.join(`
13
- `)}function Hi(e,t){return F(e.map(e=>{let n=String(e.value),r=e.status?Ri(e.status,t)(n):t.colors.bold(n);return`${e.label} ${r}`}).join(t.colors.dim(` · `)),t.columns).join(`
14
- `)}function Ui(e,t){let n=Ri(e.status,t),r=[t.colors.bold(e.title)];e.target&&r.push(t.colors.dim(e.target)),r.push(``),r.push(`${n(zi(e.status))} ${F(e.summary,Math.max(1,t.columns-6)).join(`
15
- `)}`),e.metrics?.length&&r.push(Hi(e.metrics,t));for(let n of e.sections.filter(e=>e.diagnostics.length>0))r.push(``,t.colors.bold(n.title)),r.push(n.diagnostics.map(e=>Vi(e,t)).join(`
10
+ `)}function Vi(e,t,n,r={}){return t.length===0?n.colors.dim(`No results.`):r.layout===`table`||r.layout!==`records`&&Ii(e,t,n)?Ri(e,t,n):Bi(e,t,n,r)}function Hi(e,t){if(e.length===0)return``;let n=Math.min(28,Math.max(...e.map(([e])=>N(e))));return e.flatMap(([e,r])=>{let i=zi(e,r,n,t);return i.length>0&&(i[0]=(i[0]??``).replace(e,t.colors.bold(e))),i}).join(`
11
+ `)}function Ui(e,t){let n=[t.colors.bold(e.title)];return e.body&&n.push(...P(e.body,t.columns)),e.command&&n.push(t.colors.cyan(Mi(e.command,t.columns))),n.join(`
12
+ `)}function Wi(e,t){return e===`pass`?t.colors.green:e===`warning`?t.colors.yellow:e===`fail`?t.colors.red:e===`unknown`?t.colors.blue:e===`info`?t.colors.cyan:t.colors.dim}function Gi(e){return e===`warning`?`WARN`:e===`notApplicable`?`N/A`:e.toUpperCase()}function Ki(e,t,n){let r=` `.repeat(t);return P(e,Math.max(1,n-t)).map(e=>`${r}${e}`)}function qi(e,t){let n=Wi(e.status,t)(`[${Gi(e.status)}]`.padEnd(10)),r=Math.max(1,t.columns-10),i=P(e.title,r).map((e,r)=>`${r===0?n:` `.repeat(10)}${t.colors.bold(e)}`);i.push(...Ki(e.explanation,10,t.columns));for(let n of e.evidence??[]){let e=P(n,Math.max(1,t.columns-20));i.push(...e.map((e,n)=>`${` `.repeat(10)}${n===0?`${t.colors.dim(`Evidence`)} `:` `}${e}`))}if(e.fix){let n=P(e.fix,Math.max(1,t.columns-15));i.push(...n.map((e,n)=>`${` `.repeat(10)}${n===0?`${t.colors.cyan(t.colors.bold(`Fix`))} `:` `}${e}`))}return i.join(`
13
+ `)}function Ji(e,t){return P(e.map(e=>{let n=String(e.value),r=e.status?Wi(e.status,t)(n):t.colors.bold(n);return`${e.label} ${r}`}).join(t.colors.dim(` · `)),t.columns).join(`
14
+ `)}function Yi(e,t){let n=Wi(e.status,t),r=[t.colors.bold(e.title)];e.target&&r.push(t.colors.dim(e.target)),r.push(``),r.push(`${n(Gi(e.status))} ${P(e.summary,Math.max(1,t.columns-6)).join(`
15
+ `)}`),e.metrics?.length&&r.push(Ji(e.metrics,t));for(let n of e.sections.filter(e=>e.diagnostics.length>0))r.push(``,t.colors.bold(n.title)),r.push(n.diagnostics.map(e=>qi(e,t)).join(`
16
16
 
17
- `));if(e.notes?.length){r.push(``,t.colors.bold(`Notes`));for(let n of e.notes){let e=F(n,Math.max(1,t.columns-2));r.push(...e.map((e,t)=>`${t===0?`- `:` `}${e}`))}}return r.join(`
18
- `)}function Wi(e,t,n=`${t}s`){return e===1?t:n}function Gi(e,t,n){let r=` `.repeat(t);return F(e,Math.max(1,n-t)).map(e=>`${r}${e}`)}function Ki(e,t,n){return[t.colors.bold(e),...n?F(n,t.columns):[]].join(`
19
- `)}function qi(e,t){let n={pass:t.colors.green,warn:t.colors.yellow,fail:t.colors.red};return e.map(e=>{let r=[`${n[e.status](e.status.toUpperCase().padEnd(4))} ${t.colors.bold(e.label)}`];if(r.push(...Gi(e.detail,6,t.columns)),e.fix){let n=F(e.fix,Math.max(1,t.columns-11));r.push(...n.map((e,n)=>`${` `.repeat(6)}${n===0?`${t.colors.bold(`Fix`)} `:` `}${e}`))}return r.join(`
17
+ `));if(e.notes?.length){r.push(``,t.colors.bold(`Notes`));for(let n of e.notes){let e=P(n,Math.max(1,t.columns-2));r.push(...e.map((e,t)=>`${t===0?`- `:` `}${e}`))}}return r.join(`
18
+ `)}function Xi(e,t,n=`${t}s`){return e===1?t:n}function Zi(e,t,n){let r=` `.repeat(t);return P(e,Math.max(1,n-t)).map(e=>`${r}${e}`)}function Qi(e,t,n){return[t.colors.bold(e),...n?P(n,t.columns):[]].join(`
19
+ `)}function $i(e,t){let n={pass:t.colors.green,warn:t.colors.yellow,fail:t.colors.red};return e.map(e=>{let r=[`${n[e.status](e.status.toUpperCase().padEnd(4))} ${t.colors.bold(e.label)}`];if(r.push(...Zi(e.detail,6,t.columns)),e.fix){let n=P(e.fix,Math.max(1,t.columns-11));r.push(...n.map((e,n)=>`${` `.repeat(6)}${n===0?`${t.colors.bold(`Fix`)} `:` `}${e}`))}return r.join(`
20
20
  `)}).join(`
21
21
 
22
- `)}function Ji(e){let t=e.filter(e=>e.status===`pass`).length,n=e.filter(e=>e.status===`warn`).length,r=e.filter(e=>e.status===`fail`).length;return`${t} ${Wi(t,`check`)} passed, ${n} ${Wi(n,`warning`)}, ${r} failed.`}function Yi(e,t,n){let r=n.columns-t-2-2;return r<24||P(e.id)>t?[...Gi(e.id,2,n.columns).map(e=>n.colors.cyan(e)),...Gi(e.name,4,n.columns)].join(`
23
- `):F(e.name,r).map((r,i)=>{let a=i===0?e.id.padEnd(t):``.padEnd(t);return` ${n.colors.cyan(a)}${` `.repeat(2)}${r}`}).join(`
24
- `)}function Xi(e){let t=e.replaceAll(`-`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Zi(e,t,n){let r=/* @__PURE__ */ new Map;for(let t of e){let e=r.get(t.category)??[];e.push(t),r.set(t.category,e)}let i=`${e.length} ${Wi(e.length,n.noun)} across ${r.size} ${Wi(r.size,`category`,`categories`)}.`,a=Math.min(30,Math.max(...e.map(e=>P(e.id)),0)),o=Object.keys(n.categoryLabels??{}).filter(e=>r.has(e)),s=[...r.keys()].filter(e=>!o.includes(e));return[i,...[...o,...s].map(e=>{let i=r.get(e)??[],o=n.categoryLabels?.[e]??Xi(e);return[t.colors.bold(`${o} (${i.length})`),...i.map(e=>Yi(e,a,t))].join(`
22
+ `)}function ea(e){let t=e.filter(e=>e.status===`pass`).length,n=e.filter(e=>e.status===`warn`).length,r=e.filter(e=>e.status===`fail`).length;return`${t} ${Xi(t,`check`)} passed, ${n} ${Xi(n,`warning`)}, ${r} failed.`}function ta(e,t,n){let r=n.columns-t-2-2;return r<24||N(e.id)>t?[...Zi(e.id,2,n.columns).map(e=>n.colors.cyan(e)),...Zi(e.name,4,n.columns)].join(`
23
+ `):P(e.name,r).map((r,i)=>{let a=i===0?e.id.padEnd(t):``.padEnd(t);return` ${n.colors.cyan(a)}${` `.repeat(2)}${r}`}).join(`
24
+ `)}function na(e){let t=e.replaceAll(`-`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function ra(e,t,n){let r=/* @__PURE__ */ new Map;for(let t of e){let e=r.get(t.category)??[];e.push(t),r.set(t.category,e)}let i=`${e.length} ${Xi(e.length,n.noun)} across ${r.size} ${Xi(r.size,`category`,`categories`)}.`,a=Math.min(30,Math.max(...e.map(e=>N(e.id)),0)),o=Object.keys(n.categoryLabels??{}).filter(e=>r.has(e)),s=[...r.keys()].filter(e=>!o.includes(e));return[i,...[...o,...s].map(e=>{let i=r.get(e)??[],o=n.categoryLabels?.[e]??na(e);return[t.colors.bold(`${o} (${i.length})`),...i.map(e=>ta(e,a,t))].join(`
25
25
  `)})].join(`
26
26
 
27
- `)}function Qi(e,t,n){return e.length===0?t.colors.dim(n.empty):e.map(e=>{let n=[t.colors.bold(e.title)];e.description&&n.push(...Gi(e.description,2,t.columns));let r=e.meta?.filter(Boolean).join(` · `);return r&&n.push(...Gi(r,2,t.columns).map(e=>t.colors.dim(e))),n.join(`
27
+ `)}function ia(e,t,n){return e.length===0?t.colors.dim(n.empty):e.map(e=>{let n=[t.colors.bold(e.title)];e.description&&n.push(...Zi(e.description,2,t.columns));let r=e.meta?.filter(Boolean).join(` · `);return r&&n.push(...Zi(r,2,t.columns).map(e=>t.colors.dim(e))),n.join(`
28
28
  `)}).join(`
29
29
 
30
- `)}function $i(e,t,n){let r=t.filter(e=>e.trim().length>0).flatMap(e=>F(e,n.columns));return[n.colors.bold(e),...r].join(`
31
- `)}function ea(e,t,n){let r=t.flatMap(e=>F(e,Math.max(1,n.columns-2)).map((e,t)=>`${t===0?`- `:` `}${e}`));return[n.colors.bold(e),...r].join(`
32
- `)}function ta(e,t){return e.length===0?t.colors.dim(`No parameters.`):Qi(e.map(e=>({title:e.name,description:e.description,meta:[e.type,e.required?`required`:`optional`]})),t,{empty:`No parameters.`})}function I(e={}){return!(e.json||!process.stdin.isTTY||!process.stdout.isTTY||process.env.CI)}function L(e){let t=e&&typeof e==`object`&&!Array.isArray(e)?on():void 0,n=t?{...e,updateNotice:t}:e;process.stdout.write(`${JSON.stringify(n,null,2)}\n`)}function R(e){let t=Ii(e,N());t&&process.stdout.write(`${t}\n`)}function z(e,t){process.stdout.write(`${Fi(e,t,N())}\n`)}function na(e){process.stdout.write(`${Li(e,N())}\n`)}function ra(e,t){process.stdout.write(`${Ki(e,N(),t)}\n`)}function ia(e){process.stdout.write(`${qi(e,N())}\n`)}function aa(e){process.stdout.write(`${Ui(e,N())}\n`)}function oa(e,t){process.stdout.write(`${Zi(e,N(),t)}\n`)}function sa(e,t){process.stdout.write(`${Qi(e,N(),t)}\n`)}function ca(e,...t){process.stdout.write(`${$i(e,t,N())}\n`)}function la(e,t){process.stdout.write(`${ea(e,t,N())}\n`)}function ua(e){process.stdout.write(`${ta(e,N())}\n`)}function da(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function B(e){return typeof e==`symbol`&&process.exit(1),e}function fa(e){if(!e)return;let t=Date.now();return e=>{let n=((Date.now()-t)/1e3).toFixed(1);process.stderr.write(`[seo ${n}s] ${e}\n`)}}const pa={site:`--site`,url:`--url`,section:`--section`,date:`--date`,pages:`--pages`,dimensions:`--dimensions`,detail:`--detail`,offset:`--offset`,max_urls:`--max-urls`,mark:`--mark`,issues:`--issues`,note:`--note`,end_date:`--end-date`},ma=e=>/^[\w:/.,<>@#?=&%+-]+$/.test(String(e))?String(e):`"${e}"`,ha=(e,t)=>[`seo ${e}`,...Object.entries(t??{}).filter(([,e])=>e!==void 0).map(([e,t])=>`${pa[e]??`--${e}`} ${ma(t??``)}`)].join(` `),ga={account:{type:`string`,description:`Saved Google account email.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},refresh:{type:`boolean`,default:!1,description:`Bypass the local cache and fetch fresh data.`}},_a={"start-date":{type:`string`,description:`Optional YYYY-MM-DD.`},"end-date":{type:`string`,description:`Optional YYYY-MM-DD.`}},va={detail:{type:`string`,description:`summary (default), rows for the next page, or full.`},offset:{type:`string`,description:`rows only: the first row.`}};function V(e){let t=T(e.detail)??`summary`;if(![`summary`,`rows`,`full`].includes(t))throw new d(`INVALID_INPUT`,`--detail is summary, rows or full.`);return t}function ya(e,t){return bi(t,{refresh:E(e.refresh),account:T(e.account)})}async function H(e,t){try{let n=await t({...we({call:ha,account:T(e.account),refresh:E(e.refresh)}),progress:fa(!j(e))});j(e)?L(n.data):process.stdout.write(`${n.text}\n`)}catch(e){throw f(e)}}const ba=x({meta:{name:`report`,description:"Start here. No --site: last week across your audited sites (weekly site audit, after `seo login`). --site: overview and every section. Add --section for one"},args:{site:{type:`string`,description:"Site, URL or Search Console property. Leave it out for the summary of every audited site (weekly site audit, after `seo login`)."},section:{type:`string`,description:`Optional, needs --site. One of ${[...It,xt,An].join(`, `)}. issues keeps a list of what was found for the site, on this machine. ${An} lays the latest Google ranking update (or the latest that started by --end-date) over the site.`},mark:{type:`string`,description:`With --site and --issues: ${bn.join(`, `)}. Records what the person decided; runs no checks.`},issues:{type:`string`,description:`With --mark: issue ids from --section issues, comma-separated.`},note:{type:`string`,description:`Optional, with --mark: why.`},..._a,...va,...ga},run:async({args:e})=>{let t=T(e.section),n=[...It,xt,An];if(t&&!n.includes(t))throw new d(`INVALID_INPUT`,`--section is one of ${n.join(`, `)}.`);let r=T(e.site),i=T(e.mark),a=T(e.issues);if(i||a){if(i&&!bn.includes(i))throw new d(`INVALID_INPUT`,`--mark is one of ${bn.join(`, `)}.`);let n=await ya(e,M(r));await H(e,r=>gn({site:n,section:t,mark:i,issues:a?.split(`,`),note:T(e.note)},r));return}if(!r&&!t&&ot()){await H(e,e=>ve(e));return}let o=t===`bing`?await ya(e,r).catch(()=>M(r)):await ya(e,r).catch(async n=>{if(t||!r)throw n;return await H(e,t=>Ln({site:M(r),startDate:T(e[`start-date`]),endDate:T(e[`end-date`])},t).catch(()=>{throw n})),null});o!==null&&await H(e,n=>gn({site:o,section:t,startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),detail:V(e),offset:O(e.offset)},n))}}),xa=x({meta:{name:`page`,description:`One URL: live page facts, Google index status and its queries`},args:{url:{type:`string`,description:`The page URL.`,required:!0},..._a,...va,...ga},run:async({args:e})=>{let t=T(e.url)??``;if(!/^https?:\/\/\S+$/.test(t))throw new d(`INVALID_INPUT`,`--url must be a full http(s) URL.`);let n=await ya(e,t);await H(e,r=>at({site:n,url:t,startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),detail:V(e),offset:O(e.offset)},r))}}),Sa=x({meta:{name:`compare`,description:`Equal periods before and after a date, with the pages and queries that moved`},args:{site:{type:`string`,description:`Site, URL or Search Console property.`},date:{type:`string`,description:`YYYY-MM-DD: the first day after the change.`,required:!0},pages:{type:`string`,description:`Optional URL text, such as /blog/.`},...ga},run:async({args:e})=>{let t=await ya(e,T(e.site));await H(e,n=>he({site:t,date:T(e.date)??``,pages:T(e.pages)},n))}}),Ca=x({meta:{name:`index`,description:`Google indexing reasons for known URLs, checked live, and pages that lost most of their clicks`},args:{site:{type:`string`,description:`Site, URL or Search Console property.`},"max-urls":{type:`string`,description:`How many URLs to ask Google about, 100 by default. Ask for more when you want a fuller picture; it stops at the URL Inspection quota left today.`},..._a,...va,...ga},run:async({args:e})=>{let t=await ya(e,T(e.site)),n=O(e[`max-urls`]);if(n!==void 0&&(!Number.isInteger(n)||n<1||n>2e3))throw new d(`INVALID_INPUT`,`--max-urls is a whole number from 1 to ${kt}.`);await H(e,r=>ct({site:t,startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),detail:V(e),offset:O(e.offset),maxUrls:n},r))}});function wa(e){if(e!==void 0){if(Wt.includes(e))return e;throw new d(`INVALID_INPUT`,`--query-preset is ${Wt.join(`, `)}.`)}}const Ta=x({meta:{name:`data`,description:`Raw Search Console or Bing rows beside the previous period, or Clicky landing pages`},args:{site:{type:`string`,description:`Site, URL or Search Console property.`},source:{type:`string`,description:`search_console (default), bing or clicky. Bing takes the first dimension, query or page. Clicky takes the site or its Clicky site ID.`},dimensions:{type:`string`,description:`Comma-separated: ${Jt.join(`, `)}. Default query.`},page:{type:`string`,description:`Optional: only rows for pages whose URL contains this.`},query:{type:`string`,description:`Optional: only rows for queries that contain this.`},"query-preset":{type:`string`,description:`Optional: questions, long_tail (8+ words) or comparisons queries only.`},"page-regex":{type:`string`,description:`Optional: only rows for pages whose URL matches this RE2 regular expression.`},"query-regex":{type:`string`,description:`Optional: only rows for queries that match this RE2 regular expression.`},"exclude-query-regex":{type:`string`,description:`Optional: leave out queries that match this RE2 regular expression, such as your brand.`},..._a,...va,...ga},run:async({args:e})=>{let t=A(e.dimensions)??[`query`],n=t.filter(e=>!Jt.includes(e));if(n.length)throw new d(`INVALID_INPUT`,`Unknown dimensions: ${n.join(`, `)}. Use ${Jt.join(`, `)}.`);let i=T(e.source)??`search_console`;if(![`search_console`,`bing`,`clicky`].includes(i))throw new d(`INVALID_INPUT`,`--source is search_console, bing or clicky.`);if(i===`clicky`){let t=M(T(e.site));await H(e,async()=>Vn({site:t,startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),detail:V(e),offset:O(e.offset)},await r(),{connect:"save it at https://seoskill.dev/account#keys and run `seo login`, or run `seo analytics clicky connect` to keep it on this machine only.",refresh:nn,call:e=>ha(`data`,{source:`clicky`,site:t,detail:`rows`,offset:e})}));return}if(i===`bing`){let n=M(T(e.site));await H(e,r=>Nt({site:n,dimension:t[0]===`page`?`page`:`query`,startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),detail:V(e),offset:O(e.offset)},r));return}let a=await ya(e,T(e.site)),o=_t({page:T(e.page),query:T(e.query),pageRegex:T(e[`page-regex`]),queryRegex:T(e[`query-regex`]),queryPreset:wa(T(e[`query-preset`])),excludeQueryRegex:T(e[`exclude-query-regex`])});await H(e,n=>Gn({site:a,dimensions:t,filters:o,startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),detail:V(e),offset:O(e.offset)},n))}}),Ea=x({meta:{name:`research`,description:`Keyword, SERP, competitor, backlink and AI answer data from your DataForSEO or Ahrefs key`},args:{action:{type:`positional`,required:!0,description:dt.join(`, `)},provider:{type:`string`,description:`${Ie.join(`, `)}, or for serp an installed provider package with live search results. Default: the saved key, DataForSEO when both are saved.`},scope:{type:`string`,description:`${Tt.join(`, `)}. Default: from the target. A domain is the whole site, a path ending in / is every URL under it (example.com/blog/), any other path is one page.`},keywords:{type:`string`,description:`Comma-separated keywords.`},tasks:{type:`string`,description:`ai_answers only: comma-separated tasks an earlier run returned as not ready.`},also:{type:`string`,description:`ai_answers only: the brand's other domains, comma-separated, such as claude.ai beside claude.com. A citation to any of them counts as citing the target.`},brand:{type:`string`,description:`ai_answers only: comma-separated brand names that count as a mention, such as Datadog for datadoghq.com. Default: each domain's name.`},target:{type:`string`,description:`Domain, subfolder ending in / or page URL.`},competitors:{type:`string`,description:`link_gap only: 2 to 5 comma-separated competitor domains.`},country:{type:`string`,description:`Two-letter country code. Default us.`},depth:{type:`string`,description:`serp only: results per keyword, 1 to 100. Default 20. Deeper costs more.`},device:{type:`string`,description:`serp only: desktop (default) or mobile. Google ranks pages differently on each. DataForSEO only.`},...va,account:ga.account,json:ga.json,refresh:{type:`boolean`,default:!1,description:`Ask the provider again instead of reading the result saved in the last day.`}},run:async({args:t})=>{let n=T(t.action);if(!dt.includes(n))throw new d(`INVALID_INPUT`,`The action is one of ${dt.join(`, `)}.`);let i=await r(),a=T(t.provider),o=T(t.scope);if(o&&!Tt.includes(o))throw new d(`INVALID_INPUT`,`--scope is one of ${Tt.join(`, `)}.`);let s=T(t.device);if(s&&!rr.includes(s))throw new d(`INVALID_INPUT`,`--device is one of ${rr.join(`, `)}.`);let c=A(t.keywords)??[],l=T(t.target),u=A(t.competitors)??[],f=T(t.country);if(n===`ai_answers`){if(a&&a!==`dataforseo`)throw new d(`INVALID_INPUT`,`ai_answers uses dataforseo.`);let e=A(t.tasks)??[],r=A(t.also),o=A(t.brand),s=c.length||e.length?l??``:await ya(t,l);await H(t,a=>pn({site:s,country:f??`us`,detail:V(t),offset:O(t.offset)??0,questions:c,tasks:e,also:r,brand:o,waitSeconds:240},i,a,(e,t)=>ha(`research`,{action:n,target:l,also:r?.join(`,`),brand:o?.join(`,`),tasks:t.join(`,`)||void 0,country:f,detail:`rows`,offset:e}).replace(`--action `,``)))}else await H(t,()=>e({provider:a,scope:o,depth:O(t.depth),device:s,action:n,keywords:c,target:l,competitors:u,country:f,detail:V(t),offset:O(t.offset)},i,{store:$t(E(t.refresh)),installedSerp:un,call:e=>ha(`research`,{action:n,provider:a,scope:o,depth:O(t.depth),device:s,keywords:c.join(`,`)||void 0,target:l,competitors:u.join(`,`)||void 0,country:f,detail:`rows`,offset:e}).replace(`--action `,``)}))}}),Da=x({meta:{name:`lint`,description:`Check copy for patterns common in AI-written text, weak copy and title and description length`},args:{paths:{type:`positional`,required:!1,description:"Files, folders or globs: .md, .mdx, .html, .astro or .txt. Up to 100 files. `seo lint rules` lists the rules instead (add --only ai for the AI-pattern rules)."},url:{type:`string`,description:`Instead of files: a live page. Checks its main content as Markdown (what seo page --detail full shows), with the blog preset unless you set one.`},only:{type:`string`,description:`Check only these categories, comma-separated: ${$n.join(`, `)}. ai is patterns common in AI-written text; copy is weak copy and house style such as dashes; seo is titles, descriptions and headings.`},preset:{type:`string`,description:`${Ye.join(`, `)}. Default blog for Markdown and text, landing for HTML and Astro. meta reads one title or description per line of a .txt file; start a line with "title:" or "description:" to say which.`},"meta-kind":{type:`string`,description:`With --preset meta: title or description, what a line with no "title:" or "description:" label is. Default: a line up to 70 characters is a title, a longer one a description.`},format:{type:`string`,description:`${Ge.join(`, `)}. Default: from each file name.`},"fail-on":{type:`string`,description:`error (default) or warning: exit with code 1 when a finding at that level or above is found. A file or page that could not be checked in full also exits with code 1.`},ignore:{type:`string`,description:`Rule ids or review lenses to skip, comma-separated.`},"ignore-phrase":{type:`string`,description:`A phrase to allow, such as a product name a rule keeps matching. Repeat it for more.`},json:ga.json},run:async({args:e})=>{let t=T(e.preset);if(t&&!Ye.includes(t))throw new d(`INVALID_INPUT`,`--preset is one of ${Ye.join(`, `)}.`);let n=T(e[`meta-kind`]);if(n&&!Yn.includes(n))throw new d(`INVALID_INPUT`,`--meta-kind is ${Yn.join(` or `)}.`);let r=T(e.format);if(r&&!Ge.includes(r))throw new d(`INVALID_INPUT`,`--format is one of ${Ge.join(`, `)}.`);let i=T(e[`fail-on`])??`error`;if(i!==`error`&&i!==`warning`)throw new d(`INVALID_INPUT`,`--fail-on is error or warning.`);let a=(e._??[]).filter(e=>typeof e==`string`),o=T(e.url),s=!o&&a.length===1&&a[0]===`rules`&&!y(`rules`);if(!s&&!!o==a.length>0)throw new d(`INVALID_INPUT`,`Give files, folders or globs to check, or --url with a live page, but not both.`);let c=A(e.only);if(c?.filter(e=>!$n.includes(e))?.length)throw new d(`INVALID_INPUT`,`--only takes ${$n.join(`, `)}, comma-separated.`);let l=[].concat(e[`ignore-phrase`]??[]).filter(e=>typeof e==`string`);try{if(s){let t=await Qt({rules:!0,only:c});j(e)?L(t.data):process.stdout.write(`${t.text}\n`);return}let{pageMarkdown:u}=we({call:ha}),d=await Qt({paths:o?void 0:a,url:o,preset:t,format:r,ignoreRules:A(e.ignore),ignorePhrases:l,only:c,metaKind:n},e=>Kn(e),u&&(e=>u(e,2e5)));j(e)?L(d.data):process.stdout.write(`${d.text}\n`);let{errors:f,warnings:p,skipped:ee,partial:m}=d.data;(f>0||i===`warning`&&p>0||ee>0||m>0)&&(process.exitCode=1)}catch(e){throw f(e)}}});function Oa(e){return e===`keychain`?`system keychain`:e===`file`?`private local file`:e===`environment`?Xt:e??`missing`}function ka(e){if(e&&Me(e))return e.trim();throw new d(`INVALID_INPUT`,`No Clicky site given. Pass --site-id with the numeric Clicky site ID.`)}async function Aa(e,t){return m({siteId:e,sitekey:t}).catch(e=>{throw new d(e instanceof ne&&e.code===`auth`?`AUTH_REQUIRED`:`PROVIDER_UNAVAILABLE`,e instanceof Error?e.message:String(e))})}const ja={type:`boolean`,default:!1,description:`Print machine-readable JSON.`},Ma={type:`string`,description:`Numeric Clicky site ID.`},Na=x({meta:{name:`connect`,description:`Check and save a Clicky site on this machine`},args:{"site-id":Ma,json:ja},run:async({args:e})=>{let t=j(e),n=I({json:t});n&&Wr(`Connect Clicky`);let r=ka(T(e[`site-id`])??(n?B(await Xr({message:`Clicky site ID`,validate:e=>Me(e??``)?void 0:`Enter the numeric site ID from Clicky`})):void 0)),i=process.env.SEO_CLICKY_SITEKEY?.trim()||(n?B(await Jr({message:`Clicky sitekey`,validate:e=>an(e??``)?void 0:`Enter the sitekey from Clicky (Preferences, Info)`})):void 0);if(!i)throw new d(`AUTH_REQUIRED`,`Run this command in a terminal or set ${Xt}.`);let a=await Aa(r,i.trim()),o=await Dt(r,i.trim()),s={siteId:r,domain:a,connected:!0,credentialSource:o};if(t){L(s);return}let c=`Clicky site ${r}${a?` (${a})`:``} saved in the ${Oa(o)}. Next: seo analytics clicky report --site ${r}`;n?C(c):process.stdout.write(`${c}\n`)}}),Pa=x({meta:{name:`status`,description:`Show a Clicky site saved on this machine`},args:{"site-id":Ma,check:{type:`boolean`,default:!1,description:`Check the saved sitekey with Clicky.`},json:ja},run:async({args:e})=>{let t=ka(T(e[`site-id`])),n=await jn(t),r=E(e.check);r&&n&&await Aa(t,n.siteKey);let i={siteId:t,connected:!!n,credentialSource:n?.source,liveCheck:r?n?`passed`:`unavailable`:`not-requested`};j(e)?L(i):R([[`Site ID`,t],[`Connected`,i.connected?`yes`:`no`],[`Credential`,Oa(i.credentialSource)],[`Live check`,i.liveCheck]])}}),Fa=x({meta:{name:`report`,description:`Clicky landing pages, traffic sources and search engines`},args:{site:{type:`string`,description:`The site, or its numeric Clicky site ID.`},..._a,...va,json:ja},run:async({args:e})=>{let t=M(T(e.site));await H(e,async()=>Vn({site:t,startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),detail:V(e),offset:O(e.offset)},await r(),{connect:"save it at https://seoskill.dev/account#keys and run `seo login`, or run `seo analytics clicky connect` to keep it on this machine only.",refresh:nn,call:e=>`seo analytics clicky report --site ${t} --detail rows --offset ${e}`}))}}),Ia=x({meta:{name:`disconnect`,description:`Remove a Clicky site saved on this machine`},args:{"site-id":Ma,json:ja},run:async({args:e})=>{let t=ka(T(e[`site-id`]));await yt(t);let n=!!process.env[Xt],r={siteId:t,savedCredentialRemoved:!0,environmentCredential:n?`active`:`missing`};j(e)?L(r):process.stdout.write(n?`Saved sitekey removed. ${Xt} is still active.\n`:`Clicky is disconnected for this site.
33
- `)}}),La=x({meta:{name:`clicky`,description:`Read Clicky, or save a Clicky site on this machine only`},subCommands:{connect:Na,status:Pa,report:Fa,disconnect:Ia}}),Ra=x({meta:{name:`properties`,description:`List Google Analytics accounts and properties`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},account:{type:`string`,description:`Saved Google account email.`}},run:async({args:e})=>{let t=await Oe(T(e.account)),n=t.flatMap(e=>e.propertySummaries.map(t=>({account:e.displayName??e.account,property:Te(t.property),displayName:t.displayName??t.property})));j(e)?L({accountSummaries:t,properties:n}):z([`Property`,`Name`,`Account`],n.map(e=>[e.property,e.displayName,e.account]))}}),za=x({meta:{name:`report`,description:`Google Analytics landing pages for visits from search`},args:{property:{type:`string`,description:"Numeric Google Analytics property ID. Run `seo analytics google properties` to list them."},..._a,...va,json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=xi(T(e.property));await H(e,async()=>wn({property:t,startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),detail:V(e),offset:O(e.offset)},await Bt(await te(),t,pe.signIn),{signIn:pe.signIn,call:e=>`seo analytics google report --property ${t} --detail rows --offset ${e}`}))}}),Ba=x({meta:{name:`google`,description:`Read Google Analytics properties and reports`},subCommands:{properties:Ra,report:za}}),Va=x({meta:{name:`analytics`,description:`Read analytics data from connected providers`},subCommands:{clicky:La,google:Ba}});function Ha(){return`Your browser will open. Choose your Google account and select all permission boxes for read-only access. Keep this terminal open and finish the browser steps within five minutes.`}async function Ua(){return S(Ha(),`Google sign-in`),Se()}function Wa(e){return e?e===`environment-json`?`SEO_GOOGLE_SERVICE_ACCOUNT_JSON`:e===`environment-file`?`SEO_GOOGLE_SERVICE_ACCOUNT_FILE`:`GOOGLE_APPLICATION_CREDENTIALS`:`invalid or conflicting configuration`}function Ga(e){return e.active===`keychain`?`system keychain`:e.configured===`keychain`?`private file fallback`:`private file`}function Ka(e){return e===`shared`?`SEO Skill app`:`Local OAuth config`}function qa(e){let t=[[`Account`,e.accountEmail]],n=new Set(e.scope.split(/\s+/u).filter(Boolean));return n.has(`https://www.googleapis.com/auth/webmasters.readonly`)?t.push([`Search Console`,`Read only`]):t.push([`Search Console`,`Not granted`]),n.has(`https://www.googleapis.com/auth/analytics.readonly`)?t.push([`Google Analytics`,`Read only`]):t.push([`Google Analytics`,`Not granted`]),t.push([`OAuth app`,Ka(e.clientSource)],[`Expires`,fi(e.expiresAt)]),t}const Ja=x({meta:{name:`auth`,description:`Authentication commands`},subCommands:{login:x({meta:{name:`login`,description:`Run Google OAuth flow`},run:async()=>{if((await Be()).activeMode===`service-account`)throw new d(`AUTH_CONFIG_REQUIRED`,`A service account is active from the environment. Unset its credential variable before running browser OAuth.`);let e=await Ua();R(qa({accountEmail:e.account_email,clientSource:e.client_source,expiresAt:e.expires_at,scope:e.scope}))}}),logout:x({meta:{name:`logout`,description:`Delete a local Google login`},args:{account:{type:`string`,description:`Delete the login for this Google account.`},all:{type:`boolean`,default:!1,description:`Delete every saved Google login.`}},run:async({args:e})=>{let t=await Be(),n=T(e.account);if(n&&e.all)throw new d(`INVALID_INPUT`,`Use either --account or --all, not both.`);let r=e.all?void 0:n??t.accounts.find(e=>e.active)?.accountEmail;await s(r),t.activeMode===`service-account`?process.stdout.write(`${e.all?`Deleted all local Google logins.`:r?`Deleted the local login for ${r}.`:`No local Google login was found.`} Service account credentials remain available through the environment.\n`):process.stdout.write(`${e.all?`Deleted all local Google logins.`:r?`Deleted the local login for ${r}.`:`No local Google login was found.`}\nRevoke at https://myaccount.google.com/permissions if you also want Google to forget the grant.\n`)}}),whoami:x({meta:{name:`whoami`,description:`Show the signed-in Google account`},args:{account:{type:`string`,description:`Show this saved Google account.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await Be();if(t.activeMode===`service-account`){let n={mode:`service-account`,account:t.identity??null,source:Wa(t.serviceAccount.source)};if(j(e)){L(n);return}R([[`Account type`,`Service account`],[`Account`,t.identity??`Invalid configuration`],[`Credentials`,n.source],[`Access`,`Search Console and Google Analytics, read only`]]);return}let n=T(e.account),r=n?await rt(n):t.tokens;if(n&&!r)throw new d(`AUTH_REQUIRED`,`Google account ${n} is not connected.`);if(r)j(e)?L({mode:`oauth`,account:r.account_email,scopes:r.scope.split(/\s+/u).filter(Boolean),clientSource:r.client_source,expiresAt:r.expires_at}):R(qa({accountEmail:r.account_email,clientSource:r.client_source,expiresAt:r.expires_at,scope:r.scope}));else{if(j(e)){L({mode:`oauth`,account:null});return}process.stdout.write(`Not logged in.
34
- `)}}}),status:x({meta:{name:`status`,description:`Show local Google auth status`},args:{account:{type:`string`,description:`Show status for this saved Google account.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await Be(),n=T(e.account),r=n?await rt(n):t.tokens;if(n&&!r&&t.activeMode!==`service-account`)throw new d(`AUTH_REQUIRED`,`Google account ${n} is not connected.`);let i=t.activeMode===`oauth`?await ue():void 0;if(j(e)){L({authenticated:t.activeMode===`oauth`?!!r:t.serviceAccount.configured,mode:t.activeMode,identity:t.identity,account:t.activeMode===`oauth`?r?.account_email:void 0,scopes:t.activeMode===`oauth`?r?.scope:void 0,clientSource:t.activeMode===`oauth`?r?.client_source:void 0,expiresAt:t.activeMode===`oauth`?r?.expires_at:void 0,sharedConfigured:t.sharedConfigured,byoConfigured:t.byoConfigured,serviceAccount:{configured:t.serviceAccount.configured,identity:t.serviceAccount.identity,source:t.serviceAccount.source,error:t.serviceAccount.error},accounts:t.accounts,...i?{tokenStorage:i}:{}});return}if(t.activeMode===`service-account`){let e=[[`Mode`,`service account`],[`Identity`,t.identity??`unavailable`],[`Source`,Wa(t.serviceAccount.source)],[`Scopes`,`Search Console readonly, Google Analytics readonly`],[`Storage`,`credentials stay in the environment`]];t.serviceAccount.error&&e.push([`Status`,t.serviceAccount.error]),R(e);return}if(!r){let e=t.serviceAccount.error?t.serviceAccount.error:t.sharedConfigured?`Shared seo app available`:t.byoConfigured?`Local OAuth config available`:`No OAuth client configured`;process.stdout.write(`Not logged in. ${e}. Run \`seo auth login\` to connect Google.\n`);return}let a=i??await ue();R([[`Account`,r.account_email],[`Connected accounts`,String(t.accounts.length)],[`Scopes`,r.scope],[`Client`,Ka(r.client_source)],[`Expires`,fi(r.expires_at)],[`Tokens file`,gt().tokensFile],[`Token storage`,Ga(a)],...a.reason?[[`Storage note`,a.reason]]:[],[`OAuth mode`,t.sharedConfigured?`SEO Skill app available`:t.byoConfigured?`Local OAuth config available`:`missing`],[`Revoke at`,`https://myaccount.google.com/permissions`]])}}),storage:x({meta:{name:`storage`,description:`Show or change local OAuth token storage`},args:{keychain:{type:`boolean`,default:!1,description:`Store OAuth tokens in the system keychain when available.`},file:{type:`boolean`,default:!1,description:`Store OAuth tokens in the private local file.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{if(e.keychain&&e.file)throw new d(`INVALID_INPUT`,`Choose either --keychain or --file, not both.`);let t=e.keychain||e.file?await ye(e.keychain?`keychain`:`file`):await ue();j(e)?L(t):R([[`Configured storage`,t.configured],[`Active storage`,Ga(t)],...t.reason?[[`Note`,t.reason]]:[]])}}),refresh:x({meta:{name:`refresh`,description:`Refresh the Google OAuth token`},args:{account:{type:`string`,description:`Refresh this saved Google account.`}},run:async({args:e})=>{if((await Be()).activeMode===`service-account`){process.stdout.write(`Service accounts request short-lived Google tokens automatically. No local refresh token is stored.
35
- `);return}let t=await ar(T(e.account));process.stdout.write(`Refreshed. New expiry ${new Date(t.expires_at).toISOString()}.\n`)}}),accounts:x({meta:{name:`accounts`,description:`List saved Google accounts`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:({args:e})=>{let t=Ze();j(e)?L({accounts:t}):t.length===0?process.stdout.write(`No Google accounts are connected.
36
- `):R(t.map(e=>[e.active?`Active account`:`Account`,e.accountEmail]))}}),use:x({meta:{name:`use`,description:`Select the default Google account`},args:{account:{type:`positional`,required:!0,description:`Saved Google account email.`}},run:({args:e})=>{let t=T(e.account);if(!t)throw new d(`INVALID_INPUT`,`Google account is required.`);se(t),process.stdout.write(`Default Google account: ${t}\n`)}}),"setup-client":x({meta:{name:`setup-client`,description:`Save your own Google Desktop OAuth client`},args:{json:{type:`boolean`,default:!1,description:`Return a structured error instead of prompting.`}},run:async({args:e})=>{if(!I({json:j(e)}))throw new d(`INVALID_INPUT`,"`seo auth setup-client` needs an interactive terminal. Run it without --json, or set SEO_GOOGLE_CLIENT_ID and SEO_GOOGLE_CLIENT_SECRET.");Wr(`Local Google OAuth client`),S(`This is the advanced path.
30
+ `)}function aa(e,t,n){let r=t.filter(e=>e.trim().length>0).flatMap(e=>P(e,n.columns));return[n.colors.bold(e),...r].join(`
31
+ `)}function oa(e,t,n){let r=t.flatMap(e=>P(e,Math.max(1,n.columns-2)).map((e,t)=>`${t===0?`- `:` `}${e}`));return[n.colors.bold(e),...r].join(`
32
+ `)}function sa(e,t){return e.length===0?t.colors.dim(`No parameters.`):ia(e.map(e=>({title:e.name,description:e.description,meta:[e.type,e.required?`required`:`optional`]})),t,{empty:`No parameters.`})}function F(e={}){return!(e.json||!process.stdin.isTTY||!process.stdout.isTTY||process.env.CI)}function I(e){let t=e&&typeof e==`object`&&!Array.isArray(e)?dn():void 0,n=t?{...e,updateNotice:t}:e;process.stdout.write(`${JSON.stringify(n,null,2)}\n`)}function L(e){let t=Hi(e,M());t&&process.stdout.write(`${t}\n`)}function R(e,t){process.stdout.write(`${Vi(e,t,M())}\n`)}function ca(e){process.stdout.write(`${Ui(e,M())}\n`)}function la(e,t){process.stdout.write(`${Qi(e,M(),t)}\n`)}function ua(e){process.stdout.write(`${$i(e,M())}\n`)}function da(e){process.stdout.write(`${Yi(e,M())}\n`)}function fa(e,t){process.stdout.write(`${ra(e,M(),t)}\n`)}function pa(e,t){process.stdout.write(`${ia(e,M(),t)}\n`)}function ma(e,...t){process.stdout.write(`${aa(e,t,M())}\n`)}function ha(e,t){process.stdout.write(`${oa(e,t,M())}\n`)}function ga(e){process.stdout.write(`${sa(e,M())}\n`)}function _a(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function z(e){return typeof e==`symbol`&&process.exit(1),e}function va(e){if(!e)return;let t=Date.now();return e=>{let n=((Date.now()-t)/1e3).toFixed(1);process.stderr.write(`[seo ${n}s] ${e}\n`)}}const ya={site:`--site`,url:`--url`,section:`--section`,date:`--date`,pages:`--pages`,dimensions:`--dimensions`,detail:`--detail`,offset:`--offset`,max_urls:`--max-urls`,mark:`--mark`,issues:`--issues`,note:`--note`,end_date:`--end-date`},ba=e=>/^[\w:/.,<>@#?=&%+-]+$/.test(String(e))?String(e):`"${e}"`,xa=(e,t)=>[`seo ${e}`,...Object.entries(t??{}).filter(([,e])=>e!==void 0).map(([e,t])=>`${ya[e]??`--${e}`} ${ba(t??``)}`)].join(` `),Sa={account:{type:`string`,description:`Saved Google account email.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},refresh:{type:`boolean`,default:!1,description:`Bypass the local cache and fetch fresh data.`}},Ca={"start-date":{type:`string`,description:`Optional YYYY-MM-DD.`},"end-date":{type:`string`,description:`Optional YYYY-MM-DD.`}},B={detail:{type:`string`,description:`summary (default), rows for the next page, or full.`},offset:{type:`string`,description:`rows only: the first row.`}};function V(e){let t=w(e.detail)??`summary`;if(![`summary`,`rows`,`full`].includes(t))throw new g(`INVALID_INPUT`,`--detail is summary, rows or full.`);return t}function wa(e,t){return Ei(t,{refresh:T(e.refresh),account:w(e.account)})}async function H(e,t){try{let n=await t({...De({call:xa,account:w(e.account),refresh:T(e.refresh)}),progress:va(!A(e))});A(e)?I(n.data):process.stdout.write(`${n.text}\n`)}catch(e){throw p(e)}}const Ta=b({meta:{name:`report`,description:"Start here. No --site: last week across your audited sites (weekly site audit, after `seo login`). --site: overview and every section. Add --section for one"},args:{site:{type:`string`,description:"Site, URL or Search Console property. Leave it out for the summary of every audited site (weekly site audit, after `seo login`)."},section:{type:`string`,description:`Optional, needs --site. One of ${[...wt,Kn,Mt].join(`, `)}. issues keeps a list of what was found for the site, on this machine. ${Mt} lays the latest Google ranking update (or the latest that started by --end-date) over the site.`},mark:{type:`string`,description:`With --site and --issues: ${It.join(`, `)}. Records what the person decided; runs no checks.`},issues:{type:`string`,description:`With --mark: issue ids from --section issues, comma-separated.`},note:{type:`string`,description:`Optional, with --mark: why.`},...Ca,...B,...Sa},run:async({args:e})=>{let t=w(e.section),n=[...wt,Kn,Mt];if(t&&!n.includes(t))throw new g(`INVALID_INPUT`,`--section is one of ${n.join(`, `)}.`);let r=w(e.site),i=w(e.mark),a=w(e.issues);if(i||a){if(i&&!It.includes(i))throw new g(`INVALID_INPUT`,`--mark is one of ${It.join(`, `)}.`);let n=await wa(e,j(r));await H(e,r=>Rn({site:n,section:t,mark:i,issues:a?.split(`,`),note:w(e.note)},r));return}if(!r&&!t&&Vn()){await H(e,e=>ct(e));return}let o=t===`bing`?await wa(e,r).catch(()=>j(r)):await wa(e,r).catch(async n=>{if(t||!r)throw n;return await H(e,t=>Tn({site:j(r),startDate:w(e[`start-date`]),endDate:w(e[`end-date`])},t).catch(()=>{throw n})),null});o!==null&&await H(e,n=>Rn({site:o,section:t,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),detail:V(e),offset:D(e.offset)},n))}}),Ea=b({meta:{name:`page`,description:`One URL: live page facts, Google index status and its queries`},args:{url:{type:`string`,description:`The page URL.`,required:!0},...Ca,...B,...Sa},run:async({args:e})=>{let t=w(e.url)??``;if(!/^https?:\/\/\S+$/.test(t))throw new g(`INVALID_INPUT`,`--url must be a full http(s) URL.`);let n=await wa(e,t);await H(e,r=>zt({site:n,url:t,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),detail:V(e),offset:D(e.offset)},r))}}),Da="save it at https://seoskill.dev/account#simple-analytics and run `seo login`, or run `seo analytics simple-analytics connect` to keep it on this machine only.",Oa=b({meta:{name:`compare`,description:`Equal periods before and after a date, with the pages and queries that moved`},args:{site:{type:`string`,description:`Site, URL or Search Console property.`},date:{type:`string`,description:`YYYY-MM-DD: the first day after the change.`,required:!0},pages:{type:`string`,description:`Optional URL text, such as /blog/.`},...Sa},run:async({args:e})=>{let t=await wa(e,w(e.site));await H(e,async n=>ze({site:t,date:w(e.date)??``,pages:w(e.pages)},n,await r().catch(()=>void 0)))}}),ka=b({meta:{name:`index`,description:`Google indexing reasons for known URLs, checked live, and pages that lost most of their clicks`},args:{site:{type:`string`,description:`Site, URL or Search Console property.`},"max-urls":{type:`string`,description:`How many URLs to ask Google about, 100 by default. Ask for more when you want a fuller picture; it stops at the URL Inspection quota left today.`},...Ca,...B,...Sa},run:async({args:t})=>{let n=await wa(t,w(t.site)),r=D(t[`max-urls`]);if(r!==void 0&&(!Number.isInteger(r)||r<1||r>2e3))throw new g(`INVALID_INPUT`,`--max-urls is a whole number from 1 to ${kn}.`);await H(t,i=>e({site:n,startDate:w(t[`start-date`]),endDate:w(t[`end-date`]),detail:V(t),offset:D(t.offset),maxUrls:r},i))}}),Aa=b({meta:{name:`data`,description:`Raw Search Console or Bing rows beside the previous period, or Clicky or Simple Analytics landing pages`},args:{site:{type:`string`,description:`Site, URL or Search Console property.`},source:{type:`string`,description:`search_console (default), bing, clicky or simple_analytics. Bing takes the first dimension, query or page. Clicky takes the site or its Clicky site ID. Simple Analytics takes the site.`},dimensions:{type:`string`,description:`Comma-separated: ${Ot.join(`, `)}. Default query.`},page:{type:`string`,description:`Optional: only rows for pages whose URL contains this.`},query:{type:`string`,description:`Optional: only rows for queries that contain this.`},"page-regex":{type:`string`,description:`Optional: only rows for pages whose URL matches this RE2 regular expression.`},"query-regex":{type:`string`,description:`Optional: only rows for queries that match this RE2 regular expression.`},"exclude-query-regex":{type:`string`,description:`Optional: leave out queries that match this RE2 regular expression, such as your brand.`},...Ca,...B,...Sa},run:async({args:e})=>{let t=k(e.dimensions)??[`query`],n=t.filter(e=>!Ot.includes(e));if(n.length)throw new g(`INVALID_INPUT`,`Unknown dimensions: ${n.join(`, `)}. Use ${Ot.join(`, `)}.`);let i=w(e.source)??`search_console`;if(![`search_console`,`bing`,`clicky`,`simple_analytics`].includes(i))throw new g(`INVALID_INPUT`,`--source is search_console, bing, clicky or simple_analytics.`);if(i===`simple_analytics`){let t=j(w(e.site));await H(e,async()=>Hn({site:t,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),detail:V(e),offset:D(e.offset)},await r(),{connect:Da,call:e=>xa(`data`,{source:`simple_analytics`,site:t,detail:`rows`,offset:e})}));return}if(i===`clicky`){let t=j(w(e.site));await H(e,async()=>Zt({site:t,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),detail:V(e),offset:D(e.offset)},await r(),{connect:"save it at https://seoskill.dev/account#keys and run `seo login`, or run `seo analytics clicky connect` to keep it on this machine only.",refresh:sn,call:e=>xa(`data`,{source:`clicky`,site:t,detail:`rows`,offset:e})}));return}if(i===`bing`){let n=j(w(e.site));await H(e,r=>qt({site:n,dimension:t[0]===`page`?`page`:`query`,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),detail:V(e),offset:D(e.offset)},r));return}let a=await wa(e,w(e.site)),o=ir({page:w(e.page),query:w(e.query),pageRegex:w(e[`page-regex`]),queryRegex:w(e[`query-regex`]),excludeQueryRegex:w(e[`exclude-query-regex`])});await H(e,n=>Je({site:a,dimensions:t,filters:o,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),detail:V(e),offset:D(e.offset)},n))}}),ja=b({meta:{name:`research`,description:`Keyword, SERP, competitor, backlink and AI answer data from your DataForSEO or Ahrefs key`},args:{action:{type:`positional`,required:!0,description:xn.join(`, `)},provider:{type:`string`,description:`${Fn.join(`, `)}, or for serp an installed provider package with live search results. Default: the saved key, DataForSEO when both are saved.`},scope:{type:`string`,description:`${er.join(`, `)}. Default: from the target. A domain is the whole site, a path ending in / is every URL under it (example.com/blog/), any other path is one page.`},keywords:{type:`string`,description:`Comma-separated keywords.`},tasks:{type:`string`,description:`ai_answers only: comma-separated tasks an earlier run returned as not ready.`},also:{type:`string`,description:`ai_answers only: the brand's other domains, comma-separated, such as claude.ai beside claude.com. A citation to any of them counts as citing the target.`},brand:{type:`string`,description:`ai_answers only: comma-separated brand names that count as a mention, such as Datadog for datadoghq.com. Default: each domain's name.`},target:{type:`string`,description:`Domain, subfolder ending in / or page URL.`},competitors:{type:`string`,description:`link_gap only: 2 to 5 comma-separated competitor domains.`},country:{type:`string`,description:`Two-letter country code. Default us.`},depth:{type:`string`,description:`serp only: results per keyword, 1 to 100. Default 20. Deeper costs more.`},device:{type:`string`,description:`serp only: desktop (default) or mobile. Google ranks pages differently on each. DataForSEO only.`},...B,account:Sa.account,json:Sa.json,refresh:{type:`boolean`,default:!1,description:`Ask the provider again instead of reading the result saved in the last day.`}},run:async({args:e})=>{let t=w(e.action);if(!xn.includes(t))throw new g(`INVALID_INPUT`,`The action is one of ${xn.join(`, `)}.`);let n=await r(),i=w(e.provider),a=w(e.scope);if(a&&!er.includes(a))throw new g(`INVALID_INPUT`,`--scope is one of ${er.join(`, `)}.`);let o=w(e.device);if(o&&!ee.includes(o))throw new g(`INVALID_INPUT`,`--device is one of ${ee.join(`, `)}.`);let s=k(e.keywords)??[],c=w(e.target),l=k(e.competitors)??[],u=w(e.country);if(t===`ai_answers`){if(i&&i!==`dataforseo`)throw new g(`INVALID_INPUT`,`ai_answers uses dataforseo.`);let r=k(e.tasks)??[],a=k(e.also),o=k(e.brand),l=s.length||r.length?c??``:await wa(e,c);await H(e,i=>cr({site:l,country:u??`us`,detail:V(e),offset:D(e.offset)??0,questions:s,tasks:r,also:a,brand:o,waitSeconds:240},n,i,(e,n)=>xa(`research`,{action:t,target:c,also:a?.join(`,`),brand:o?.join(`,`),tasks:n.join(`,`)||void 0,country:u,detail:`rows`,offset:e}).replace(`--action `,``)))}else await H(e,()=>tn({provider:i,scope:a,depth:D(e.depth),device:o,action:t,keywords:s,target:c,competitors:l,country:u,detail:V(e),offset:D(e.offset)},n,{store:nn(T(e.refresh)),installedSerp:hn,call:n=>xa(`research`,{action:t,provider:i,scope:a,depth:D(e.depth),device:o,keywords:s.join(`,`)||void 0,target:c,competitors:l.join(`,`)||void 0,country:u,detail:`rows`,offset:n}).replace(`--action `,``)}))}}),Ma=b({meta:{name:`lint`,description:`Check copy for patterns common in AI-written text, weak copy and title and description length`},args:{paths:{type:`positional`,required:!1,description:"Files, folders or globs: .md, .mdx, .html, .astro or .txt. Up to 100 files. `seo lint rules` lists the rules instead (add --only ai for the AI-pattern rules)."},url:{type:`string`,description:`Instead of files: a live page. Checks its main content as Markdown (what seo page --detail full shows), with the blog preset unless you set one.`},only:{type:`string`,description:`Check only these categories, comma-separated: ${ae.join(`, `)}. ai is patterns common in AI-written text; copy is weak copy and house style such as dashes; seo is titles, descriptions and headings.`},preset:{type:`string`,description:`${o.join(`, `)}. Default blog for Markdown and text, landing for HTML and Astro. meta reads one title or description per line of a .txt file; start a line with "title:" or "description:" to say which.`},"meta-kind":{type:`string`,description:`With --preset meta: title or description, what a line with no "title:" or "description:" label is. Default: a line up to 70 characters is a title, a longer one a description.`},format:{type:`string`,description:`${h.join(`, `)}. Default: from each file name.`},"fail-on":{type:`string`,description:`error (default) or warning: exit with code 1 when a finding at that level or above is found. A file or page that could not be checked in full also exits with code 1.`},ignore:{type:`string`,description:`Rule ids or review lenses to skip, comma-separated.`},"ignore-phrase":{type:`string`,description:`A phrase to allow, such as a product name a rule keeps matching. Repeat it for more.`},json:Sa.json},run:async({args:e})=>{let t=w(e.preset);if(t&&!o.includes(t))throw new g(`INVALID_INPUT`,`--preset is one of ${o.join(`, `)}.`);let n=w(e[`meta-kind`]);if(n&&!un.includes(n))throw new g(`INVALID_INPUT`,`--meta-kind is ${un.join(` or `)}.`);let r=w(e.format);if(r&&!h.includes(r))throw new g(`INVALID_INPUT`,`--format is one of ${h.join(`, `)}.`);let i=w(e[`fail-on`])??`error`;if(i!==`error`&&i!==`warning`)throw new g(`INVALID_INPUT`,`--fail-on is error or warning.`);let a=(e._??[]).filter(e=>typeof e==`string`),s=w(e.url),c=!s&&a.length===1&&a[0]===`rules`&&!v(`rules`);if(!c&&!!s==a.length>0)throw new g(`INVALID_INPUT`,`Give files, folders or globs to check, or --url with a live page, but not both.`);let l=k(e.only);if(l?.filter(e=>!ae.includes(e))?.length)throw new g(`INVALID_INPUT`,`--only takes ${ae.join(`, `)}, comma-separated.`);let u=[].concat(e[`ignore-phrase`]??[]).filter(e=>typeof e==`string`);try{if(c){let t=await mn({rules:!0,only:l});A(e)?I(t.data):process.stdout.write(`${t.text}\n`);return}let{pageMarkdown:o}=De({call:xa}),d=await mn({paths:s?void 0:a,url:s,preset:t,format:r,ignoreRules:k(e.ignore),ignorePhrases:u,only:l,metaKind:n},e=>Zn(e),o&&(e=>o(e,2e5)));A(e)?I(d.data):process.stdout.write(`${d.text}\n`);let{errors:f,warnings:ee,skipped:p,partial:te}=d.data;(f>0||i===`warning`&&ee>0||p>0||te>0)&&(process.exitCode=1)}catch(e){throw p(e)}}});function Na(e){return e===`keychain`?`system keychain`:e===`file`?`private local file`:e===`environment`?fn:e??`missing`}function Pa(e){if(e&&Ne(e))return e.trim();throw new g(`INVALID_INPUT`,`No Clicky site given. Pass --site-id with the numeric Clicky site ID.`)}async function Fa(e,t){return Ae({siteId:e,sitekey:t}).catch(e=>{throw new g(e instanceof on&&e.code===`auth`?`AUTH_REQUIRED`:`PROVIDER_UNAVAILABLE`,e instanceof Error?e.message:String(e))})}const Ia={type:`boolean`,default:!1,description:`Print machine-readable JSON.`},La={type:`string`,description:`Numeric Clicky site ID.`},Ra=b({meta:{name:`connect`,description:`Check and save a Clicky site on this machine`},args:{"site-id":La,json:Ia},run:async({args:e})=>{let t=A(e),n=F({json:t});n&&Xr(`Connect Clicky`);let r=Pa(w(e[`site-id`])??(n?z(await ni({message:`Clicky site ID`,validate:e=>Ne(e??``)?void 0:`Enter the numeric site ID from Clicky`})):void 0)),i=process.env.SEO_CLICKY_SITEKEY?.trim()||(n?z(await ei({message:`Clicky sitekey`,validate:e=>Re(e??``)?void 0:`Enter the sitekey from Clicky (Preferences, Info)`})):void 0);if(!i)throw new g(`AUTH_REQUIRED`,`Run this command in a terminal or set ${fn}.`);let a=await Fa(r,i.trim()),o=await Dn(r,i.trim()),s={siteId:r,domain:a,connected:!0,credentialSource:o};if(t){I(s);return}let c=`Clicky site ${r}${a?` (${a})`:``} saved in the ${Na(o)}. Next: seo analytics clicky report --site ${r}`;n?S(c):process.stdout.write(`${c}\n`)}}),za=b({meta:{name:`status`,description:`Show a Clicky site saved on this machine`},args:{"site-id":La,check:{type:`boolean`,default:!1,description:`Check the saved sitekey with Clicky.`},json:Ia},run:async({args:e})=>{let t=Pa(w(e[`site-id`])),n=await Vt(t),r=T(e.check);r&&n&&await Fa(t,n.siteKey);let i={siteId:t,connected:!!n,credentialSource:n?.source,liveCheck:r?n?`passed`:`unavailable`:`not-requested`};A(e)?I(i):L([[`Site ID`,t],[`Connected`,i.connected?`yes`:`no`],[`Credential`,Na(i.credentialSource)],[`Live check`,i.liveCheck]])}}),Ba=b({meta:{name:`report`,description:`Clicky landing pages, traffic sources and search engines`},args:{site:{type:`string`,description:`The site, or its numeric Clicky site ID.`},...Ca,...B,json:Ia},run:async({args:e})=>{let t=j(w(e.site));await H(e,async()=>Zt({site:t,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),detail:V(e),offset:D(e.offset)},await r(),{connect:"save it at https://seoskill.dev/account#keys and run `seo login`, or run `seo analytics clicky connect` to keep it on this machine only.",refresh:sn,call:e=>`seo analytics clicky report --site ${t} --detail rows --offset ${e}`}))}}),Va=b({meta:{name:`disconnect`,description:`Remove a Clicky site saved on this machine`},args:{"site-id":La,json:Ia},run:async({args:e})=>{let t=Pa(w(e[`site-id`]));await Wn(t);let n=!!process.env[fn],r={siteId:t,savedCredentialRemoved:!0,environmentCredential:n?`active`:`missing`};A(e)?I(r):process.stdout.write(n?`Saved sitekey removed. ${fn} is still active.\n`:`Clicky is disconnected for this site.
33
+ `)}}),Ha=b({meta:{name:`clicky`,description:`Read Clicky, or save a Clicky site on this machine only`},subCommands:{connect:Ra,status:za,report:Ba,disconnect:Va}}),Ua=b({meta:{name:`properties`,description:`List Google Analytics accounts and properties`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},account:{type:`string`,description:`Saved Google account email.`}},run:async({args:e})=>{let t=await Ue(w(e.account)),n=t.flatMap(e=>e.propertySummaries.map(t=>({account:e.displayName??e.account,property:Te(t.property),displayName:t.displayName??t.property})));A(e)?I({accountSummaries:t,properties:n}):R([`Property`,`Name`,`Account`],n.map(e=>[e.property,e.displayName,e.account]))}}),Wa=b({meta:{name:`report`,description:`Google Analytics landing pages for visits from search`},args:{property:{type:`string`,description:"Numeric Google Analytics property ID. Run `seo analytics google properties` to list them."},...Ca,...B,json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=Di(w(e.property));await H(e,async()=>Xn({property:t,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),detail:V(e),offset:D(e.offset)},await bt(await ne(),t,rt.signIn),{signIn:rt.signIn,call:e=>`seo analytics google report --property ${t} --detail rows --offset ${e}`}))}}),Ga=b({meta:{name:`google`,description:`Read Google Analytics properties and reports`},subCommands:{properties:Ua,report:Wa}});function Ka(e){return e===`keychain`?`system keychain`:e===`file`?`private local file`:e===`environment`?je:e??`missing`}const qa={type:`boolean`,default:!1,description:`Print machine-readable JSON.`},Ja=b({meta:{name:`connect`,description:`Save a Simple Analytics API key on this machine`},args:{json:qa},run:async({args:e})=>{let t=A(e),n=F({json:t});n&&Xr(`Connect Simple Analytics`);let r=process.env.SEO_SIMPLE_ANALYTICS_KEY?.trim()||(n?z(await ei({message:`Simple Analytics API key`,validate:e=>Qe(e??``)?void 0:`Enter an API key that starts with sa_api_key_ (Account settings, API keys)`})):void 0);if(!r)throw new g(`AUTH_REQUIRED`,`Run this command in a terminal or set ${je}.`);let i=await he(r);if(t){I({connected:!0,credentialSource:i});return}let a=`Simple Analytics API key saved in the ${Ka(i)}. Next: seo analytics simple-analytics report --site example.com`;n?S(a):process.stdout.write(`${a}\n`)}}),Ya=b({meta:{name:`status`,description:`Show whether a Simple Analytics API key is saved here`},args:{json:qa},run:async({args:e})=>{let t=await oe(),n={connected:!!t,credentialSource:t?.source};A(e)?I(n):L([[`Connected`,n.connected?`yes`:`no`],[`Credential`,Ka(n.credentialSource)]])}}),Xa=b({meta:{name:`report`,description:`Simple Analytics landing pages, referrers, utm_source tags and AI tools`},args:{site:{type:`string`,description:`The site, such as example.com.`},...Ca,...B,json:qa},run:async({args:e})=>{let t=j(w(e.site));await H(e,async()=>Hn({site:t,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),detail:V(e),offset:D(e.offset)},await r(),{connect:Da,call:e=>`seo analytics simple-analytics report --site ${t} --detail rows --offset ${e}`}))}}),Za=b({meta:{name:`disconnect`,description:`Remove the Simple Analytics API key saved on this machine`},args:{json:qa},run:async({args:e})=>{await Ie();let t=!!process.env[je];A(e)?I({savedCredentialRemoved:!0,environmentCredential:t?`active`:`missing`}):process.stdout.write(t?`Saved key removed. ${je} is still active.\n`:`Simple Analytics is disconnected on this machine.
34
+ `)}}),Qa=b({meta:{name:`simple-analytics`,description:`Read Simple Analytics, or save its API key on this machine only`},subCommands:{connect:Ja,status:Ya,report:Xa,disconnect:Za}}),$a=b({meta:{name:`analytics`,description:`Read analytics data from connected providers`},subCommands:{clicky:Ha,google:Ga,"simple-analytics":Qa}});function eo(){return`Your browser will open. Choose your Google account and select all permission boxes for read-only access. Keep this terminal open and finish the browser steps within five minutes.`}async function to(){return x(eo(),`Google sign-in`),pe()}function no(e){return e?e===`environment-json`?`SEO_GOOGLE_SERVICE_ACCOUNT_JSON`:e===`environment-file`?`SEO_GOOGLE_SERVICE_ACCOUNT_FILE`:`GOOGLE_APPLICATION_CREDENTIALS`:`invalid or conflicting configuration`}function ro(e){return e.active===`keychain`?`system keychain`:e.configured===`keychain`?`private file fallback`:`private file`}function io(e){return e===`shared`?`SEO Skill app`:`Local OAuth config`}function ao(e){let t=[[`Account`,e.accountEmail]],n=new Set(e.scope.split(/\s+/u).filter(Boolean));return n.has(`https://www.googleapis.com/auth/webmasters.readonly`)?t.push([`Search Console`,`Read only`]):t.push([`Search Console`,`Not granted`]),n.has(`https://www.googleapis.com/auth/analytics.readonly`)?t.push([`Google Analytics`,`Read only`]):t.push([`Google Analytics`,`Not granted`]),t.push([`OAuth app`,io(e.clientSource)],[`Expires`,vi(e.expiresAt)]),t}const oo=b({meta:{name:`auth`,description:`Authentication commands`},subCommands:{login:b({meta:{name:`login`,description:`Run Google OAuth flow`},run:async()=>{if((await et()).activeMode===`service-account`)throw new g(`AUTH_CONFIG_REQUIRED`,`A service account is active from the environment. Unset its credential variable before running browser OAuth.`);let e=await to();L(ao({accountEmail:e.account_email,clientSource:e.client_source,expiresAt:e.expires_at,scope:e.scope}))}}),logout:b({meta:{name:`logout`,description:`Delete a local Google login`},args:{account:{type:`string`,description:`Delete the login for this Google account.`},all:{type:`boolean`,default:!1,description:`Delete every saved Google login.`}},run:async({args:e})=>{let t=await et(),n=w(e.account);if(n&&e.all)throw new g(`INVALID_INPUT`,`Use either --account or --all, not both.`);let r=e.all?void 0:n??t.accounts.find(e=>e.active)?.accountEmail;await ue(r),t.activeMode===`service-account`?process.stdout.write(`${e.all?`Deleted all local Google logins.`:r?`Deleted the local login for ${r}.`:`No local Google login was found.`} Service account credentials remain available through the environment.\n`):process.stdout.write(`${e.all?`Deleted all local Google logins.`:r?`Deleted the local login for ${r}.`:`No local Google login was found.`}\nRevoke at https://myaccount.google.com/permissions if you also want Google to forget the grant.\n`)}}),whoami:b({meta:{name:`whoami`,description:`Show the signed-in Google account`},args:{account:{type:`string`,description:`Show this saved Google account.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await et();if(t.activeMode===`service-account`){let n={mode:`service-account`,account:t.identity??null,source:no(t.serviceAccount.source)};if(A(e)){I(n);return}L([[`Account type`,`Service account`],[`Account`,t.identity??`Invalid configuration`],[`Credentials`,n.source],[`Access`,`Search Console and Google Analytics, read only`]]);return}let n=w(e.account),r=n?await ft(n):t.tokens;if(n&&!r)throw new g(`AUTH_REQUIRED`,`Google account ${n} is not connected.`);if(r)A(e)?I({mode:`oauth`,account:r.account_email,scopes:r.scope.split(/\s+/u).filter(Boolean),clientSource:r.client_source,expiresAt:r.expires_at}):L(ao({accountEmail:r.account_email,clientSource:r.client_source,expiresAt:r.expires_at,scope:r.scope}));else{if(A(e)){I({mode:`oauth`,account:null});return}process.stdout.write(`Not logged in.
35
+ `)}}}),status:b({meta:{name:`status`,description:`Show local Google auth status`},args:{account:{type:`string`,description:`Show status for this saved Google account.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await et(),n=w(e.account),r=n?await ft(n):t.tokens;if(n&&!r&&t.activeMode!==`service-account`)throw new g(`AUTH_REQUIRED`,`Google account ${n} is not connected.`);let i=t.activeMode===`oauth`?await jn():void 0;if(A(e)){I({authenticated:t.activeMode===`oauth`?!!r:t.serviceAccount.configured,mode:t.activeMode,identity:t.identity,account:t.activeMode===`oauth`?r?.account_email:void 0,scopes:t.activeMode===`oauth`?r?.scope:void 0,clientSource:t.activeMode===`oauth`?r?.client_source:void 0,expiresAt:t.activeMode===`oauth`?r?.expires_at:void 0,sharedConfigured:t.sharedConfigured,byoConfigured:t.byoConfigured,serviceAccount:{configured:t.serviceAccount.configured,identity:t.serviceAccount.identity,source:t.serviceAccount.source,error:t.serviceAccount.error},accounts:t.accounts,...i?{tokenStorage:i}:{}});return}if(t.activeMode===`service-account`){let e=[[`Mode`,`service account`],[`Identity`,t.identity??`unavailable`],[`Source`,no(t.serviceAccount.source)],[`Scopes`,`Search Console readonly, Google Analytics readonly`],[`Storage`,`credentials stay in the environment`]];t.serviceAccount.error&&e.push([`Status`,t.serviceAccount.error]),L(e);return}if(!r){let e=t.serviceAccount.error?t.serviceAccount.error:t.sharedConfigured?`Shared seo app available`:t.byoConfigured?`Local OAuth config available`:`No OAuth client configured`;process.stdout.write(`Not logged in. ${e}. Run \`seo auth login\` to connect Google.\n`);return}let a=i??await jn();L([[`Account`,r.account_email],[`Connected accounts`,String(t.accounts.length)],[`Scopes`,r.scope],[`Client`,io(r.client_source)],[`Expires`,vi(r.expires_at)],[`Tokens file`,qe().tokensFile],[`Token storage`,ro(a)],...a.reason?[[`Storage note`,a.reason]]:[],[`OAuth mode`,t.sharedConfigured?`SEO Skill app available`:t.byoConfigured?`Local OAuth config available`:`missing`],[`Revoke at`,`https://myaccount.google.com/permissions`]])}}),storage:b({meta:{name:`storage`,description:`Show or change local OAuth token storage`},args:{keychain:{type:`boolean`,default:!1,description:`Store OAuth tokens in the system keychain when available.`},file:{type:`boolean`,default:!1,description:`Store OAuth tokens in the private local file.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{if(e.keychain&&e.file)throw new g(`INVALID_INPUT`,`Choose either --keychain or --file, not both.`);let t=e.keychain||e.file?await ht(e.keychain?`keychain`:`file`):await jn();A(e)?I(t):L([[`Configured storage`,t.configured],[`Active storage`,ro(t)],...t.reason?[[`Note`,t.reason]]:[]])}}),refresh:b({meta:{name:`refresh`,description:`Refresh the Google OAuth token`},args:{account:{type:`string`,description:`Refresh this saved Google account.`}},run:async({args:e})=>{if((await et()).activeMode===`service-account`){process.stdout.write(`Service accounts request short-lived Google tokens automatically. No local refresh token is stored.
36
+ `);return}let t=await ot(w(e.account));process.stdout.write(`Refreshed. New expiry ${new Date(t.expires_at).toISOString()}.\n`)}}),accounts:b({meta:{name:`accounts`,description:`List saved Google accounts`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:({args:e})=>{let t=ye();A(e)?I({accounts:t}):t.length===0?process.stdout.write(`No Google accounts are connected.
37
+ `):L(t.map(e=>[e.active?`Active account`:`Account`,e.accountEmail]))}}),use:b({meta:{name:`use`,description:`Select the default Google account`},args:{account:{type:`positional`,required:!0,description:`Saved Google account email.`}},run:({args:e})=>{let t=w(e.account);if(!t)throw new g(`INVALID_INPUT`,`Google account is required.`);lt(t),process.stdout.write(`Default Google account: ${t}\n`)}}),"setup-client":b({meta:{name:`setup-client`,description:`Save your own Google Desktop OAuth client`},args:{json:{type:`boolean`,default:!1,description:`Return a structured error instead of prompting.`}},run:async({args:e})=>{if(!F({json:A(e)}))throw new g(`INVALID_INPUT`,"`seo auth setup-client` needs an interactive terminal. Run it without --json, or set SEO_GOOGLE_CLIENT_ID and SEO_GOOGLE_CLIENT_SECRET.");Xr(`Local Google OAuth client`),x(`This is the advanced path.
37
38
  Most users should use the shared seo Google app.
38
- Your actual sensitive data is the local refresh token, not the desktop app client secret.`,`Advanced`);let t=B(await Xr({message:`Google Desktop OAuth client ID`,validate:e=>e?void 0:`Client ID is required`})),n=B(await Jr({message:`Google Desktop OAuth client secret`,validate:e=>e?void 0:`Client secret is required`}));En({clientId:t,clientSecret:n}),C(`Saved local OAuth config to ${gt().oauthClientFile}`)}})}}),Ya=[`gsc`,`google-analytics`,`dataforseo`,`ahrefs`,`clicky`,`http`];function Xa(e){if(e!==void 0){if(typeof e==`string`&&Ya.includes(e))return e;throw new d(`INVALID_INPUT`,`--provider must be one of: ${Ya.join(`, `)}.`)}}const Za=x({meta:{name:`cache`,description:`Cache helpers`},subCommands:{stats:x({meta:{name:`stats`,description:`Show local cache size and row counts`},run:async()=>{let e=ie();R([[`DB`,e.dbPath],[`Size`,da(e.sizeBytes)],[`Cached data`,`${da(e.logicalSizeBytes)} of ${da(e.maxSizeBytes)} automatic limit`],[`Sites`,String(e.counts.sites??0)],[`Search Console`,String(e.counts.gsc_cache??0)],[`URL Inspection`,String(e.counts.url_inspection_cache??0)],[`Google Analytics`,String(e.counts.google_analytics_cache??0)],[`DataForSEO`,String(e.counts.provider_cache??0)],[`Ahrefs`,String(e.counts.ahrefs_cache??0)],[`Clicky`,String(e.counts.clicky_cache??0)],[`HTTP`,String(e.counts.http_cache??0)]])}}),clear:x({meta:{name:`clear`,description:`Clear cached API and HTTP data`},args:{provider:{type:`string`,description:`Optional cache provider: gsc, google-analytics, dataforseo, ahrefs, clicky, or http`}},run:async({args:e})=>{let t=Pe(Xa(e.provider));process.stdout.write(`Removed ${t} cached rows.\n`)}})}});function U(e){return Math.round(e).toLocaleString(`en-GB`)}function Qa(e){return e.toFixed(1)}function W(e){return`${(e*100).toFixed(1)}%`}function G(e,t=72){return Ei(e,t)}function $a(e){return e.verification?.requested?`${e.verification.verified} checked, ${e.verification.failed} failed`:`off`}function eo(e){return{title:e.title,target:e.target,status:e.status,summary:e.summary,metrics:e.metrics,sections:(e.diagnostics??[]).map(e=>({title:e.title,diagnostics:e.items})),notes:e.notes}}function K(e){aa(eo(e))}function q(e,t){z(e,t.slice(0,25)),t.length>25&&process.stdout.write(`Showing 25 of ${t.length}. Use --json for full data.\n`)}function J(e,t,n=5){let r=t.filter(e=>e.action.trim().length>0).slice(0,n),i=to(e,r);i&&(process.stdout.write(`
39
- `),aa(i),t.length>r.length&&process.stdout.write(`Showing ${r.length} of ${t.length}. Use --json for full data.\n`))}function to(e,t){if(t.length)return{title:e,status:`info`,summary:`${t.length} ${t.length===1?`action`:`actions`} shown.`,sections:[{title:`Actions`,diagnostics:t.map(e=>({status:`info`,title:e.label,explanation:e.context??`Review the evidence before making changes.`,fix:e.action}))}]}}function no(e){process.stdout.write(`\nNext: ${e}\n`)}function Y(e,t){let n=t.filter(e=>e.trim().length>0);if(n.length){process.stdout.write(`\n${e}\n`);for(let e of n)process.stdout.write(`- ${e}\n`)}}const ro=x({meta:{name:`content`,description:`Optimize page content from real GSC queries`},subCommands:{optimize:x({meta:{name:`optimize`,description:`Build a content optimization report for one URL`},args:{site:{type:`string`},url:{type:`string`,required:!0},days:{type:`string`,description:`GSC lookback days. Defaults to 28.`},limit:{type:`string`,description:`Maximum GSC queries to inspect. Defaults to 25.`},"min-impressions":{type:`string`,description:`Minimum query impressions. Defaults to 10.`},"include-brand":{type:`boolean`,default:!1,description:`Include branded queries.`},"verify-content":pi(`Fetch the page for content checks. Defaults to true.`,`Skip fetching the page for content checks.`),js:{type:`boolean`,default:!1,description:`Force JavaScript rendering for page extraction.`},refresh:{type:`boolean`,default:!1,description:`Bypass local GSC and HTTP cache.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=j(e),n=M(T(e.site)),r=await Ct({site:n,url:T(e.url)??``,days:O(e.days),limit:O(e.limit),minImpressions:O(e[`min-impressions`]),includeBrand:E(e[`include-brand`]),verifyContent:E(e[`verify-content`])!==!1,js:E(e.js)?!0:`auto`,refresh:E(e.refresh)});t?L(r):(K({title:`Content optimization`,target:r.url,status:`info`,summary:r.summary.verdict,metrics:[{label:`Score`,value:`${r.summary.score}/100`},{label:`Primary intent`,value:r.summary.primaryIntent},{label:`Primary query`,value:r.summary.primaryQuery??`None`},{label:`Queries`,value:U(r.summary.queries)},{label:`Opportunities`,value:U(r.summary.opportunities)},{label:`Estimated lift`,value:U(r.summary.estimatedClickLift)}]}),J(`Top actions`,r.topActions.map(e=>({label:e.title,action:e.action,context:e.plainEnglish}))),r.brief.sections.length&&(process.stdout.write(`
39
+ Your actual sensitive data is the local refresh token, not the desktop app client secret.`,`Advanced`);let t=z(await ni({message:`Google Desktop OAuth client ID`,validate:e=>e?void 0:`Client ID is required`})),n=z(await ei({message:`Google Desktop OAuth client secret`,validate:e=>e?void 0:`Client secret is required`}));Be({clientId:t,clientSecret:n}),S(`Saved local OAuth config to ${qe().oauthClientFile}`)}})}}),so=[`gsc`,`google-analytics`,`dataforseo`,`ahrefs`,`clicky`,`http`];function co(e){if(e!==void 0){if(typeof e==`string`&&so.includes(e))return e;throw new g(`INVALID_INPUT`,`--provider must be one of: ${so.join(`, `)}.`)}}const lo=b({meta:{name:`cache`,description:`Cache helpers`},subCommands:{stats:b({meta:{name:`stats`,description:`Show local cache size and row counts`},run:async()=>{let e=c();L([[`DB`,e.dbPath],[`Size`,_a(e.sizeBytes)],[`Cached data`,`${_a(e.logicalSizeBytes)} of ${_a(e.maxSizeBytes)} automatic limit`],[`Sites`,String(e.counts.sites??0)],[`Search Console`,String(e.counts.gsc_cache??0)],[`URL Inspection`,String(e.counts.url_inspection_cache??0)],[`Google Analytics`,String(e.counts.google_analytics_cache??0)],[`DataForSEO`,String(e.counts.provider_cache??0)],[`Ahrefs`,String(e.counts.ahrefs_cache??0)],[`Clicky`,String(e.counts.clicky_cache??0)],[`HTTP`,String(e.counts.http_cache??0)]])}}),clear:b({meta:{name:`clear`,description:`Clear cached API and HTTP data`},args:{provider:{type:`string`,description:`Optional cache provider: gsc, google-analytics, dataforseo, ahrefs, clicky, or http`}},run:async({args:e})=>{let t=ur(co(e.provider));process.stdout.write(`Removed ${t} cached rows.\n`)}})}});function U(e){return Math.round(e).toLocaleString(`en-GB`)}function uo(e){return e.toFixed(1)}function W(e){return`${(e*100).toFixed(1)}%`}function G(e,t=72){return Mi(e,t)}function fo(e){return e.verification?.requested?`${e.verification.verified} checked, ${e.verification.failed} failed`:`off`}function po(e){return{title:e.title,target:e.target,status:e.status,summary:e.summary,metrics:e.metrics,sections:(e.diagnostics??[]).map(e=>({title:e.title,diagnostics:e.items})),notes:e.notes}}function K(e){da(po(e))}function q(e,t){R(e,t.slice(0,25)),t.length>25&&process.stdout.write(`Showing 25 of ${t.length}. Use --json for full data.\n`)}function J(e,t,n=5){let r=t.filter(e=>e.action.trim().length>0).slice(0,n),i=mo(e,r);i&&(process.stdout.write(`
40
+ `),da(i),t.length>r.length&&process.stdout.write(`Showing ${r.length} of ${t.length}. Use --json for full data.\n`))}function mo(e,t){if(t.length)return{title:e,status:`info`,summary:`${t.length} ${t.length===1?`action`:`actions`} shown.`,sections:[{title:`Actions`,diagnostics:t.map(e=>({status:`info`,title:e.label,explanation:e.context??`Review the evidence before making changes.`,fix:e.action}))}]}}function ho(e){process.stdout.write(`\nNext: ${e}\n`)}function Y(e,t){let n=t.filter(e=>e.trim().length>0);if(n.length){process.stdout.write(`\n${e}\n`);for(let e of n)process.stdout.write(`- ${e}\n`)}}const go=b({meta:{name:`content`,description:`Optimize page content from real GSC queries`},subCommands:{optimize:b({meta:{name:`optimize`,description:`Build a content optimization report for one URL`},args:{site:{type:`string`},url:{type:`string`,required:!0},days:{type:`string`,description:`GSC lookback days. Defaults to 28.`},limit:{type:`string`,description:`Maximum GSC queries to inspect. Defaults to 25.`},"min-impressions":{type:`string`,description:`Minimum query impressions. Defaults to 10.`},"include-brand":{type:`boolean`,default:!1,description:`Include branded queries.`},"verify-content":yi(`Fetch the page for content checks. Defaults to true.`,`Skip fetching the page for content checks.`),js:{type:`boolean`,default:!1,description:`Force JavaScript rendering for page extraction.`},refresh:{type:`boolean`,default:!1,description:`Bypass local GSC and HTTP cache.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=A(e),n=j(w(e.site)),r=await Xe({site:n,url:w(e.url)??``,days:D(e.days),limit:D(e.limit),minImpressions:D(e[`min-impressions`]),includeBrand:T(e[`include-brand`]),verifyContent:T(e[`verify-content`])!==!1,js:T(e.js)?!0:`auto`,refresh:T(e.refresh)});t?I(r):(K({title:`Content optimization`,target:r.url,status:`info`,summary:r.summary.verdict,metrics:[{label:`Score`,value:`${r.summary.score}/100`},{label:`Primary intent`,value:r.summary.primaryIntent},{label:`Primary query`,value:r.summary.primaryQuery??`None`},{label:`Queries`,value:U(r.summary.queries)},{label:`Opportunities`,value:U(r.summary.opportunities)},{label:`Estimated lift`,value:U(r.summary.estimatedClickLift)}]}),J(`Top actions`,r.topActions.map(e=>({label:e.title,action:e.action,context:e.plainEnglish}))),r.brief.sections.length&&(process.stdout.write(`
40
41
  Suggested sections
41
42
  `),q([`Heading`,`Queries`],r.brief.sections.map(e=>[G(e.heading,48),G(e.queries.join(`, `),80)]))),r.intentMix.length&&(process.stdout.write(`
42
43
  Intent mix
43
- `),q([`Intent`,`Queries`,`Impressions`,`Clicks`],r.intentMix.map(e=>[e.intent,U(e.queries),U(e.impressions),U(e.clicks)]))),Y(`Caveats`,r.caveats))}})}});var io=class{stream;buffer=``;constructor(e){this.stream=e}async write(e){this.buffer+=e,this.buffer.length>=65536&&await this.flush()}async flush(){if(!this.buffer)return;let e=this.buffer;this.buffer=``,this.stream.write(e)||await new Promise((e,t)=>{let n=()=>{i(),e()},r=e=>{i(),t(e)},i=()=>{this.stream.off(`drain`,n),this.stream.off(`error`,r)};this.stream.once(`drain`,n),this.stream.once(`error`,r)})}};function ao(e){return` `.repeat(e)}function oo(e){return e&&typeof e==`object`&&`toJSON`in e&&typeof e.toJSON==`function`?e.toJSON():e}async function so(e,t,n,r,i=!1){let a=oo(t);if(a===null)return await e.write(`null`),!0;if(typeof a==`string`||typeof a==`boolean`)return await e.write(JSON.stringify(a)),!0;if(typeof a==`number`)return await e.write(Number.isFinite(a)?String(a):`null`),!0;if(typeof a==`bigint`&&JSON.stringify(a),a===void 0||typeof a==`function`||typeof a==`symbol`)return i&&await e.write(`null`),i;if(!a||typeof a!=`object`)return!1;if(r.has(a))throw TypeError(`Converting circular structure to JSON`);r.add(a);try{if(Array.isArray(a)){if(a.length===0)return await e.write(`[]`),!0;await e.write(`[
44
+ `),q([`Intent`,`Queries`,`Impressions`,`Clicks`],r.intentMix.map(e=>[e.intent,U(e.queries),U(e.impressions),U(e.clicks)]))),Y(`Caveats`,r.caveats))}})}});var _o=class{stream;buffer=``;constructor(e){this.stream=e}async write(e){this.buffer+=e,this.buffer.length>=65536&&await this.flush()}async flush(){if(!this.buffer)return;let e=this.buffer;this.buffer=``,this.stream.write(e)||await new Promise((e,t)=>{let n=()=>{i(),e()},r=e=>{i(),t(e)},i=()=>{this.stream.off(`drain`,n),this.stream.off(`error`,r)};this.stream.once(`drain`,n),this.stream.once(`error`,r)})}};function vo(e){return` `.repeat(e)}function yo(e){return e&&typeof e==`object`&&`toJSON`in e&&typeof e.toJSON==`function`?e.toJSON():e}async function bo(e,t,n,r,i=!1){let a=yo(t);if(a===null)return await e.write(`null`),!0;if(typeof a==`string`||typeof a==`boolean`)return await e.write(JSON.stringify(a)),!0;if(typeof a==`number`)return await e.write(Number.isFinite(a)?String(a):`null`),!0;if(typeof a==`bigint`&&JSON.stringify(a),a===void 0||typeof a==`function`||typeof a==`symbol`)return i&&await e.write(`null`),i;if(!a||typeof a!=`object`)return!1;if(r.has(a))throw TypeError(`Converting circular structure to JSON`);r.add(a);try{if(Array.isArray(a)){if(a.length===0)return await e.write(`[]`),!0;await e.write(`[
44
45
  `);for(let t=0;t<a.length;t+=1)t>0&&await e.write(`,
45
- `),await e.write(ao(n+1)),await so(e,a[t],n+1,r,!0);return await e.write(`\n${ao(n)}]`),!0}let t=Object.entries(a).filter(([,e])=>{let t=oo(e);return![`undefined`,`function`,`symbol`].includes(typeof t)});if(t.length===0)return await e.write(`{}`),!0;await e.write(`{
46
+ `),await e.write(vo(n+1)),await bo(e,a[t],n+1,r,!0);return await e.write(`\n${vo(n)}]`),!0}let t=Object.entries(a).filter(([,e])=>{let t=yo(e);return![`undefined`,`function`,`symbol`].includes(typeof t)});if(t.length===0)return await e.write(`{}`),!0;await e.write(`{
46
47
  `);for(let i=0;i<t.length;i+=1){let[a,o]=t[i];i>0&&await e.write(`,
47
- `),await e.write(`${ao(n+1)}${JSON.stringify(a)}: `),await so(e,o,n+1,r)}return await e.write(`\n${ao(n)}}`),!0}finally{r.delete(a)}}async function co(e,t){let n=new io(e);await so(n,t,0,/* @__PURE__ */ new Set)||await n.write(`undefined`),await n.write(`
48
- `),await n.flush()}async function lo(e,t){if(!e){await co(process.stdout,t);return}await Ar(_(e),{recursive:!0});let n=yr(e);try{await co(n,t),n.end(),await ei(n)}catch(e){throw n.destroy(),e}process.stdout.write(`Wrote ${e}\n`)}function uo(e){return e.length?e.join(`, `):`none`}function fo(e,t){let n=e.robotsTxt,r=(n?.botAccess??[]).filter(e=>e.purpose===t),i=t===`search`?`AI search bots`:`AI training bots`;if(!n||r.some(e=>e.allowed===null))return{status:`unknown`,title:`${i}: unknown`,explanation:n?.servesHtml?`robots.txt returned a web page, such as a bot challenge, not a robots.txt file.`:`robots.txt could not be read (${n?.availability??`not checked`}).`};let a=r.filter(e=>e.allowed===!1);return{status:a.length?t===`search`?`warning`:`info`:`pass`,title:a.length?`${i}: ${a.length} of ${r.length} blocked`:`${i}: all ${r.length} allowed`,explanation:a.length?`Blocked: ${uo(a.map(e=>e.userAgent))}.`:`Checked: ${uo(r.map(e=>e.userAgent))}.`}}function po(e){let t=e.markdownNegotiation,n=e.markdownCopies,r=t?.markdown?`Accept: text/markdown returns Markdown${t.varyAccept?` with Vary: Accept`:` without Vary: Accept`}.`:t?.availability===`available`?`Accept: text/markdown returns ${t.contentType||`no content type`}.`:`Accept: text/markdown could not be checked (${t?.availability??`not checked`}).`,i=n?` ${n.publicPagesWithLink} of ${n.publicPages} public pages link to a Markdown copy${n.privatePagesWithLink?`, and ${n.privatePagesWithLink} signed-in pages do`:``}. ${n.checked} copies checked, ${n.broken.length} broken.${n.largest?` Largest checked copy: about ${n.largest.estimatedTokens} tokens.`:``}`:``;return{status:t?.markdown||n?.publicPagesWithLink?n?.broken.length||n?.privatePagesWithLink?`warning`:`pass`:t?.availability===`available`?`info`:`unknown`,title:`Markdown copies`,explanation:`${r}${i}`}}function mo(e){let t=e.llmsTxt;if(!t||t.availability===void 0)return{status:`unknown`,title:`llms.txt`,explanation:`Not checked.`};if(t.availability!==`available`)return{status:t.availability===`absent`?`info`:`unknown`,title:`llms.txt`,explanation:t.availability===`absent`?`Not found (HTTP ${t.status??`none`}).`:`Could not be read (${t.availability}).`};let n=t.links;return{status:n?.broken.length?`warning`:`pass`,title:`llms.txt`,explanation:n?`${n.found} same-site links; ${n.checked} checked, ${n.broken.length} broken.`:`Present.`}}function ho(e){if(!e)return[];let t=(e.agentResources??[]).filter(e=>e.exists).map(e=>new URL(e.url).pathname),n=[...e.robotsTxt?.contentSignals??[],...e.startPageHeaders?.contentSignal?[e.startPageHeaders.contentSignal]:[]];return[fo(e,`search`),fo(e,`training`),po(e),mo(e),{status:`info`,title:`Agent files`,explanation:`Found: ${uo(t)}.`},{status:`info`,title:`Content-Signal and Link header`,explanation:`Content-Signal: ${uo([...new Set(n)])}. Link header relations on the start page: ${uo(e.startPageHeaders?.linkRelations??[])}.`}]}function go(e){return e===`high`?`fail`:`warning`}function _o(e,t=ht(e)){let n=Ht(e),r=e.status===`failed`||e.summary.highIssues>0?`fail`:e.status===`partial`?`unknown`:e.summary.mediumIssues>0||e.summary.lowIssues>0?`warning`:`pass`,i=e.access.samples.slice(0,5).map(e=>({status:`fail`,title:e.evidence.guidance.summary,explanation:`${e.evidence.provider} returned ${e.evidence.kind} evidence for the crawler request.`,evidence:[e.url],fix:e.evidence.guidance.recommendedAction})),a=t.slice(0,10).map(e=>({status:go(e.severity),title:`${e.title} on ${e.count} ${e.count===1?`URL`:`URLs`}`,explanation:g(e.ruleId)?.whyItMatters??e.whyThisRanks,evidence:e.sampleUrls.slice(0,5),fix:e.howToFix})),o=n.slice(0,10).map(e=>({status:`warning`,title:`${e.title} on ${e.count} ${e.count===1?`URL`:`URLs`}`,explanation:g(e.ruleId)?.whyItMatters??e.whyThisRanks,evidence:e.sampleUrls.slice(0,5),fix:e.howToFix}));aa({title:e.config.strategy===`health`?`Sitemap health pass`:`Site crawl`,target:e.config.url,status:r,summary:sn(e)??(e.status===`partial`?`Partial evidence from ${e.summary.totalPages} retained pages. Review the caveats before treating missing findings as an all-clear.`:`${e.summary.totalPages} pages retained with ${e.issues.length} findings.`),metrics:[{label:`Pages`,value:e.summary.totalPages},{label:`High`,value:e.summary.highIssues,status:`fail`},{label:`Medium`,value:e.summary.mediumIssues,status:`warning`},{label:`Low`,value:e.summary.lowIssues,status:`info`},{label:`Failed fetches`,value:e.summary.failedUrls}],sections:[{title:`Access diagnostics`,diagnostics:i},{title:`Prioritised fixes`,diagnostics:a},{title:`Review before changing anything`,diagnostics:o},{title:`Agent access`,diagnostics:ho(e.ai)},...!i.length&&!a.length&&!o.length?[{title:`Checks`,diagnostics:[{status:`pass`,title:`No prioritised findings were observed`,explanation:`The evaluated crawl evidence did not produce a prioritised fix or review item.`}]}]:[]],notes:[`Strategy: ${e.config.strategy}. Data: ${e.status}. Report: ${e.id}.`,...e.warnings,...e.caveats]})}const vo={"google-analytics-property":{type:`string`,description:`Google Analytics property ID for landing-page sessions.`},"clicky-site-id":{type:`string`,description:`Clicky site ID for landing-page visits.`}};function yo(e){let t=T(e[`google-analytics-property`]),n=T(e[`clicky-site-id`]);if(t&&n)throw new d(`INVALID_INPUT`,`Pass either --google-analytics-property or --clicky-site-id, not both.`);if(t)return{provider:`google`,propertyId:t};if(n)return{provider:`clicky`,siteId:vn(n)}}const bo=[`health`,`sitemap-url`,`site`,`severity`,`fail-on`,`csv`,`max-pages`,`max-depth`,`include`,`exclude`],xo=[`GPTBot`,`OAI-SearchBot`,`ClaudeBot`,`PerplexityBot`,`Google-Extended`,`CCBot`];async function So(e){process.stdout.write(e)||await new Promise(e=>process.stdout.once(`drain`,e))}async function Co(e,t){let n=T(e.format),r=j(e);if(n&&n!==`jsonl`&&n!==`pretty`)throw new d(`INVALID_INPUT`,`Sites mode writes one JSON row per line. Use --format jsonl (or --json), or --format pretty for counts only.`);if(r&&n===`pretty`)throw new d(`INVALID_INPUT`,`Use either --json or --format, not both.`);for(let t of bo)if(e[t]!==void 0&&e[t]!==!1)throw new d(`INVALID_INPUT`,`--${t} does not apply to sites mode.`);let i=r||n===`jsonl`,a=T(e.output),o=T(e.crawlUrl)??T(e.url),s=o?[o,...t]:t;if(!s.length)throw new d(`INVALID_INPUT`,`No sites given. Pass --urls example.com,example.org or --urls-file with one site per line.`);a&&await Ar(_(a),{recursive:!0});let c=a?await jr(a,`w`):void 0,l=async e=>{c?await c.write(e):i&&await So(e)},u=!i&&process.stderr.isTTY,f=0,p;try{p=await pt({sites:s,concurrency:O(e.concurrency),respectRobots:!D(e,`robots`),onRow:async e=>{await l(`${JSON.stringify(e)}\n`),f+=1,u&&process.stderr.write(`\rChecked ${f} sites`)}}),u&&f&&process.stderr.write(`
49
- `),await l(`${JSON.stringify(p)}\n`)}finally{await c?.close()}i||To(p,a),a&&process.stdout.write(`Wrote ${a}\n`)}function wo(e,t,n=[]){return[e,[`${t.available} found`,...n,`${t.absent} missing`,`${t[`access-blocked`]} access blocked`,`${t[`rate-limited`]} rate limited`,`${t.unreachable} unreachable (${t.failed} with no response)`,...t.unreadable?[`${t.unreadable} answered with a web page, so the rules are unknown`]:[]].join(`, `)]}function To(e,t){let n=[e.invalid?`${e.invalid} not valid sites`:``,e.duplicatesRemoved?`${e.duplicatesRemoved} duplicates removed`:``].filter(Boolean),r=e.homepage;R([[`Sites`,`${e.checked} checked of ${e.sites}${n.length?` (${n.join(`, `)})`:``}. Limit ${st.toLocaleString(`en-US`)} per run.`],wo(`robots.txt`,e.robotsTxt),[`Home page`,[`${r.available} answered 2xx`,`${r.absent} answered 4xx`,`${r[`access-blocked`]} access blocked`,`${r[`rate-limited`]} rate limited`,`${r.unreachable} unreachable (${r.failed} with no response)`,`${r.skipped} not requested because robots.txt disallows it or could not be read`].join(`, `)],wo(`llms.txt`,e.llmsTxt,[`${e.llmsTxt.startsWithH1} start with an H1`]),...e.botAccess.filter(e=>xo.includes(e.userAgent)).map(e=>[e.userAgent,`${e.blocked} block it in robots.txt, ${e.allowed} allow it, ${e.unknown} unknown (robots.txt not read)`]),[`Run`,`${e.status}, ${Math.round(e.durationMs/1e3)}s, ${e.concurrency} sites at a time, ${e.timeoutMs/1e3}s per request`]]),t||process.stdout.write(`
48
+ `),await e.write(`${vo(n+1)}${JSON.stringify(a)}: `),await bo(e,o,n+1,r)}return await e.write(`\n${vo(n)}}`),!0}finally{r.delete(a)}}async function xo(e,t){let n=new _o(e);await bo(n,t,0,/* @__PURE__ */ new Set)||await n.write(`undefined`),await n.write(`
49
+ `),await n.flush()}async function So(e,t){if(!e){await xo(process.stdout,t);return}await Ir(_r(e),{recursive:!0});let n=Tr(e);try{await xo(n,t),n.end(),await oi(n)}catch(e){throw n.destroy(),e}process.stdout.write(`Wrote ${e}\n`)}function Co(e){return e.length?e.join(`, `):`none`}function wo(e,t){let n=e.robotsTxt,r=(n?.botAccess??[]).filter(e=>e.purpose===t),i=t===`search`?`AI search bots`:`AI training bots`;if(!n||r.some(e=>e.allowed===null))return{status:`unknown`,title:`${i}: unknown`,explanation:n?.servesHtml?`robots.txt returned a web page, such as a bot challenge, not a robots.txt file.`:`robots.txt could not be read (${n?.availability??`not checked`}).`};let a=r.filter(e=>e.allowed===!1);return{status:a.length?t===`search`?`warning`:`info`:`pass`,title:a.length?`${i}: ${a.length} of ${r.length} blocked`:`${i}: all ${r.length} allowed`,explanation:a.length?`Blocked: ${Co(a.map(e=>e.userAgent))}.`:`Checked: ${Co(r.map(e=>e.userAgent))}.`}}function To(e){let t=e.markdownNegotiation,n=e.markdownCopies,r=t?.markdown?`Accept: text/markdown returns Markdown${t.varyAccept?` with Vary: Accept`:` without Vary: Accept`}.`:t?.availability===`available`?`Accept: text/markdown returns ${t.contentType||`no content type`}.`:`Accept: text/markdown could not be checked (${t?.availability??`not checked`}).`,i=n?` ${n.publicPagesWithLink} of ${n.publicPages} public pages link to a Markdown copy${n.privatePagesWithLink?`, and ${n.privatePagesWithLink} signed-in pages do`:``}. ${n.checked} copies checked, ${n.broken.length} broken.${n.largest?` Largest checked copy: about ${n.largest.estimatedTokens} tokens.`:``}`:``;return{status:t?.markdown||n?.publicPagesWithLink?n?.broken.length||n?.privatePagesWithLink?`warning`:`pass`:t?.availability===`available`?`info`:`unknown`,title:`Markdown copies`,explanation:`${r}${i}`}}function Eo(e){let t=e.llmsTxt;if(!t||t.availability===void 0)return{status:`unknown`,title:`llms.txt`,explanation:`Not checked.`};if(t.availability!==`available`)return{status:t.availability===`absent`?`info`:`unknown`,title:`llms.txt`,explanation:t.availability===`absent`?`Not found (HTTP ${t.status??`none`}).`:`Could not be read (${t.availability}).`};let n=t.links;return{status:n?.broken.length?`warning`:`pass`,title:`llms.txt`,explanation:n?`${n.found} same-site links; ${n.checked} checked, ${n.broken.length} broken.`:`Present.`}}function Do(e){if(!e)return[];let t=(e.agentResources??[]).filter(e=>e.exists).map(e=>new URL(e.url).pathname),n=[...e.robotsTxt?.contentSignals??[],...e.startPageHeaders?.contentSignal?[e.startPageHeaders.contentSignal]:[]];return[wo(e,`search`),wo(e,`training`),To(e),Eo(e),{status:`info`,title:`Agent files`,explanation:`Found: ${Co(t)}.`},{status:`info`,title:`Content-Signal and Link header`,explanation:`Content-Signal: ${Co([...new Set(n)])}. Link header relations on the start page: ${Co(e.startPageHeaders?.linkRelations??[])}.`}]}function Oo(e){return e===`high`?`fail`:`warning`}function ko(e,t=Ke(e)){let n=nr(e),r=e.status===`failed`||e.summary.highIssues>0?`fail`:e.status===`partial`?`unknown`:e.summary.mediumIssues>0||e.summary.lowIssues>0?`warning`:`pass`,i=e.access.samples.slice(0,5).map(e=>({status:`fail`,title:e.evidence.guidance.summary,explanation:`${e.evidence.provider} returned ${e.evidence.kind} evidence for the crawler request.`,evidence:[e.url],fix:e.evidence.guidance.recommendedAction})),a=t.slice(0,10).map(e=>({status:Oo(e.severity),title:`${e.title} on ${e.count} ${e.count===1?`URL`:`URLs`}`,explanation:an(e.ruleId)?.whyItMatters??e.whyThisRanks,evidence:e.sampleUrls.slice(0,5),fix:e.howToFix})),o=n.slice(0,10).map(e=>({status:`warning`,title:`${e.title} on ${e.count} ${e.count===1?`URL`:`URLs`}`,explanation:an(e.ruleId)?.whyItMatters??e.whyThisRanks,evidence:e.sampleUrls.slice(0,5),fix:e.howToFix}));da({title:e.config.strategy===`health`?`Sitemap health pass`:`Site crawl`,target:e.config.url,status:r,summary:gn(e)??(e.status===`partial`?`Partial evidence from ${e.summary.totalPages} retained pages. Review the caveats before treating missing findings as an all-clear.`:`${e.summary.totalPages} pages retained with ${e.issues.length} findings.`),metrics:[{label:`Pages`,value:e.summary.totalPages},{label:`High`,value:e.summary.highIssues,status:`fail`},{label:`Medium`,value:e.summary.mediumIssues,status:`warning`},{label:`Low`,value:e.summary.lowIssues,status:`info`},{label:`Failed fetches`,value:e.summary.failedUrls}],sections:[{title:`Access diagnostics`,diagnostics:i},{title:`Prioritised fixes`,diagnostics:a},{title:`Review before changing anything`,diagnostics:o},{title:`Agent access`,diagnostics:Do(e.ai)},...!i.length&&!a.length&&!o.length?[{title:`Checks`,diagnostics:[{status:`pass`,title:`No prioritised findings were observed`,explanation:`The evaluated crawl evidence did not produce a prioritised fix or review item.`}]}]:[]],notes:[`Strategy: ${e.config.strategy}. Data: ${e.status}. Report: ${e.id}.`,...e.warnings,...e.caveats]})}const Ao={"google-analytics-property":{type:`string`,description:`Google Analytics property ID for landing-page sessions.`},"clicky-site-id":{type:`string`,description:`Clicky site ID for landing-page visits.`}};function jo(e){let t=w(e[`google-analytics-property`]),n=w(e[`clicky-site-id`]);if(t&&n)throw new g(`INVALID_INPUT`,`Pass either --google-analytics-property or --clicky-site-id, not both.`);if(t)return{provider:`google`,propertyId:t};if(n)return{provider:`clicky`,siteId:Pt(n)}}const Mo=[`health`,`sitemap-url`,`site`,`severity`,`fail-on`,`csv`,`max-pages`,`max-depth`,`include`,`exclude`],No=[`GPTBot`,`OAI-SearchBot`,`ClaudeBot`,`PerplexityBot`,`Google-Extended`,`CCBot`];async function Po(e){process.stdout.write(e)||await new Promise(e=>process.stdout.once(`drain`,e))}async function Fo(e,t){let n=w(e.format),r=A(e);if(n&&n!==`jsonl`&&n!==`pretty`)throw new g(`INVALID_INPUT`,`Sites mode writes one JSON row per line. Use --format jsonl (or --json), or --format pretty for counts only.`);if(r&&n===`pretty`)throw new g(`INVALID_INPUT`,`Use either --json or --format, not both.`);for(let t of Mo)if(e[t]!==void 0&&e[t]!==!1)throw new g(`INVALID_INPUT`,`--${t} does not apply to sites mode.`);let i=r||n===`jsonl`,a=w(e.output),o=w(e.crawlUrl)??w(e.url),s=o?[o,...t]:t;if(!s.length)throw new g(`INVALID_INPUT`,`No sites given. Pass --urls example.com,example.org or --urls-file with one site per line.`);a&&await Ir(_r(a),{recursive:!0});let c=a?await Lr(a,`w`):void 0,l=async e=>{c?await c.write(e):i&&await Po(e)},u=!i&&process.stderr.isTTY,d=0,f;try{f=await yn({sites:s,concurrency:D(e.concurrency),respectRobots:!E(e,`robots`),onRow:async e=>{await l(`${JSON.stringify(e)}\n`),d+=1,u&&process.stderr.write(`\rChecked ${d} sites`)}}),u&&d&&process.stderr.write(`
50
+ `),await l(`${JSON.stringify(f)}\n`)}finally{await c?.close()}i||Lo(f,a),a&&process.stdout.write(`Wrote ${a}\n`)}function Io(e,t,n=[]){return[e,[`${t.available} found`,...n,`${t.absent} missing`,`${t[`access-blocked`]} access blocked`,`${t[`rate-limited`]} rate limited`,`${t.unreachable} unreachable (${t.failed} with no response)`,...t.unreadable?[`${t.unreadable} answered with a web page, so the rules are unknown`]:[]].join(`, `)]}function Lo(e,t){let n=[e.invalid?`${e.invalid} not valid sites`:``,e.duplicatesRemoved?`${e.duplicatesRemoved} duplicates removed`:``].filter(Boolean),r=e.homepage;L([[`Sites`,`${e.checked} checked of ${e.sites}${n.length?` (${n.join(`, `)})`:``}. Limit ${Bn.toLocaleString(`en-US`)} per run.`],Io(`robots.txt`,e.robotsTxt),[`Home page`,[`${r.available} answered 2xx`,`${r.absent} answered 4xx`,`${r[`access-blocked`]} access blocked`,`${r[`rate-limited`]} rate limited`,`${r.unreachable} unreachable (${r.failed} with no response)`,`${r.skipped} not requested because robots.txt disallows it or could not be read`].join(`, `)],Io(`llms.txt`,e.llmsTxt,[`${e.llmsTxt.startsWithH1} start with an H1`]),...e.botAccess.filter(e=>No.includes(e.userAgent)).map(e=>[e.userAgent,`${e.blocked} block it in robots.txt, ${e.allowed} allow it, ${e.unknown} unknown (robots.txt not read)`]),[`Run`,`${e.status}, ${Math.round(e.durationMs/1e3)}s, ${e.concurrency} sites at a time, ${e.timeoutMs/1e3}s per request`]]),t||process.stdout.write(`
50
51
  Add --json for one row per site, or --output <file> to save the rows.
51
- `)}function Eo(e){let t=e.trim();if(/^https?:\/\//i.test(t))return t;if(t.startsWith(`sc-domain:`))return`https://${t.slice(10)}/`;if(/^[a-z0-9-]+(\.[a-z0-9-]+)+(:\d+)?(\/\S*)?$/i.test(t))return`https://${t.includes(`/`)?t:`${t}/`}`}function Do(e){return e?e.backpressure?.status===`stopped`?`stopped: ${e.backpressure.reason??`origin cooldown`}`:e.backpressure?.status===`slowed`?`slowed ${e.backpressure.delayMs}ms`:e.rendering?.status===`unavailable`?`raw HTML; rendering unavailable`:e.rendering?.status===`failed`?`raw HTML; rendering failed`:e.blocked?`blocked`:e.rendered?`rendered`:e.cache===`hit`?`cached`:e.fetched?`fetched`:e.source:`-`}function Oo(e){return e?e===`serp-framing`?`wording gap`:e===`content-gap`?`content gap`:e===`technical-check`?`technical check`:`covered`:`-`}const ko={high:3,medium:2,low:1},Ao=x({meta:{name:`crawl`,description:`Run a fast sitemap health pass or a full technical crawl`},args:{crawlUrl:{type:`positional`,required:!1,description:`Site start URL. Optional with --sitemap-url.`},url:{type:`string`,description:`Start URL to crawl. Defaults to the --site home page.`},site:{type:`string`,description:`GSC property URL for joining page metrics.`},...vo,mode:{type:`string`,description:`Crawl mode: site, page, list, sitemap, or sites. Start with sitemap --health for large sites. sites checks robots.txt, the home page and llms.txt for up to 1,000 sites from --urls or --urls-file.`},health:{type:`boolean`,default:!1,description:`Run the uncached sitemap status and redirect pass before a full audit. No page-body analysis.`},"sitemap-url":{type:`string`,description:`Explicit sitemap URL. Selects sitemap mode when --mode is omitted.`},urls:{type:`string`,description:`Comma-separated URLs for list mode, or sites for sites mode.`},"urls-file":{type:`string`,description:`File with one URL per line for list mode, or one site per line for sites mode.`},"max-pages":{type:`string`,description:`Maximum pages to crawl, up to 10,000. Defaults to 500.`},"max-depth":{type:`string`,description:`Maximum click depth, up to 64. Defaults to 16.`},concurrency:{type:`string`,description:`Parallel page fetches, up to 16. Defaults to 8, or progressively up to 4 with --health. In sites mode, sites checked at once.`},"fetch-interval-cap":{type:`string`,description:`Maximum page fetches per interval per host.`},"fetch-interval-ms":{type:`string`,description:`Fetch rate interval in milliseconds.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache and fetch fresh pages.`},include:{type:`string`,description:`Comma-separated URL patterns to include.`},exclude:{type:`string`,description:`Comma-separated URL patterns to exclude.`},"no-sitemap":{type:`boolean`,default:!1,description:`Do not seed URLs from sitemap.xml.`},"no-robots":{type:`boolean`,default:!1,description:`Do not skip URLs disallowed by robots.txt.`},"no-external":{type:`boolean`,default:!1,description:`Do not check external links. Reserved for full link checks.`},js:{type:`boolean`,default:!1,description:`Legacy alias for --rendering on.`},rendering:{type:`string`,description:`JavaScript rendering mode: auto, on, or off. Defaults to auto.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON. Alias for --format json, or --format jsonl in sites mode.`},format:{type:`string`,description:`Output format: pretty, json, csv, html, markdown, or junit. JUnit requires --health. Sites mode takes jsonl or pretty.`},output:{type:`string`,description:`Write output to this path instead of stdout.`},csv:{type:`string`,description:`CSV table to render: issues or pages. Defaults to issues.`},severity:{type:`string`,description:`Only show top fixes at this severity.`},"fail-on":{type:`string`,description:`Exit non-zero when issues exist at this severity or above.`}},run:async({args:e})=>{let t=jo(e.mode);if(t===`sites`){await Co(e,await Io(e));return}let n=j(e),r=Po(e.format,n),i=T(e.output),a=Fo(e.csv),o=Mo(e.severity),s=Mo(e[`fail-on`]),c=await Io(e),l=No(e),u=T(e[`sitemap-url`]),f=E(e.health);if(r===`junit`&&!f)throw new d(`INVALID_INPUT`,`--format junit requires --health.`);if((f||u)&&t&&t!==`sitemap`)throw new d(`INVALID_INPUT`,`--health and --sitemap-url require sitemap mode.`);if(f&&D(e,`sitemap`))throw new d(`INVALID_INPUT`,`--health cannot be combined with --no-sitemap.`);if((f||u)&&c.length)throw new d(`INVALID_INPUT`,`--health and --sitemap-url cannot be combined with URL list input.`);let p=T(e.site),ee=(l?Eo(l)??l:void 0)??(p?Eo(p):void 0)??(u?new URL(`/`,u).toString():void 0)??c[0];if(!ee)throw new d(`INVALID_INPUT`,"No crawl URL given. Pass a URL, --url or --site. Run `seo sites` to list your Search Console properties.");let m=await Re({url:ee,site:p,mode:t??(f||u?`sitemap`:c.length?`list`:void 0),strategy:f?`health`:`full`,sitemapUrl:u,urls:c,maxPages:O(e[`max-pages`]),maxDepth:O(e[`max-depth`]),concurrency:O(e.concurrency),refresh:E(e.refresh),fetchRate:vi({...e,"fetch-concurrency":e.concurrency}),include:A(e.include),exclude:A(e.exclude),googleAnalyticsPropertyId:T(e[`google-analytics-property`]),analyticsConnection:yo(e),useSitemap:!D(e,`sitemap`),respectRobots:!D(e,`robots`),checkExternal:!D(e,`external`),js:mi(e)}),te=ht(m,{severity:o}),h=s?m.issues.some(e=>ko[e.severity]>=ko[s]):!1,g=m.status===`failed`,ne={...m,topFixes:te,reviewObservations:Ht(m,{severity:o}),...s?{failOn:s,failedThreshold:h}:{}};r===`json`?(await lo(i,ne),(g||h)&&(process.exitCode=1)):r===`csv`?(await Ro(i,a===`pages`?dn(m):zn(m)),(g||h)&&(process.exitCode=1)):r===`html`?(await Ro(i,jt(m,te)),(g||h)&&(process.exitCode=1)):r===`junit`?(await Ro(i,Rt(m)),(g||h)&&(process.exitCode=1)):r===`markdown`?(await Ro(i,Sn(m,te)),(g||h)&&(process.exitCode=1)):i?(await Ro(i,Kt(m,te)),(g||h)&&(process.exitCode=1)):(_o(m,te),s&&(process.stdout.write(`
52
+ `)}function Ro(e){let t=e.trim();if(/^https?:\/\//i.test(t))return t;if(t.startsWith(`sc-domain:`))return`https://${t.slice(10)}/`;if(/^[a-z0-9-]+(\.[a-z0-9-]+)+(:\d+)?(\/\S*)?$/i.test(t))return`https://${t.includes(`/`)?t:`${t}/`}`}function zo(e){return e?e.backpressure?.status===`stopped`?`stopped: ${e.backpressure.reason??`origin cooldown`}`:e.backpressure?.status===`slowed`?`slowed ${e.backpressure.delayMs}ms`:e.rendering?.status===`unavailable`?`raw HTML; rendering unavailable`:e.rendering?.status===`failed`?`raw HTML; rendering failed`:e.blocked?`blocked`:e.rendered?`rendered`:e.cache===`hit`?`cached`:e.fetched?`fetched`:e.source:`-`}function Bo(e){return e?e===`serp-framing`?`wording gap`:e===`content-gap`?`content gap`:e===`technical-check`?`technical check`:`covered`:`-`}const Vo={high:3,medium:2,low:1},Ho=b({meta:{name:`crawl`,description:`Run a fast sitemap health pass or a full technical crawl`},args:{crawlUrl:{type:`positional`,required:!1,description:`Site start URL. Optional with --sitemap-url.`},url:{type:`string`,description:`Start URL to crawl. Defaults to the --site home page.`},site:{type:`string`,description:`GSC property URL for joining page metrics.`},...Ao,mode:{type:`string`,description:`Crawl mode: site, page, list, sitemap, or sites. Start with sitemap --health for large sites. sites checks robots.txt, the home page and llms.txt for up to 1,000 sites from --urls or --urls-file.`},health:{type:`boolean`,default:!1,description:`Run the uncached sitemap status and redirect pass before a full audit. No page-body analysis.`},"sitemap-url":{type:`string`,description:`Explicit sitemap URL. Selects sitemap mode when --mode is omitted.`},urls:{type:`string`,description:`Comma-separated URLs for list mode, or sites for sites mode.`},"urls-file":{type:`string`,description:`File with one URL per line for list mode, or one site per line for sites mode.`},"max-pages":{type:`string`,description:`Maximum pages to crawl, up to 10,000. Defaults to 500.`},"max-depth":{type:`string`,description:`Maximum click depth, up to 64. Defaults to 16.`},concurrency:{type:`string`,description:`Parallel page fetches, up to 16. Defaults to 8, or progressively up to 4 with --health. In sites mode, sites checked at once.`},"fetch-interval-cap":{type:`string`,description:`Maximum page fetches per interval per host.`},"fetch-interval-ms":{type:`string`,description:`Fetch rate interval in milliseconds.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache and fetch fresh pages.`},include:{type:`string`,description:`Comma-separated URL patterns to include.`},exclude:{type:`string`,description:`Comma-separated URL patterns to exclude.`},"no-sitemap":{type:`boolean`,default:!1,description:`Do not seed URLs from sitemap.xml.`},"no-robots":{type:`boolean`,default:!1,description:`Do not skip URLs disallowed by robots.txt.`},"no-external":{type:`boolean`,default:!1,description:`Do not check external links. Reserved for full link checks.`},js:{type:`boolean`,default:!1,description:`Legacy alias for --rendering on.`},rendering:{type:`string`,description:`JavaScript rendering mode: auto, on, or off. Defaults to auto.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON. Alias for --format json, or --format jsonl in sites mode.`},format:{type:`string`,description:`Output format: pretty, json, csv, html, markdown, or junit. JUnit requires --health. Sites mode takes jsonl or pretty.`},output:{type:`string`,description:`Write output to this path instead of stdout.`},csv:{type:`string`,description:`CSV table to render: issues or pages. Defaults to issues.`},severity:{type:`string`,description:`Only show top fixes at this severity.`},"fail-on":{type:`string`,description:`Exit non-zero when issues exist at this severity or above.`}},run:async({args:e})=>{let t=Uo(e.mode);if(t===`sites`){await Fo(e,await Jo(e));return}let n=A(e),r=Ko(e.format,n),i=w(e.output),a=qo(e.csv),o=Wo(e.severity),s=Wo(e[`fail-on`]),c=await Jo(e),l=Go(e),u=w(e[`sitemap-url`]),d=T(e.health);if(r===`junit`&&!d)throw new g(`INVALID_INPUT`,`--format junit requires --health.`);if((d||u)&&t&&t!==`sitemap`)throw new g(`INVALID_INPUT`,`--health and --sitemap-url require sitemap mode.`);if(d&&E(e,`sitemap`))throw new g(`INVALID_INPUT`,`--health cannot be combined with --no-sitemap.`);if((d||u)&&c.length)throw new g(`INVALID_INPUT`,`--health and --sitemap-url cannot be combined with URL list input.`);let f=w(e.site),ee=(l?Ro(l)??l:void 0)??(f?Ro(f):void 0)??(u?new URL(`/`,u).toString():void 0)??c[0];if(!ee)throw new g(`INVALID_INPUT`,"No crawl URL given. Pass a URL, --url or --site. Run `seo sites` to list your Search Console properties.");let p=await Nn({url:ee,site:f,mode:t??(d||u?`sitemap`:c.length?`list`:void 0),strategy:d?`health`:`full`,sitemapUrl:u,urls:c,maxPages:D(e[`max-pages`]),maxDepth:D(e[`max-depth`]),concurrency:D(e.concurrency),refresh:T(e.refresh),fetchRate:wi({...e,"fetch-concurrency":e.concurrency}),include:k(e.include),exclude:k(e.exclude),googleAnalyticsPropertyId:w(e[`google-analytics-property`]),analyticsConnection:jo(e),useSitemap:!E(e,`sitemap`),respectRobots:!E(e,`robots`),checkExternal:!E(e,`external`),js:bi(e)}),te=Ke(p,{severity:o}),m=s?p.issues.some(e=>Vo[e.severity]>=Vo[s]):!1,h=p.status===`failed`,ne={...p,topFixes:te,reviewObservations:nr(p,{severity:o}),...s?{failOn:s,failedThreshold:m}:{}};r===`json`?(await So(i,ne),(h||m)&&(process.exitCode=1)):r===`csv`?(await Xo(i,a===`pages`?or(p):Yt(p)),(h||m)&&(process.exitCode=1)):r===`html`?(await Xo(i,Gt(p,te)),(h||m)&&(process.exitCode=1)):r===`junit`?(await Xo(i,vt(p)),(h||m)&&(process.exitCode=1)):r===`markdown`?(await Xo(i,Jn(p,te)),(h||m)&&(process.exitCode=1)):i?(await Xo(i,Et(p,te)),(h||m)&&(process.exitCode=1)):(ko(p,te),s&&(process.stdout.write(`
52
53
  Run metadata
53
- `),R([[`Fail threshold`,s]])),(g||h)&&(process.exitCode=1))}});function jo(e){let t=T(e);if(t){if([`site`,`page`,`list`,`sitemap`,`sites`].includes(t))return t;throw new d(`INVALID_INPUT`,`Mode must be one of: site, page, list, sitemap, sites.`)}}function Mo(e){let t=T(e);if(t){if([`low`,`medium`,`high`].includes(t))return t;throw new d(`INVALID_INPUT`,`Severity must be one of: low, medium, high.`)}}function No(e){let t=T(e.crawlUrl),n=T(e.url);if(t&&n&&t!==n)throw new d(`INVALID_INPUT`,`Use either a URL argument or --url, not both.`);return t??n}function Po(e,t){let n=T(e);if(t&&n&&n!==`json`)throw new d(`INVALID_INPUT`,`Use either --json or --format, not both.`);if(!n)return t?`json`:`pretty`;if([`pretty`,`json`,`csv`,`html`,`markdown`,`junit`].includes(n))return n;throw new d(`INVALID_INPUT`,`Format must be one of: pretty, json, csv, html, markdown, junit.`)}function Fo(e){let t=T(e);if(!t)return`issues`;if([`issues`,`pages`].includes(t))return t;throw new d(`INVALID_INPUT`,`CSV table must be one of: issues, pages.`)}async function Io(e){let t=A(e.urls)??[],n=T(e[`urls-file`]);return n&&t.push(...Lo(await b(n,`utf8`))),[...new Set(t)]}function Lo(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`))}async function Ro(e,t){e?(await Ar(_(e),{recursive:!0}),await Fr(e,t),process.stdout.write(`Wrote ${e}\n`)):process.stdout.write(t)}const zo=x({meta:{name:`gsc-query`,description:`Run a raw Search Console Search Analytics query`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},account:{type:`string`,description:`Saved Google account email.`},"start-date":{type:`string`,description:`Start date YYYY-MM-DD.`},"end-date":{type:`string`,description:`End date YYYY-MM-DD. Without dates: the last 28 days of final data.`},dimensions:{type:`string`,description:`Comma-separated GSC dimensions, for example query,page.`},type:{type:`string`,description:`Search type. Defaults to web.`},limit:{type:`string`,description:`Maximum rows to request and print.`},body:{type:`string`,description:`Raw Search Analytics JSON body.`},"body-file":{type:`string`,description:`Path to a Search Analytics JSON body file.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},refresh:{type:`boolean`,default:!1,description:`Bypass local cache and fetch fresh GSC data.`}},run:async({args:e})=>{let t=await yi(e.body,e[`body-file`])??{startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),dimensions:A(e.dimensions)??[`query`,`page`],type:T(e.type)??`web`,rowLimit:O(e.limit),dataState:`final`};try{Object.assign(t,Wn({startDate:T(t.startDate),endDate:T(t.endDate)},28))}catch(e){throw f(e)}let n=j(e),r=M(T(e.site)??T(t.siteUrl));delete t.siteUrl;let i=await qn(r,t,{refresh:E(e.refresh),accountEmail:T(e.account)}),a=O(e.limit),o=a?i.rows.slice(0,a):i.rows;n?L({site:r,request:t,...i,rows:o,rowsReturned:o.length}):(K({title:`Search Console query`,target:r,status:i.rowsFetched>o.length?`unknown`:`info`,summary:`${o.length} rows returned from ${i.rowsFetched} fetched rows.`,metrics:[{label:`Rows returned`,value:o.length},{label:`Rows fetched`,value:i.rowsFetched},{label:`API calls`,value:i.calls}]}),z([`Keys`,`Clicks`,`Impr`,`CTR`,`Pos`],o.slice(0,25).map(e=>[e.keys.join(` | `),Math.round(e.clicks),Math.round(e.impressions),e.ctr.toFixed(3),e.position.toFixed(1)])))}}),Bo=x({meta:{name:`url-inspect`,description:`Inspect a URL with the Search Console URL Inspection API`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},account:{type:`string`,description:`Saved Google account email.`},url:{type:`string`,description:`URL to inspect.`},language:{type:`string`,description:`Optional inspection language code.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=j(e),n=M(T(e.site)),r=T(e.url);if(!r)throw Error(`Pass --url.`);let i=await qe({siteUrl:n,inspectionUrl:r,accountEmail:T(e.account),languageCode:T(e.language)});if(t){L(i);return}let a=i.inspectionResult?.indexStatusResult;K({title:`URL Inspection`,target:r,status:a===void 0?`unknown`:a.verdict===`PASS`?`pass`:`warning`,summary:a===void 0?`Google did not return index status evidence for this URL.`:`${a.verdict??`Unknown`}: ${a.coverageState??`Coverage state unavailable`}.`,metrics:[{label:`Property`,value:n},{label:`Robots`,value:a?.robotsTxtState??`Unknown`},{label:`Last crawl`,value:a?.lastCrawlTime??`Unknown`},{label:`Google canonical`,value:a?.googleCanonical??`Unknown`}]})}}),Vo={days:{cli:`days`,arg:{type:`string`,description:`GSC lookback window. Defaults to 28.`}},recentDays:{cli:`recent`,arg:{type:`string`,description:`Recent anomaly window in days. Defaults to 14.`}},range:{cli:`days`,arg:{type:`string`,description:`GSC lookback window. Defaults to 28.`}},limit:{cli:`limit`,arg:{type:`string`,description:`Maximum rows to return.`}},checkLimit:{cli:`check-limit`,arg:{type:`string`,description:`Maximum candidate pages to fetch and check.`}},minImpressions:{cli:`min-impressions`,arg:{type:`string`,description:`Minimum query impressions.`}},includeBrand:{cli:`include-brand`,arg:{type:`boolean`,default:!1,description:`Include branded queries in opportunity reports.`}},verifyContent:{cli:`verify-content`,arg:{type:`boolean`,default:!1,description:`Verify top opportunities against page title, meta, and content.`}},verifyLimit:{cli:`verify-limit`,arg:{type:`string`,description:`Maximum opportunity URLs to verify.`}},js:{cli:`js`,arg:{type:`boolean`,default:!1,description:`Force JavaScript rendering for verified pages.`}},fetchConcurrency:{cli:`fetch-concurrency`,arg:{type:`string`,description:`Maximum concurrent page fetches per host, up to 16. Defaults to 4.`}},fetchIntervalCap:{cli:`fetch-interval-cap`,arg:{type:`string`,description:`Maximum page fetches per interval per host. Defaults to 4.`}},fetchIntervalMs:{cli:`fetch-interval-ms`,arg:{type:`string`,description:`Fetch rate interval in milliseconds. Defaults to 1000.`}},refresh:{cli:`refresh`,arg:{type:`boolean`,default:!1,description:`Bypass local cache and fetch fresh data.`}}};function X(e,t={}){return Object.fromEntries(e.map(e=>{let n=Vo[e];return[n.cli,{...n.arg,...t[e]}]}))}function Ho(e){return e.toLocaleString(`en-GB`,{maximumFractionDigits:e>=100?0:1})}function Uo(e){if(e===null)return`n/a`;let t=Math.abs(e)>=10?e.toFixed(0):e.toFixed(1);return`${e>0?`+`:``}${t}%`}const Wo=x({meta:{name:`traffic-anomaly`,description:`Detect unusual recent GSC traffic movement`},args:{site:{type:`string`},...X([`days`,`recentDays`,`refresh`],{days:{description:`Baseline window length in days. Defaults to 90.`},recentDays:{description:`Recent anomaly window in days. Defaults to 7.`},refresh:{description:`Bypass local cache and fetch fresh GSC data.`}}),json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=j(e),n=await c({site:M(T(e.site)),days:O(e.days),recentDays:O(e.recent),refresh:E(e.refresh)});t?L(n):(K({title:`Traffic anomaly report`,target:n.site,status:n.coverage?.status===`complete`?n.anomalies.some(e=>e.significant)?`warning`:`pass`:`unknown`,summary:n.anomalies.some(e=>e.significant)?`At least one recent metric moved beyond the report threshold.`:`No significant recent movement was found in the retained evidence.`,metrics:[{label:`Metrics checked`,value:n.anomalies.length},{label:`Significant`,value:n.anomalies.filter(e=>e.significant).length},{label:`Observed days`,value:n.coverage?.observedDays??`Unavailable`},{label:`Expected days`,value:n.coverage?.expectedDays??`Unavailable`}]}),q([`Metric`,`Direction`,`Baseline/day`,`Recent/day`,`Change`,`z`,`Significant`],n.anomalies.map(e=>[e.metric,e.direction,Ho(e.baselineMean),Ho(e.comparisonMean),Uo(e.percentChange),e.zScore??`n/a`,e.significant?`yes`:`no`])),n.coverage&&Y(`Evidence coverage`,[`${n.coverage.observedDays} of ${n.coverage.expectedDays} requested calendar days returned date aggregates.`,...n.coverage.caveats]))}}),Go=x({meta:{name:`update-correlate`,description:`Compare traffic movement with official Google update windows`},args:{site:{type:`string`},...X([`days`,`recentDays`,`refresh`],{days:{description:`Baseline window length in days. Defaults to 90.`},recentDays:{description:`Recent anomaly window in days. Defaults to 7.`},refresh:{description:`Bypass local cache and fetch fresh GSC data.`}}),"padding-days":{type:`string`,description:`Days around update windows to count as overlap.`},"known-change":{type:`string`,description:`Manual site-side change to treat as a confounder, for example pruning pages or blocking traffic.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=j(e),n=M(T(e.site)),r=await tt({site:n,days:O(e.days),recentDays:O(e.recent),paddingDays:O(e[`padding-days`]),knownConfounders:T(e[`known-change`])?[T(e[`known-change`])??``]:void 0,refresh:E(e.refresh)});t?L(r):(K({title:`Google update correlation`,target:r.site,status:`unknown`,summary:r.summary,metrics:[{label:`Classification`,value:r.classification.replaceAll(`-`,` `)},{label:`Attribution`,value:r.attribution.replaceAll(`-`,` `)},{label:`Confidence`,value:r.confidence},{label:`Updates matched`,value:r.overlappingUpdates.length},{label:`Known confounders`,value:r.confounders.length},{label:`Source`,value:r.source.name}]}),Y(`Evidence`,r.evidence),Y(`Report caveats`,r.caveats),Y(`Recommended next checks`,r.actions),q([`Metric`,`Direction`,`Baseline/day`,`Recent/day`,`Change`,`z`],r.anomalies.map(e=>[e.metric,e.direction,Ho(e.baselineMean),Ho(e.comparisonMean),Uo(e.percentChange),e.zScore??`n/a`])),r.overlappingUpdates.length&&(process.stdout.write(`
54
+ `),L([[`Fail threshold`,s]])),(h||m)&&(process.exitCode=1))}});function Uo(e){let t=w(e);if(t){if([`site`,`page`,`list`,`sitemap`,`sites`].includes(t))return t;throw new g(`INVALID_INPUT`,`Mode must be one of: site, page, list, sitemap, sites.`)}}function Wo(e){let t=w(e);if(t){if([`low`,`medium`,`high`].includes(t))return t;throw new g(`INVALID_INPUT`,`Severity must be one of: low, medium, high.`)}}function Go(e){let t=w(e.crawlUrl),n=w(e.url);if(t&&n&&t!==n)throw new g(`INVALID_INPUT`,`Use either a URL argument or --url, not both.`);return t??n}function Ko(e,t){let n=w(e);if(t&&n&&n!==`json`)throw new g(`INVALID_INPUT`,`Use either --json or --format, not both.`);if(!n)return t?`json`:`pretty`;if([`pretty`,`json`,`csv`,`html`,`markdown`,`junit`].includes(n))return n;throw new g(`INVALID_INPUT`,`Format must be one of: pretty, json, csv, html, markdown, junit.`)}function qo(e){let t=w(e);if(!t)return`issues`;if([`issues`,`pages`].includes(t))return t;throw new g(`INVALID_INPUT`,`CSV table must be one of: issues, pages.`)}async function Jo(e){let t=k(e.urls)??[],n=w(e[`urls-file`]);return n&&t.push(...Yo(await y(n,`utf8`))),[...new Set(t)]}function Yo(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`))}async function Xo(e,t){e?(await Ir(_r(e),{recursive:!0}),await Vr(e,t),process.stdout.write(`Wrote ${e}\n`)):process.stdout.write(t)}const Zo=b({meta:{name:`gsc-query`,description:`Run a raw Search Console Search Analytics query`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},account:{type:`string`,description:`Saved Google account email.`},"start-date":{type:`string`,description:`Start date YYYY-MM-DD.`},"end-date":{type:`string`,description:`End date YYYY-MM-DD. Without dates: the last 28 days of final data.`},dimensions:{type:`string`,description:`Comma-separated GSC dimensions, for example query,page.`},type:{type:`string`,description:`Search type. Defaults to web.`},limit:{type:`string`,description:`Maximum rows to request and print.`},body:{type:`string`,description:`Raw Search Analytics JSON body.`},"body-file":{type:`string`,description:`Path to a Search Analytics JSON body file.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},refresh:{type:`boolean`,default:!1,description:`Bypass local cache and fetch fresh GSC data.`}},run:async({args:e})=>{let t=await Ti(e.body,e[`body-file`])??{startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),dimensions:k(e.dimensions)??[`query`,`page`],type:w(e.type)??`web`,rowLimit:D(e.limit),dataState:`final`};try{Object.assign(t,f({startDate:w(t.startDate),endDate:w(t.endDate)},28))}catch(e){throw p(e)}let n=A(e),r=j(w(e.site)??w(t.siteUrl));delete t.siteUrl;let i=await cn(r,t,{refresh:T(e.refresh),accountEmail:w(e.account)}),a=D(e.limit),o=a?i.rows.slice(0,a):i.rows;n?I({site:r,request:t,...i,rows:o,rowsReturned:o.length}):(K({title:`Search Console query`,target:r,status:i.rowsFetched>o.length?`unknown`:`info`,summary:`${o.length} rows returned from ${i.rowsFetched} fetched rows.`,metrics:[{label:`Rows returned`,value:o.length},{label:`Rows fetched`,value:i.rowsFetched},{label:`API calls`,value:i.calls}]}),R([`Keys`,`Clicks`,`Impr`,`CTR`,`Pos`],o.slice(0,25).map(e=>[e.keys.join(` | `),Math.round(e.clicks),Math.round(e.impressions),e.ctr.toFixed(3),e.position.toFixed(1)])))}}),Qo=b({meta:{name:`url-inspect`,description:`Inspect a URL with the Search Console URL Inspection API`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},account:{type:`string`,description:`Saved Google account email.`},url:{type:`string`,description:`URL to inspect.`},language:{type:`string`,description:`Optional inspection language code.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=A(e),n=j(w(e.site)),r=w(e.url);if(!r)throw Error(`Pass --url.`);let a=await i({siteUrl:n,inspectionUrl:r,accountEmail:w(e.account),languageCode:w(e.language)});if(t){I(a);return}let o=a.inspectionResult?.indexStatusResult;K({title:`URL Inspection`,target:r,status:o===void 0?`unknown`:o.verdict===`PASS`?`pass`:`warning`,summary:o===void 0?`Google did not return index status evidence for this URL.`:`${o.verdict??`Unknown`}: ${o.coverageState??`Coverage state unavailable`}.`,metrics:[{label:`Property`,value:n},{label:`Robots`,value:o?.robotsTxtState??`Unknown`},{label:`Last crawl`,value:o?.lastCrawlTime??`Unknown`},{label:`Google canonical`,value:o?.googleCanonical??`Unknown`}]})}}),$o={days:{cli:`days`,arg:{type:`string`,description:`GSC lookback window. Defaults to 28.`}},recentDays:{cli:`recent`,arg:{type:`string`,description:`Recent anomaly window in days. Defaults to 14.`}},range:{cli:`days`,arg:{type:`string`,description:`GSC lookback window. Defaults to 28.`}},limit:{cli:`limit`,arg:{type:`string`,description:`Maximum rows to return.`}},checkLimit:{cli:`check-limit`,arg:{type:`string`,description:`Maximum candidate pages to fetch and check.`}},minImpressions:{cli:`min-impressions`,arg:{type:`string`,description:`Minimum query impressions.`}},includeBrand:{cli:`include-brand`,arg:{type:`boolean`,default:!1,description:`Include branded queries in opportunity reports.`}},verifyContent:{cli:`verify-content`,arg:{type:`boolean`,default:!1,description:`Verify top opportunities against page title, meta, and content.`}},verifyLimit:{cli:`verify-limit`,arg:{type:`string`,description:`Maximum opportunity URLs to verify.`}},js:{cli:`js`,arg:{type:`boolean`,default:!1,description:`Force JavaScript rendering for verified pages.`}},fetchConcurrency:{cli:`fetch-concurrency`,arg:{type:`string`,description:`Maximum concurrent page fetches per host, up to 16. Defaults to 4.`}},fetchIntervalCap:{cli:`fetch-interval-cap`,arg:{type:`string`,description:`Maximum page fetches per interval per host. Defaults to 4.`}},fetchIntervalMs:{cli:`fetch-interval-ms`,arg:{type:`string`,description:`Fetch rate interval in milliseconds. Defaults to 1000.`}},refresh:{cli:`refresh`,arg:{type:`boolean`,default:!1,description:`Bypass local cache and fetch fresh data.`}}};function X(e,t={}){return Object.fromEntries(e.map(e=>{let n=$o[e];return[n.cli,{...n.arg,...t[e]}]}))}function es(e){return e.toLocaleString(`en-GB`,{maximumFractionDigits:e>=100?0:1})}function ts(e){if(e===null)return`n/a`;let t=Math.abs(e)>=10?e.toFixed(0):e.toFixed(1);return`${e>0?`+`:``}${t}%`}const ns=b({meta:{name:`traffic-anomaly`,description:`Detect unusual recent GSC traffic movement`},args:{site:{type:`string`},...X([`days`,`recentDays`,`refresh`],{days:{description:`Baseline window length in days. Defaults to 90.`},recentDays:{description:`Recent anomaly window in days. Defaults to 7.`},refresh:{description:`Bypass local cache and fetch fresh GSC data.`}}),json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=A(e),n=await de({site:j(w(e.site)),days:D(e.days),recentDays:D(e.recent),refresh:T(e.refresh)});t?I(n):(K({title:`Traffic anomaly report`,target:n.site,status:n.coverage?.status===`complete`?n.anomalies.some(e=>e.significant)?`warning`:`pass`:`unknown`,summary:n.anomalies.some(e=>e.significant)?`At least one recent metric moved beyond the report threshold.`:`No significant recent movement was found in the retained evidence.`,metrics:[{label:`Metrics checked`,value:n.anomalies.length},{label:`Significant`,value:n.anomalies.filter(e=>e.significant).length},{label:`Observed days`,value:n.coverage?.observedDays??`Unavailable`},{label:`Expected days`,value:n.coverage?.expectedDays??`Unavailable`}]}),q([`Metric`,`Direction`,`Baseline/day`,`Recent/day`,`Change`,`z`,`Significant`],n.anomalies.map(e=>[e.metric,e.direction,es(e.baselineMean),es(e.comparisonMean),ts(e.percentChange),e.zScore??`n/a`,e.significant?`yes`:`no`])),n.coverage&&Y(`Evidence coverage`,[`${n.coverage.observedDays} of ${n.coverage.expectedDays} requested calendar days returned date aggregates.`,...n.coverage.caveats]))}}),rs=b({meta:{name:`update-correlate`,description:`Compare traffic movement with official Google update windows`},args:{site:{type:`string`},...X([`days`,`recentDays`,`refresh`],{days:{description:`Baseline window length in days. Defaults to 90.`},recentDays:{description:`Recent anomaly window in days. Defaults to 7.`},refresh:{description:`Bypass local cache and fetch fresh GSC data.`}}),"padding-days":{type:`string`,description:`Days around update windows to count as overlap.`},"known-change":{type:`string`,description:`Manual site-side change to treat as a confounder, for example pruning pages or blocking traffic.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=A(e),n=j(w(e.site)),r=await Ce({site:n,days:D(e.days),recentDays:D(e.recent),paddingDays:D(e[`padding-days`]),knownConfounders:w(e[`known-change`])?[w(e[`known-change`])??``]:void 0,refresh:T(e.refresh)});t?I(r):(K({title:`Google update correlation`,target:r.site,status:`unknown`,summary:r.summary,metrics:[{label:`Classification`,value:r.classification.replaceAll(`-`,` `)},{label:`Attribution`,value:r.attribution.replaceAll(`-`,` `)},{label:`Confidence`,value:r.confidence},{label:`Updates matched`,value:r.overlappingUpdates.length},{label:`Known confounders`,value:r.confounders.length},{label:`Source`,value:r.source.name}]}),Y(`Evidence`,r.evidence),Y(`Report caveats`,r.caveats),Y(`Recommended next checks`,r.actions),q([`Metric`,`Direction`,`Baseline/day`,`Recent/day`,`Change`,`z`],r.anomalies.map(e=>[e.metric,e.direction,es(e.baselineMean),es(e.comparisonMean),ts(e.percentChange),e.zScore??`n/a`])),r.overlappingUpdates.length&&(process.stdout.write(`
54
55
  Updates
55
- `),z([`Start`,`End`,`Type`,`Name`],r.overlappingUpdates.map(e=>[e.start.slice(0,10),e.end?.slice(0,10)??`open`,e.type,e.name]))),no(`seo segment-impact --site ${JSON.stringify(n)} --dimension page`))}}),Ko={site:{type:`string`,description:`Search Console property, for example sc-domain:example.com.`}};function qo(e){return{type:`string`,description:`Output folder. Defaults to ./seo-export/<site>-${e}-YYYY-MM-DD.`}}function Jo(e){return e.toLowerCase().replace(/^sc-domain:/,``).replace(/^https?:\/\//,``).replace(/[^a-z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``)}function Yo(e){let t=(/* @__PURE__ */ new Date()).toISOString().slice(0,10),n=Jo(e.site);return mr(process.cwd(),`seo-export`,`${n}-${e.report}-${t}`)}async function Xo(e,t){await Ar(e,{recursive:!0});let n=[];for(let r of t){let t=mr(e,r.filename);await Fr(t,tr(r.rows,r.headers),`utf8`),n.push(t)}return n}function Zo(e,t){process.stdout.write(`Wrote ${_e(t.length,`CSV file`)} to ${e}\n`);for(let e of t)process.stdout.write(`- ${e}\n`)}const Qo=x({meta:{name:`refresh-priorities`,description:`Export the ranked SEO priority queue, score breakdowns, grouped findings, and diagnosis detail CSVs.`},args:{...Ko,out:qo(`refresh-priorities`),...X([`days`,`recentDays`,`limit`,`includeBrand`,`refresh`],{days:{description:`Diagnosis window length in days. Defaults to 90.`},limit:{description:`Maximum queue items to export. Defaults to 25.`}}),...vo,"verify-content":pi(`Verify top opportunities against page title, meta, and content. Defaults to true.`,`Skip page content verification.`),"verify-limit":{type:`string`,description:`Maximum opportunity URLs to verify. Defaults to 5.`}},run:async({args:e})=>{let t=M(T(e.site)),n=await tn({site:t,days:O(e.days),recentDays:O(e.recent),limit:O(e.limit),includeBrand:E(e[`include-brand`]),googleAnalyticsPropertyId:T(e[`google-analytics-property`]),analyticsConnection:yo(e),verifyContent:E(e[`verify-content`]),verifyLimit:O(e[`verify-limit`]),refresh:E(e.refresh)}),r=T(e.out)??Yo({report:`refresh-priorities`,site:t});Zo(r,await Xo(r,Un(n)))}}),$o=x({meta:{name:`update-postmortem`,description:`Export update postmortem attribution, findings, template movement, and segment movers.`},args:{...Ko,out:qo(`update-postmortem`),...X([`days`,`recentDays`,`limit`,`includeBrand`,`refresh`],{days:{description:`Diagnosis window length in days. Defaults to 90.`},limit:{description:`Maximum winners/losers per segment. Defaults to 20.`}}),"known-change":{type:`string`,description:`Manual site-side change to treat as a confounder, for example pruning pages or blocking traffic.`}},run:async({args:e})=>{let t=M(T(e.site)),n=await a({site:t,days:O(e.days),recentDays:O(e.recent),limit:O(e.limit),includeBrand:E(e[`include-brand`]),knownConfounders:T(e[`known-change`])?[T(e[`known-change`])??``]:void 0,refresh:E(e.refresh)}),r=T(e.out)??Yo({report:`update-postmortem`,site:t});Zo(r,await Xo(r,ci(n)))}}),es=x({meta:{name:`export`,description:`Export full report data to CSV files`},subCommands:{"update-postmortem":$o,"refresh-priorities":Qo}});function ts(e,t,n={}){if(process.platform!==`win32`)return zr(e,t,n);let r=e=>/^[\w./:=@\\-]+$/.test(e)?e:`"${e.replaceAll(`"`,`""`)}"`;return zr([e,...t].map(r).join(` `),{...n,shell:!0})}function ns(e){let t=e.platform===`win32`?gr:fr;return e.platform===`win32`?e.env.APPDATA??t.resolve(e.home,`AppData/Roaming`):e.platform===`darwin`?t.resolve(e.home,`Library/Application Support`):e.env.XDG_CONFIG_HOME??t.resolve(e.home,`.config`)}function rs(e={}){let t=e.home??lr(),n=e.platform??process.platform,r=ns({home:t,platform:n,env:e.env??process.env}),i=n===`win32`?gr:fr,a=[];if(n===`darwin`||n===`win32`){let e=i.resolve(r,`Claude`);a.push({kind:`json`,client:`claude-desktop`,label:`Claude Desktop`,path:i.resolve(e,`claude_desktop_config.json`),commandNames:[],detectionPaths:n===`darwin`?[e,`/Applications/Claude.app`]:[e]})}return a.push({kind:`json`,client:`claude-code`,label:`Claude Code`,path:i.resolve(t,`.claude.json`),includeType:!0,commandNames:[`claude`],detectionPaths:[i.resolve(t,`.claude`)]},{kind:`native`,client:`codex`,label:`Codex`,path:i.resolve(t,`.codex/config.toml`),executable:`codex`,commandNames:[`codex`],detectionPaths:[i.resolve(t,`.codex`)]},{kind:`json`,client:`cursor`,label:`Cursor`,path:i.resolve(t,`.cursor/mcp.json`),commandNames:[`cursor`,`cursor-agent`],detectionPaths:[i.resolve(t,`.cursor`),...n===`darwin`?[`/Applications/Cursor.app`]:[]]}),a}function is(e,t={}){let n=t.platform??process.platform,r=t.exists??y,i=t.nodePath??process.execPath,a=n===`win32`?[`${e}.cmd`,`${e}.exe`,e]:[e],o=(t.path??process.env.PATH??``).split(n===`win32`?`;`:`:`).filter(Boolean);for(let e of o)for(let t of a){let n=v(e,t);if(r(n))return n}for(let e of a){let t=v(_(i),e);if(r(t))return t}return e}function as(e){return is(e)!==e}function os(e={}){let t=e.targets??rs(),n=e.hasCommand??as,r=e.hasPath??y;return t.filter(e=>e.kind===`native`?e.commandNames.some(n):r(e.path)||e.detectionPaths.some(r)||e.commandNames.some(n))}const ss={insertSpaces:!0,tabSize:2,eol:`
56
- `};function cs(){return(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g,`-`)}function ls(e,t){br(_(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.${Date.now()}.tmp`,r=y(e)?Er(e).mode&511:384;Dr(n,t,{encoding:`utf8`,mode:r}),wr(n,e)}function us(e){let t=`${e}.bak-${cs()}`,n=t,r=2;for(;y(n);)n=`${t}-${r}`,r+=1;vr(e,n,_r.COPYFILE_EXCL)}function ds(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fs(e){if(!y(e.path))return{source:`{}
57
- `,config:{}};let t=xr(e.path,`utf8`),n=[],r=ri(t,n,{allowTrailingComma:!0});if(n.length>0){let t=n[0],r=t?`${ii(t.error)} at offset ${t.offset}`:`unknown parse error`;throw Error(`Cannot update ${e.path}: invalid JSONC (${r}).`)}if(!ds(r))throw Error(`Cannot update ${e.path}: config root must be an object.`);if(r.mcpServers!==void 0&&!ds(r.mcpServers))throw Error(`Cannot update ${e.path}: mcpServers must be an object.`);return{source:t,config:r}}function ps(e){return e.includes(`mcp`)&&e.includes(`serve`)&&e.some(e=>e===`seo`||e.startsWith(`seo@`)||e===`@seo/cli`)}function ms(e,t){return typeof e.command!=`string`||t.length!==3||t[1]!==`mcp`||t[2]!==`serve`||!ds(e.env)?!1:e.env.SEO_MCP_CONFIGURED_BY===`seo`}function hs(e){if(!ds(e)||!Array.isArray(e.args))return!1;let t=e.args.filter(e=>typeof e==`string`);return ps(t)||ms(e,t)}function gs(e){let t=ti(e.source,ni(e.source,[`mcpServers`,e.name??`seo`],e.value,{formattingOptions:ss}));y(e.target.path)&&us(e.target.path),ls(e.target.path,t)}function _s(e,t){let n=ts(e,t,{encoding:`utf8`});return{status:n.status,stdout:String(n.stdout??``),stderr:String(n.stderr??``),error:n.error}}function vs(e){let t=e.replaceAll(`\\`,`/`).toLowerCase();return t.includes(`/_npx/`)||t.includes(`/.npm/_npx/`)||t.includes(`/.cache/pnpm/dlx/`)}function ys(e){if(!e||!y(e))return;let t=Cr(e);return vs(t)?void 0:t}function bs(e={}){let t=ys(e.cliPath??process.argv[1]);if(t)return{command:e.nodePath??process.execPath,args:[t,`mcp`,`serve`]};let n=`seo@${e.version??Cn}`;return(e.platform??process.platform)===`win32`?{command:`cmd`,args:[`/c`,`npx`,`-y`,n,`mcp`,`serve`]}:{command:`npx`,args:[`-y`,n,`mcp`,`serve`]}}function xs(e=!1,t=bs()){let n=gt(),r={command:t.command,args:t.args,env:{SEO_CONFIG_DIR:n.configDir,SEO_MCP_CONFIGURED_BY:`seo`}};return e&&(r.type=`stdio`),r}function Ss(e){return e.includes(`SEO_MCP_CONFIGURED_BY`)||/args:\s+-y\s+(?:seo(?:@\S+)?|@seo\/cli)\s+mcp\s+serve\b/.test(e)}function Cs(e,t,n){let r=is(e.executable),i=n.runCommand(r,[`mcp`,`get`,`seo`]);if(i.error?.code===`ENOENT`)throw Error("Cannot install SEO MCP for Codex: the `codex` command is not available on PATH. Install Codex CLI or choose another MCP client.");let a=i.status===0;if(a&&!Ss(i.stdout))throw Error(`Cannot ${t} SEO MCP: ${e.path} already has an unmanaged mcp_servers.seo entry.`);if(t===`install`&&a&&!n.reinstall||t===`uninstall`&&!a)return{client:e.client,path:e.path,changed:!1};if(t===`install`&&a){let e=n.runCommand(r,[`mcp`,`remove`,`seo`]);if(e.error||e.status!==0){let t=e.error?.message??e.stderr.trim()??`unknown error`;throw Error(`Cannot reinstall SEO MCP for Codex: ${t}`)}}let o=gt(),s=t===`install`?[`mcp`,`add`,`seo`,`--env`,`SEO_CONFIG_DIR=${o.configDir}`,`--env`,`SEO_MCP_CONFIGURED_BY=seo`,`--`,n.serverCommand.command,...n.serverCommand.args]:[`mcp`,`remove`,`seo`],c=n.runCommand(r,s);if(c.error||c.status!==0){let e=c.error?.message??c.stderr.trim()??`unknown error`;throw Error(`Cannot ${t} SEO MCP for Codex: ${e}`)}return{client:e.client,path:e.path,changed:!0}}function ws(e,t={}){let n={runCommand:t.runCommand??_s,reinstall:t.reinstall??!1,serverCommand:t.serverCommand??bs()};if(e.kind===`native`)return Cs(e,`install`,n);let{source:r,config:i}=fs(e),a=i.mcpServers?.seo,o=xs(e.includeType,n.serverCommand);if(Ir(a,o)&&!n.reinstall)return{client:e.client,path:e.path,changed:!1};if(a!==void 0&&!hs(a))throw Error(`Cannot install SEO MCP: ${e.path} already has an unmanaged mcpServers.seo entry.`);return gs({target:e,source:r,value:o}),{client:e.client,path:e.path,changed:!0}}function Ts(e,t={}){if(e.kind===`native`)return Cs(e,`uninstall`,{runCommand:t.runCommand??_s,reinstall:!1,serverCommand:bs()});if(!y(e.path))return{client:e.client,path:e.path,changed:!1};let{source:n,config:r}=fs(e),i=r.mcpServers;if(i?.seo===void 0)return{client:e.client,path:e.path,changed:!1};if(!hs(i.seo))throw Error(`Cannot uninstall SEO MCP: ${e.path} has an unmanaged mcpServers.seo entry.`);return gs({target:e,source:n,value:void 0}),{client:e.client,path:e.path,changed:!0}}const Es=`https://seoskill.dev/mcp`,Ds=`seoskill`;function Os(e){return e.client!==`claude-desktop`}function ks(e){return e.includeType?{type:`http`,url:Es}:{url:Es}}function As(e){return ds(e)&&e.url===`https://seoskill.dev/mcp`}function js(e,t={}){if(!Os(e))throw Error(`${e.label} takes the hosted server from its Connectors settings, not its config file.`);if(e.kind===`native`){let n=t.runCommand??_s,r=is(e.executable),i=n(r,[`mcp`,`get`,Ds]);if(i.error?.code===`ENOENT`)throw Error("Cannot add the hosted MCP server for Codex: the `codex` command is not available on PATH.");if(i.status===0){if(i.stdout.includes(`https://seoskill.dev/mcp`))return{client:e.client,path:e.path,changed:!1};throw Error(`Cannot add the hosted MCP server: ${e.path} already has a different mcp_servers.${Ds} entry.`)}let a=n(r,[`mcp`,`add`,Ds,`--url`,Es]);if(a.error||a.status!==0){let e=a.error?.message??a.stderr.trim()??`unknown error`;throw Error(`Cannot add the hosted MCP server for Codex: ${e}`)}return{client:e.client,path:e.path,changed:!0}}let{source:n,config:r}=fs(e),i=r.mcpServers?.[Ds];if(As(i))return{client:e.client,path:e.path,changed:!1};if(i!==void 0)throw Error(`Cannot add the hosted MCP server: ${e.path} already has a different mcpServers.${Ds} entry.`);return gs({target:e,source:n,value:ks(e),name:Ds}),{client:e.client,path:e.path,changed:!0}}const Ms=e=>process.stdout.write(`${e}\n`);async function Ns(){let{google:e,bing:t,keys:n}=await lt();return{status:`linked`,google:e.map(e=>e.email),bing:t.length,keys:Object.keys(n).filter(e=>e!==`x-dataforseo-login`&&!e.startsWith(`x-clicky-`)),clicky:Object.keys(n).filter(e=>e.startsWith(ln)).length}}function Ps(e){return[`Linked to your seoskill.dev account.`,`Google: ${e.google.join(`, `)||`none`}.`,`Bing: ${e.bing?`${e.bing} linked`:`not connected (add it at ${ge}/account)`}.`,`Keys: ${e.keys.length?e.keys.map(e=>e.replace(/^x-|-(key|password)$/g,``)).join(`, `):`none`}.`,`Clicky: ${e.clicky?`${e.clicky} site${e.clicky===1?``:`s`}`:`none`}.`,`Next: seo sites, then seo report --site <site>.`].join(`
58
- `)}const Fs=x({meta:{name:`login`,description:`Link this machine to your seoskill.dev account: its Google accounts, Bing and keys`},args:{json:{type:`boolean`,default:!1,description:`Print JSON.`}},run:async({args:e})=>{let t=j(e),n=async()=>{let e=await Ns();t?L(e):Ms(Ps(e))};if(process.env.SEO_TOKEN?.trim()){await n();return}if(In()){let e=await Le();if(e===`linked`)return n();if(e===`pending`&&!I({json:t})){let e=In();t?L({status:`pending`,...Ls(e)}):Ms(`Waiting for approval. Open ${e?.url} and click "Link this machine", then run \`seo login\` again.`);return}}else if(ot()){await n();return}let r=In()??await hn();if(!I({json:t}))t?L({status:`pending`,...Ls(r)}):Ms([`Open this link in the person's browser and ask them to approve it:`,r.url,`Code: ${r.code}. After they approve, run \`seo login\` again.`].join(`
59
- `));else{if(await Is())return n();Ms("The login expired. Run `seo login` again."),process.exitCode=1}}});async function Is(){let e=In()??await hn();for(Ms(`Opening ${e.url}\nApprove code ${e.code} there. Waiting…`),await Ft(e.url);In();){await new Promise(e=>setTimeout(e,3e3));let e=await Le();if(e===`linked`)return!0;if(e===`expired`)break}return!1}const Ls=e=>({url:e?.url,code:e?.code}),Rs=x({meta:{name:`logout`,description:`Unlink this machine from your seoskill.dev account`},args:{json:{type:`boolean`,default:!1,description:`Print JSON.`}},run:async({args:e})=>{let t=await ft();j(e)?L({unlinked:t}):Ms(t?`This machine is no longer linked to your seoskill.dev account.`:`This machine was not linked.`)}});function zs(e={}){let t=ts(`npx`,[`-y`,`skills`,`add`,`iannuttall/seo`],{stdio:e.quiet?`ignore`:`inherit`});return t.error?{status:`failed`,error:t.error.message}:t.status===0?{status:`installed`}:{status:`failed`,error:`npx skills add exited with status ${t.status??`unknown`}.`}}async function Bs(e){let t=async()=>{let{google:e}=await lt().catch(()=>({google:[]}));return{status:`linked`,accountEmail:e.map(e=>e.email).join(`, `)||void 0}};if(process.env.SEO_TOKEN?.trim()||ot())return t();if(!e.interactive)return null;let n=B(await Yr({message:`How do you want to sign in?`,options:[{value:`account`,label:`Sign in or create a free seoskill.dev account`,hint:`Recommended. Your Google accounts, Bing and keys in one place, for the CLI and the hosted MCP`},{value:`local`,label:`Sign in with Google on this machine only`},{value:`skip`,label:`Skip for now`}]}));return n===`skip`?{status:`skipped`}:n===`local`?null:await Is()?t():(S("The link expired. Run `seo login` to try again.",`Not signed in`),{status:`skipped`})}function Vs(e){let t={value:`skip`,label:`Skip for now`};return e.sharedConfigured||e.byoConfigured?[{value:`login`,label:`Connect Google`,hint:`Opens your browser for read-only Search Console and Google Analytics access`},t]:[{value:`setup`,label:`Set up Google login for local development`,hint:`This source checkout does not include the public app credentials`},t]}async function Hs(){let e=await Ua();return S(`Connected as ${e.account_email}. seo has read-only access and cannot change your site.`,`Google connected`),{status:`connected`,accountEmail:e.account_email}}async function Us(e){let n=await Be();if(n.activeMode===`service-account`)return{status:`service-account`,accountEmail:n.identity};if(!e.interactive){if(n.tokens)return{status:`already-connected`,accountEmail:n.tokens.account_email};throw new d(`AUTH_REQUIRED`,t())}let r=Ze();if(r.length>0){let e=B(await Yr({message:`Google account to use`,options:[...r.map(e=>({value:{type:`account`,accountEmail:e.accountEmail},label:e.accountEmail,hint:e.active?`Current default`:void 0})),{value:{type:`connect`},label:`Connect another Google account`}]}));if(e.type===`account`)return se(e.accountEmail),{status:`already-connected`,accountEmail:e.accountEmail};if(n.sharedConfigured||n.byoConfigured)return Hs()}let i=B(await Yr({message:`Connect Google now?`,options:Vs({sharedConfigured:n.sharedConfigured,byoConfigured:n.byoConfigured})}));if(i===`skip`)return{status:`skipped`};if(i===`setup`){let e=B(await Xr({message:`Google Desktop OAuth client ID`,validate:e=>e?void 0:`Client ID is required`})),t=B(await Jr({message:`Google Desktop OAuth client secret`,validate:e=>e?void 0:`Client secret is required`}));En({clientId:e,clientSecret:t})}return Hs()}async function Ws(){return B(await Ur({message:`Install the SEO skill so your agents know how to use seo?`,initialValue:!0}))?zs():{status:`declined`}}async function Gs(){let e=os();if(e.length===0)return[];let t=B(await Yr({message:`Add an MCP server to your agents?`,options:[{value:`hosted`,label:`Free hosted server (recommended)`,hint:`${Es}, your agent asks you to sign in with Google`},{value:`local`,label:`Local server`,hint:`Runs on this machine with the sign-in from this setup`},{value:`skip`,label:`Skip for now`}]}));if(t===`skip`)return[];let n=B(await qr({message:`Which agents?`,options:e.map(e=>({value:e.client,label:e.label,hint:e.path})),initialValues:e.map(e=>e.client)})),r=e.filter(e=>n.includes(e.client)).map(e=>{let n=t===`hosted`&&Os(e)?`hosted`:`local`;try{return{...n===`hosted`?js(e):ws(e),server:n}}catch(t){return{client:e.client,path:e.path,server:n,changed:!1,error:t instanceof Error?t.message:String(t)}}});return t===`hosted`&&r.some(e=>e.client===`claude-desktop`)&&S(`Claude Desktop got the local server. To use the hosted one there, open Settings, then Connectors, and add ${Es} as a custom connector.`,`Claude Desktop`),r}const Ks=[`seo sites`,`seo report --site <site>`],qs=[`Sign in or create your free seoskill.dev account, or sign in with Google on this machine only (read-only Search Console and Google Analytics).`,`Add the free hosted MCP server (${Es}) or a local one to your agents.`,`Install the SEO skill for your agents.`];function Js(e){return e.status===`skipped`?`skipped`:e.status===`linked`?`seoskill.dev account${e.accountEmail?` (${e.accountEmail})`:``}`:e.status===`service-account`?`service account${e.accountEmail?` ${e.accountEmail}`:``}`:e.accountEmail??`connected`}function Ys(e){return e.status===`installed`?`installed`:e.status===`failed`?`install failed`:`not installed`}function Xs(e){return e.length===0?`not added`:e.map(e=>e.error?`${e.client} skipped`:`${e.client} (${e.server})`).join(`, `)}function Zs(){process.stdout.write(`
60
- `),na({title:`Help other people find SEO Skill`,body:`If SEO Skill saved you time, a GitHub star helps other people find it.`,command:`https://github.com/iannuttall/seo`})}async function Qs(e){let t=j(e);if(t||Wr(process.argv[2]===`setup`?`seo setup`:`seo start`),e[`dry-run`]){t?L({dryRun:!0,steps:qs,next:Ks}):(S(qs.map((e,t)=>`${t+1}. ${e}`).join(`
61
- `),`Setup will`),S(Ks.join(`
62
- `),`Then run`),C(`Dry run complete. Nothing was changed.`));return}Ut();let n=I({json:t}),r=await Bs({interactive:n})??await Us({interactive:n}),i=n?await Gs():[],a=n?await Ws():{status:`skipped`};if(t){L({auth:r,mcp:i,skill:a,next:Ks});return}R([[`Sign-in`,Js(r)],[`MCP server`,Xs(i)],[`SEO skill`,Ys(a)]]);let o=i.filter(e=>e.error);o.length&&S(o.map(e=>`${e.client}: ${e.error}`).join(`
63
- `),`MCP setup skipped`),a.error&&S(a.error,`SEO skill install failed`),S(`seo sites list your Search Console properties
64
- seo report --site <site> run the main report for one of them`,`Try next`),C(`Setup complete.`),Zs()}const $s=x({meta:{name:`setup`,description:`Sign in with Google, then add the MCP server and skill`},args:{"dry-run":{type:`boolean`,default:!1,description:`Show what setup does without changing anything.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON. Never prompts.`}},run:async({args:e})=>Qs(e)}),ec=x({...$s,meta:{name:`start`,description:`Start here: sign in with Google, then add the MCP server and skill to your agents`}}),tc=x({...ec,meta:{name:`init`,description:"Legacy alias for `seo start`."}}),nc=x({meta:{name:`logs`,description:`Manage local log retention`},subCommands:{prune:x({meta:{name:`prune`,description:`Rotate large logs and remove old local logs`},args:{quiet:{type:`boolean`,default:!1,description:`Do not print a result.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=di();j(e)?L(t):e.quiet||process.stdout.write(`Rotated ${t.rotated} and removed ${t.removed} log files. ${da(t.sizeBytes)} retained.\n`)}})}}),rc=[{client:`claude-desktop`,flag:`claude-desktop`},{client:`claude-code`,flag:`claude-code`},{client:`codex`,flag:`codex`},{client:`cursor`,flag:`cursor`}];function ic(e,t){return E(e.all)?t:rc.filter(({flag:t})=>E(e[t])).map(({client:e})=>e)}const ac=x({meta:{name:`mcp`,description:`MCP server helpers`},subCommands:{serve:x({meta:{name:`serve`,description:`Run the SEO MCP server`},args:{test:{type:`boolean`,default:!1,description:`Start in test mode`}},run:async({args:e})=>{let{startMcpServer:t}=await import(`./dist-CeZ3yzNP.js`);await t({test:E(e.test)})}}),install:x({meta:{name:`install`,description:`Install or remove SEO MCP config for local clients`},args:{uninstall:{type:`boolean`,default:!1,description:`Remove the SEO MCP config instead of adding it`},reinstall:{type:`boolean`,default:!1,description:`Rewrite an existing managed SEO MCP config`},"claude-desktop":{type:`boolean`,default:!1,description:`Update Claude Desktop`},"claude-code":{type:`boolean`,default:!1,description:`Update Claude Code`},codex:{type:`boolean`,default:!1,description:`Update Codex CLI, app, and IDE extension`},cursor:{type:`boolean`,default:!1,description:`Update Cursor`},all:{type:`boolean`,default:!1,description:`Update every detected MCP client`},json:{type:`boolean`,default:!1,description:`Print structured JSON output`}},run:async({args:e})=>{if(E(e.uninstall)&&E(e.reinstall))throw new d(`INVALID_INPUT`,`Use either --uninstall or --reinstall, not both.`);let t=rs(),n=os({targets:t}),r=j(e),i=ic(e,n.map(e=>e.client));if(i.length===0){if(!I({json:r}))throw new d(`INVALID_INPUT`,`Choose an MCP client with --claude-desktop, --claude-code, --codex, --cursor, or --all.`);let a=n.length>0?n:t;i=B(await qr({message:e.uninstall?`Remove seo from which MCP clients?`:`Install seo into which MCP clients?`,options:a.map(e=>({value:e.client,label:e.label,hint:e.path})),initialValues:n.map(e=>e.client),required:!0}))}let a=i.filter(e=>!t.some(t=>t.client===e));if(a.length>0)throw new d(`INVALID_INPUT`,`MCP setup is not supported for ${a.join(`, `)} on ${process.platform}.`);let o=t.filter(e=>i.includes(e.client)).map(t=>E(e.uninstall)?Ts(t):ws(t,{reinstall:E(e.reinstall)}));if(r)L({operation:E(e.uninstall)?`uninstall`:`install`,results:o});else for(let e of o)process.stdout.write(`${e.changed?`updated`:`skipped`} ${e.client} · ${e.path}\n`)}})}}),oc=x({meta:{name:`index-coverage`,description:`Find crawlable pages that deserve a closer Google index check`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},url:{type:`string`,description:`Start URL to crawl. Defaults to the home page.`},sitemaps:{type:`string`,description:`Comma-separated XML sitemap URLs. Defaults to declarations captured by the crawl.`},days:{type:`string`,description:`Finalized Search Console date range. Defaults to 90 days.`},"row-limit":{type:`string`,description:`Maximum Search Console page rows. Defaults to 100000.`},"max-sitemap-urls":{type:`string`,description:`Maximum sitemap inventory URLs. Defaults to 100000.`},limit:{type:`string`,description:`Maximum URLs returned in each evidence group. Defaults to 100.`},refresh:{type:`boolean`,default:!1,description:`Bypass the local Search Console cache.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=j(e),n=M(T(e.site)),r=_i(e.sitemaps),i=await Ve({site:n,url:T(e.url),sitemaps:r.length?r:void 0,days:O(e.days),rowLimit:O(e[`row-limit`]),maxSitemapUrls:O(e[`max-sitemap-urls`]),itemsPerSection:O(e.limit),refresh:E(e.refresh)});t?L(i):(K({title:`Index coverage`,target:i.site,status:i.sources.crawl.completeness===`complete`&&i.sources.searchConsole.completeness===`complete`?i.summary.crawlableCandidatesWithoutRetainedSearchVisibility>0?`warning`:`pass`:`unknown`,summary:`${i.summary.crawlableCandidatesWithoutRetainedSearchVisibility} crawlable pages need URL Inspection review.`,metrics:[{label:`Crawl report`,value:i.input.crawlReport.id},{label:`Crawl evidence`,value:i.sources.crawl.completeness},{label:`Sitemap evidence`,value:i.sources.sitemap.completeness},{label:`Search evidence`,value:i.sources.searchConsole.completeness},{label:`Search window`,value:`${i.sources.searchConsole.startDate} to ${i.sources.searchConsole.endDate}`},{label:`Search-visible pages`,value:i.summary.retainedSearchVisibleUrls},{label:`Blocked/non-indexable`,value:i.summary.blockedOrNonIndexableCrawlUrls},{label:`Sitemap only`,value:i.summary.sitemapOnlyUrls},{label:`Search Console only`,value:i.summary.searchConsoleOnlyUrls}]}),i.crawlableWithoutRetainedSearchVisibility.items.length&&(process.stdout.write(`
56
+ `),R([`Start`,`End`,`Type`,`Name`],r.overlappingUpdates.map(e=>[e.start.slice(0,10),e.end?.slice(0,10)??`open`,e.type,e.name]))),ho(`seo segment-impact --site ${JSON.stringify(n)} --dimension page`))}}),is={site:{type:`string`,description:`Search Console property, for example sc-domain:example.com.`}};function as(e){return{type:`string`,description:`Output folder. Defaults to ./seo-export/<site>-${e}-YYYY-MM-DD.`}}function os(e){return e.toLowerCase().replace(/^sc-domain:/,``).replace(/^https?:\/\//,``).replace(/[^a-z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``)}function ss(e){let t=(/* @__PURE__ */ new Date()).toISOString().slice(0,10),n=os(e.site);return br(process.cwd(),`seo-export`,`${n}-${e.report}-${t}`)}async function cs(e,t){await Ir(e,{recursive:!0});let n=[];for(let r of t){let t=br(e,r.filename);await Vr(t,Qn(r.rows,r.headers),`utf8`),n.push(t)}return n}function ls(e,t){process.stdout.write(`Wrote ${n(t.length,`CSV file`)} to ${e}\n`);for(let e of t)process.stdout.write(`- ${e}\n`)}const us=b({meta:{name:`refresh-priorities`,description:`Export the ranked SEO priority queue, score breakdowns, grouped findings, and diagnosis detail CSVs.`},args:{...is,out:as(`refresh-priorities`),...X([`days`,`recentDays`,`limit`,`includeBrand`,`refresh`],{days:{description:`Diagnosis window length in days. Defaults to 90.`},limit:{description:`Maximum queue items to export. Defaults to 25.`}}),...Ao,"verify-content":yi(`Verify top opportunities against page title, meta, and content. Defaults to true.`,`Skip page content verification.`),"verify-limit":{type:`string`,description:`Maximum opportunity URLs to verify. Defaults to 5.`}},run:async({args:e})=>{let t=j(w(e.site)),n=await _e({site:t,days:D(e.days),recentDays:D(e.recent),limit:D(e.limit),includeBrand:T(e[`include-brand`]),googleAnalyticsPropertyId:w(e[`google-analytics-property`]),analyticsConnection:jo(e),verifyContent:T(e[`verify-content`]),verifyLimit:D(e[`verify-limit`]),refresh:T(e.refresh)}),r=w(e.out)??ss({report:`refresh-priorities`,site:t});ls(r,await cs(r,d(n)))}}),ds=b({meta:{name:`update-postmortem`,description:`Export update postmortem attribution, findings, template movement, and segment movers.`},args:{...is,out:as(`update-postmortem`),...X([`days`,`recentDays`,`limit`,`includeBrand`,`refresh`],{days:{description:`Diagnosis window length in days. Defaults to 90.`},limit:{description:`Maximum winners/losers per segment. Defaults to 20.`}}),"known-change":{type:`string`,description:`Manual site-side change to treat as a confounder, for example pruning pages or blocking traffic.`}},run:async({args:e})=>{let t=j(w(e.site)),n=await ce({site:t,days:D(e.days),recentDays:D(e.recent),limit:D(e.limit),includeBrand:T(e[`include-brand`]),knownConfounders:w(e[`known-change`])?[w(e[`known-change`])??``]:void 0,refresh:T(e.refresh)}),r=w(e.out)??ss({report:`update-postmortem`,site:t});ls(r,await cs(r,mi(n)))}}),fs=b({meta:{name:`export`,description:`Export full report data to CSV files`},subCommands:{"update-postmortem":ds,"refresh-priorities":us}});function ps(e,t,n={}){if(process.platform!==`win32`)return Gr(e,t,n);let r=e=>/^[\w./:=@\\-]+$/.test(e)?e:`"${e.replaceAll(`"`,`""`)}"`;return Gr([e,...t].map(r).join(` `),{...n,shell:!0})}function ms(e){let t=e.platform===`win32`?Sr:vr;return e.platform===`win32`?e.env.APPDATA??t.resolve(e.home,`AppData/Roaming`):e.platform===`darwin`?t.resolve(e.home,`Library/Application Support`):e.env.XDG_CONFIG_HOME??t.resolve(e.home,`.config`)}function hs(e={}){let t=e.home??mr(),n=e.platform??process.platform,r=ms({home:t,platform:n,env:e.env??process.env}),i=n===`win32`?Sr:vr,a=[];if(n===`darwin`||n===`win32`){let e=i.resolve(r,`Claude`);a.push({kind:`json`,client:`claude-desktop`,label:`Claude Desktop`,path:i.resolve(e,`claude_desktop_config.json`),commandNames:[],detectionPaths:n===`darwin`?[e,`/Applications/Claude.app`]:[e]})}return a.push({kind:`json`,client:`claude-code`,label:`Claude Code`,path:i.resolve(t,`.claude.json`),includeType:!0,commandNames:[`claude`],detectionPaths:[i.resolve(t,`.claude`)]},{kind:`native`,client:`codex`,label:`Codex`,path:i.resolve(t,`.codex/config.toml`),executable:`codex`,commandNames:[`codex`],detectionPaths:[i.resolve(t,`.codex`)]},{kind:`json`,client:`cursor`,label:`Cursor`,path:i.resolve(t,`.cursor/mcp.json`),commandNames:[`cursor`,`cursor-agent`],detectionPaths:[i.resolve(t,`.cursor`),...n===`darwin`?[`/Applications/Cursor.app`]:[]]}),a}function gs(e,t={}){let n=t.platform??process.platform,r=t.exists??v,i=t.nodePath??process.execPath,a=n===`win32`?[`${e}.cmd`,`${e}.exe`,e]:[e],o=(t.path??process.env.PATH??``).split(n===`win32`?`;`:`:`).filter(Boolean);for(let e of o)for(let t of a){let n=_(e,t);if(r(n))return n}for(let e of a){let t=_(_r(i),e);if(r(t))return t}return e}function _s(e){return gs(e)!==e}function vs(e={}){let t=e.targets??hs(),n=e.hasCommand??_s,r=e.hasPath??v;return t.filter(e=>e.kind===`native`?e.commandNames.some(n):r(e.path)||e.detectionPaths.some(r)||e.commandNames.some(n))}const ys={insertSpaces:!0,tabSize:2,eol:`
57
+ `};function bs(){return(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g,`-`)}function xs(e,t){Er(_r(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.${Date.now()}.tmp`,r=v(e)?Mr(e).mode&511:384;Nr(n,t,{encoding:`utf8`,mode:r}),Ar(n,e)}function Ss(e){let t=`${e}.bak-${bs()}`,n=t,r=2;for(;v(n);)n=`${t}-${r}`,r+=1;wr(e,n,Cr.COPYFILE_EXCL)}function Cs(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ws(e){if(!v(e.path))return{source:`{}
58
+ `,config:{}};let t=Dr(e.path,`utf8`),n=[],r=li(t,n,{allowTrailingComma:!0});if(n.length>0){let t=n[0],r=t?`${ui(t.error)} at offset ${t.offset}`:`unknown parse error`;throw Error(`Cannot update ${e.path}: invalid JSONC (${r}).`)}if(!Cs(r))throw Error(`Cannot update ${e.path}: config root must be an object.`);if(r.mcpServers!==void 0&&!Cs(r.mcpServers))throw Error(`Cannot update ${e.path}: mcpServers must be an object.`);return{source:t,config:r}}function Ts(e){return e.includes(`mcp`)&&e.includes(`serve`)&&e.some(e=>e===`seo`||e.startsWith(`seo@`)||e===`@seo/cli`)}function Es(e,t){return typeof e.command!=`string`||t.length!==3||t[1]!==`mcp`||t[2]!==`serve`||!Cs(e.env)?!1:e.env.SEO_MCP_CONFIGURED_BY===`seo`}function Ds(e){if(!Cs(e)||!Array.isArray(e.args))return!1;let t=e.args.filter(e=>typeof e==`string`);return Ts(t)||Es(e,t)}function Os(e){let t=si(e.source,ci(e.source,[`mcpServers`,e.name??`seo`],e.value,{formattingOptions:ys}));v(e.target.path)&&Ss(e.target.path),xs(e.target.path,t)}function ks(e,t){let n=ps(e,t,{encoding:`utf8`});return{status:n.status,stdout:String(n.stdout??``),stderr:String(n.stderr??``),error:n.error}}function As(e){let t=e.replaceAll(`\\`,`/`).toLowerCase();return t.includes(`/_npx/`)||t.includes(`/.npm/_npx/`)||t.includes(`/.cache/pnpm/dlx/`)}function js(e){if(!e||!v(e))return;let t=kr(e);return As(t)?void 0:t}function Ms(e={}){let t=js(e.cliPath??process.argv[1]);if(t)return{command:e.nodePath??process.execPath,args:[t,`mcp`,`serve`]};let n=`seo@${e.version??Yn}`;return(e.platform??process.platform)===`win32`?{command:`cmd`,args:[`/c`,`npx`,`-y`,n,`mcp`,`serve`]}:{command:`npx`,args:[`-y`,n,`mcp`,`serve`]}}function Ns(e=!1,t=Ms()){let n=qe(),r={command:t.command,args:t.args,env:{SEO_CONFIG_DIR:n.configDir,SEO_MCP_CONFIGURED_BY:`seo`}};return e&&(r.type=`stdio`),r}function Ps(e){return e.includes(`SEO_MCP_CONFIGURED_BY`)||/args:\s+-y\s+(?:seo(?:@\S+)?|@seo\/cli)\s+mcp\s+serve\b/.test(e)}function Fs(e,t,n){let r=gs(e.executable),i=n.runCommand(r,[`mcp`,`get`,`seo`]);if(i.error?.code===`ENOENT`)throw Error("Cannot install SEO MCP for Codex: the `codex` command is not available on PATH. Install Codex CLI or choose another MCP client.");let a=i.status===0;if(a&&!Ps(i.stdout))throw Error(`Cannot ${t} SEO MCP: ${e.path} already has an unmanaged mcp_servers.seo entry.`);if(t===`install`&&a&&!n.reinstall||t===`uninstall`&&!a)return{client:e.client,path:e.path,changed:!1};if(t===`install`&&a){let e=n.runCommand(r,[`mcp`,`remove`,`seo`]);if(e.error||e.status!==0){let t=e.error?.message??e.stderr.trim()??`unknown error`;throw Error(`Cannot reinstall SEO MCP for Codex: ${t}`)}}let o=qe(),s=t===`install`?[`mcp`,`add`,`seo`,`--env`,`SEO_CONFIG_DIR=${o.configDir}`,`--env`,`SEO_MCP_CONFIGURED_BY=seo`,`--`,n.serverCommand.command,...n.serverCommand.args]:[`mcp`,`remove`,`seo`],c=n.runCommand(r,s);if(c.error||c.status!==0){let e=c.error?.message??c.stderr.trim()??`unknown error`;throw Error(`Cannot ${t} SEO MCP for Codex: ${e}`)}return{client:e.client,path:e.path,changed:!0}}function Is(e,t={}){let n={runCommand:t.runCommand??ks,reinstall:t.reinstall??!1,serverCommand:t.serverCommand??Ms()};if(e.kind===`native`)return Fs(e,`install`,n);let{source:r,config:i}=ws(e),a=i.mcpServers?.seo,o=Ns(e.includeType,n.serverCommand);if(Hr(a,o)&&!n.reinstall)return{client:e.client,path:e.path,changed:!1};if(a!==void 0&&!Ds(a))throw Error(`Cannot install SEO MCP: ${e.path} already has an unmanaged mcpServers.seo entry.`);return Os({target:e,source:r,value:o}),{client:e.client,path:e.path,changed:!0}}function Ls(e,t={}){if(e.kind===`native`)return Fs(e,`uninstall`,{runCommand:t.runCommand??ks,reinstall:!1,serverCommand:Ms()});if(!v(e.path))return{client:e.client,path:e.path,changed:!1};let{source:n,config:r}=ws(e),i=r.mcpServers;if(i?.seo===void 0)return{client:e.client,path:e.path,changed:!1};if(!Ds(i.seo))throw Error(`Cannot uninstall SEO MCP: ${e.path} has an unmanaged mcpServers.seo entry.`);return Os({target:e,source:n,value:void 0}),{client:e.client,path:e.path,changed:!0}}const Rs=`https://seoskill.dev/mcp`,zs=`seoskill`;function Bs(e){return e.client!==`claude-desktop`}function Vs(e){return e.includeType?{type:`http`,url:Rs}:{url:Rs}}function Hs(e){return Cs(e)&&e.url===`https://seoskill.dev/mcp`}function Us(e,t={}){if(!Bs(e))throw Error(`${e.label} takes the hosted server from its Connectors settings, not its config file.`);if(e.kind===`native`){let n=t.runCommand??ks,r=gs(e.executable),i=n(r,[`mcp`,`get`,zs]);if(i.error?.code===`ENOENT`)throw Error("Cannot add the hosted MCP server for Codex: the `codex` command is not available on PATH.");if(i.status===0){if(i.stdout.includes(`https://seoskill.dev/mcp`))return{client:e.client,path:e.path,changed:!1};throw Error(`Cannot add the hosted MCP server: ${e.path} already has a different mcp_servers.${zs} entry.`)}let a=n(r,[`mcp`,`add`,zs,`--url`,Rs]);if(a.error||a.status!==0){let e=a.error?.message??a.stderr.trim()??`unknown error`;throw Error(`Cannot add the hosted MCP server for Codex: ${e}`)}return{client:e.client,path:e.path,changed:!0}}let{source:n,config:r}=ws(e),i=r.mcpServers?.[zs];if(Hs(i))return{client:e.client,path:e.path,changed:!1};if(i!==void 0)throw Error(`Cannot add the hosted MCP server: ${e.path} already has a different mcpServers.${zs} entry.`);return Os({target:e,source:n,value:Vs(e),name:zs}),{client:e.client,path:e.path,changed:!0}}const Ws=e=>process.stdout.write(`${e}\n`);async function Gs(){let{google:e,bing:t,keys:n}=await Rt();return{status:`linked`,google:e.map(e=>e.email),bing:t.length,keys:Object.keys(n).filter(e=>e!==`x-dataforseo-login`&&!e.startsWith(`x-clicky-`)),clicky:Object.keys(n).filter(e=>e.startsWith(vn)).length}}function Ks(e){return[`Linked to your seoskill.dev account.`,`Google: ${e.google.join(`, `)||`none`}.`,`Bing: ${e.bing?`${e.bing} linked`:`not connected (add it at ${t}/account)`}.`,`Keys: ${e.keys.length?e.keys.map(e=>e.replace(/^x-|-(key|password)$/g,``)).join(`, `):`none`}.`,`Clicky: ${e.clicky?`${e.clicky} site${e.clicky===1?``:`s`}`:`none`}.`,`Next: seo sites, then seo report --site <site>.`].join(`
59
+ `)}const qs=b({meta:{name:`login`,description:`Link this machine to your seoskill.dev account: its Google accounts, Bing and keys`},args:{json:{type:`boolean`,default:!1,description:`Print JSON.`}},run:async({args:e})=>{let t=A(e),n=async()=>{let e=await Gs();t?I(e):Ws(Ks(e))};if(process.env.SEO_TOKEN?.trim()){await n();return}if(wn()){let e=await Pn();if(e===`linked`)return n();if(e===`pending`&&!F({json:t})){let e=wn();t?I({status:`pending`,...Ys(e)}):Ws(`Waiting for approval. Open ${e?.url} and click "Link this machine", then run \`seo login\` again.`);return}}else if(Vn()){await n();return}let r=wn()??await Ln();if(!F({json:t}))t?I({status:`pending`,...Ys(r)}):Ws([`Open this link in the person's browser and ask them to approve it:`,r.url,`Code: ${r.code}. After they approve, run \`seo login\` again.`].join(`
60
+ `));else{if(await Js())return n();Ws("The login expired. Run `seo login` again."),process.exitCode=1}}});async function Js(){let e=wn()??await Ln();for(Ws(`Opening ${e.url}\nApprove code ${e.code} there. Waiting…`),await Ct(e.url);wn();){await new Promise(e=>setTimeout(e,3e3));let e=await Pn();if(e===`linked`)return!0;if(e===`expired`)break}return!1}const Ys=e=>({url:e?.url,code:e?.code}),Xs=b({meta:{name:`logout`,description:`Unlink this machine from your seoskill.dev account`},args:{json:{type:`boolean`,default:!1,description:`Print JSON.`}},run:async({args:e})=>{let t=await bn();A(e)?I({unlinked:t}):Ws(t?`This machine is no longer linked to your seoskill.dev account.`:`This machine was not linked.`)}});function Zs(e={}){let t=ps(`npx`,[`-y`,`skills`,`add`,`iannuttall/seo`],{stdio:e.quiet?`ignore`:`inherit`});return t.error?{status:`failed`,error:t.error.message}:t.status===0?{status:`installed`}:{status:`failed`,error:`npx skills add exited with status ${t.status??`unknown`}.`}}async function Qs(e){let t=async()=>{let{google:e}=await Rt().catch(()=>({google:[]}));return{status:`linked`,accountEmail:e.map(e=>e.email).join(`, `)||void 0}};if(process.env.SEO_TOKEN?.trim()||Vn())return t();if(!e.interactive)return null;let n=z(await ti({message:`How do you want to sign in?`,options:[{value:`account`,label:`Sign in or create a free seoskill.dev account`,hint:`Recommended. Your Google accounts, Bing and keys in one place, for the CLI and the hosted MCP`},{value:`local`,label:`Sign in with Google on this machine only`},{value:`skip`,label:`Skip for now`}]}));return n===`skip`?{status:`skipped`}:n===`local`?null:await Js()?t():(x("The link expired. Run `seo login` to try again.",`Not signed in`),{status:`skipped`})}function $s(e){let t={value:`skip`,label:`Skip for now`};return e.sharedConfigured||e.byoConfigured?[{value:`login`,label:`Connect Google`,hint:`Opens your browser for read-only Search Console and Google Analytics access`},t]:[{value:`setup`,label:`Set up Google login for local development`,hint:`This source checkout does not include the public app credentials`},t]}async function ec(){let e=await to();return x(`Connected as ${e.account_email}. seo has read-only access and cannot change your site.`,`Google connected`),{status:`connected`,accountEmail:e.account_email}}async function tc(e){let t=await et();if(t.activeMode===`service-account`)return{status:`service-account`,accountEmail:t.identity};if(!e.interactive){if(t.tokens)return{status:`already-connected`,accountEmail:t.tokens.account_email};throw new g(`AUTH_REQUIRED`,en())}let n=ye();if(n.length>0){let e=z(await ti({message:`Google account to use`,options:[...n.map(e=>({value:{type:`account`,accountEmail:e.accountEmail},label:e.accountEmail,hint:e.active?`Current default`:void 0})),{value:{type:`connect`},label:`Connect another Google account`}]}));if(e.type===`account`)return lt(e.accountEmail),{status:`already-connected`,accountEmail:e.accountEmail};if(t.sharedConfigured||t.byoConfigured)return ec()}let r=z(await ti({message:`Connect Google now?`,options:$s({sharedConfigured:t.sharedConfigured,byoConfigured:t.byoConfigured})}));if(r===`skip`)return{status:`skipped`};if(r===`setup`){let e=z(await ni({message:`Google Desktop OAuth client ID`,validate:e=>e?void 0:`Client ID is required`})),t=z(await ei({message:`Google Desktop OAuth client secret`,validate:e=>e?void 0:`Client secret is required`}));Be({clientId:e,clientSecret:t})}return ec()}async function nc(){return z(await Yr({message:`Install the SEO skill so your agents know how to use seo?`,initialValue:!0}))?Zs():{status:`declined`}}async function rc(){let e=vs();if(e.length===0)return[];let t=z(await ti({message:`Add an MCP server to your agents?`,options:[{value:`hosted`,label:`Free hosted server (recommended)`,hint:`${Rs}, your agent asks you to sign in with Google`},{value:`local`,label:`Local server`,hint:`Runs on this machine with the sign-in from this setup`},{value:`skip`,label:`Skip for now`}]}));if(t===`skip`)return[];let n=z(await $r({message:`Which agents?`,options:e.map(e=>({value:e.client,label:e.label,hint:e.path})),initialValues:e.map(e=>e.client)})),r=e.filter(e=>n.includes(e.client)).map(e=>{let n=t===`hosted`&&Bs(e)?`hosted`:`local`;try{return{...n===`hosted`?Us(e):Is(e),server:n}}catch(t){return{client:e.client,path:e.path,server:n,changed:!1,error:t instanceof Error?t.message:String(t)}}});return t===`hosted`&&r.some(e=>e.client===`claude-desktop`)&&x(`Claude Desktop got the local server. To use the hosted one there, open Settings, then Connectors, and add ${Rs} as a custom connector.`,`Claude Desktop`),r}const ic=[`seo sites`,`seo report --site <site>`],ac=[`Sign in or create your free seoskill.dev account, or sign in with Google on this machine only (read-only Search Console and Google Analytics).`,`Add the free hosted MCP server (${Rs}) or a local one to your agents.`,`Install the SEO skill for your agents.`];function oc(e){return e.status===`skipped`?`skipped`:e.status===`linked`?`seoskill.dev account${e.accountEmail?` (${e.accountEmail})`:``}`:e.status===`service-account`?`service account${e.accountEmail?` ${e.accountEmail}`:``}`:e.accountEmail??`connected`}function sc(e){return e.status===`installed`?`installed`:e.status===`failed`?`install failed`:`not installed`}function cc(e){return e.length===0?`not added`:e.map(e=>e.error?`${e.client} skipped`:`${e.client} (${e.server})`).join(`, `)}function lc(){process.stdout.write(`
61
+ `),ca({title:`Help other people find SEO Skill`,body:`If SEO Skill saved you time, a GitHub star helps other people find it.`,command:`https://github.com/iannuttall/seo`})}async function uc(e){let t=A(e);if(t||Xr(process.argv[2]===`setup`?`seo setup`:`seo start`),e[`dry-run`]){t?I({dryRun:!0,steps:ac,next:ic}):(x(ac.map((e,t)=>`${t+1}. ${e}`).join(`
62
+ `),`Setup will`),x(ic.join(`
63
+ `),`Then run`),S(`Dry run complete. Nothing was changed.`));return}rr();let n=F({json:t}),r=await Qs({interactive:n})??await tc({interactive:n}),i=n?await rc():[],a=n?await nc():{status:`skipped`};if(t){I({auth:r,mcp:i,skill:a,next:ic});return}L([[`Sign-in`,oc(r)],[`MCP server`,cc(i)],[`SEO skill`,sc(a)]]);let o=i.filter(e=>e.error);o.length&&x(o.map(e=>`${e.client}: ${e.error}`).join(`
64
+ `),`MCP setup skipped`),a.error&&x(a.error,`SEO skill install failed`),x(`seo sites list your Search Console properties
65
+ seo report --site <site> run the main report for one of them`,`Try next`),S(`Setup complete.`),lc()}const dc=b({meta:{name:`setup`,description:`Sign in with Google, then add the MCP server and skill`},args:{"dry-run":{type:`boolean`,default:!1,description:`Show what setup does without changing anything.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON. Never prompts.`}},run:async({args:e})=>uc(e)}),fc=b({...dc,meta:{name:`start`,description:`Start here: sign in with Google, then add the MCP server and skill to your agents`}}),pc=b({...fc,meta:{name:`init`,description:"Legacy alias for `seo start`."}}),mc=b({meta:{name:`logs`,description:`Manage local log retention`},subCommands:{prune:b({meta:{name:`prune`,description:`Rotate large logs and remove old local logs`},args:{quiet:{type:`boolean`,default:!1,description:`Do not print a result.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=_i();A(e)?I(t):e.quiet||process.stdout.write(`Rotated ${t.rotated} and removed ${t.removed} log files. ${_a(t.sizeBytes)} retained.\n`)}})}}),hc=[{client:`claude-desktop`,flag:`claude-desktop`},{client:`claude-code`,flag:`claude-code`},{client:`codex`,flag:`codex`},{client:`cursor`,flag:`cursor`}];function gc(e,t){return T(e.all)?t:hc.filter(({flag:t})=>T(e[t])).map(({client:e})=>e)}const _c=b({meta:{name:`mcp`,description:`MCP server helpers`},subCommands:{serve:b({meta:{name:`serve`,description:`Run the SEO MCP server`},args:{test:{type:`boolean`,default:!1,description:`Start in test mode`}},run:async({args:e})=>{let{startMcpServer:t}=await import(`./dist-DzcRsuc4.js`);await t({test:T(e.test)})}}),install:b({meta:{name:`install`,description:`Install or remove SEO MCP config for local clients`},args:{uninstall:{type:`boolean`,default:!1,description:`Remove the SEO MCP config instead of adding it`},reinstall:{type:`boolean`,default:!1,description:`Rewrite an existing managed SEO MCP config`},"claude-desktop":{type:`boolean`,default:!1,description:`Update Claude Desktop`},"claude-code":{type:`boolean`,default:!1,description:`Update Claude Code`},codex:{type:`boolean`,default:!1,description:`Update Codex CLI, app, and IDE extension`},cursor:{type:`boolean`,default:!1,description:`Update Cursor`},all:{type:`boolean`,default:!1,description:`Update every detected MCP client`},json:{type:`boolean`,default:!1,description:`Print structured JSON output`}},run:async({args:e})=>{if(T(e.uninstall)&&T(e.reinstall))throw new g(`INVALID_INPUT`,`Use either --uninstall or --reinstall, not both.`);let t=hs(),n=vs({targets:t}),r=A(e),i=gc(e,n.map(e=>e.client));if(i.length===0){if(!F({json:r}))throw new g(`INVALID_INPUT`,`Choose an MCP client with --claude-desktop, --claude-code, --codex, --cursor, or --all.`);let a=n.length>0?n:t;i=z(await $r({message:e.uninstall?`Remove seo from which MCP clients?`:`Install seo into which MCP clients?`,options:a.map(e=>({value:e.client,label:e.label,hint:e.path})),initialValues:n.map(e=>e.client),required:!0}))}let a=i.filter(e=>!t.some(t=>t.client===e));if(a.length>0)throw new g(`INVALID_INPUT`,`MCP setup is not supported for ${a.join(`, `)} on ${process.platform}.`);let o=t.filter(e=>i.includes(e.client)).map(t=>T(e.uninstall)?Ls(t):Is(t,{reinstall:T(e.reinstall)}));if(r)I({operation:T(e.uninstall)?`uninstall`:`install`,results:o});else for(let e of o)process.stdout.write(`${e.changed?`updated`:`skipped`} ${e.client} · ${e.path}\n`)}})}}),vc=b({meta:{name:`index-coverage`,description:`Find crawlable pages that deserve a closer Google index check`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},url:{type:`string`,description:`Start URL to crawl. Defaults to the home page.`},sitemaps:{type:`string`,description:`Comma-separated XML sitemap URLs. Defaults to declarations captured by the crawl.`},days:{type:`string`,description:`Finalized Search Console date range. Defaults to 90 days.`},"row-limit":{type:`string`,description:`Maximum Search Console page rows. Defaults to 100000.`},"max-sitemap-urls":{type:`string`,description:`Maximum sitemap inventory URLs. Defaults to 100000.`},limit:{type:`string`,description:`Maximum URLs returned in each evidence group. Defaults to 100.`},refresh:{type:`boolean`,default:!1,description:`Bypass the local Search Console cache.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=A(e),n=j(w(e.site)),r=Ci(e.sitemaps),i=await tt({site:n,url:w(e.url),sitemaps:r.length?r:void 0,days:D(e.days),rowLimit:D(e[`row-limit`]),maxSitemapUrls:D(e[`max-sitemap-urls`]),itemsPerSection:D(e.limit),refresh:T(e.refresh)});t?I(i):(K({title:`Index coverage`,target:i.site,status:i.sources.crawl.completeness===`complete`&&i.sources.searchConsole.completeness===`complete`?i.summary.crawlableCandidatesWithoutRetainedSearchVisibility>0?`warning`:`pass`:`unknown`,summary:`${i.summary.crawlableCandidatesWithoutRetainedSearchVisibility} crawlable pages need URL Inspection review.`,metrics:[{label:`Crawl report`,value:i.input.crawlReport.id},{label:`Crawl evidence`,value:i.sources.crawl.completeness},{label:`Sitemap evidence`,value:i.sources.sitemap.completeness},{label:`Search evidence`,value:i.sources.searchConsole.completeness},{label:`Search window`,value:`${i.sources.searchConsole.startDate} to ${i.sources.searchConsole.endDate}`},{label:`Search-visible pages`,value:i.summary.retainedSearchVisibleUrls},{label:`Blocked/non-indexable`,value:i.summary.blockedOrNonIndexableCrawlUrls},{label:`Sitemap only`,value:i.summary.sitemapOnlyUrls},{label:`Search Console only`,value:i.summary.searchConsoleOnlyUrls}]}),i.crawlableWithoutRetainedSearchVisibility.items.length&&(process.stdout.write(`
65
66
  Representative URL Inspection candidates
66
- `),z([`URL`,`Status`,`In sitemap`],i.crawlableWithoutRetainedSearchVisibility.items.map(e=>[G(e.url,80),e.status,e.inSitemap?`yes`:`no`]))),Y(`How to read this report`,i.caveats))}}),sc=x({meta:{name:`link-recover`,description:`Find search-value URLs that are now broken, blocked, or poorly redirected`},args:{site:{type:`string`},...X([`days`,`limit`,`minImpressions`,`refresh`,`js`],{days:{description:`GSC lookback window. Defaults to 90.`},limit:{description:`Maximum GSC pages to check. Defaults to 50.`},minImpressions:{description:`Minimum impressions to check a page. Defaults to 100.`},refresh:{description:`Bypass local GSC and HTTP caches.`},js:{description:`Force JavaScript rendering for final page extraction.`}}),"min-clicks":{type:`string`,description:`Minimum clicks to check a page. Defaults to 1.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=j(e),n=await me({site:M(T(e.site)),days:O(e.days),limit:O(e.limit),minClicks:O(e[`min-clicks`]),minImpressions:O(e[`min-impressions`]),refresh:E(e.refresh),js:E(e.js)?!0:`auto`});t?L(n):(K({title:`Link recovery`,target:n.site,status:n.warnings.length>0?`unknown`:n.summary.recoverable>0?`warning`:`pass`,summary:n.summary.recoverable>0?`${U(n.summary.recoverable)} previously visible URLs need recovery review.`:`No recoverable URLs were found in the retained evidence.`,metrics:[{label:`Range`,value:`${n.range.startDate} to ${n.range.endDate}`},{label:`Checked`,value:U(n.summary.checked)},{label:`Recoverable`,value:U(n.summary.recoverable)},{label:`High severity`,value:U(n.summary.high)},{label:`Clicks at risk`,value:U(n.summary.clicksAtRisk)},{label:`Impressions at risk`,value:U(n.summary.impressionsAtRisk)}]}),n.items.length&&(q([`Severity`,`Issue`,`Clicks`,`Impr`,`URL`,`Action`],n.items.map(e=>[e.severity,e.issue,U(e.clicks),U(e.impressions),G(e.url,56),G(e.recommendation.action,72)])),J(`Top recovery actions`,n.items.map(e=>({label:G(e.url,96),context:`${e.severity}, ${U(e.clicks)} clicks at risk`,action:e.recommendation.action})))),Y(`Warnings`,n.warnings.slice(0,10)))}}),cc=x({meta:{name:`redirect-trace`,description:`Trace redirects and report final indexability/canonical issues, or check a redirect map`},args:{url:{type:`string`,description:`URL to trace.`},map:{type:`string`,description:`CSV of old_url,expected_new_url lines (header optional), or one URL per line. Traces up to ${je.toLocaleString(`en-US`)} rows, 5 at a time.`},"max-hops":{type:`string`,description:`Maximum redirect hops to follow, up to 10. Defaults to 10.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache for final page extraction.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering for final page extraction.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=T(e.map);if(t){await fc(e,t);return}let n=T(e.url);if(!n)throw new d(`INVALID_INPUT`,`Pass --url to trace one URL, or --map with a CSV of old and expected URLs.`);let r=await Ce({url:n,maxHops:O(e[`max-hops`]),refresh:E(e.refresh),js:E(e.js)?!0:`auto`});j(e)?L(r):(K({title:`Redirect trace`,target:r.url,status:r.summary.issues.length>0||r.summary.error?`warning`:r.summary.finalIndexable===void 0?`unknown`:`pass`,summary:[r.summary.error?`${r.summary.outcome===`timeout`?`Timed out`:`Failed`} at ${r.finalUrl}: ${r.summary.error}`:r.summary.issues.length>0?``:`${r.summary.hops} redirect ${r.summary.hops===1?`hop`:`hops`} ended at HTTP ${r.summary.finalStatus}.`,r.summary.issues.join(`, `)].filter(Boolean).join(` `),metrics:[{label:`Final URL`,value:r.finalUrl},{label:`Final status`,value:r.summary.finalStatus??`No response`},{label:`Indexable`,value:r.summary.finalIndexable===void 0?`Unknown`:r.summary.finalIndexable?`Yes`:`No`},{label:`Hops`,value:r.summary.hops}]}),z([`#`,`Status`,`URL`,`Next`],r.chain.map((e,t)=>[t+1,e.status,G(e.url,72),G(e.nextUrl??`-`,72)])),r.finalPage&&(process.stdout.write(`
67
+ `),R([`URL`,`Status`,`In sitemap`],i.crawlableWithoutRetainedSearchVisibility.items.map(e=>[G(e.url,80),e.status,e.inSitemap?`yes`:`no`]))),Y(`How to read this report`,i.caveats))}}),yc=b({meta:{name:`link-recover`,description:`Find search-value URLs that are now broken, blocked, or poorly redirected`},args:{site:{type:`string`},...X([`days`,`limit`,`minImpressions`,`refresh`,`js`],{days:{description:`GSC lookback window. Defaults to 90.`},limit:{description:`Maximum GSC pages to check. Defaults to 50.`},minImpressions:{description:`Minimum impressions to check a page. Defaults to 100.`},refresh:{description:`Bypass local GSC and HTTP caches.`},js:{description:`Force JavaScript rendering for final page extraction.`}}),"min-clicks":{type:`string`,description:`Minimum clicks to check a page. Defaults to 1.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=A(e),n=await it({site:j(w(e.site)),days:D(e.days),limit:D(e.limit),minClicks:D(e[`min-clicks`]),minImpressions:D(e[`min-impressions`]),refresh:T(e.refresh),js:T(e.js)?!0:`auto`});t?I(n):(K({title:`Link recovery`,target:n.site,status:n.warnings.length>0?`unknown`:n.summary.recoverable>0?`warning`:`pass`,summary:n.summary.recoverable>0?`${U(n.summary.recoverable)} previously visible URLs need recovery review.`:`No recoverable URLs were found in the retained evidence.`,metrics:[{label:`Range`,value:`${n.range.startDate} to ${n.range.endDate}`},{label:`Checked`,value:U(n.summary.checked)},{label:`Recoverable`,value:U(n.summary.recoverable)},{label:`High severity`,value:U(n.summary.high)},{label:`Clicks at risk`,value:U(n.summary.clicksAtRisk)},{label:`Impressions at risk`,value:U(n.summary.impressionsAtRisk)}]}),n.items.length&&(q([`Severity`,`Issue`,`Clicks`,`Impr`,`URL`,`Action`],n.items.map(e=>[e.severity,e.issue,U(e.clicks),U(e.impressions),G(e.url,56),G(e.recommendation.action,72)])),J(`Top recovery actions`,n.items.map(e=>({label:G(e.url,96),context:`${e.severity}, ${U(e.clicks)} clicks at risk`,action:e.recommendation.action})))),Y(`Warnings`,n.warnings.slice(0,10)))}}),bc=b({meta:{name:`redirect-trace`,description:`Trace redirects and report final indexability/canonical issues, or check a redirect map`},args:{url:{type:`string`,description:`URL to trace.`},map:{type:`string`,description:`CSV of old_url,expected_new_url lines (header optional), or one URL per line. Traces up to ${Me.toLocaleString(`en-US`)} rows, 5 at a time.`},"max-hops":{type:`string`,description:`Maximum redirect hops to follow, up to 10. Defaults to 10.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache for final page extraction.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering for final page extraction.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=w(e.map);if(t){await wc(e,t);return}let n=w(e.url);if(!n)throw new g(`INVALID_INPUT`,`Pass --url to trace one URL, or --map with a CSV of old and expected URLs.`);let r=await me({url:n,maxHops:D(e[`max-hops`]),refresh:T(e.refresh),js:T(e.js)?!0:`auto`});A(e)?I(r):(K({title:`Redirect trace`,target:r.url,status:r.summary.issues.length>0||r.summary.error?`warning`:r.summary.finalIndexable===void 0?`unknown`:`pass`,summary:[r.summary.error?`${r.summary.outcome===`timeout`?`Timed out`:`Failed`} at ${r.finalUrl}: ${r.summary.error}`:r.summary.issues.length>0?``:`${r.summary.hops} redirect ${r.summary.hops===1?`hop`:`hops`} ended at HTTP ${r.summary.finalStatus}.`,r.summary.issues.join(`, `)].filter(Boolean).join(` `),metrics:[{label:`Final URL`,value:r.finalUrl},{label:`Final status`,value:r.summary.finalStatus??`No response`},{label:`Indexable`,value:r.summary.finalIndexable===void 0?`Unknown`:r.summary.finalIndexable?`Yes`:`No`},{label:`Hops`,value:r.summary.hops}]}),R([`#`,`Status`,`URL`,`Next`],r.chain.map((e,t)=>[t+1,e.status,G(e.url,72),G(e.nextUrl??`-`,72)])),r.finalPage&&(process.stdout.write(`
67
68
  Final page
68
- `),R([[`Title`,r.finalPage.title??`-`],[`Canonical`,r.finalPage.canonical??`-`],[`Meta robots`,r.finalPage.metaRobots??`-`]])),Y(`Warnings`,r.warnings.slice(0,10)))}}),lc={matches:`matches`,chain:`chain`,redirects:`redirects`,wrong_target:`wrong target`,not_redirected:`not redirected`,loop:`loop`,too_many_hops:`too many hops`,timeout:`timeout`,error:`error`},uc=[`matches`,`redirects`];async function dc(e){process.stdout.write(e)||await new Promise(e=>process.stdout.once(`drain`,e))}async function fc(e,t){for(let t of[`url`,`max-hops`])if(T(e[t])!==void 0)throw new d(`INVALID_INPUT`,`--${t} does not apply to --map.`);for(let t of[`refresh`,`js`])if(e[t]===!0)throw new d(`INVALID_INPUT`,`--${t} does not apply to --map.`);let n=(await Pr(t)).size;if(n>2e6)throw new d(`INVALID_INPUT`,`${t} is ${n.toLocaleString(`en-US`)} bytes. Map mode reads up to ${p.toLocaleString(`en-US`)} bytes and ${je.toLocaleString(`en-US`)} rows per run, so split the file.`);let r=rn(await b(t,`utf8`)),a=j(e),o=!a&&process.stderr.isTTY,s=[],c=0,l=0,u=await i(r,async e=>{l+=1,a?await dc(`${JSON.stringify(e)}\n`):uc.includes(e.verdict)&&e.final_status===200||(c+=1,s.length<50&&s.push(e)),o&&process.stderr.write(`\rTraced ${l} of ${r.length}`)});if(o&&process.stderr.write(`
69
- `),a){await dc(`${JSON.stringify(u)}\n`);return}let f=Object.keys(lc).filter(e=>u.verdicts[e]).map(e=>`${u.verdicts[e]} ${lc[e]}`);K({title:`Redirect map`,target:t,status:uc.reduce((e,t)=>e+(u.verdicts[t]??0),0)===u.rows&&!u.final_not_200?`pass`:`warning`,summary:`${u.rows} rows traced: ${f.join(`, `)}.${u.final_not_200?` ${u.final_not_200} ended on a status other than 200.`:``}`,metrics:[{label:`Rows`,value:u.rows},...Object.keys(lc).filter(e=>u.verdicts[e]).map(e=>({label:lc[e],value:u.verdicts[e]??0}))]}),s.length&&(process.stdout.write(`
69
+ `),L([[`Title`,r.finalPage.title??`-`],[`Canonical`,r.finalPage.canonical??`-`],[`Meta robots`,r.finalPage.metaRobots??`-`]])),Y(`Warnings`,r.warnings.slice(0,10)))}}),xc={matches:`matches`,chain:`chain`,redirects:`redirects`,wrong_target:`wrong target`,not_redirected:`not redirected`,loop:`loop`,too_many_hops:`too many hops`,timeout:`timeout`,error:`error`},Sc=[`matches`,`redirects`];async function Cc(e){process.stdout.write(e)||await new Promise(e=>process.stdout.once(`drain`,e))}async function wc(e,t){for(let t of[`url`,`max-hops`])if(w(e[t])!==void 0)throw new g(`INVALID_INPUT`,`--${t} does not apply to --map.`);for(let t of[`refresh`,`js`])if(e[t]===!0)throw new g(`INVALID_INPUT`,`--${t} does not apply to --map.`);let n=(await Br(t)).size;if(n>2e6)throw new g(`INVALID_INPUT`,`${t} is ${n.toLocaleString(`en-US`)} bytes. Map mode reads up to ${Oe.toLocaleString(`en-US`)} bytes and ${Me.toLocaleString(`en-US`)} rows per run, so split the file.`);let r=Le(await y(t,`utf8`)),i=A(e),a=!i&&process.stderr.isTTY,o=[],s=0,c=0,l=await se(r,async e=>{c+=1,i?await Cc(`${JSON.stringify(e)}\n`):Sc.includes(e.verdict)&&e.final_status===200||(s+=1,o.length<50&&o.push(e)),a&&process.stderr.write(`\rTraced ${c} of ${r.length}`)});if(a&&process.stderr.write(`
70
+ `),i){await Cc(`${JSON.stringify(l)}\n`);return}let u=Object.keys(xc).filter(e=>l.verdicts[e]).map(e=>`${l.verdicts[e]} ${xc[e]}`);K({title:`Redirect map`,target:t,status:Sc.reduce((e,t)=>e+(l.verdicts[t]??0),0)===l.rows&&!l.final_not_200?`pass`:`warning`,summary:`${l.rows} rows traced: ${u.join(`, `)}.${l.final_not_200?` ${l.final_not_200} ended on a status other than 200.`:``}`,metrics:[{label:`Rows`,value:l.rows},...Object.keys(xc).filter(e=>l.verdicts[e]).map(e=>({label:xc[e],value:l.verdicts[e]??0}))]}),o.length&&(process.stdout.write(`
70
71
  Rows to look at
71
- `),z([`Line`,`Verdict`,`Hops`,`Status`,`Old URL`,`Ends at`],s.map(e=>[e.line,lc[e.verdict],e.hops,e.final_status??`-`,G(e.url,50),G(e.error?`${e.error} at ${e.final_url}`:e.final_url,72)])),c>s.length&&process.stdout.write(`Showing the first ${s.length}. Use --json for every row.\n`)),process.stdout.write(`\nEach hop waits up to ${h/1e3}s, up to 10 hops per URL, with the SEO Skill crawler user agent.\n`)}const pc=x({meta:{name:`ai-referrals`,description:`Find AI referral traffic detected in Google Analytics`},args:{property:{type:`string`,description:"Numeric Google Analytics property ID. Run `seo analytics google properties` to list them."},"start-date":{type:`string`,default:`28daysAgo`},"end-date":{type:`string`,default:`yesterday`},"max-rows":{type:`string`,description:`Maximum Google Analytics rows per query. Defaults to 100000.`},"result-limit":{type:`string`,description:`Maximum ranked landing pages returned. Defaults to 25.`},limit:{type:`string`,description:`Legacy alias for --max-rows.`},refresh:{type:`boolean`,default:!1,description:`Bypass cached Google Analytics responses.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=j(e),n=xi(T(e.property)),r=await en({property:n,startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),maxRows:k(e[`max-rows`],`--max-rows`),resultLimit:k(e[`result-limit`],`--result-limit`),limit:k(e.limit,`--limit`),refresh:e.refresh===!0});if(t)L(r);else{if(K({title:`AI referral report`,target:r.property,status:r.dataStatus===`complete`?`info`:`unknown`,summary:r.summary.verdict,metrics:[{label:`Evidence`,value:r.dataStatus===`complete`?`Complete`:`Partial`,status:r.dataStatus===`complete`?`pass`:`unknown`},{label:`AI sessions`,value:U(r.summary.sessions)},{label:`AI users`,value:r.summary.totalUsers===null?`Unavailable`:U(r.summary.totalUsers)},{label:`Sources`,value:U(r.summary.sources)},{label:`Landing pages`,value:U(r.summary.landingPages)},{label:`Landing-page output`,value:`${U(r.selection.landingPages.returnedRows)} returned / ${U(r.selection.landingPages.retainedRows)} retained`},{label:`Source rows`,value:U(r.dataSource.sourceDiscovery.returnedRows)}]}),r.sources.length&&(process.stdout.write(`
72
+ `),R([`Line`,`Verdict`,`Hops`,`Status`,`Old URL`,`Ends at`],o.map(e=>[e.line,xc[e.verdict],e.hops,e.final_status??`-`,G(e.url,50),G(e.error?`${e.error} at ${e.final_url}`:e.final_url,72)])),s>o.length&&process.stdout.write(`Showing the first ${o.length}. Use --json for every row.\n`)),process.stdout.write(`\nEach hop waits up to ${rn/1e3}s, up to 10 hops per URL, with the SEO Skill crawler user agent.\n`)}const Tc=b({meta:{name:`ai-referrals`,description:`Find AI referral traffic detected in Google Analytics`},args:{property:{type:`string`,description:"Numeric Google Analytics property ID. Run `seo analytics google properties` to list them."},"start-date":{type:`string`,default:`28daysAgo`},"end-date":{type:`string`,default:`yesterday`},"max-rows":{type:`string`,description:`Maximum Google Analytics rows per query. Defaults to 100000.`},"result-limit":{type:`string`,description:`Maximum ranked landing pages returned. Defaults to 25.`},limit:{type:`string`,description:`Legacy alias for --max-rows.`},refresh:{type:`boolean`,default:!1,description:`Bypass cached Google Analytics responses.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=A(e),n=Di(w(e.property)),r=await ge({property:n,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),maxRows:O(e[`max-rows`],`--max-rows`),resultLimit:O(e[`result-limit`],`--result-limit`),limit:O(e.limit,`--limit`),refresh:e.refresh===!0});if(t)I(r);else{if(K({title:`AI referral report`,target:r.property,status:r.dataStatus===`complete`?`info`:`unknown`,summary:r.summary.verdict,metrics:[{label:`Evidence`,value:r.dataStatus===`complete`?`Complete`:`Partial`,status:r.dataStatus===`complete`?`pass`:`unknown`},{label:`AI sessions`,value:U(r.summary.sessions)},{label:`AI users`,value:r.summary.totalUsers===null?`Unavailable`:U(r.summary.totalUsers)},{label:`Sources`,value:U(r.summary.sources)},{label:`Landing pages`,value:U(r.summary.landingPages)},{label:`Landing-page output`,value:`${U(r.selection.landingPages.returnedRows)} returned / ${U(r.selection.landingPages.retainedRows)} retained`},{label:`Source rows`,value:U(r.dataSource.sourceDiscovery.returnedRows)}]}),r.sources.length&&(process.stdout.write(`
72
73
  AI sources
73
74
  `),q([`Source`,`Sessions`,`Events`,`Share of AI sessions`],r.sources.map(e=>[e.label,U(e.sessions),U(e.eventCount),W(e.shareOfAiSessions)]))),r.landingPages.length&&(process.stdout.write(`
74
75
  Landing pages
75
76
  `),q([`Landing page`,`Sessions`,`Events`,`Top source`],r.landingPages.map(e=>[G(e.landingPage,64),U(e.sessions),U(e.eventCount),e.topSourceDetails.label]))),r.dataSource.partialReasons.length){process.stdout.write(`
76
77
  Evidence warnings
77
- `);for(let e of r.dataSource.partialReasons)process.stdout.write(`- ${e}\n`)}process.stdout.write(`\nNote: ${r.summary.caveat}\n`)}}}),mc=x({meta:{name:`cannibal`,description:`Find queries with material exposure across multiple URLs`},args:{site:{type:`string`},...X([`days`,`limit`,`includeBrand`,`minImpressions`,`refresh`],{minImpressions:{description:`Minimum query impressions. Defaults to 50.`}}),"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=j(e),n=E(e.refresh),r=M(T(e.site)),i=await be({site:r,days:k(e.days,`--days`),limit:k(e.limit,`--limit`),minImpressions:k(e[`min-impressions`],`--min-impressions`),brandTerms:[...A(e[`brand-terms`])??[]],includeBrand:E(e[`include-brand`]),refresh:n});t?L(i):(K({title:`Cannibalisation report`,target:i.site,status:i.dataStatus===`complete`?`info`:`unknown`,summary:i.summary.verdict,metrics:[{label:`Evidence`,value:i.dataStatus},{label:`Range`,value:`${i.range.startDate} to ${i.range.endDate}`},{label:`Eligible`,value:U(i.summary.eligibleClusters)},{label:`Returned`,value:U(i.summary.returnedClusters)},{label:`Suppressed brand queries`,value:U(i.summary.suppressedQueries)},{label:`GSC completeness`,value:i.source.completeness},{label:`Brand queries`,value:E(e[`include-brand`])?`included`:`excluded`}]}),q([`Query`,`URLs`,`Property impr`,`Exposure`,`HHI`,`Review first`],i.items.map(e=>[G(e.query,42),e.pages.length,e.propertyImpressions===void 0?`n/a`:U(e.propertyImpressions),U(e.pageExposureImpressions),e.hhi.toFixed(2),G(e.suggestedOwnerUrl,56)])),J(`Top cannibalisation actions`,i.items.map(e=>({label:e.query,context:`${e.pages.length} material URLs; first review ${G(e.suggestedOwnerUrl,64)}`,action:e.recommendation.action}))),Y(`Report caveats`,i.caveats),Y(`Provider usage`,[i.ledgerSummary]))}}),hc=x({meta:{name:`ctr-underperformers`,description:`Find high-impression queries with weak CTR for their position`},args:{site:{type:`string`},...X([`includeBrand`,`minImpressions`],{minImpressions:{description:`Minimum query impressions. Defaults to 1 per 5,000 retained impressions, from 30 to 200.`}}),json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=j(e),n=M(T(e.site)),r=await ut({site:n,minImpressions:O(e[`min-impressions`]),includeBrand:E(e[`include-brand`])});t?L(r):(K({title:`CTR underperformers`,target:r.site,status:r.dataStatus===`partial`?`unknown`:`info`,summary:r.summary.verdict,metrics:[{label:`Underperformers`,value:U(r.summary.underperformers)},{label:`Estimated click gap`,value:U(r.summary.estimatedClickShortfall)},{label:`Brand queries`,value:r.summary.brandFiltering},{label:`Evidence`,value:r.dataStatus},{label:`GSC completeness`,value:r.source.completeness}]}),Y(`Why this matters`,[`These queries already have visibility; the fastest win is usually better SERP framing, not new content.`,`Start with high-impression rows where actual CTR is far below the expected CTR for that ranking position.`]),Y(`Recommended actions`,r.recommendations),Y(`Report caveats`,r.caveats),q([`Query`,`URL`,`Pos`,`Impr`,`CTR`,`Expected`,`Gap`,`Action`],r.items.map(e=>[G(e.query,36),G(e.url,48),Qa(e.position),U(e.impressions),W(e.actualCtr),W(e.expectedCtr),U(e.clickShortfall),G(e.recommendation.action,72)])),J(`Top CTR actions`,r.items.map(e=>({label:e.query,context:`${U(e.clickShortfall)} click gap, ${W(e.actualCtr)} CTR`,action:e.recommendation.action}))))}});function gc(e){return e>0?Qa(e):`n/a`}const _c=x({meta:{name:`decaying`,description:`Find query/page rows losing clicks between two GSC windows`},args:{site:{type:`string`},...X([`days`,`limit`,`includeBrand`,`refresh`]),comparison:{type:`string`,description:`Comparison: previous-period or year-over-year.`},"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude.`},"min-drop-pct":{type:`string`,description:`Minimum click drop percentage. Defaults to 20.`},"min-previous-clicks":{type:`string`,description:`Minimum previous-window clicks for a query/page row. Defaults to 2.`},"min-click-loss":{type:`string`,description:`Minimum absolute click loss. Defaults to 1.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=j(e),n=E(e.refresh),r=T(e.comparison),i=k(e.days,`--days`),a=k(e.limit,`--limit`),o=k(e[`min-drop-pct`],`--min-drop-pct`),s=k(e[`min-previous-clicks`],`--min-previous-clicks`),c=k(e[`min-click-loss`],`--min-click-loss`);if(r!==void 0&&r!==`previous-period`&&r!==`year-over-year`)throw new d(`INVALID_INPUT`,`--comparison must be previous-period or year-over-year.`);let l=M(T(e.site)),u=await ce({site:l,days:i,limit:a,comparison:r,brandTerms:[...A(e[`brand-terms`])??[]],includeBrand:E(e[`include-brand`]),minDropPct:o,minPreviousClicks:s,minClickLoss:c,refresh:n});t?L(u):(K({title:`Decaying pages`,target:u.site,status:u.dataStatus===`complete`?u.summary.returnedRows>0?`warning`:`pass`:`unknown`,summary:u.summary.verdict,metrics:[{label:`Evidence`,value:u.dataStatus},{label:`Comparison`,value:u.comparison},{label:`Observed declines`,value:U(u.summary.returnedRows)},{label:`Eligible declines`,value:U(u.summary.eligibleRows)},{label:`Decay clusters`,value:U(u.summary.groups)},{label:`Observed click decline`,value:U(u.summary.returnedObservedRetainedQueryClickLoss)},{label:`Eligible click decline`,value:U(u.summary.observedRetainedQueryClickLoss)},{label:`Brand queries`,value:u.summary.brandFiltering},{label:`Minimum drop`,value:`${u.filters.minDropPct}%`},{label:`Minimum previous clicks`,value:U(u.filters.minPreviousClicks)},{label:`GSC completeness`,value:u.source.completeness}]}),Y(`Why this matters`,[`This report compares retained query/page rows and only counts declines observed in both windows.`,`Position, CTR, and impression movements are signals for investigation, not proof of cause.`]),Y(`Recommended actions`,u.recommendations),Y(`Report caveats`,u.caveats),Y(`Warnings`,u.warnings),u.items.length&&(u.groups.length&&(q([`Cluster`,`Rows`,`Observed loss`,`Drop`,`Sample query`,`Action`],u.groups.map(e=>[G(e.label,42),U(e.count),U(e.totalClickLoss),`${e.averageDropPct.toFixed(1)}%`,G(e.sampleQueries[0]??`-`,40),G(e.recommendation,72)])),J(`Top decay cluster actions`,u.groups.map(e=>({label:e.label,context:`${U(e.count)} retained rows, ${U(e.totalClickLoss)} observed click decline`,action:e.recommendation})))),q([`Query`,`Template`,`URL`,`Signals`,`Decline`,`Clicks`,`Impr`,`CTR`,`Pos`,`Action`],u.items.map(e=>[G(e.query,32),G(e.template.label,26),G(e.url,44),e.signals.join(`, `),U(e.clickLoss),`${U(e.previous.clicks)} -> ${U(e.current.clicks)}`,`${U(e.previous.impressions)} -> ${U(e.current.impressions)}`,`${W(e.previous.ctr)} -> ${W(e.current.ctr)}`,`${gc(e.previous.position)} -> ${gc(e.current.position)}`,G(e.recommendation.action,64)])),J(`Top decay actions`,u.items.map(e=>({label:e.query,context:`${e.template.label}, ${U(e.clickLoss)} fewer observed clicks`,action:e.recommendation.action})))))}}),vc=x({meta:{name:`internal-links`,description:`Internal links to add across a site (--site) or to one page (--url), placed in real sentences`},args:{site:{type:`string`,description:`Site to audit: a domain, URL or Search Console property.`},url:{type:`string`,description:`One page to find internal links to.`},"max-pages":{type:`string`,description:`Site audits only: pages to crawl, 500 by default, up to 5,000.`},..._a,...va,refresh:{type:`boolean`,default:!1,description:`Bypass the local cache and fetch fresh data.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=j(e),n=E(e.refresh),r=T(e.url),i=T(e.site);if(!!r==!!i)throw new d(`INVALID_INPUT`,`Send --site to audit a whole site, or --url to find links to one page.`);let a=T(e[`max-pages`]),o=a===void 0?void 0:O(a);if(a!==void 0&&o===void 0)throw new d(`INVALID_INPUT`,`--max-pages is a whole number.`);let s=r??i,c=await or({site:s,targetUrl:r,maxPages:o,startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),refresh:n},{...await Ae({site:s,refresh:n}),progress:fa(!t&&process.stderr.isTTY)});if(t){L(c);return}let l={...r?{url:r}:{site:i},...o===void 0?{}:{"max-pages":o}};process.stdout.write(`${Nn(c,{detail:V(e),offset:O(e.offset)??0,more:(e,t)=>ha(`internal-links`,{...l,detail:e,offset:t})})}\n`)}}),yc=x({meta:{name:`page-opportunities`,description:`Find first-party traffic growth opportunities for one URL`},args:{site:{type:`string`},url:{type:`string`,required:!0},...X([`days`,`limit`,`minImpressions`,`includeBrand`,`js`,`refresh`],{limit:{description:`Maximum page queries to inspect. Defaults to 25.`},minImpressions:{description:`Minimum query impressions. Defaults to 10.`},includeBrand:{description:`Include branded queries in page opportunity reports.`},js:{description:`Force JavaScript rendering for page extraction.`},refresh:{description:`Bypass local GSC and HTTP cache.`}}),"verify-content":pi(`Fetch the page for title/H1/body checks. Defaults to true.`,`Skip fetching the page for title/H1/body checks.`),json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=j(e),n=M(T(e.site)),r=await Zn({site:n,url:T(e.url)??``,days:O(e.days),limit:O(e.limit),minImpressions:O(e[`min-impressions`]),includeBrand:E(e[`include-brand`]),verifyContent:E(e[`verify-content`])!==!1,js:E(e.js)?!0:`auto`,refresh:E(e.refresh)});t?L(r):(K({title:`Page opportunities`,target:r.url,status:r.verification.status===`failed`?`unknown`:`info`,summary:r.summary.verdict,metrics:[{label:`Title`,value:r.page?.title??`Not fetched`},{label:`Fetch`,value:Do(r.page?.fetchDiagnostics)},{label:`Verification`,value:r.verification.status},{label:`Rows`,value:`${U(r.selection.returnedRows)} returned / ${U(r.selection.eligibleRows)} eligible / ${U(r.selection.sourceRows)} source`},{label:`Queries`,value:U(r.summary.queries)},{label:`Impressions`,value:U(r.summary.impressions)},{label:`Opportunities`,value:U(r.summary.opportunities)},{label:`CTR shortfall`,value:U(r.summary.estimatedCtrClickShortfall)},{label:`Focus`,value:r.summary.focus},{label:`Evidence`,value:r.dataStatus}]}),Y(`Why this matters`,[`This report starts from queries where this exact URL already has impressions, so recommendations stay tied to first-party demand.`,`Content verification separates body gaps from title/meta framing issues, which helps avoid adding copy when the page already covers the query.`]),Y(`Recommended actions`,r.recommendations),Y(`Report caveats`,r.caveats),r.items.length?(q([`Type`,`Query`,`Evidence`,`Pos`,`CTR`,`Expected`,`Impr`,`Shortfall`,`Action`],r.items.map(e=>[e.opportunityType,G(e.query,38),e.verification.signals.length?e.verification.signals.join(`, `):e.verification.status,e.position.toFixed(1),W(e.ctr),e.expectedCtr===void 0?`n/a`:W(e.expectedCtr),U(e.impressions),e.estimatedCtrClickShortfall===void 0?`n/a`:U(e.estimatedCtrClickShortfall),G(e.recommendation,72)])),J(`Top page actions`,r.items.map(e=>({label:e.query,context:`${e.opportunityType}, ${U(e.impressions)} impressions`,action:e.recommendation})))):process.stdout.write(r.dataStatus===`empty`?`No GSC query rows found for this exact URL.
78
+ `);for(let e of r.dataSource.partialReasons)process.stdout.write(`- ${e}\n`)}process.stdout.write(`\nNote: ${r.summary.caveat}\n`)}}}),Ec=b({meta:{name:`cannibal`,description:`Find queries with material exposure across multiple URLs`},args:{site:{type:`string`},...X([`days`,`limit`,`includeBrand`,`minImpressions`,`refresh`],{minImpressions:{description:`Minimum query impressions. Defaults to 50.`}}),"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=A(e),n=T(e.refresh),r=j(w(e.site)),i=await gt({site:r,days:O(e.days,`--days`),limit:O(e.limit,`--limit`),minImpressions:O(e[`min-impressions`],`--min-impressions`),brandTerms:[...k(e[`brand-terms`])??[]],includeBrand:T(e[`include-brand`]),refresh:n});t?I(i):(K({title:`Cannibalisation report`,target:i.site,status:i.dataStatus===`complete`?`info`:`unknown`,summary:i.summary.verdict,metrics:[{label:`Evidence`,value:i.dataStatus},{label:`Range`,value:`${i.range.startDate} to ${i.range.endDate}`},{label:`Eligible`,value:U(i.summary.eligibleClusters)},{label:`Returned`,value:U(i.summary.returnedClusters)},{label:`Suppressed brand queries`,value:U(i.summary.suppressedQueries)},{label:`GSC completeness`,value:i.source.completeness},{label:`Brand queries`,value:T(e[`include-brand`])?`included`:`excluded`}]}),q([`Query`,`URLs`,`Property impr`,`Exposure`,`HHI`,`Review first`],i.items.map(e=>[G(e.query,42),e.pages.length,e.propertyImpressions===void 0?`n/a`:U(e.propertyImpressions),U(e.pageExposureImpressions),e.hhi.toFixed(2),G(e.suggestedOwnerUrl,56)])),J(`Top cannibalisation actions`,i.items.map(e=>({label:e.query,context:`${e.pages.length} material URLs; first review ${G(e.suggestedOwnerUrl,64)}`,action:e.recommendation.action}))),Y(`Report caveats`,i.caveats),Y(`Provider usage`,[i.ledgerSummary]))}}),Dc=b({meta:{name:`ctr-underperformers`,description:`Find high-impression queries with weak CTR for their position`},args:{site:{type:`string`},...X([`includeBrand`,`minImpressions`],{minImpressions:{description:`Minimum query impressions. Defaults to 1 per 5,000 retained impressions, from 30 to 200.`}}),json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=A(e),n=j(w(e.site)),r=await Lt({site:n,minImpressions:D(e[`min-impressions`]),includeBrand:T(e[`include-brand`])});t?I(r):(K({title:`CTR underperformers`,target:r.site,status:r.dataStatus===`partial`?`unknown`:`info`,summary:r.summary.verdict,metrics:[{label:`Underperformers`,value:U(r.summary.underperformers)},{label:`Estimated click gap`,value:U(r.summary.estimatedClickShortfall)},{label:`Brand queries`,value:r.summary.brandFiltering},{label:`Evidence`,value:r.dataStatus},{label:`GSC completeness`,value:r.source.completeness}]}),Y(`Why this matters`,[`These queries already have visibility; the fastest win is usually better SERP framing, not new content.`,`Start with high-impression rows where actual CTR is far below the expected CTR for that ranking position.`]),Y(`Recommended actions`,r.recommendations),Y(`Report caveats`,r.caveats),q([`Query`,`URL`,`Pos`,`Impr`,`CTR`,`Expected`,`Gap`,`Action`],r.items.map(e=>[G(e.query,36),G(e.url,48),uo(e.position),U(e.impressions),W(e.actualCtr),W(e.expectedCtr),U(e.clickShortfall),G(e.recommendation.action,72)])),J(`Top CTR actions`,r.items.map(e=>({label:e.query,context:`${U(e.clickShortfall)} click gap, ${W(e.actualCtr)} CTR`,action:e.recommendation.action}))))}});function Oc(e){return e>0?uo(e):`n/a`}const kc=b({meta:{name:`decaying`,description:`Find query/page rows losing clicks between two GSC windows`},args:{site:{type:`string`},...X([`days`,`limit`,`includeBrand`,`refresh`]),comparison:{type:`string`,description:`Comparison: previous-period or year-over-year.`},"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude.`},"min-drop-pct":{type:`string`,description:`Minimum click drop percentage. Defaults to 20.`},"min-previous-clicks":{type:`string`,description:`Minimum previous-window clicks for a query/page row. Defaults to 2.`},"min-click-loss":{type:`string`,description:`Minimum absolute click loss. Defaults to 1.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=A(e),n=T(e.refresh),r=w(e.comparison),i=O(e.days,`--days`),a=O(e.limit,`--limit`),o=O(e[`min-drop-pct`],`--min-drop-pct`),s=O(e[`min-previous-clicks`],`--min-previous-clicks`),c=O(e[`min-click-loss`],`--min-click-loss`);if(r!==void 0&&r!==`previous-period`&&r!==`year-over-year`)throw new g(`INVALID_INPUT`,`--comparison must be previous-period or year-over-year.`);let l=j(w(e.site)),u=await ut({site:l,days:i,limit:a,comparison:r,brandTerms:[...k(e[`brand-terms`])??[]],includeBrand:T(e[`include-brand`]),minDropPct:o,minPreviousClicks:s,minClickLoss:c,refresh:n});t?I(u):(K({title:`Decaying pages`,target:u.site,status:u.dataStatus===`complete`?u.summary.returnedRows>0?`warning`:`pass`:`unknown`,summary:u.summary.verdict,metrics:[{label:`Evidence`,value:u.dataStatus},{label:`Comparison`,value:u.comparison},{label:`Observed declines`,value:U(u.summary.returnedRows)},{label:`Eligible declines`,value:U(u.summary.eligibleRows)},{label:`Decay clusters`,value:U(u.summary.groups)},{label:`Observed click decline`,value:U(u.summary.returnedObservedRetainedQueryClickLoss)},{label:`Eligible click decline`,value:U(u.summary.observedRetainedQueryClickLoss)},{label:`Brand queries`,value:u.summary.brandFiltering},{label:`Minimum drop`,value:`${u.filters.minDropPct}%`},{label:`Minimum previous clicks`,value:U(u.filters.minPreviousClicks)},{label:`GSC completeness`,value:u.source.completeness}]}),Y(`Why this matters`,[`This report compares retained query/page rows and only counts declines observed in both windows.`,`Position, CTR, and impression movements are signals for investigation, not proof of cause.`]),Y(`Recommended actions`,u.recommendations),Y(`Report caveats`,u.caveats),Y(`Warnings`,u.warnings),u.items.length&&(u.groups.length&&(q([`Cluster`,`Rows`,`Observed loss`,`Drop`,`Sample query`,`Action`],u.groups.map(e=>[G(e.label,42),U(e.count),U(e.totalClickLoss),`${e.averageDropPct.toFixed(1)}%`,G(e.sampleQueries[0]??`-`,40),G(e.recommendation,72)])),J(`Top decay cluster actions`,u.groups.map(e=>({label:e.label,context:`${U(e.count)} retained rows, ${U(e.totalClickLoss)} observed click decline`,action:e.recommendation})))),q([`Query`,`Template`,`URL`,`Signals`,`Decline`,`Clicks`,`Impr`,`CTR`,`Pos`,`Action`],u.items.map(e=>[G(e.query,32),G(e.template.label,26),G(e.url,44),e.signals.join(`, `),U(e.clickLoss),`${U(e.previous.clicks)} -> ${U(e.current.clicks)}`,`${U(e.previous.impressions)} -> ${U(e.current.impressions)}`,`${W(e.previous.ctr)} -> ${W(e.current.ctr)}`,`${Oc(e.previous.position)} -> ${Oc(e.current.position)}`,G(e.recommendation.action,64)])),J(`Top decay actions`,u.items.map(e=>({label:e.query,context:`${e.template.label}, ${U(e.clickLoss)} fewer observed clicks`,action:e.recommendation.action})))))}}),Ac=b({meta:{name:`internal-links`,description:`Internal links to add across a site (--site) or to one page (--url), placed in real sentences`},args:{site:{type:`string`,description:`Site to audit: a domain, URL or Search Console property.`},url:{type:`string`,description:`One page to find internal links to.`},"max-pages":{type:`string`,description:`Site audits only: pages to crawl, 500 by default, up to 5,000.`},...Ca,...B,refresh:{type:`boolean`,default:!1,description:`Bypass the local cache and fetch fresh data.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=A(e),n=T(e.refresh),r=w(e.url),i=w(e.site);if(!!r==!!i)throw new g(`INVALID_INPUT`,`Send --site to audit a whole site, or --url to find links to one page.`);let a=w(e[`max-pages`]),o=a===void 0?void 0:D(a);if(a!==void 0&&o===void 0)throw new g(`INVALID_INPUT`,`--max-pages is a whole number.`);let s=r??i,c=await st({site:s,targetUrl:r,maxPages:o,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),refresh:n},{...await Pe({site:s,refresh:n}),progress:va(!t&&process.stderr.isTTY)});if(t){I(c);return}let l={...r?{url:r}:{site:i},...o===void 0?{}:{"max-pages":o}};process.stdout.write(`${Ut(c,{detail:V(e),offset:D(e.offset)??0,more:(e,t)=>xa(`internal-links`,{...l,detail:e,offset:t})})}\n`)}}),jc=b({meta:{name:`page-opportunities`,description:`Find first-party traffic growth opportunities for one URL`},args:{site:{type:`string`},url:{type:`string`,required:!0},...X([`days`,`limit`,`minImpressions`,`includeBrand`,`js`,`refresh`],{limit:{description:`Maximum page queries to inspect. Defaults to 25.`},minImpressions:{description:`Minimum query impressions. Defaults to 10.`},includeBrand:{description:`Include branded queries in page opportunity reports.`},js:{description:`Force JavaScript rendering for page extraction.`},refresh:{description:`Bypass local GSC and HTTP cache.`}}),"verify-content":yi(`Fetch the page for title/H1/body checks. Defaults to true.`,`Skip fetching the page for title/H1/body checks.`),json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=A(e),n=j(w(e.site)),r=await re({site:n,url:w(e.url)??``,days:D(e.days),limit:D(e.limit),minImpressions:D(e[`min-impressions`]),includeBrand:T(e[`include-brand`]),verifyContent:T(e[`verify-content`])!==!1,js:T(e.js)?!0:`auto`,refresh:T(e.refresh)});t?I(r):(K({title:`Page opportunities`,target:r.url,status:r.verification.status===`failed`?`unknown`:`info`,summary:r.summary.verdict,metrics:[{label:`Title`,value:r.page?.title??`Not fetched`},{label:`Fetch`,value:zo(r.page?.fetchDiagnostics)},{label:`Verification`,value:r.verification.status},{label:`Rows`,value:`${U(r.selection.returnedRows)} returned / ${U(r.selection.eligibleRows)} eligible / ${U(r.selection.sourceRows)} source`},{label:`Queries`,value:U(r.summary.queries)},{label:`Impressions`,value:U(r.summary.impressions)},{label:`Opportunities`,value:U(r.summary.opportunities)},{label:`CTR shortfall`,value:U(r.summary.estimatedCtrClickShortfall)},{label:`Focus`,value:r.summary.focus},{label:`Evidence`,value:r.dataStatus}]}),Y(`Why this matters`,[`This report starts from queries where this exact URL already has impressions, so recommendations stay tied to first-party demand.`,`Content verification separates body gaps from title/meta framing issues, which helps avoid adding copy when the page already covers the query.`]),Y(`Recommended actions`,r.recommendations),Y(`Report caveats`,r.caveats),r.items.length?(q([`Type`,`Query`,`Evidence`,`Pos`,`CTR`,`Expected`,`Impr`,`Shortfall`,`Action`],r.items.map(e=>[e.opportunityType,G(e.query,38),e.verification.signals.length?e.verification.signals.join(`, `):e.verification.status,e.position.toFixed(1),W(e.ctr),e.expectedCtr===void 0?`n/a`:W(e.expectedCtr),U(e.impressions),e.estimatedCtrClickShortfall===void 0?`n/a`:U(e.estimatedCtrClickShortfall),G(e.recommendation,72)])),J(`Top page actions`,r.items.map(e=>({label:e.query,context:`${e.opportunityType}, ${U(e.impressions)} impressions`,action:e.recommendation})))):process.stdout.write(r.dataStatus===`empty`?`No GSC query rows found for this exact URL.
78
79
  `:`GSC rows were found, but none met the report criteria.
79
- `))}}),bc=x({meta:{name:`query-cluster`,description:`Cluster GSC queries into repeated demand themes`},args:{site:{type:`string`},scope:{type:`string`},...X([`includeBrand`,`minImpressions`,`limit`],{includeBrand:{description:`Include branded queries in query clustering.`},minImpressions:{description:`Minimum impressions per query. Defaults to 25.`},limit:{description:`Maximum clusters to return. Defaults to 25; max 100.`}}),json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=j(e),n=M(T(e.site)),r=await Fe({site:n,scope:T(e.scope),includeBrand:E(e[`include-brand`]),minImpressions:O(e[`min-impressions`]),limit:O(e.limit)});t?L(r):(K({title:`Query clusters`,target:r.site,status:`info`,summary:r.summary.verdict,metrics:[{label:`Scope`,value:r.scope??`All pages`},{label:`Clusters`,value:U(r.summary.clusters)},{label:`Queries`,value:U(r.summary.queries)},{label:`Impressions`,value:U(r.summary.impressions)},{label:`Clicks`,value:U(r.summary.clicks)},{label:`Minimum impressions`,value:U(r.summary.minImpressions)},{label:`Result limit`,value:U(r.summary.limit)},{label:`High opportunity`,value:U(r.summary.highOpportunityClusters)},{label:`Brand queries`,value:r.summary.brandFiltering}]}),Y(`Why this matters`,[`Clusters show repeated demand themes, so they are better inputs for page sections, hubs, and templates than one-off query exports.`,`Prioritise clusters with high impressions and low clicks; they usually reveal unclear intent coverage or weak SERP framing.`]),Y(`Recommended actions`,r.recommendations),Y(`Report caveats`,r.caveats),q([`Cluster`,`Intent`,`Queries`,`Impr`,`CTR`,`Expected`,`Lift`,`Action`],r.clusters.map(e=>[G(e.label,32),e.intent,e.queries.length,U(e.totals?.impressions??0),W(e.totals?.ctr??0),W(e.benchmark?.expectedCtr??0),e.estimatedClickLift===void 0?`-`:U(e.estimatedClickLift),G(e.recommendation??``,72)])),J(`Top cluster actions`,r.clusters.map(e=>({label:e.label,context:`${U(e.totals?.impressions??0)} impressions, ${e.estimatedClickLift===void 0?`ranking opportunity`:`${U(e.estimatedClickLift)} estimated click lift`}`,action:e.recommendation??``}))))}}),xc=x({meta:{name:`quick-wins`,description:`Find high-ranking low-CTR query/page opportunities`},args:{site:{type:`string`},...X([`days`,`limit`,`includeBrand`,`minImpressions`,`verifyContent`,`verifyLimit`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=j(e),n=O(e[`verify-limit`]),r=E(e[`verify-content`])===!0||n!==void 0,i=M(T(e.site)),a=await it({site:i,days:O(e.days),limit:O(e.limit),minImpressions:O(e[`min-impressions`]),brandTerms:[...A(e[`brand-terms`])??[]],includeBrand:E(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:E(e.js)?!0:void 0,rate:vi(e),refresh:E(e.refresh)});t?L(a):(K({title:`Quick wins`,target:a.site,status:a.source.possiblyTruncated?`unknown`:`info`,summary:a.summary.verdict,metrics:[{label:`Eligible rows`,value:U(a.summary.eligibleRows)},{label:`Returned rows`,value:U(a.summary.returnedRows)},{label:`Query clusters`,value:U(a.summary.repeatedQueryGroups)},{label:`Template patterns`,value:U(a.summary.templatePatterns)},{label:`CTR click shortfall`,value:U(a.summary.returnedEstimatedCtrClickShortfall)},{label:`Brand queries`,value:a.summary.brandFiltering},{label:`Evidence`,value:a.dataStatus},{label:`Verification`,value:$a(a)}]}),Y(`Why this matters`,[`These rows have GSC average positions from 4 to 10 and observed CTR below a site-peer or versioned fallback target.`,`Page evidence is needed before treating a CTR shortfall as a title, content, or technical finding.`]),Y(`Recommended actions`,a.recommendations),Y(`Report caveats`,a.caveats),a.items.length&&(a.templateRecommendations.length&&(q([`Template`,`URLs`,`Rows`,`Shortfall`,`Impr`,`Action`],a.templateRecommendations.map(e=>[G(e.templateLabel,34),U(e.urlCount),U(e.rowCount),U(e.totalEstimatedCtrClickShortfall),U(e.totalImpressions),G(e.action,72)])),J(`Top template actions`,a.templateRecommendations.map(e=>({label:e.templateLabel,context:`${U(e.urlCount)} URLs, ${U(e.totalEstimatedCtrClickShortfall)} heuristic CTR click shortfall`,action:`${e.action} ${e.evidence}`})))),a.groups.length&&(q([`Cluster`,`URLs`,`Rows`,`Shortfall`,`Impr`,`Sample URL`,`Action`],a.groups.map(e=>[G(e.label,44),U(e.urlCount),U(e.rowCount),U(e.totalEstimatedCtrClickShortfall),U(e.totalImpressions),G(e.sampleUrls[0]??`-`,46),G(e.recommendation,72)])),J(`Top cluster actions`,a.groups.map(e=>({label:e.label,context:`${U(e.urlCount)} URLs, ${U(e.totalEstimatedCtrClickShortfall)} heuristic CTR click shortfall`,action:e.recommendation})))),q([`Query`,`Template`,`URL`,`Pos`,`Impr`,`CTR / target`,`Shortfall`,`Fetch`,`Check`,`Action`],a.items.map(e=>[G(e.query,36),G(e.template.label,24),G(e.url,48),Qa(e.position),U(e.impressions),`${W(e.ctr)} / ${W(e.targetCtr)}`,U(e.estimatedCtrClickShortfall),Do(e.contentVerification?.fetchDiagnostics),Oo(e.contentVerification?.classification),G(e.recommendation.action,64)])),J(`Top opportunity actions`,a.items.map(e=>({label:e.query,context:`${e.template.label}, pos ${Qa(e.position)}, ${U(e.impressions)} impressions`,action:e.recommendation.action})))))}}),Sc=x({meta:{name:`second-page`,description:`Find URLs averaging positions above 10 through 20 in GSC`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},...X([`range`,`minImpressions`,`limit`,`includeBrand`,`verifyContent`,`verifyLimit`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=j(e),n=O(e[`verify-limit`]),r=E(e[`verify-content`])===!0||n!==void 0,i=M(T(e.site)),a=await ke({site:i,range:O(e.days),minImpressions:O(e[`min-impressions`]),limit:T(e.limit)?Number(T(e.limit)):10,includeBrand:E(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:E(e.js)?!0:void 0,rate:vi(e),refresh:E(e.refresh)});t?L(a):(K({title:`Second-page opportunities`,target:a.site,status:a.source.possiblyTruncated||a.summary.fetchFailures>0?`unknown`:`info`,summary:a.summary.verdict,metrics:[{label:`Eligible pages`,value:U(a.summary.eligiblePages)},{label:`Returned pages`,value:U(a.summary.returnedPages)},{label:`Eligible queries`,value:U(a.summary.eligibleQueries)},{label:`Impressions`,value:U(a.summary.eligibleImpressions)},{label:`Content issues`,value:U(a.summary.contentIssues)},{label:`Technical issues`,value:U(a.summary.technicalIssues)},{label:`Fetch failures`,value:U(a.summary.fetchFailures)},{label:`Brand queries`,value:a.summary.brandFiltering},{label:`Evidence`,value:a.dataStatus},{label:`Verification`,value:$a(a)}]}),Y(`Recommended actions`,a.recommendations),Y(`Report caveats`,a.caveats),a.items.length?(q([`Query`,`Template`,`Pos`,`Impr`,`CTR`,`Queries`,`Fetch`,`Check`,`Action`],a.items.map(e=>[e.primaryQuery,e.template.label,e.position.toFixed(1),Math.round(e.impressions),e.ctr.toFixed(3),U(e.queryCount),Do(e.fetchDiagnostics),Oo(e.contentVerification?.classification),e.recommendation.action])),J(`Top second-page actions`,a.items.map(e=>({label:e.primaryQuery,context:`${e.template.label}, pos ${Qa(e.position)}, ${U(e.impressions)} impressions`,action:e.recommendation.action}))),process.stdout.write(`${a.ledgerSummary}\n`)):(process.stdout.write(`No average-position candidates matched this report.
80
- `),process.stdout.write(`${a.ledgerSummary}\n`)))}}),Cc=x({meta:{name:`audit-page`,description:`Fetch one page and audit title, metadata, content, links, and schema`},args:{url:{type:`string`,required:!0,description:`URL to audit.`},site:{type:`string`,description:`Optional GSC property for page search metrics, for example sc-domain:example.com.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering for extraction.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache.`}},run:async({args:e})=>{let t=await Ue({url:T(e.url)??``,site:T(e.site),js:E(e.js)?!0:`auto`,refresh:E(e.refresh)});j(e)?L(t):K({title:`Page audit`,target:t.url,status:t.issues.some(e=>e.severity===`high`)?`fail`:t.issues.length>0?`warning`:`pass`,summary:t.issues.length>0?`${t.issues.length} ${t.issues.length===1?`issue needs`:`issues need`} review.`:`No page issues were found by the available checks.`,metrics:[{label:`Final URL`,value:t.page.finalUrl},{label:`Title`,value:t.page.title||(t.page.title===``?`Empty`:`Missing`)},{label:`Meta description`,value:t.page.metaDescription||(t.page.metaDescription===``?`Empty`:`Missing`)},{label:`Words`,value:t.page.wordCount},{label:`Fetch`,value:Do(t.fetchDiagnostics)}],diagnostics:[{title:`Issues`,items:t.issues.map(e=>({status:e.severity===`high`?`fail`:`warning`,title:`${e.code}: ${e.principle}`,explanation:e.detail}))}]})}});function wc(e){let t=T(e)??`mobile`;if(t!==`mobile`&&t!==`desktop`)throw new d(`INVALID_INPUT`,`Invalid --strategy. Use mobile or desktop.`);return t}function Tc(e){return e?e.displayValue??String(e.value??`not measured`):`not measured`}function Ec(e){if(!e)return`not available`;let t=e.unit===`milliseconds`?`ms`:``;return`${e.p75}${t} (${e.rating})`}const Dc=x({meta:{name:`perf`,description:`Audit lab performance and field Core Web Vitals`},subCommands:{audit:x({meta:{name:`audit`,description:`Run a Lighthouse/Core Web Vitals performance audit`},args:{url:{type:`string`,description:`URL to audit.`},strategy:{type:`string`,default:`mobile`,description:`Audit strategy: mobile or desktop.`},"lighthouse-bin":{type:`string`,description:`Custom Lighthouse binary path. Defaults to the bundled version.`},"crux-key":{type:`string`,description:`CrUX API key. Prefer SEO_CRUX_API_KEY to avoid shell history.`},raw:{type:`boolean`,default:!1,description:`Include the full Lighthouse JSON in JSON output.`},refresh:{type:`boolean`,default:!1,description:`Bypass the local performance report cache.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=j(e),n=T(e.url);if(!n)throw new d(`INVALID_INPUT`,`No URL given. Pass --url.`);let r=await ae({url:n,strategy:wc(e.strategy),lighthouseBin:T(e[`lighthouse-bin`]),cruxApiKey:T(e[`crux-key`]),refresh:E(e.refresh),includeRaw:t&&E(e.raw)});t?L(r):(K({title:`Performance report`,target:r.url,status:r.dataStatus===`partial`?`unknown`:r.grade===`good`?`pass`:`warning`,summary:r.headline,metrics:[{label:`Source`,value:r.source},{label:`Strategy`,value:r.strategy},{label:`Lab score`,value:r.score===void 0?`Unknown`:`${r.score}/100`},{label:`Lab grade`,value:r.grade},{label:`Evidence`,value:r.dataStatus},{label:`FCP`,value:Tc(r.metrics.firstContentfulPaint)},{label:`LCP`,value:Tc(r.metrics.largestContentfulPaint)},{label:`TBT`,value:Tc(r.metrics.totalBlockingTime)},{label:`CLS`,value:Tc(r.metrics.cumulativeLayoutShift)},{label:`INP`,value:Tc(r.metrics.interactionToNextPaint)},{label:`Server response`,value:Tc(r.metrics.serverResponseTime)},{label:`Fallback fetch`,value:Tc(r.metrics.fallbackFetchDuration)},{label:`Field data`,value:r.fieldData?`${r.fieldData.scope} ${r.fieldData.formFactor.toLowerCase()} (${r.fieldData.assessment.status})`:r.fieldDataStatus.status},{label:`Field LCP p75`,value:Ec(r.fieldData?.metrics.largestContentfulPaint)},{label:`Field INP p75`,value:Ec(r.fieldData?.metrics.interactionToNextPaint)},{label:`Field CLS p75`,value:Ec(r.fieldData?.metrics.cumulativeLayoutShift)},{label:`Field period`,value:r.fieldData?.collectionPeriod?.firstDate&&r.fieldData.collectionPeriod.lastDate?`${r.fieldData.collectionPeriod.firstDate} to ${r.fieldData.collectionPeriod.lastDate}`:`Unavailable`}]}),J(`Top actions`,r.topActions.map(e=>({label:e.title,action:e.action,context:e.plainEnglish}))),Y(`Caveats`,r.caveats))}})}}),Oc=x({meta:{name:`doctor`,description:`Check local auth, scopes, config, and defaults`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await Ke();j(e)?(L(t),t.ok||(process.exitCode=1)):(ra(`SEO doctor`,Ji(t.checks)),process.stdout.write(`
81
- `),ia(t.checks),process.stdout.write(`\nChecked ${t.generatedAt}\n`),t.ok||(process.exitCode=1))}}),kc=e=>{let t=T(e)??`page`;if(t!==`page`&&t!==`query`&&t!==`country`&&t!==`device`)throw Error(`Invalid --dimension. Use page, query, country, or device.`);return t},Ac=x({meta:{name:`segment-impact`,description:`Compare GSC movement by page, query, device, or country`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},dimension:{type:`string`,default:`page`,description:`Segment by page, query, country, or device.`},...X([`days`,`limit`,`refresh`],{days:{description:`Recent window length from 1 to 240 days. Defaults to 28.`},limit:{description:`Maximum segment rows to print. Defaults to 25.`},refresh:{description:`Bypass local cache and fetch fresh GSC data.`}}),compare:{type:`string`,description:`Legacy 1-240 day comparison length. Must equal the current window.`},"start-date":{type:`string`,description:`Exact current-window start date in YYYY-MM-DD format.`},"end-date":{type:`string`,description:`Exact current-window end date in YYYY-MM-DD format.`},"max-rows":{type:`string`,description:`Maximum retained GSC rows per window. Defaults to 100000.`},"unmatched-limit":{type:`string`,description:`Maximum one-window evidence rows to return. Defaults to 25.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=j(e),n=kc(e.dimension),r=k(e.days,`--days`),i=k(e.compare,`--compare`),a=k(e.limit,`--limit`),o=k(e[`unmatched-limit`],`--unmatched-limit`),s=k(e[`max-rows`],`--max-rows`),c=M(T(e.site)),l=await Dn({site:c,dimension:n,days:r,compareDays:i,startDate:T(e[`start-date`]),endDate:T(e[`end-date`]),limit:a,unmatchedLimit:o,maxRows:s,refresh:E(e.refresh)});t?L(l):(K({title:`Segment impact`,target:l.site,status:l.dataStatus===`complete`?`info`:`unknown`,summary:l.summary.verdict,metrics:[{label:`Dimension`,value:l.dimension},{label:`Evidence`,value:l.dataStatus},{label:`Before`,value:`${l.before.startDate} to ${l.before.endDate}`},{label:`After`,value:`${l.after.startDate} to ${l.after.endDate}`}]}),z([`Segment`,`Clicks before`,`Clicks after`,`Delta`,`Pos delta`],l.items.map(e=>[e.key,e.beforeClicks,e.afterClicks,e.clickDelta,e.positionDelta??`-`])),l.unmatchedSegments.length&&(process.stdout.write(`
80
+ `))}}),Mc=b({meta:{name:`query-cluster`,description:`Cluster GSC queries into repeated demand themes`},args:{site:{type:`string`},scope:{type:`string`},...X([`includeBrand`,`minImpressions`,`limit`],{includeBrand:{description:`Include branded queries in query clustering.`},minImpressions:{description:`Minimum impressions per query. Defaults to 25.`},limit:{description:`Maximum clusters to return. Defaults to 25; max 100.`}}),json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=A(e),n=j(w(e.site)),r=await dr({site:n,scope:w(e.scope),includeBrand:T(e[`include-brand`]),minImpressions:D(e[`min-impressions`]),limit:D(e.limit)});t?I(r):(K({title:`Query clusters`,target:r.site,status:`info`,summary:r.summary.verdict,metrics:[{label:`Scope`,value:r.scope??`All pages`},{label:`Clusters`,value:U(r.summary.clusters)},{label:`Queries`,value:U(r.summary.queries)},{label:`Impressions`,value:U(r.summary.impressions)},{label:`Clicks`,value:U(r.summary.clicks)},{label:`Minimum impressions`,value:U(r.summary.minImpressions)},{label:`Result limit`,value:U(r.summary.limit)},{label:`High opportunity`,value:U(r.summary.highOpportunityClusters)},{label:`Brand queries`,value:r.summary.brandFiltering}]}),Y(`Why this matters`,[`Clusters show repeated demand themes, so they are better inputs for page sections, hubs, and templates than one-off query exports.`,`Prioritise clusters with high impressions and low clicks; they usually reveal unclear intent coverage or weak SERP framing.`]),Y(`Recommended actions`,r.recommendations),Y(`Report caveats`,r.caveats),q([`Cluster`,`Intent`,`Queries`,`Impr`,`CTR`,`Expected`,`Lift`,`Action`],r.clusters.map(e=>[G(e.label,32),e.intent,e.queries.length,U(e.totals?.impressions??0),W(e.totals?.ctr??0),W(e.benchmark?.expectedCtr??0),e.estimatedClickLift===void 0?`-`:U(e.estimatedClickLift),G(e.recommendation??``,72)])),J(`Top cluster actions`,r.clusters.map(e=>({label:e.label,context:`${U(e.totals?.impressions??0)} impressions, ${e.estimatedClickLift===void 0?`ranking opportunity`:`${U(e.estimatedClickLift)} estimated click lift`}`,action:e.recommendation??``}))))}}),Nc=b({meta:{name:`quick-wins`,description:`Find high-ranking low-CTR query/page opportunities`},args:{site:{type:`string`},...X([`days`,`limit`,`includeBrand`,`minImpressions`,`verifyContent`,`verifyLimit`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),"brand-terms":{type:`string`,description:`Comma-separated brand terms to exclude.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=A(e),n=D(e[`verify-limit`]),r=T(e[`verify-content`])===!0||n!==void 0,i=j(w(e.site)),a=await pt({site:i,days:D(e.days),limit:D(e.limit),minImpressions:D(e[`min-impressions`]),brandTerms:[...k(e[`brand-terms`])??[]],includeBrand:T(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:T(e.js)?!0:void 0,rate:wi(e),refresh:T(e.refresh)});t?I(a):(K({title:`Quick wins`,target:a.site,status:a.source.possiblyTruncated?`unknown`:`info`,summary:a.summary.verdict,metrics:[{label:`Eligible rows`,value:U(a.summary.eligibleRows)},{label:`Returned rows`,value:U(a.summary.returnedRows)},{label:`Query clusters`,value:U(a.summary.repeatedQueryGroups)},{label:`Template patterns`,value:U(a.summary.templatePatterns)},{label:`CTR click shortfall`,value:U(a.summary.returnedEstimatedCtrClickShortfall)},{label:`Brand queries`,value:a.summary.brandFiltering},{label:`Evidence`,value:a.dataStatus},{label:`Verification`,value:fo(a)}]}),Y(`Why this matters`,[`These rows have GSC average positions from 4 to 10 and observed CTR below a site-peer or versioned fallback target.`,`Page evidence is needed before treating a CTR shortfall as a title, content, or technical finding.`]),Y(`Recommended actions`,a.recommendations),Y(`Report caveats`,a.caveats),a.items.length&&(a.templateRecommendations.length&&(q([`Template`,`URLs`,`Rows`,`Shortfall`,`Impr`,`Action`],a.templateRecommendations.map(e=>[G(e.templateLabel,34),U(e.urlCount),U(e.rowCount),U(e.totalEstimatedCtrClickShortfall),U(e.totalImpressions),G(e.action,72)])),J(`Top template actions`,a.templateRecommendations.map(e=>({label:e.templateLabel,context:`${U(e.urlCount)} URLs, ${U(e.totalEstimatedCtrClickShortfall)} heuristic CTR click shortfall`,action:`${e.action} ${e.evidence}`})))),a.groups.length&&(q([`Cluster`,`URLs`,`Rows`,`Shortfall`,`Impr`,`Sample URL`,`Action`],a.groups.map(e=>[G(e.label,44),U(e.urlCount),U(e.rowCount),U(e.totalEstimatedCtrClickShortfall),U(e.totalImpressions),G(e.sampleUrls[0]??`-`,46),G(e.recommendation,72)])),J(`Top cluster actions`,a.groups.map(e=>({label:e.label,context:`${U(e.urlCount)} URLs, ${U(e.totalEstimatedCtrClickShortfall)} heuristic CTR click shortfall`,action:e.recommendation})))),q([`Query`,`Template`,`URL`,`Pos`,`Impr`,`CTR / target`,`Shortfall`,`Fetch`,`Check`,`Action`],a.items.map(e=>[G(e.query,36),G(e.template.label,24),G(e.url,48),uo(e.position),U(e.impressions),`${W(e.ctr)} / ${W(e.targetCtr)}`,U(e.estimatedCtrClickShortfall),zo(e.contentVerification?.fetchDiagnostics),Bo(e.contentVerification?.classification),G(e.recommendation.action,64)])),J(`Top opportunity actions`,a.items.map(e=>({label:e.query,context:`${e.template.label}, pos ${uo(e.position)}, ${U(e.impressions)} impressions`,action:e.recommendation.action})))))}}),Pc=b({meta:{name:`second-page`,description:`Find URLs averaging positions above 10 through 20 in GSC`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},...X([`range`,`minImpressions`,`limit`,`includeBrand`,`verifyContent`,`verifyLimit`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=A(e),n=D(e[`verify-limit`]),r=T(e[`verify-content`])===!0||n!==void 0,i=j(w(e.site)),a=await We({site:i,range:D(e.days),minImpressions:D(e[`min-impressions`]),limit:w(e.limit)?Number(w(e.limit)):10,includeBrand:T(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:T(e.js)?!0:void 0,rate:wi(e),refresh:T(e.refresh)});t?I(a):(K({title:`Second-page opportunities`,target:a.site,status:a.source.possiblyTruncated||a.summary.fetchFailures>0?`unknown`:`info`,summary:a.summary.verdict,metrics:[{label:`Eligible pages`,value:U(a.summary.eligiblePages)},{label:`Returned pages`,value:U(a.summary.returnedPages)},{label:`Eligible queries`,value:U(a.summary.eligibleQueries)},{label:`Impressions`,value:U(a.summary.eligibleImpressions)},{label:`Content issues`,value:U(a.summary.contentIssues)},{label:`Technical issues`,value:U(a.summary.technicalIssues)},{label:`Fetch failures`,value:U(a.summary.fetchFailures)},{label:`Brand queries`,value:a.summary.brandFiltering},{label:`Evidence`,value:a.dataStatus},{label:`Verification`,value:fo(a)}]}),Y(`Recommended actions`,a.recommendations),Y(`Report caveats`,a.caveats),a.items.length?(q([`Query`,`Template`,`Pos`,`Impr`,`CTR`,`Queries`,`Fetch`,`Check`,`Action`],a.items.map(e=>[e.primaryQuery,e.template.label,e.position.toFixed(1),Math.round(e.impressions),e.ctr.toFixed(3),U(e.queryCount),zo(e.fetchDiagnostics),Bo(e.contentVerification?.classification),e.recommendation.action])),J(`Top second-page actions`,a.items.map(e=>({label:e.primaryQuery,context:`${e.template.label}, pos ${uo(e.position)}, ${U(e.impressions)} impressions`,action:e.recommendation.action}))),process.stdout.write(`${a.ledgerSummary}\n`)):(process.stdout.write(`No average-position candidates matched this report.
81
+ `),process.stdout.write(`${a.ledgerSummary}\n`)))}}),Fc=b({meta:{name:`audit-page`,description:`Fetch one page and audit title, metadata, content, links, and schema`},args:{url:{type:`string`,required:!0,description:`URL to audit.`},site:{type:`string`,description:`Optional GSC property for page search metrics, for example sc-domain:example.com.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering for extraction.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache.`}},run:async({args:e})=>{let t=await te({url:w(e.url)??``,site:w(e.site),js:T(e.js)?!0:`auto`,refresh:T(e.refresh)});A(e)?I(t):K({title:`Page audit`,target:t.url,status:t.issues.some(e=>e.severity===`high`)?`fail`:t.issues.length>0?`warning`:`pass`,summary:t.issues.length>0?`${t.issues.length} ${t.issues.length===1?`issue needs`:`issues need`} review.`:`No page issues were found by the available checks.`,metrics:[{label:`Final URL`,value:t.page.finalUrl},{label:`Title`,value:t.page.title||(t.page.title===``?`Empty`:`Missing`)},{label:`Meta description`,value:t.page.metaDescription||(t.page.metaDescription===``?`Empty`:`Missing`)},{label:`Words`,value:t.page.wordCount},{label:`Fetch`,value:zo(t.fetchDiagnostics)}],diagnostics:[{title:`Issues`,items:t.issues.map(e=>({status:e.severity===`high`?`fail`:`warning`,title:`${e.code}: ${e.principle}`,explanation:e.detail}))}]})}});function Ic(e){let t=w(e)??`mobile`;if(t!==`mobile`&&t!==`desktop`)throw new g(`INVALID_INPUT`,`Invalid --strategy. Use mobile or desktop.`);return t}function Lc(e){return e?e.displayValue??String(e.value??`not measured`):`not measured`}function Rc(e){if(!e)return`not available`;let t=e.unit===`milliseconds`?`ms`:``;return`${e.p75}${t} (${e.rating})`}const zc=b({meta:{name:`perf`,description:`Audit lab performance and field Core Web Vitals`},subCommands:{audit:b({meta:{name:`audit`,description:`Run a Lighthouse/Core Web Vitals performance audit`},args:{url:{type:`string`,description:`URL to audit.`},strategy:{type:`string`,default:`mobile`,description:`Audit strategy: mobile or desktop.`},"lighthouse-bin":{type:`string`,description:`Custom Lighthouse binary path. Defaults to the bundled version.`},"crux-key":{type:`string`,description:`CrUX API key. Prefer SEO_CRUX_API_KEY to avoid shell history.`},raw:{type:`boolean`,default:!1,description:`Include the full Lighthouse JSON in JSON output.`},refresh:{type:`boolean`,default:!1,description:`Bypass the local performance report cache.`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=A(e),n=w(e.url);if(!n)throw new g(`INVALID_INPUT`,`No URL given. Pass --url.`);let r=await l({url:n,strategy:Ic(e.strategy),lighthouseBin:w(e[`lighthouse-bin`]),cruxApiKey:w(e[`crux-key`]),refresh:T(e.refresh),includeRaw:t&&T(e.raw)});t?I(r):(K({title:`Performance report`,target:r.url,status:r.dataStatus===`partial`?`unknown`:r.grade===`good`?`pass`:`warning`,summary:r.headline,metrics:[{label:`Source`,value:r.source},{label:`Strategy`,value:r.strategy},{label:`Lab score`,value:r.score===void 0?`Unknown`:`${r.score}/100`},{label:`Lab grade`,value:r.grade},{label:`Evidence`,value:r.dataStatus},{label:`FCP`,value:Lc(r.metrics.firstContentfulPaint)},{label:`LCP`,value:Lc(r.metrics.largestContentfulPaint)},{label:`TBT`,value:Lc(r.metrics.totalBlockingTime)},{label:`CLS`,value:Lc(r.metrics.cumulativeLayoutShift)},{label:`INP`,value:Lc(r.metrics.interactionToNextPaint)},{label:`Server response`,value:Lc(r.metrics.serverResponseTime)},{label:`Fallback fetch`,value:Lc(r.metrics.fallbackFetchDuration)},{label:`Field data`,value:r.fieldData?`${r.fieldData.scope} ${r.fieldData.formFactor.toLowerCase()} (${r.fieldData.assessment.status})`:r.fieldDataStatus.status},{label:`Field LCP p75`,value:Rc(r.fieldData?.metrics.largestContentfulPaint)},{label:`Field INP p75`,value:Rc(r.fieldData?.metrics.interactionToNextPaint)},{label:`Field CLS p75`,value:Rc(r.fieldData?.metrics.cumulativeLayoutShift)},{label:`Field period`,value:r.fieldData?.collectionPeriod?.firstDate&&r.fieldData.collectionPeriod.lastDate?`${r.fieldData.collectionPeriod.firstDate} to ${r.fieldData.collectionPeriod.lastDate}`:`Unavailable`}]}),J(`Top actions`,r.topActions.map(e=>({label:e.title,action:e.action,context:e.plainEnglish}))),Y(`Caveats`,r.caveats))}})}}),Bc=b({meta:{name:`doctor`,description:`Check local auth, scopes, config, and defaults`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await Ye();A(e)?(I(t),t.ok||(process.exitCode=1)):(la(`SEO doctor`,ea(t.checks)),process.stdout.write(`
82
+ `),ua(t.checks),process.stdout.write(`\nChecked ${t.generatedAt}\n`),t.ok||(process.exitCode=1))}}),Vc=e=>{let t=w(e)??`page`;if(t!==`page`&&t!==`query`&&t!==`country`&&t!==`device`)throw Error(`Invalid --dimension. Use page, query, country, or device.`);return t},Hc=b({meta:{name:`segment-impact`,description:`Compare GSC movement by page, query, device, or country`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},dimension:{type:`string`,default:`page`,description:`Segment by page, query, country, or device.`},...X([`days`,`limit`,`refresh`],{days:{description:`Recent window length from 1 to 240 days. Defaults to 28.`},limit:{description:`Maximum segment rows to print. Defaults to 25.`},refresh:{description:`Bypass local cache and fetch fresh GSC data.`}}),compare:{type:`string`,description:`Legacy 1-240 day comparison length. Must equal the current window.`},"start-date":{type:`string`,description:`Exact current-window start date in YYYY-MM-DD format.`},"end-date":{type:`string`,description:`Exact current-window end date in YYYY-MM-DD format.`},"max-rows":{type:`string`,description:`Maximum retained GSC rows per window. Defaults to 100000.`},"unmatched-limit":{type:`string`,description:`Maximum one-window evidence rows to return. Defaults to 25.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=A(e),n=Vc(e.dimension),r=O(e.days,`--days`),i=O(e.compare,`--compare`),a=O(e.limit,`--limit`),o=O(e[`unmatched-limit`],`--unmatched-limit`),s=O(e[`max-rows`],`--max-rows`),c=j(w(e.site)),l=await Ve({site:c,dimension:n,days:r,compareDays:i,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),limit:a,unmatchedLimit:o,maxRows:s,refresh:T(e.refresh)});t?I(l):(K({title:`Segment impact`,target:l.site,status:l.dataStatus===`complete`?`info`:`unknown`,summary:l.summary.verdict,metrics:[{label:`Dimension`,value:l.dimension},{label:`Evidence`,value:l.dataStatus},{label:`Before`,value:`${l.before.startDate} to ${l.before.endDate}`},{label:`After`,value:`${l.after.startDate} to ${l.after.endDate}`}]}),R([`Segment`,`Clicks before`,`Clicks after`,`Delta`,`Pos delta`],l.items.map(e=>[e.key,e.beforeClicks,e.afterClicks,e.clickDelta,e.positionDelta??`-`])),l.unmatchedSegments.length&&(process.stdout.write(`
82
83
  One-window evidence (not treated as zero)
83
- `),z([`Segment`,`Retained in`,`Clicks`,`Impressions`],l.unmatchedSegments.map(e=>[e.key,e.retainedIn,e.clicks,e.impressions]))),Y(`Warnings`,l.warnings))}});function jc(e){return`${U(e)} ${e===1?`row`:`rows`}`}const Mc=x({meta:{name:`striking-distance`,description:`Find query/page rows averaging positions above 10 through 20`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},...X([`days`,`minImpressions`,`limit`,`includeBrand`,`verifyContent`,`verifyLimit`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=j(e),n=O(e[`verify-limit`]),r=E(e[`verify-content`])===!0||n!==void 0,i=M(T(e.site)),a=await Qe({site:i,days:O(e.days),minImpressions:O(e[`min-impressions`]),limit:O(e.limit),includeBrand:E(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:E(e.js)?!0:void 0,rate:vi(e),refresh:E(e.refresh)});t?L(a):(K({title:`Striking-distance opportunities`,target:a.site,status:a.source.possiblyTruncated?`unknown`:`info`,summary:a.summary.verdict,metrics:[{label:`Eligible rows`,value:U(a.summary.eligibleRows)},{label:`Returned rows`,value:U(a.summary.returnedRows)},{label:`Template groups`,value:U(a.summary.groups)},{label:`Impressions`,value:U(a.summary.eligibleImpressions)},{label:`Brand queries`,value:a.summary.brandFiltering},{label:`Verification`,value:a.verification.requested?`Requested`:`Off`},{label:`Evidence`,value:a.dataStatus}]}),Y(`Why this matters`,[`These rows have a GSC average position above 10 and at most 20. Treat them as candidates for investigation, not guaranteed page-two rankings.`,`Groups use all eligible rows. A shared-template label is only a candidate until recurring evidence is verified across distinct URLs.`]),Y(`Recommended actions`,a.recommendations),Y(`Report caveats`,a.caveats),a.groups.length&&(q([`Group`,`Rows`,`URLs`,`Impr`,`Avg pos`,`Scope`,`Action`],a.groups.map(e=>[G(e.label,36),U(e.rowCount),U(e.uniqueUrls),U(e.totalImpressions),Qa(e.impressionWeightedPosition),e.actionScope,G(e.recommendation.action,72)])),J(`Top striking-distance group actions`,a.groups.map(e=>({label:e.label,context:`${jc(e.rowCount)}, ${U(e.totalImpressions)} impressions`,action:e.recommendation.action})))),a.items.length?(q([`Query`,`Template`,`URL`,`Impr`,`CTR`,`Pos`,`Score`,`Fetch`,`Check`,`Action`],a.items.map(e=>[G(e.query,36),G(e.template.label,24),G(e.url,48),U(e.impressions),W(e.ctr),Qa(e.position),e.priority.score,Do(e.contentVerification?.fetchDiagnostics),Oo(e.contentVerification?.classification),G(e.recommendation.action,72)])),J(`Top striking-distance actions`,a.items.map(e=>({label:e.query,context:`${e.template.label}, pos ${Qa(e.position)}, ${U(e.impressions)} impressions`,action:e.recommendation.action})))):process.stdout.write(`No striking-distance opportunities matched these filters.
84
- `))}});function Nc(e){return e===`keychain`?`system keychain`:e===`file`?`private local file`:e??`missing`}function Pc(e){return e===null?`unavailable`:`$${(e/1e6).toFixed(2)}`}function Fc(e){return e.limit===null?e.used===null?`not reported`:`${e.used.toLocaleString(`en-US`)} used; no key limit`:`${(e.remaining??0).toLocaleString(`en-US`)} of ${e.limit.toLocaleString(`en-US`)} remaining`}const Ic=x({meta:{name:`connect`,description:`Validate and save an Ahrefs API v3 key`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{if(!I({json:j(e)}))throw new d(`AUTH_REQUIRED`,`Run \`seo providers ahrefs connect\` in a terminal. Agents and CI can set ${le}.`);Wr(`Connect Ahrefs`),S(`Paste an API v3 key from Ahrefs Account settings. The validation check and Domain Rating are free; other research can consume API units.`,`API key`);let t=B(await Jr({message:`Ahrefs API v3 key`,validate:e=>e?.trim()?void 0:`API key is required`})),n=await new xn({apiKey:t}).limitsAndUsage(),r=await oe(t);S(`${n.subscription} subscription. API key units: ${Fc(n.apiKeyUnits)}.`,`Connection verified`),C(`Saved in the ${Nc(r)}. Run seo providers ahrefs status --check to verify it again.`)}}),Lc=x({meta:{name:`status`,description:`Show the local Ahrefs connection`},args:{check:{type:`boolean`,default:!1,description:`Verify the API key with the free account endpoint.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await nt(),n=!!e.check,r=n&&t?await new xn().limitsAndUsage():void 0,i={connected:!!t,apiVersion:t?3:null,credentialSource:t?.source,liveCheck:r?{status:`passed`,subscription:r.subscription,apiKeyExpiresAt:r.apiKeyExpiresAt,usageResetsAt:r.usageResetsAt,apiKeyUnits:r.apiKeyUnits,workspaceUnits:r.workspaceUnits,observedAt:r.observedAt,requestCostUnits:r.requestCostUnits}:{status:n?`unavailable`:`not-requested`}};j(e)?L(i):R([[`Connected`,i.connected?`yes`:`no`],[`API version`,i.apiVersion?`Version 3`:`not connected`],[`Credential`,Nc(i.credentialSource)],[`Live check`,i.liveCheck.status===`passed`?`passed at ${i.liveCheck.observedAt}`:i.liveCheck.status===`unavailable`?`not available without credentials`:`not requested; pass --check to verify`],...r?[[`Subscription`,r.subscription],[`API key units`,Fc(r.apiKeyUnits)],[`Workspace units`,Fc(r.workspaceUnits)],[`Usage resets`,r.usageResetsAt],[`Key expires`,r.apiKeyExpiresAt]]:[]])}}),Rc=x({meta:{name:`disconnect`,description:`Remove the saved Ahrefs API v3 key`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{await Xe();let t=!!process.env[le]?.trim(),n={savedCredentialRemoved:!0,environmentCredential:t?`active`:`missing`,note:t?`The environment variable was not changed. Clear ${le} to fully disconnect.`:`Ahrefs is disconnected.`};j(e)?L(n):process.stdout.write(`${n.note}\n`)}}),zc=x({meta:{name:`ahrefs`,description:`Connect Ahrefs for optional search and link data`},subCommands:{connect:Ic,status:Lc,disconnect:Rc}}),Bc="Run `seo providers bing connect` with a new API key.",Vc=x({meta:{name:`connect`,description:`Check and save a Bing Webmaster Tools API key`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{if(!I({json:j(e)}))throw new d(`AUTH_REQUIRED`,`Run \`seo providers bing connect\` in a terminal. Agents and CI can set ${ze}.`);Wr(`Connect Bing Webmaster Tools`),S(`In Bing Webmaster Tools, open Settings, then API access, and copy the API key. Bing data is free.`,`API key`);let t=B(await Jr({message:`Bing Webmaster API key`,validate:e=>e?.trim()?void 0:`API key is required`})),n=await We(Qn({apiKey:t},{signIn:Bc})),r=await $e(t);S(`${n.filter(e=>e.verified).length} verified sites.`,`Connection verified`),C(`Saved in the ${Nc(r)}.`)}}),Hc=x({meta:{name:`status`,description:`Show the Bing Webmaster connection`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await o(),n=t?await We(Qn({apiKey:t.apiKey},{signIn:Bc})):null,r={connected:!!t,credentialSource:t?.source??null,sites:n?.filter(e=>e.verified).map(e=>e.url)??[]};j(e)?L(r):process.stdout.write(t?`Connected (${Nc(t.source)}). Verified sites: ${r.sites.join(`, `)||`none`}.\n`:"Not connected. Run `seo providers bing connect`.\n")}}),Uc=x({meta:{name:`disconnect`,description:`Remove the saved Bing Webmaster API key`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{await ir();let t=!!process.env[ze]?.trim(),n=t?`The saved key is removed. Clear ${ze} to fully disconnect.`:`Bing is disconnected.`;j(e)?L({removed:!0,environment:t}):process.stdout.write(`${n}\n`)}}),Wc=x({meta:{name:`bing`,description:`Connect Bing Webmaster Tools for Bing search data`},subCommands:{connect:Vc,status:Hc,disconnect:Uc}}),Gc=x({meta:{name:`connect`,description:`Validate and save DataForSEO API credentials`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{if(!I({json:j(e)}))throw new d(`AUTH_REQUIRED`,`Run \`seo providers dataforseo connect\` in a terminal. Agents and CI can set ${De} and ${Ne}.`);Wr(`Connect DataForSEO`),S(`Use the API login and API password from DataForSEO API Access. The validation call is free; later research reports can make charged requests.`,`API credentials`);let t=B(await Xr({message:`DataForSEO API login`,validate:e=>e?.trim()?void 0:`API login is required`})),n=B(await Jr({message:`DataForSEO API password`,validate:e=>e?void 0:`API password is required`})),r={login:t.trim(),password:n},i=await new Lt({credentials:()=>r}).userData(),a=await xe(r);S(`${i.login} is connected with an account balance of ${Pc(i.balanceMicros)}.`,`Connection verified`),C(`Saved in the ${Nc(a)}. Run seo providers dataforseo status --check to verify it again.`)}}),Kc=x({meta:{name:`status`,description:`Show the local DataForSEO connection`},args:{check:{type:`boolean`,default:!1,description:`Verify credentials with the free account endpoint.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await fe(),n=!!e.check,r=n&&t?await new Lt().userData():void 0,i={connected:!!t,credentialSource:t?.source,migratedLegacyCredentials:t?.migrated??!1,liveCheck:r?{status:`passed`,account:r.login,timezone:r.timezone,balanceMicros:r.balanceMicros,observedAt:r.observedAt,requestCostMicros:r.requestCostMicros}:{status:n?`unavailable`:`not-requested`}};j(e)?L(i):R([[`Connected`,i.connected?`yes`:`no`],[`Credential`,Nc(i.credentialSource)],[`Live check`,i.liveCheck.status===`passed`?`passed at ${i.liveCheck.observedAt}`:i.liveCheck.status===`unavailable`?`not available without credentials`:`not requested; pass --check to verify`],...r?[[`Account`,r.login],[`Balance`,Pc(r.balanceMicros)]]:[]])}}),qc=x({meta:{name:`disconnect`,description:`Remove saved DataForSEO credentials`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{await re();let t=!!process.env[De]?.trim(),n=!!process.env[Ne],r={savedCredentialsRemoved:!0,environmentCredentials:t&&n?`active`:t||n?`partial`:`missing`,note:t||n?`Environment variables were not changed. Clear ${De} and ${Ne} to fully disconnect.`:`DataForSEO is disconnected.`};j(e)?L(r):process.stdout.write(`${r.note}\n`)}}),Jc=x({meta:{name:`dataforseo`,description:`Connect DataForSEO for optional search data`},subCommands:{connect:Gc,status:Kc,disconnect:qc}});function Yc(e){if(!e)return{};let t;try{t=JSON.parse(e)}catch{throw new d(`INVALID_INPUT`,`--account must be a JSON object.`)}if(!t||Array.isArray(t)||typeof t!=`object`)throw new d(`INVALID_INPUT`,`--account must be a JSON object.`);let n=Object.entries(t);if(n.length>20||n.some(([e,t])=>!e||e.length>64||typeof t!=`string`||t.length>4096))throw new d(`INVALID_INPUT`,`--account must contain at most 20 bounded string fields.`);return Object.fromEntries(n.map(([e,t])=>[e,t.trim()]))}function Xc(e){if(!e)return{};let t;try{t=JSON.parse(e)}catch{throw new d(`INVALID_INPUT`,`--params must be a JSON object.`)}if(!t||Array.isArray(t)||typeof t!=`object`)throw new d(`INVALID_INPUT`,`--params must be a JSON object.`);let n=Object.entries(t);if(n.length>100||n.some(([e])=>!/^[A-Za-z][A-Za-z0-9-]{0,63}$/u.test(e))||Buffer.byteLength(e)>65536)throw new d(`INVALID_INPUT`,`--params must be a JSON object smaller than 64 KiB.`);return Object.fromEntries(n)}async function Zc(e){let t=await Pt(),n=t.registry.get(e);if(n)return n;let r=t.failures.find(t=>t.id===e);throw r?new d(`INVALID_INPUT`,`Provider ${e} could not load: ${r.message}`):new d(`INVALID_INPUT`,`Provider ${e} is not installed.`)}function Qc(e,t){let n=new Set(e.connection.fields.filter(e=>e.kind===`account`).map(e=>e.id)),r=Object.keys(t).find(e=>!n.has(e));if(r)throw new d(`INVALID_INPUT`,`${r} is not an account field for ${e.displayName}.`);let i=e.connection.normalizeAccount?e.connection.normalizeAccount(t):{...t};if(Object.keys(i).find(e=>!n.has(e)))throw new d(`PROVIDER_UNAVAILABLE`,`${e.displayName} returned an unknown account field.`);for(let t of e.connection.fields.filter(e=>e.kind===`account`&&e.required!==!1))if(!i[t.id]?.trim())throw new d(`INVALID_INPUT`,`${t.label} is required.`);return i}async function $c(){return er()}const el={list:x({meta:{name:`list`,description:`List installed provider packages`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await $c();j(e)?L(t):t.installed.length>0?z([`Installed provider`,`Package`,`Version`,`Status`],t.installed.map(e=>[e.id,e.package,e.version,e.loadStatus])):process.stdout.write(`No provider extensions are installed.
85
- `)}}),describe:x({meta:{name:`describe`,description:`Describe one installed provider for an agent`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=T(e.id)??``,n=await Hn(t);j(e)?L(n):R([[`Provider`,n.displayName],[`Package`,`${n.package}@${n.version}`],[`Description`,n.description],[`Capabilities`,n.capabilities.map(e=>e.id).join(`, `)||`none`],[`Actions`,n.actions.map(e=>e.id).join(`, `)||`none`]])}}),install:x({meta:{name:`install`,description:`Install one provider package from npm`},args:{package:{type:`positional`,required:!0,description:`npm package name with an optional exact version.`},yes:{type:`boolean`,default:!1,description:`Approve third-party code installation without prompting.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=T(e.package)??``,n=j(e),r=E(e.yes),i=I({json:n});if(!r&&!i)throw new d(`INVALID_INPUT`,`Provider installation runs third-party code. Review the package, then pass --yes to approve it in JSON or CI mode.`);let a;try{a=await Gt(t)}catch(e){throw new d(`INVALID_INPUT`,e instanceof Error?e.message:String(e))}if(!r&&(Wr(`Install provider package`),S([`${a.package}@${a.version}`,`Publisher: ${a.publisher??`not supplied by npm`}`,`Repository: ${a.repository??`not supplied by npm`}`,`Integrity: ${a.integrity}`].join(`
86
- `),`Package`),S(`This package can read files, use the network, and run with the same local permissions as seo. Installing it is not a security review or endorsement.`,`Third-party code`),!B(await Ur({message:`Install ${a.package}@${a.version}?`,initialValue:!1})))){C(`Provider was not installed.`);return}let o;try{o=await Vt(a)}catch(e){throw new d(`PROVIDER_UNAVAILABLE`,e instanceof Error?e.message:String(e))}n?L({installed:o,package:a}):C(`Installed provider ${o.id} from ${o.package}@${o.version}.`)}}),remove:x({meta:{name:`remove`,description:`Remove one installed provider extension`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},yes:{type:`boolean`,default:!1,description:`Remove the package without prompting.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=T(e.id)??``,n=j(e),r=E(e.yes),i=I({json:n});if(!r&&!i)throw new d(`INVALID_INPUT`,`Pass --yes to remove a provider extension in JSON or CI mode.`);if(!r&&!B(await Ur({message:`Remove provider ${t}?`,initialValue:!1})))return;let a=await mt(t);if(!a)throw new d(`INVALID_INPUT`,`Provider ${t} is not installed.`);n?L({removed:a}):process.stdout.write(`Removed ${t}.\n`)}}),connect:x({meta:{name:`connect`,description:`Validate and save one installed provider connection`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},account:{type:`string`,description:`Account fields as JSON. Secret fields must use their environment variables.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=T(e.id)??``,r=j(e),i=I({json:r}),a=await Zc(t),o={...Xn(t),...Yc(T(e.account))},s={};if(i){Wr(`Connect ${a.displayName}`),a.connection.verificationNotice&&S(a.connection.verificationNotice,`Connection check`);for(let e of a.connection.fields){if(e.kind===`account`){let t=B(await Xr({message:e.label,placeholder:e.description,initialValue:o[e.id],validate:t=>e.required!==!1&&!t?.trim()?`${e.label} is required`:void 0}));t?.trim()&&(o[e.id]=t.trim());continue}if(e.envVar&&process.env[e.envVar]?.trim())continue;let t=B(await Jr({message:e.label,validate:t=>e.required!==!1&&!t?.trim()?`${e.label} is required`:void 0}));t?.trim()&&(s[e.id]=t.trim())}}o=Qc(a,o);let c={...s};Object.keys(c).length===0&&(c=await mn({providerId:t,account:o,fields:a.connection.fields})),await n({providerId:t,account:o,credentials:c}),Object.keys(s).length>0&&await On({providerId:t,account:o,credentials:s}),He(t,o);let l={provider:t,connected:!0,account:o,capabilities:(a.capabilities??[]).map(e=>e.id),actions:(a.actions??[]).map(e=>e.id)};r?L(l):C(`Connected ${a.displayName}. Run seo providers describe ${t} to see what it can do.`)}}),status:x({meta:{name:`status`,description:`Show one installed provider connection`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},check:{type:`boolean`,default:!1,description:`Run the provider connection check.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=T(e.id)??``,r=await Zc(t),i=Xn(t),a;try{a=await mn({providerId:t,account:i,fields:r.connection.fields})}catch{a=void 0}let o=r.connection.fields.filter(e=>e.kind===`account`&&e.required!==!1).every(e=>!!i[e.id]?.trim())&&a!==void 0,s=E(e.check);if(s&&!o)throw new d(`AUTH_REQUIRED`,`Provider ${t} is not connected. Run \`seo providers connect ${t}\`.`);s&&a&&await n({providerId:t,account:i,credentials:a});let c={provider:t,installed:!0,connected:o,account:i,capabilities:(r.capabilities??[]).map(e=>e.id),actions:(r.actions??[]).map(e=>e.id),check:s?`passed`:`not-requested`};j(e)?L(c):z([`Provider`,`Connected`,`Capabilities`,`Check`],[[r.displayName,o?`yes`:`no`,c.capabilities.join(`, `),c.check]])}}),disconnect:x({meta:{name:`disconnect`,description:`Remove one saved provider connection`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=T(e.id)??``;await Zc(t);let n=Xn(t);await Fn({providerId:t,account:n}),St(t);let r={provider:t,disconnected:!0,note:`Environment variables were not changed.`};j(e)?L(r):process.stdout.write(`Disconnected ${t}. ${r.note}\n`)}}),run:x({meta:{name:`run`,description:`Run one action supplied by an installed provider`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},action:{type:`positional`,required:!0,description:`Provider action id.`},account:{type:`string`,description:`Account fields as JSON. Defaults to the saved connection.`},params:{type:`string`,description:`Action parameters as a JSON object.`},refresh:{type:`boolean`,default:!1,description:`Bypass the local provider cache.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=T(e.id)??``,n=T(e.action)??``;await Zc(t);let r={...Xn(t),...Yc(T(e.account))};L(await l({providerId:t,actionId:n,account:r,params:Xc(T(e.params)),refresh:E(e.refresh)}))}}),doctor:x({meta:{name:`doctor`,description:`Validate installed provider packages and entry points`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await $c(),n={ok:t.installed.every(e=>e.loadStatus===`ready`),installed:t.installed};j(e)?L(n):n.installed.length===0?process.stdout.write(`No provider extensions are installed.
87
- `):z([`Provider`,`Package`,`Version`,`Status`],n.installed.map(e=>[e.id,e.package,e.version,e.error??e.loadStatus]))}})},tl=x({meta:{name:`providers`,description:`Connect optional data providers`},subCommands:{...el,ahrefs:zc,bing:Wc,dataforseo:Jc}}),nl={"ai-search":`AI search`,crawl:`Crawling and technical checks`,diagnosis:`Diagnosis`,monitoring:`Monitoring`,opportunities:`Opportunities`,reporting:`Reporting`,setup:`Setup`,workflows:`Workflows`};function rl(e){let t=T(e);if(t){if(!Pn.includes(t))throw new d(`INVALID_INPUT`,`Unknown report category: ${t}. Choose ${Pn.join(`, `)}.`);return t}}async function il(e,t){let n=T(e),r=T(t);if(n&&r)throw new d(`INVALID_INPUT`,`Use either --params or --params-file, not both.`);if(!n&&!r)return{};let i=n??await b(r??``,`utf8`),a;try{a=JSON.parse(i)}catch{throw new d(`INVALID_INPUT`,`Report parameters must be valid JSON.`)}if(!a||typeof a!=`object`||Array.isArray(a))throw new d(`INVALID_INPUT`,`Report parameters must be an object.`);return a}function al(e){if(!e.isError)return;let t=e.structuredContent;throw new d(t?.error?.code??`INTERNAL_ERROR`,t?.error?.message??`The report could not be completed.`)}function ol(e){if(!e||typeof e!=`object`)return[];let t=e,n=new Set(t.required??[]);return Object.entries(t.properties??{}).map(([e,t])=>{let r=Array.isArray(t.type)?t.type.join(` | `):t.type??`any`;return{name:e,type:r===`array`&&t.items?.type?`${t.items.type}[]`:t.format?`${r} (${t.format})`:r,required:n.has(e),description:t.description}})}const sl=x({meta:{name:`list`,description:`List report ids available to the CLI and MCP server`},args:{category:{type:`string`,description:`Filter by category: ${Pn.join(`, `)}.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=rl(e.category),n=_n(t);j(e)?L({reports:n,categories:Pn}):(oa(n,{noun:`report`,categoryLabels:nl}),process.stdout.write(`
88
- `),na({title:`Need the detail?`,body:`Describe one report to see when to use it, what it needs, and what the result can prove.`,command:`seo reports describe <id>`}))}}),cl=x({meta:{name:`describe`,description:`Show the purpose and parameter schema for one report`},args:{id:{type:`positional`,required:!0,description:"Report id from `seo reports list`."},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=Yt(T(e.id)??``);j(e)?L({report:t}):(ra(t.name,t.description),process.stdout.write(`
89
- `),R([[`ID`,t.id],[`Category`,t.category],[`Outcome`,t.outcome]]),process.stdout.write(`
90
- `),la(`Use when`,t.useWhen),process.stdout.write(`
91
- `),la(`Avoid when`,t.avoidWhen),process.stdout.write(`
92
- `),la(`Read in order`,t.readOrder),process.stdout.write(`
93
- `),la(`Do not claim`,t.doNotClaim),process.stdout.write(`
94
- `),ca(`Verify`,t.verify),process.stdout.write(`
95
- `),na({title:`Implement findings`,body:t.agentWorkflow.completion,command:t.agentWorkflow.actionView.cli}),t.related.length>0&&(process.stdout.write(`
96
- `),la(`Related reports`,t.related.map(e=>`${e.id}: ${e.reason}`))),process.stdout.write(`
84
+ `),R([`Segment`,`Retained in`,`Clicks`,`Impressions`],l.unmatchedSegments.map(e=>[e.key,e.retainedIn,e.clicks,e.impressions]))),Y(`Warnings`,l.warnings))}});function Uc(e){return`${U(e)} ${e===1?`row`:`rows`}`}const Wc=b({meta:{name:`striking-distance`,description:`Find query/page rows averaging positions above 10 through 20`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},...X([`days`,`minImpressions`,`limit`,`includeBrand`,`verifyContent`,`verifyLimit`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=A(e),n=D(e[`verify-limit`]),r=T(e[`verify-content`])===!0||n!==void 0,i=j(w(e.site)),a=await be({site:i,days:D(e.days),minImpressions:D(e[`min-impressions`]),limit:D(e.limit),includeBrand:T(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:T(e.js)?!0:void 0,rate:wi(e),refresh:T(e.refresh)});t?I(a):(K({title:`Striking-distance opportunities`,target:a.site,status:a.source.possiblyTruncated?`unknown`:`info`,summary:a.summary.verdict,metrics:[{label:`Eligible rows`,value:U(a.summary.eligibleRows)},{label:`Returned rows`,value:U(a.summary.returnedRows)},{label:`Template groups`,value:U(a.summary.groups)},{label:`Impressions`,value:U(a.summary.eligibleImpressions)},{label:`Brand queries`,value:a.summary.brandFiltering},{label:`Verification`,value:a.verification.requested?`Requested`:`Off`},{label:`Evidence`,value:a.dataStatus}]}),Y(`Why this matters`,[`These rows have a GSC average position above 10 and at most 20. Treat them as candidates for investigation, not guaranteed page-two rankings.`,`Groups use all eligible rows. A shared-template label is only a candidate until recurring evidence is verified across distinct URLs.`]),Y(`Recommended actions`,a.recommendations),Y(`Report caveats`,a.caveats),a.groups.length&&(q([`Group`,`Rows`,`URLs`,`Impr`,`Avg pos`,`Scope`,`Action`],a.groups.map(e=>[G(e.label,36),U(e.rowCount),U(e.uniqueUrls),U(e.totalImpressions),uo(e.impressionWeightedPosition),e.actionScope,G(e.recommendation.action,72)])),J(`Top striking-distance group actions`,a.groups.map(e=>({label:e.label,context:`${Uc(e.rowCount)}, ${U(e.totalImpressions)} impressions`,action:e.recommendation.action})))),a.items.length?(q([`Query`,`Template`,`URL`,`Impr`,`CTR`,`Pos`,`Score`,`Fetch`,`Check`,`Action`],a.items.map(e=>[G(e.query,36),G(e.template.label,24),G(e.url,48),U(e.impressions),W(e.ctr),uo(e.position),e.priority.score,zo(e.contentVerification?.fetchDiagnostics),Bo(e.contentVerification?.classification),G(e.recommendation.action,72)])),J(`Top striking-distance actions`,a.items.map(e=>({label:e.query,context:`${e.template.label}, pos ${uo(e.position)}, ${U(e.impressions)} impressions`,action:e.recommendation.action})))):process.stdout.write(`No striking-distance opportunities matched these filters.
85
+ `))}});function Gc(e){return e===`keychain`?`system keychain`:e===`file`?`private local file`:e??`missing`}function Kc(e){return e===null?`unavailable`:`$${(e/1e6).toFixed(2)}`}function qc(e){return e.limit===null?e.used===null?`not reported`:`${e.used.toLocaleString(`en-US`)} used; no key limit`:`${(e.remaining??0).toLocaleString(`en-US`)} of ${e.limit.toLocaleString(`en-US`)} remaining`}const Jc=b({meta:{name:`connect`,description:`Validate and save an Ahrefs API v3 key`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{if(!F({json:A(e)}))throw new g(`AUTH_REQUIRED`,`Run \`seo providers ahrefs connect\` in a terminal. Agents and CI can set ${xe}.`);Xr(`Connect Ahrefs`),x(`Paste an API v3 key from Ahrefs Account settings. The validation check and Domain Rating are free; other research can consume API units.`,`API key`);let t=z(await ei({message:`Ahrefs API v3 key`,validate:e=>e?.trim()?void 0:`API key is required`})),n=await new En({apiKey:t}).limitsAndUsage(),r=await dt(t);x(`${n.subscription} subscription. API key units: ${qc(n.apiKeyUnits)}.`,`Connection verified`),S(`Saved in the ${Gc(r)}. Run seo providers ahrefs status --check to verify it again.`)}}),Yc=b({meta:{name:`status`,description:`Show the local Ahrefs connection`},args:{check:{type:`boolean`,default:!1,description:`Verify the API key with the free account endpoint.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await ve(),n=!!e.check,r=n&&t?await new En().limitsAndUsage():void 0,i={connected:!!t,apiVersion:t?3:null,credentialSource:t?.source,liveCheck:r?{status:`passed`,subscription:r.subscription,apiKeyExpiresAt:r.apiKeyExpiresAt,usageResetsAt:r.usageResetsAt,apiKeyUnits:r.apiKeyUnits,workspaceUnits:r.workspaceUnits,observedAt:r.observedAt,requestCostUnits:r.requestCostUnits}:{status:n?`unavailable`:`not-requested`}};A(e)?I(i):L([[`Connected`,i.connected?`yes`:`no`],[`API version`,i.apiVersion?`Version 3`:`not connected`],[`Credential`,Gc(i.credentialSource)],[`Live check`,i.liveCheck.status===`passed`?`passed at ${i.liveCheck.observedAt}`:i.liveCheck.status===`unavailable`?`not available without credentials`:`not requested; pass --check to verify`],...r?[[`Subscription`,r.subscription],[`API key units`,qc(r.apiKeyUnits)],[`Workspace units`,qc(r.workspaceUnits)],[`Usage resets`,r.usageResetsAt],[`Key expires`,r.apiKeyExpiresAt]]:[]])}}),Xc=b({meta:{name:`disconnect`,description:`Remove the saved Ahrefs API v3 key`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{await An();let t=!!process.env[xe]?.trim(),n={savedCredentialRemoved:!0,environmentCredential:t?`active`:`missing`,note:t?`The environment variable was not changed. Clear ${xe} to fully disconnect.`:`Ahrefs is disconnected.`};A(e)?I(n):process.stdout.write(`${n.note}\n`)}}),Zc=b({meta:{name:`ahrefs`,description:`Connect Ahrefs for optional search and link data`},subCommands:{connect:Jc,status:Yc,disconnect:Xc}}),Qc="Run `seo providers bing connect` with a new API key.",$c=b({meta:{name:`connect`,description:`Check and save a Bing Webmaster Tools API key`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{if(!F({json:A(e)}))throw new g(`AUTH_REQUIRED`,`Run \`seo providers bing connect\` in a terminal. Agents and CI can set ${fe}.`);Xr(`Connect Bing Webmaster Tools`),x(`In Bing Webmaster Tools, open Settings, then API access, and copy the API key. Bing data is free.`,`API key`);let t=z(await ei({message:`Bing Webmaster API key`,validate:e=>e?.trim()?void 0:`API key is required`})),n=await m(ie({apiKey:t},{signIn:Qc})),r=await le(t);x(`${n.filter(e=>e.verified).length} verified sites.`,`Connection verified`),S(`Saved in the ${Gc(r)}.`)}}),el=b({meta:{name:`status`,description:`Show the Bing Webmaster connection`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await at(),n=t?await m(ie({apiKey:t.apiKey},{signIn:Qc})):null,r={connected:!!t,credentialSource:t?.source??null,sites:n?.filter(e=>e.verified).map(e=>e.url)??[]};A(e)?I(r):process.stdout.write(t?`Connected (${Gc(t.source)}). Verified sites: ${r.sites.join(`, `)||`none`}.\n`:"Not connected. Run `seo providers bing connect`.\n")}}),tl=b({meta:{name:`disconnect`,description:`Remove the saved Bing Webmaster API key`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{await $e();let t=!!process.env[fe]?.trim(),n=t?`The saved key is removed. Clear ${fe} to fully disconnect.`:`Bing is disconnected.`;A(e)?I({removed:!0,environment:t}):process.stdout.write(`${n}\n`)}}),nl=b({meta:{name:`bing`,description:`Connect Bing Webmaster Tools for Bing search data`},subCommands:{connect:$c,status:el,disconnect:tl}}),rl=b({meta:{name:`connect`,description:`Validate and save DataForSEO API credentials`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{if(!F({json:A(e)}))throw new g(`AUTH_REQUIRED`,`Run \`seo providers dataforseo connect\` in a terminal. Agents and CI can set ${we} and ${He}.`);Xr(`Connect DataForSEO`),x(`Use the API login and API password from DataForSEO API Access. The validation call is free; later research reports can make charged requests.`,`API credentials`);let t=z(await ni({message:`DataForSEO API login`,validate:e=>e?.trim()?void 0:`API login is required`})),n=z(await ei({message:`DataForSEO API password`,validate:e=>e?void 0:`API password is required`})),r={login:t.trim(),password:n},i=await new Bt({credentials:()=>r}).userData(),a=await nt(r);x(`${i.login} is connected with an account balance of ${Kc(i.balanceMicros)}.`,`Connection verified`),S(`Saved in the ${Gc(a)}. Run seo providers dataforseo status --check to verify it again.`)}}),il=b({meta:{name:`status`,description:`Show the local DataForSEO connection`},args:{check:{type:`boolean`,default:!1,description:`Verify credentials with the free account endpoint.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await s(),n=!!e.check,r=n&&t?await new Bt().userData():void 0,i={connected:!!t,credentialSource:t?.source,migratedLegacyCredentials:t?.migrated??!1,liveCheck:r?{status:`passed`,account:r.login,timezone:r.timezone,balanceMicros:r.balanceMicros,observedAt:r.observedAt,requestCostMicros:r.requestCostMicros}:{status:n?`unavailable`:`not-requested`}};A(e)?I(i):L([[`Connected`,i.connected?`yes`:`no`],[`Credential`,Gc(i.credentialSource)],[`Live check`,i.liveCheck.status===`passed`?`passed at ${i.liveCheck.observedAt}`:i.liveCheck.status===`unavailable`?`not available without credentials`:`not requested; pass --check to verify`],...r?[[`Account`,r.login],[`Balance`,Kc(r.balanceMicros)]]:[]])}}),al=b({meta:{name:`disconnect`,description:`Remove saved DataForSEO credentials`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{await lr();let t=!!process.env[we]?.trim(),n=!!process.env[He],r={savedCredentialsRemoved:!0,environmentCredentials:t&&n?`active`:t||n?`partial`:`missing`,note:t||n?`Environment variables were not changed. Clear ${we} and ${He} to fully disconnect.`:`DataForSEO is disconnected.`};A(e)?I(r):process.stdout.write(`${r.note}\n`)}}),ol=b({meta:{name:`dataforseo`,description:`Connect DataForSEO for optional search data`},subCommands:{connect:rl,status:il,disconnect:al}});function sl(e){if(!e)return{};let t;try{t=JSON.parse(e)}catch{throw new g(`INVALID_INPUT`,`--account must be a JSON object.`)}if(!t||Array.isArray(t)||typeof t!=`object`)throw new g(`INVALID_INPUT`,`--account must be a JSON object.`);let n=Object.entries(t);if(n.length>20||n.some(([e,t])=>!e||e.length>64||typeof t!=`string`||t.length>4096))throw new g(`INVALID_INPUT`,`--account must contain at most 20 bounded string fields.`);return Object.fromEntries(n.map(([e,t])=>[e,t.trim()]))}function cl(e){if(!e)return{};let t;try{t=JSON.parse(e)}catch{throw new g(`INVALID_INPUT`,`--params must be a JSON object.`)}if(!t||Array.isArray(t)||typeof t!=`object`)throw new g(`INVALID_INPUT`,`--params must be a JSON object.`);let n=Object.entries(t);if(n.length>100||n.some(([e])=>!/^[A-Za-z][A-Za-z0-9-]{0,63}$/u.test(e))||Buffer.byteLength(e)>65536)throw new g(`INVALID_INPUT`,`--params must be a JSON object smaller than 64 KiB.`);return Object.fromEntries(n)}async function ll(e){let t=await St(),n=t.registry.get(e);if(n)return n;let r=t.failures.find(t=>t.id===e);throw r?new g(`INVALID_INPUT`,`Provider ${e} could not load: ${r.message}`):new g(`INVALID_INPUT`,`Provider ${e} is not installed.`)}function ul(e,t){let n=new Set(e.connection.fields.filter(e=>e.kind===`account`).map(e=>e.id)),r=Object.keys(t).find(e=>!n.has(e));if(r)throw new g(`INVALID_INPUT`,`${r} is not an account field for ${e.displayName}.`);let i=e.connection.normalizeAccount?e.connection.normalizeAccount(t):{...t};if(Object.keys(i).find(e=>!n.has(e)))throw new g(`PROVIDER_UNAVAILABLE`,`${e.displayName} returned an unknown account field.`);for(let t of e.connection.fields.filter(e=>e.kind===`account`&&e.required!==!1))if(!i[t.id]?.trim())throw new g(`INVALID_INPUT`,`${t.label} is required.`);return i}async function dl(){return ar()}const fl={list:b({meta:{name:`list`,description:`List installed provider packages`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await dl();A(e)?I(t):t.installed.length>0?R([`Installed provider`,`Package`,`Version`,`Status`],t.installed.map(e=>[e.id,e.package,e.version,e.loadStatus])):process.stdout.write(`No provider extensions are installed.
86
+ `)}}),describe:b({meta:{name:`describe`,description:`Describe one installed provider for an agent`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=w(e.id)??``,n=await qn(t);A(e)?I(n):L([[`Provider`,n.displayName],[`Package`,`${n.package}@${n.version}`],[`Description`,n.description],[`Capabilities`,n.capabilities.map(e=>e.id).join(`, `)||`none`],[`Actions`,n.actions.map(e=>e.id).join(`, `)||`none`]])}}),install:b({meta:{name:`install`,description:`Install one provider package from npm`},args:{package:{type:`positional`,required:!0,description:`npm package name with an optional exact version.`},yes:{type:`boolean`,default:!1,description:`Approve third-party code installation without prompting.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=w(e.package)??``,n=A(e),r=T(e.yes),i=F({json:n});if(!r&&!i)throw new g(`INVALID_INPUT`,`Provider installation runs third-party code. Review the package, then pass --yes to approve it in JSON or CI mode.`);let a;try{a=await Jt(t)}catch(e){throw new g(`INVALID_INPUT`,e instanceof Error?e.message:String(e))}if(!r&&(Xr(`Install provider package`),x([`${a.package}@${a.version}`,`Publisher: ${a.publisher??`not supplied by npm`}`,`Repository: ${a.repository??`not supplied by npm`}`,`Integrity: ${a.integrity}`].join(`
87
+ `),`Package`),x(`This package can read files, use the network, and run with the same local permissions as seo. Installing it is not a security review or endorsement.`,`Third-party code`),!z(await Yr({message:`Install ${a.package}@${a.version}?`,initialValue:!1})))){S(`Provider was not installed.`);return}let o;try{o=await Wt(a)}catch(e){throw new g(`PROVIDER_UNAVAILABLE`,e instanceof Error?e.message:String(e))}n?I({installed:o,package:a}):S(`Installed provider ${o.id} from ${o.package}@${o.version}.`)}}),remove:b({meta:{name:`remove`,description:`Remove one installed provider extension`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},yes:{type:`boolean`,default:!1,description:`Remove the package without prompting.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=w(e.id)??``,n=A(e),r=T(e.yes),i=F({json:n});if(!r&&!i)throw new g(`INVALID_INPUT`,`Pass --yes to remove a provider extension in JSON or CI mode.`);if(!r&&!z(await Yr({message:`Remove provider ${t}?`,initialValue:!1})))return;let a=await _t(t);if(!a)throw new g(`INVALID_INPUT`,`Provider ${t} is not installed.`);n?I({removed:a}):process.stdout.write(`Removed ${t}.\n`)}}),connect:b({meta:{name:`connect`,description:`Validate and save one installed provider connection`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},account:{type:`string`,description:`Account fields as JSON. Secret fields must use their environment variables.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=w(e.id)??``,n=A(e),r=F({json:n}),i=await ll(t),a={...tr(t),...sl(w(e.account))},o={};if(r){Xr(`Connect ${i.displayName}`),i.connection.verificationNotice&&x(i.connection.verificationNotice,`Connection check`);for(let e of i.connection.fields){if(e.kind===`account`){let t=z(await ni({message:e.label,placeholder:e.description,initialValue:a[e.id],validate:t=>e.required!==!1&&!t?.trim()?`${e.label} is required`:void 0}));t?.trim()&&(a[e.id]=t.trim());continue}if(e.envVar&&process.env[e.envVar]?.trim())continue;let t=z(await ei({message:e.label,validate:t=>e.required!==!1&&!t?.trim()?`${e.label} is required`:void 0}));t?.trim()&&(o[e.id]=t.trim())}}a=ul(i,a);let s={...o};Object.keys(s).length===0&&(s=await In({providerId:t,account:a,fields:i.connection.fields})),await $t({providerId:t,account:a,credentials:s}),Object.keys(o).length>0&&await At({providerId:t,account:a,credentials:o}),Ge(t,a);let c={provider:t,connected:!0,account:a,capabilities:(i.capabilities??[]).map(e=>e.id),actions:(i.actions??[]).map(e=>e.id)};n?I(c):S(`Connected ${i.displayName}. Run seo providers describe ${t} to see what it can do.`)}}),status:b({meta:{name:`status`,description:`Show one installed provider connection`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},check:{type:`boolean`,default:!1,description:`Run the provider connection check.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=w(e.id)??``,n=await ll(t),r=tr(t),i;try{i=await In({providerId:t,account:r,fields:n.connection.fields})}catch{i=void 0}let a=n.connection.fields.filter(e=>e.kind===`account`&&e.required!==!1).every(e=>!!r[e.id]?.trim())&&i!==void 0,o=T(e.check);if(o&&!a)throw new g(`AUTH_REQUIRED`,`Provider ${t} is not connected. Run \`seo providers connect ${t}\`.`);o&&i&&await $t({providerId:t,account:r,credentials:i});let s={provider:t,installed:!0,connected:a,account:r,capabilities:(n.capabilities??[]).map(e=>e.id),actions:(n.actions??[]).map(e=>e.id),check:o?`passed`:`not-requested`};A(e)?I(s):R([`Provider`,`Connected`,`Capabilities`,`Check`],[[n.displayName,a?`yes`:`no`,s.capabilities.join(`, `),s.check]])}}),disconnect:b({meta:{name:`disconnect`,description:`Remove one saved provider connection`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=w(e.id)??``;await ll(t);let n=tr(t);await Cn({providerId:t,account:n}),Tt(t);let r={provider:t,disconnected:!0,note:`Environment variables were not changed.`};A(e)?I(r):process.stdout.write(`Disconnected ${t}. ${r.note}\n`)}}),run:b({meta:{name:`run`,description:`Run one action supplied by an installed provider`},args:{id:{type:`positional`,required:!0,description:`Installed provider id.`},action:{type:`positional`,required:!0,description:`Provider action id.`},account:{type:`string`,description:`Account fields as JSON. Defaults to the saved connection.`},params:{type:`string`,description:`Action parameters as a JSON object.`},refresh:{type:`boolean`,default:!1,description:`Bypass the local provider cache.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=w(e.id)??``,n=w(e.action)??``;await ll(t);let r={...tr(t),...sl(w(e.account))};I(await u({providerId:t,actionId:n,account:r,params:cl(w(e.params)),refresh:T(e.refresh)}))}}),doctor:b({meta:{name:`doctor`,description:`Validate installed provider packages and entry points`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=await dl(),n={ok:t.installed.every(e=>e.loadStatus===`ready`),installed:t.installed};A(e)?I(n):n.installed.length===0?process.stdout.write(`No provider extensions are installed.
88
+ `):R([`Provider`,`Package`,`Version`,`Status`],n.installed.map(e=>[e.id,e.package,e.version,e.error??e.loadStatus]))}})},pl=b({meta:{name:`providers`,description:`Connect optional data providers`},subCommands:{...fl,ahrefs:Zc,bing:nl,dataforseo:ol}}),ml={"ai-search":`AI search`,crawl:`Crawling and technical checks`,diagnosis:`Diagnosis`,monitoring:`Monitoring`,opportunities:`Opportunities`,reporting:`Reporting`,setup:`Setup`,workflows:`Workflows`};function hl(e){let t=w(e);if(t){if(!zn.includes(t))throw new g(`INVALID_INPUT`,`Unknown report category: ${t}. Choose ${zn.join(`, `)}.`);return t}}async function gl(e,t){let n=w(e),r=w(t);if(n&&r)throw new g(`INVALID_INPUT`,`Use either --params or --params-file, not both.`);if(!n&&!r)return{};let i=n??await y(r??``,`utf8`),a;try{a=JSON.parse(i)}catch{throw new g(`INVALID_INPUT`,`Report parameters must be valid JSON.`)}if(!a||typeof a!=`object`||Array.isArray(a))throw new g(`INVALID_INPUT`,`Report parameters must be an object.`);return a}function _l(e){if(!e.isError)return;let t=e.structuredContent;throw new g(t?.error?.code??`INTERNAL_ERROR`,t?.error?.message??`The report could not be completed.`)}function vl(e){if(!e||typeof e!=`object`)return[];let t=e,n=new Set(t.required??[]);return Object.entries(t.properties??{}).map(([e,t])=>{let r=Array.isArray(t.type)?t.type.join(` | `):t.type??`any`;return{name:e,type:r===`array`&&t.items?.type?`${t.items.type}[]`:t.format?`${r} (${t.format})`:r,required:n.has(e),description:t.description}})}const yl=b({meta:{name:`list`,description:`List report ids available to the CLI and MCP server`},args:{category:{type:`string`,description:`Filter by category: ${zn.join(`, `)}.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=hl(e.category),n=Sn(t);A(e)?I({reports:n,categories:zn}):(fa(n,{noun:`report`,categoryLabels:ml}),process.stdout.write(`
89
+ `),ca({title:`Need the detail?`,body:`Describe one report to see when to use it, what it needs, and what the result can prove.`,command:`seo reports describe <id>`}))}}),bl=b({meta:{name:`describe`,description:`Show the purpose and parameter schema for one report`},args:{id:{type:`positional`,required:!0,description:"Report id from `seo reports list`."},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=Qt(w(e.id)??``);A(e)?I({report:t}):(la(t.name,t.description),process.stdout.write(`
90
+ `),L([[`ID`,t.id],[`Category`,t.category],[`Outcome`,t.outcome]]),process.stdout.write(`
91
+ `),ha(`Use when`,t.useWhen),process.stdout.write(`
92
+ `),ha(`Avoid when`,t.avoidWhen),process.stdout.write(`
93
+ `),ha(`Read in order`,t.readOrder),process.stdout.write(`
94
+ `),ha(`Do not claim`,t.doNotClaim),process.stdout.write(`
95
+ `),ma(`Verify`,t.verify),process.stdout.write(`
96
+ `),ca({title:`Implement findings`,body:t.agentWorkflow.completion,command:t.agentWorkflow.actionView.cli}),t.related.length>0&&(process.stdout.write(`
97
+ `),ha(`Related reports`,t.related.map(e=>`${e.id}: ${e.reason}`))),process.stdout.write(`
97
98
  Parameters
98
- `),ua(ol(t.inputSchema)),process.stdout.write(`
99
- `),na({title:`Need the exact schema?`,command:`seo reports describe ${t.id} --json`}))}}),ll=x({meta:{name:`run`,description:`Run one report with JSON parameters`},args:{id:{type:`positional`,required:!0,description:"Report id from `seo reports list`."},params:{type:`string`,description:`Report parameters as a JSON object.`},"params-file":{type:`string`,description:`Read report parameters from a JSON file.`},"actions-only":{type:`boolean`,default:!1,description:`Return findings, verification, and retained inventories without the full report body.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=T(e.id)??``,n=await il(e.params,e[`params-file`]),r=await vt(t,n,{view:E(e[`actions-only`])?`actions`:`full`});if(al(r),j(e))L(r.structuredContent??{});else for(let e of r.content)process.stdout.write(`${e.text}\n`)}}),ul=x({meta:{name:`reports`,description:`Discover and run the complete report catalog`},subCommands:{list:sl,describe:cl,run:ll}}),dl=x({meta:{name:`rules`,description:`List crawler rule ids and default guidance`},args:{category:{type:`string`,description:`Filter rules by category.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=T(e.category),n=ee().filter(e=>!t||e.category===t);j(e)?L({rules:n}):oa(n.map(e=>({id:e.id,category:e.category,name:`${e.title} · ${e.defaultSeverity}`})),{noun:`rule`})}}),fl=x({meta:{name:`explain`,description:`Explain one crawler rule in plain English`},args:{rule:{type:`string`,required:!0,description:`Rule id to explain, for example missing_title.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=T(e.rule)??``,n=g(t);if(!n)throw Error(`Unknown rule: ${t}`);j(e)?L(n):(R([[`Rule`,n.id],[`Title`,n.title],[`Category`,n.category],[`Severity`,n.defaultSeverity]]),process.stdout.write(`
100
- `),ca(`Why it matters`,n.whyItMatters),process.stdout.write(`
101
- `),ca(`How to fix`,n.howToFix),process.stdout.write(`
102
- `),ca(`Impact if ignored`,n.impactIfIgnored),process.stdout.write(`
103
- `),ca(`How to verify`,n.howToVerify))}});function pl(){return gl(`skills`,process.env.SEO_SKILLS_DIR)}function ml(){return gl(`evals`,process.env.SEO_EVALS_DIR)}function hl(){return gl(`site-kit`)}function gl(e,t){if(t)return mr(t);let n=_(Or(import.meta.url));for(let t=0;t<6;t+=1){let t=v(n,e);if(y(v(t,`README.md`)))return t;n=_(n)}throw new d(`INTERNAL_ERROR`,`Packaged ${e} could not be found. Reinstall \`seo\` and try again.`)}function _l(e){return xr(v(e,`SKILL.md`),`utf8`).match(/^description:\s*(.+)$/m)?.[1]?.trim()??``}const vl=[[`setup`,`Sign in to the accounts the site needs, one at a time`],[`market`,`Choose a market with real demand and data you can own`],[`data`,`Get, clean and keep the dataset`],[`plan`,`Plan the pages from what people search for`],[`build`,`Start the site and deploy a private preview`],[`golden-page`,`Build one page that is the best answer on the web`],[`writing`,`Write copy people enjoy and AI answers can quote`],[`scale`,`Turn the golden page into every page, with gates`],[`launch`,`Go live and get the important pages indexed`],[`grow`,`Measure with your own data and improve every week`]],yl=/* @__PURE__ */ new Set([`node_modules`,`dist`,`.astro`,`.wrangler`]);function bl(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``)}function xl(e){return bl(dr(e)).split(`-`).filter(Boolean).map(e=>`${e[0]?.toUpperCase()}${e.slice(1)}`).join(` `)}function Sl(e){let t=(e??`example.com`).trim().toLowerCase().replace(/^https?:\/\//,``).replace(/\/.*$/,``);if(!/^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/.test(t))throw new d(`INVALID_INPUT`,`--domain must be a domain such as example.com, not ${e}.`);return t}async function Cl(e,t){let n=JSON.parse(await b(e,`utf8`));t(n),await Fr(e,`${JSON.stringify(n,null,2)}\n`)}function wl(){return ts(`pnpm`,[`--version`],{stdio:`ignore`}).status===0?`pnpm`:`npm`}const Tl=x({meta:{name:`new`,description:`Copy the Astro on Cloudflare starter into a new folder`},args:{folder:{type:`positional`,required:!0,description:`Folder to create. It must not exist or must be empty.`},name:{type:`string`,description:`Site name. Defaults to the folder name.`},domain:{type:`string`,description:`Production domain. Defaults to example.com until you buy one.`},install:{type:`boolean`,default:!0,description:`Install packages after copying.`,negativeDescription:`Copy the files only.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=j(e),n=mr(String(e.folder));if(y(n)&&(await Mr(n)).some(e=>e!==`.git`))throw new d(`INVALID_INPUT`,`${n} is not empty. Choose a new folder for the site.`);let r=T(e.name)?.trim()||xl(n),i=Sl(T(e.domain)),a=bl(dr(n))||`site`,o=sr(16).toString(`hex`),s=v(hl(),`starter`);await kr(s,n,{recursive:!0,filter:e=>!pr(s,e).split(hr).some(e=>yl.has(e))}),await Nr(v(n,`gitignore`),v(n,`.gitignore`)),await Cl(v(n,`site.config.json`),e=>{e.name=r,e.domain=i,e.indexNowKey=o}),await Fr(v(n,`public`,`${o}.txt`),o),await Cl(v(n,`package.json`),e=>{e.name=a;let t=e.devDependencies;t.seo=`^${Cn}`});let c=v(n,`wrangler.jsonc`);await Fr(c,(await b(c,`utf8`)).replace(`"name": "example-site"`,`"name": ${JSON.stringify(a)}`));let l=v(n,`README.md`);await Fr(l,(await b(l,`utf8`)).replace(/^# .*$/m,`# ${r}`));let u=D(e,`install`)===!0?void 0:wl(),f=!1;u&&(t||process.stdout.write(`Installing packages with ${u}...\n`),f=ts(u,[`install`],{cwd:n,stdio:t?`ignore`:`inherit`}).status===0);let p=[`cd ${pr(process.cwd(),n)||`.`}`,`seo site guide setup`];t?L({folder:n,name:r,domain:i,installed:f,packageManager:u??null,next:p}):(ra(`Created ${r}`,n),R([[`Domain`,i],[`Packages`,f?`installed with ${u}`:u?`${u} install failed. Run it in the folder.`:`not installed`]]),process.stdout.write(`
104
- `),ca(`What is in it`,"An example site about parks, built from src/data. It already passes `seo site check`: titles, canonicals, JSON-LD, sharing images, Markdown copies, llms.txt and sitemaps are done for every page.",`Later steps replace the example data and pages with yours.`),na({title:`Next`,body:`Read the first step. Each step ends with the next one.`,command:p.join(` && `)}))}});function El(e){let t=bl(e.join(` `));return vl.find(([e])=>e===t)?.[0]}const Dl=x({meta:{name:`guide`,description:`Print the instructions for one step of building the site`},args:{step:{type:`positional`,required:!1,description:vl.map(([e])=>e).join(`, `)},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=j(e),n=e._?.length?e._:[T(e.step)??``];if(!n.join(``).trim()){if(t){L({steps:vl.map(([e,t])=>({step:e,summary:t}))});return}ra(`Build a site, one step at a time`,"Run `seo site guide <step>` and follow it before the next step."),la(`Steps`,vl.map(([e,t])=>`${e}: ${t}`)),na({title:`Start here`,command:`seo site guide setup`});return}let r=El(n);if(!r)throw new d(`INVALID_INPUT`,`Unknown step "${n.join(` `)}". Steps: ${vl.map(([e])=>e).join(`, `)}.`);let i=await b(v(hl(),`guide`,`${r}.md`),`utf8`),a=vl.findIndex(([e])=>e===r),o=vl[a+1]?.[0];t?L({step:r,number:a+1,of:vl.length,markdown:i,next:o?`seo site guide ${o}`:null}):process.stdout.write(i.endsWith(`
105
- `)?i:`${i}\n`)}});async function Ol(e){return(await Mr(e,{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(t=>pr(e,v(t.parentPath,t.name)).split(hr).join(`/`))}function kl(e){ra(e.status===`passed`?`Site check passed`:e.status===`partial`?`Site check stopped early`:`Site check failed`,e.origin),R([[`Pages`,e.pagesChecked===e.pagesFound?String(e.pagesFound):`${e.pagesChecked} of ${e.pagesFound} checked`],[`Failures`,String(e.failures)],[`Warnings`,String(e.warnings)]]),process.stdout.write(`
106
- `);for(let t of e.rules.slice(0,40)){let n=e.issues.filter(e=>e.rule===t.rule).slice(0,3).map(e=>e.found?`${e.file}: ${e.found}`:e.file);la(`${t.level===`fail`?`Fail`:`Warn`} ${t.rule} (${t.group}, ${t.count}). ${t.fix}`,t.count>n.length?[...n,`and ${t.count-n.length} more`]:n)}e.rules.length>40&&process.stdout.write(`${e.rules.length-40} more rules failed. Use --json for all of them.\n\n`),e.status===`partial`&&ca(`Not every page was checked`,`The check stops at ${e.pagesChecked} pages, so it cannot say the rest pass. Split the site or build fewer, stronger pages.`),na(e.status===`passed`?{title:`Next`,body:`Deploy the build, or read the next step of the guide.`,command:`seo site guide`}:{title:`Next`,body:`Fix the template or the data behind the first rule, then build again.`,command:`pnpm build`})}const Al=x({meta:{name:`check`,description:`Check the built site and fail on any rule it breaks`},args:{dir:{type:`string`,description:`Site folder with site.config.json. Defaults to this folder.`},dist:{type:`string`,description:`Build folder. Defaults to dist inside the site folder.`},domain:{type:`string`,description:`Production domain. Defaults to the one in site.config.json.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=j(e),n=mr(T(e.dir)??`.`),r=mr(n,T(e.dist)??`dist`),i=v(n,`site.config.json`),a=y(i)?JSON.parse(await b(i,`utf8`)):{},o=T(e.domain)??a.domain;if(!o)throw new d(`INVALID_INPUT`,"No domain. Run this in a folder made by `seo site new`, or pass --domain.");if(!y(r))throw new d(`INVALID_INPUT`,`${r} does not exist. Build the site first with \`pnpm build\`.`);let s=await At({origin:`https://${Sl(o)}`,files:await Ol(r),readText:e=>b(v(r,e),`utf8`),readBytes:e=>b(v(r,e)),allowWords:a.allowWords??[],sources:y(v(n,`src`))?{files:(await Ol(v(n,`src`))).map(e=>`src/${e}`),readText:e=>b(v(n,e),`utf8`)}:void 0});t?L(s):kl(s),s.status!==`passed`&&(process.exitCode=1)}}),jl=x({meta:{name:`site`,description:`Build a data-driven site on Astro and Cloudflare`},subCommands:{new:Tl,guide:Dl,check:Al}}),Ml=`claude -p`;function Nl(){let e=ml();return Sr(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(t=>({subject:dr(t.name,`.json`),path:v(e,t.name)})).sort((e,t)=>e.subject<t.subject?-1:+(e.subject>t.subject))}function Pl(e,t){let n;try{n=xr(t,`utf8`)}catch{throw new d(`INVALID_INPUT`,`Cannot read eval file for ${e}.`)}let r;try{r=JSON.parse(n)}catch{throw new d(`INVALID_INPUT`,`Eval file ${e}.json is not valid JSON.`)}if(!r||typeof r!=`object`||Array.isArray(r))throw new d(`INVALID_INPUT`,`Eval file ${e}.json must be an object.`);let i=r;if(i.subject!==e)throw new d(`INVALID_INPUT`,`Eval file ${e}.json must set subject to "${e}".`);if(!Array.isArray(i.evals)||i.evals.length===0)throw new d(`INVALID_INPUT`,`Eval file ${e}.json must have a non-empty evals array.`);let a=/* @__PURE__ */ new Set;return{subject:e,evals:i.evals.map((t,n)=>{let r=t,i=`${e}.json eval ${n+1}`;if(!Number.isInteger(r?.id))throw new d(`INVALID_INPUT`,`${i}: id must be an integer.`);let o=r.id;if(a.has(o))throw new d(`INVALID_INPUT`,`${i}: duplicate id ${o}.`);if(a.add(o),typeof r.prompt!=`string`||r.prompt.trim().length===0)throw new d(`INVALID_INPUT`,`${i}: prompt must be a non-empty string.`);if(typeof r.expected_output!=`string`||r.expected_output.trim().length===0)throw new d(`INVALID_INPUT`,`${i}: expected_output must be a non-empty string.`);if(!Array.isArray(r.assertions)||r.assertions.length===0||r.assertions.some(e=>typeof e!=`string`||e.trim().length===0))throw new d(`INVALID_INPUT`,`${i}: assertions must be a non-empty array of non-empty strings.`);if(r.files!==void 0&&!Array.isArray(r.files))throw new d(`INVALID_INPUT`,`${i}: files must be an array.`);return{id:o,prompt:r.prompt,expected_output:r.expected_output,assertions:r.assertions,files:r.files??[]}})}}function Fl(){let e=v(pl(),`seo`,`SKILL.md`);if(!y(e))throw new d(`INTERNAL_ERROR`,"The seo router skill could not be found. Reinstall `seo` or use --no-skill.");return xr(e,`utf8`)}function Il(e){let t=[],n=``,r=!1,i=!1,a=!1;for(let o=0;o<e.length;o+=1){let s=e[o];i?(s===`'`?i=!1:n+=s,r=!0):a?(s===`"`?a=!1:s===`\\`&&(e[o+1]===`"`||e[o+1]===`\\`)?(n+=e[o+1],o+=1):n+=s,r=!0):s===`'`?(i=!0,r=!0):s===`"`?(a=!0,r=!0):s===`\\`?o+1<e.length&&(n+=e[o+1],o+=1,r=!0):s===` `||s===` `||s===`
107
- `||s===`\r`?r&&=(t.push(n),n=``,!1):(n+=s,r=!0)}if(i||a)throw new d(`INVALID_INPUT`,`Unbalanced quote in agent command.`);return r&&t.push(n),t}function Ll(e,t){let n=Il(e);if(n.length===0)throw new d(`INVALID_INPUT`,`Agent command must not be empty.`);let r=n.some(e=>e.includes(`{prompt}`));return{argv:r?n.map(e=>e.split(`{prompt}`).join(t)):n,usesPlaceholder:r}}function Rl(e,t){return e?`${e.trim()}\n\n---\n\nUser request:\n${t}`:t}function zl(e,t,n,r=!1){let i=[`You are judging whether an AI agent response satisfies a list of assertions.`,`Judge only against the assertions. Be strict but fair.`,``,`Original request:`,e,``,`Agent response:`,t,``,`Assertions to evaluate, in this exact order:`,`<assertions>`,n.map((e,t)=>`${t+1}. ${e}`).join(`
99
+ `),ga(vl(t.inputSchema)),process.stdout.write(`
100
+ `),ca({title:`Need the exact schema?`,command:`seo reports describe ${t.id} --json`}))}}),xl=b({meta:{name:`run`,description:`Run one report with JSON parameters`},args:{id:{type:`positional`,required:!0,description:"Report id from `seo reports list`."},params:{type:`string`,description:`Report parameters as a JSON object.`},"params-file":{type:`string`,description:`Read report parameters from a JSON file.`},"actions-only":{type:`boolean`,default:!1,description:`Return findings, verification, and retained inventories without the full report body.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=w(e.id)??``,n=await gl(e.params,e[`params-file`]),r=await xt(t,n,{view:T(e[`actions-only`])?`actions`:`full`});if(_l(r),A(e))I(r.structuredContent??{});else for(let e of r.content)process.stdout.write(`${e.text}\n`)}}),Sl=b({meta:{name:`reports`,description:`Discover and run the complete report catalog`},subCommands:{list:yl,describe:bl,run:xl}}),Cl=b({meta:{name:`rules`,description:`List crawler rule ids and default guidance`},args:{category:{type:`string`,description:`Filter rules by category.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=w(e.category),n=ke().filter(e=>!t||e.category===t);A(e)?I({rules:n}):fa(n.map(e=>({id:e.id,category:e.category,name:`${e.title} · ${e.defaultSeverity}`})),{noun:`rule`})}}),wl=b({meta:{name:`explain`,description:`Explain one crawler rule in plain English`},args:{rule:{type:`string`,required:!0,description:`Rule id to explain, for example missing_title.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=w(e.rule)??``,n=an(t);if(!n)throw Error(`Unknown rule: ${t}`);A(e)?I(n):(L([[`Rule`,n.id],[`Title`,n.title],[`Category`,n.category],[`Severity`,n.defaultSeverity]]),process.stdout.write(`
101
+ `),ma(`Why it matters`,n.whyItMatters),process.stdout.write(`
102
+ `),ma(`How to fix`,n.howToFix),process.stdout.write(`
103
+ `),ma(`Impact if ignored`,n.impactIfIgnored),process.stdout.write(`
104
+ `),ma(`How to verify`,n.howToVerify))}});function Tl(){return Ol(`skills`,process.env.SEO_SKILLS_DIR)}function El(){return Ol(`evals`,process.env.SEO_EVALS_DIR)}function Dl(){return Ol(`site-kit`)}function Ol(e,t){if(t)return br(t);let n=_r(Pr(import.meta.url));for(let t=0;t<6;t+=1){let t=_(n,e);if(v(_(t,`README.md`)))return t;n=_r(n)}throw new g(`INTERNAL_ERROR`,`Packaged ${e} could not be found. Reinstall \`seo\` and try again.`)}function kl(e){return Dr(_(e,`SKILL.md`),`utf8`).match(/^description:\s*(.+)$/m)?.[1]?.trim()??``}const Al=[[`setup`,`Sign in to the accounts the site needs, one at a time`],[`market`,`Choose a market with real demand and data you can own`],[`data`,`Get, clean and keep the dataset`],[`plan`,`Plan the pages from what people search for`],[`build`,`Start the site and deploy a private preview`],[`golden-page`,`Build one page that is the best answer on the web`],[`writing`,`Write copy people enjoy and AI answers can quote`],[`scale`,`Turn the golden page into every page, with gates`],[`launch`,`Go live and get the important pages indexed`],[`grow`,`Measure with your own data and improve every week`]],jl=/* @__PURE__ */ new Set([`node_modules`,`dist`,`.astro`,`.wrangler`]);function Ml(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``)}function Nl(e){return Ml(gr(e)).split(`-`).filter(Boolean).map(e=>`${e[0]?.toUpperCase()}${e.slice(1)}`).join(` `)}function Pl(e){let t=(e??`example.com`).trim().toLowerCase().replace(/^https?:\/\//,``).replace(/\/.*$/,``);if(!/^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/.test(t))throw new g(`INVALID_INPUT`,`--domain must be a domain such as example.com, not ${e}.`);return t}async function Fl(e,t){let n=JSON.parse(await y(e,`utf8`));t(n),await Vr(e,`${JSON.stringify(n,null,2)}\n`)}function Il(){return ps(`pnpm`,[`--version`],{stdio:`ignore`}).status===0?`pnpm`:`npm`}const Ll=b({meta:{name:`new`,description:`Copy the Astro on Cloudflare starter into a new folder`},args:{folder:{type:`positional`,required:!0,description:`Folder to create. It must not exist or must be empty.`},name:{type:`string`,description:`Site name. Defaults to the folder name.`},domain:{type:`string`,description:`Production domain. Defaults to example.com until you buy one.`},install:{type:`boolean`,default:!0,description:`Install packages after copying.`,negativeDescription:`Copy the files only.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=A(e),n=br(String(e.folder));if(v(n)&&(await Rr(n)).some(e=>e!==`.git`))throw new g(`INVALID_INPUT`,`${n} is not empty. Choose a new folder for the site.`);let r=w(e.name)?.trim()||Nl(n),i=Pl(w(e.domain)),a=Ml(gr(n))||`site`,o=fr(16).toString(`hex`),s=_(Dl(),`starter`);await Fr(s,n,{recursive:!0,filter:e=>!yr(s,e).split(xr).some(e=>jl.has(e))}),await zr(_(n,`gitignore`),_(n,`.gitignore`)),await Fl(_(n,`site.config.json`),e=>{e.name=r,e.domain=i,e.indexNowKey=o}),await Vr(_(n,`public`,`${o}.txt`),o),await Fl(_(n,`package.json`),e=>{e.name=a;let t=e.devDependencies;t.seo=`^${Yn}`});let c=_(n,`wrangler.jsonc`);await Vr(c,(await y(c,`utf8`)).replace(`"name": "example-site"`,`"name": ${JSON.stringify(a)}`));let l=_(n,`README.md`);await Vr(l,(await y(l,`utf8`)).replace(/^# .*$/m,`# ${r}`));let u=E(e,`install`)===!0?void 0:Il(),d=!1;u&&(t||process.stdout.write(`Installing packages with ${u}...\n`),d=ps(u,[`install`],{cwd:n,stdio:t?`ignore`:`inherit`}).status===0);let f=[`cd ${yr(process.cwd(),n)||`.`}`,`seo site guide setup`];t?I({folder:n,name:r,domain:i,installed:d,packageManager:u??null,next:f}):(la(`Created ${r}`,n),L([[`Domain`,i],[`Packages`,d?`installed with ${u}`:u?`${u} install failed. Run it in the folder.`:`not installed`]]),process.stdout.write(`
105
+ `),ma(`What is in it`,"An example site about parks, built from src/data. It already passes `seo site check`: titles, canonicals, JSON-LD, sharing images, Markdown copies, llms.txt and sitemaps are done for every page.",`Later steps replace the example data and pages with yours.`),ca({title:`Next`,body:`Read the first step. Each step ends with the next one.`,command:f.join(` && `)}))}});function Rl(e){let t=Ml(e.join(` `));return Al.find(([e])=>e===t)?.[0]}const zl=b({meta:{name:`guide`,description:`Print the instructions for one step of building the site`},args:{step:{type:`positional`,required:!1,description:Al.map(([e])=>e).join(`, `)},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=A(e),n=e._?.length?e._:[w(e.step)??``];if(!n.join(``).trim()){if(t){I({steps:Al.map(([e,t])=>({step:e,summary:t}))});return}la(`Build a site, one step at a time`,"Run `seo site guide <step>` and follow it before the next step."),ha(`Steps`,Al.map(([e,t])=>`${e}: ${t}`)),ca({title:`Start here`,command:`seo site guide setup`});return}let r=Rl(n);if(!r)throw new g(`INVALID_INPUT`,`Unknown step "${n.join(` `)}". Steps: ${Al.map(([e])=>e).join(`, `)}.`);let i=await y(_(Dl(),`guide`,`${r}.md`),`utf8`),a=Al.findIndex(([e])=>e===r),o=Al[a+1]?.[0];t?I({step:r,number:a+1,of:Al.length,markdown:i,next:o?`seo site guide ${o}`:null}):process.stdout.write(i.endsWith(`
106
+ `)?i:`${i}\n`)}});async function Bl(e){return(await Rr(e,{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(t=>yr(e,_(t.parentPath,t.name)).split(xr).join(`/`))}function Vl(e){la(e.status===`passed`?`Site check passed`:e.status===`partial`?`Site check stopped early`:`Site check failed`,e.origin),L([[`Pages`,e.pagesChecked===e.pagesFound?String(e.pagesFound):`${e.pagesChecked} of ${e.pagesFound} checked`],[`Failures`,String(e.failures)],[`Warnings`,String(e.warnings)]]),process.stdout.write(`
107
+ `);for(let t of e.rules.slice(0,40)){let n=e.issues.filter(e=>e.rule===t.rule).slice(0,3).map(e=>e.found?`${e.file}: ${e.found}`:e.file);ha(`${t.level===`fail`?`Fail`:`Warn`} ${t.rule} (${t.group}, ${t.count}). ${t.fix}`,t.count>n.length?[...n,`and ${t.count-n.length} more`]:n)}e.rules.length>40&&process.stdout.write(`${e.rules.length-40} more rules failed. Use --json for all of them.\n\n`),e.status===`partial`&&ma(`Not every page was checked`,`The check stops at ${e.pagesChecked} pages, so it cannot say the rest pass. Split the site or build fewer, stronger pages.`),ca(e.status===`passed`?{title:`Next`,body:`Deploy the build, or read the next step of the guide.`,command:`seo site guide`}:{title:`Next`,body:`Fix the template or the data behind the first rule, then build again.`,command:`pnpm build`})}const Hl=b({meta:{name:`check`,description:`Check the built site and fail on any rule it breaks`},args:{dir:{type:`string`,description:`Site folder with site.config.json. Defaults to this folder.`},dist:{type:`string`,description:`Build folder. Defaults to dist inside the site folder.`},domain:{type:`string`,description:`Production domain. Defaults to the one in site.config.json.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=A(e),n=br(w(e.dir)??`.`),r=br(n,w(e.dist)??`dist`),i=_(n,`site.config.json`),a=v(i)?JSON.parse(await y(i,`utf8`)):{},o=w(e.domain)??a.domain;if(!o)throw new g(`INVALID_INPUT`,"No domain. Run this in a folder made by `seo site new`, or pass --domain.");if(!v(r))throw new g(`INVALID_INPUT`,`${r} does not exist. Build the site first with \`pnpm build\`.`);let s=await Nt({origin:`https://${Pl(o)}`,files:await Bl(r),readText:e=>y(_(r,e),`utf8`),readBytes:e=>y(_(r,e)),allowWords:a.allowWords??[],sources:v(_(n,`src`))?{files:(await Bl(_(n,`src`))).map(e=>`src/${e}`),readText:e=>y(_(n,e),`utf8`)}:void 0});t?I(s):Vl(s),s.status!==`passed`&&(process.exitCode=1)}}),Ul=b({meta:{name:`site`,description:`Build a data-driven site on Astro and Cloudflare`},subCommands:{new:Ll,guide:zl,check:Hl}}),Wl=`claude -p`;function Gl(){let e=El();return Or(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(t=>({subject:gr(t.name,`.json`),path:_(e,t.name)})).sort((e,t)=>e.subject<t.subject?-1:+(e.subject>t.subject))}function Kl(e,t){let n;try{n=Dr(t,`utf8`)}catch{throw new g(`INVALID_INPUT`,`Cannot read eval file for ${e}.`)}let r;try{r=JSON.parse(n)}catch{throw new g(`INVALID_INPUT`,`Eval file ${e}.json is not valid JSON.`)}if(!r||typeof r!=`object`||Array.isArray(r))throw new g(`INVALID_INPUT`,`Eval file ${e}.json must be an object.`);let i=r;if(i.subject!==e)throw new g(`INVALID_INPUT`,`Eval file ${e}.json must set subject to "${e}".`);if(!Array.isArray(i.evals)||i.evals.length===0)throw new g(`INVALID_INPUT`,`Eval file ${e}.json must have a non-empty evals array.`);let a=/* @__PURE__ */ new Set;return{subject:e,evals:i.evals.map((t,n)=>{let r=t,i=`${e}.json eval ${n+1}`;if(!Number.isInteger(r?.id))throw new g(`INVALID_INPUT`,`${i}: id must be an integer.`);let o=r.id;if(a.has(o))throw new g(`INVALID_INPUT`,`${i}: duplicate id ${o}.`);if(a.add(o),typeof r.prompt!=`string`||r.prompt.trim().length===0)throw new g(`INVALID_INPUT`,`${i}: prompt must be a non-empty string.`);if(typeof r.expected_output!=`string`||r.expected_output.trim().length===0)throw new g(`INVALID_INPUT`,`${i}: expected_output must be a non-empty string.`);if(!Array.isArray(r.assertions)||r.assertions.length===0||r.assertions.some(e=>typeof e!=`string`||e.trim().length===0))throw new g(`INVALID_INPUT`,`${i}: assertions must be a non-empty array of non-empty strings.`);if(r.files!==void 0&&!Array.isArray(r.files))throw new g(`INVALID_INPUT`,`${i}: files must be an array.`);return{id:o,prompt:r.prompt,expected_output:r.expected_output,assertions:r.assertions,files:r.files??[]}})}}function ql(){let e=_(Tl(),`seo`,`SKILL.md`);if(!v(e))throw new g(`INTERNAL_ERROR`,"The seo router skill could not be found. Reinstall `seo` or use --no-skill.");return Dr(e,`utf8`)}function Jl(e){let t=[],n=``,r=!1,i=!1,a=!1;for(let o=0;o<e.length;o+=1){let s=e[o];i?(s===`'`?i=!1:n+=s,r=!0):a?(s===`"`?a=!1:s===`\\`&&(e[o+1]===`"`||e[o+1]===`\\`)?(n+=e[o+1],o+=1):n+=s,r=!0):s===`'`?(i=!0,r=!0):s===`"`?(a=!0,r=!0):s===`\\`?o+1<e.length&&(n+=e[o+1],o+=1,r=!0):s===` `||s===` `||s===`
108
+ `||s===`\r`?r&&=(t.push(n),n=``,!1):(n+=s,r=!0)}if(i||a)throw new g(`INVALID_INPUT`,`Unbalanced quote in agent command.`);return r&&t.push(n),t}function Yl(e,t){let n=Jl(e);if(n.length===0)throw new g(`INVALID_INPUT`,`Agent command must not be empty.`);let r=n.some(e=>e.includes(`{prompt}`));return{argv:r?n.map(e=>e.split(`{prompt}`).join(t)):n,usesPlaceholder:r}}function Xl(e,t){return e?`${e.trim()}\n\n---\n\nUser request:\n${t}`:t}function Zl(e,t,n,r=!1){let i=[`You are judging whether an AI agent response satisfies a list of assertions.`,`Judge only against the assertions. Be strict but fair.`,``,`Original request:`,e,``,`Agent response:`,t,``,`Assertions to evaluate, in this exact order:`,`<assertions>`,n.map((e,t)=>`${t+1}. ${e}`).join(`
108
109
  `),`</assertions>`,``,`Judge outcomes, not narration. An assertion about reading, checking, or`,`following fields or steps passes when the reply demonstrably used that`,`information or produced the result it protects, even if the reply never`,`names the field or step. Fail it only when the reply contradicts it or`,`shows the work was not done.`,``,`Reply with STRICT JSON only. No prose, no markdown, no code fence:`,`{"results":[{"assertion":"<assertion text>","pass":true,"reason":"<short reason>"}]}`,`Return exactly ${n.length} result${n.length===1?``:`s`}, one per assertion, in the same order.`].join(`
109
- `);return r?`${i}\n\nYour previous reply could not be parsed as the required JSON with one result per assertion. Reply again with STRICT JSON only, in the exact shape shown, and nothing else.`:i}function Bl(e){let t=e.indexOf(`{`);if(t===-1)return;let n=0,r=!1,i=!1;for(let a=t;a<e.length;a+=1){let o=e[a];if(r)i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1);else if(o===`"`)r=!0;else if(o===`{`)n+=1;else if(o===`}`&&(--n,n===0))try{return JSON.parse(e.slice(t,a+1))}catch{return}}}function Vl(e,t){let n=Bl(e);if(!n||typeof n!=`object`)return{error:`Judge reply did not contain a JSON object.`};let r=n.results;return Array.isArray(r)?r.length===t.length?{verdicts:t.map((e,t)=>{let n=r[t];return{assertion:e,verdict:n?.pass===!0?`pass`:`fail`,reason:typeof n?.reason==`string`&&n.reason.trim().length>0?n.reason.trim():`No reason given.`,source:`judge verdict`}})}:{error:`Judge returned ${r.length} results for ${t.length} assertions.`}:{error:`Judge reply had no results array.`}}function Hl(e,t){return new Promise(n=>{let r=Date.now(),[i,...a]=e,o;try{o=Rr(i,a,{stdio:[`pipe`,`pipe`,`pipe`]})}catch(e){n({stdout:``,stderr:``,code:null,timedOut:!1,spawnError:e instanceof Error?e.message:String(e),durationMs:Date.now()-r});return}let s=``,c=``,l=!1,u=!1,d,f=setTimeout(()=>{u=!0,o.kill(`SIGTERM`),d=setTimeout(()=>{try{o.kill(`SIGKILL`)}catch{}},2e3),d.unref()},t.timeoutMs),p=e=>{l||(l=!0,clearTimeout(f),d&&clearTimeout(d),n({...e,durationMs:Date.now()-r}))};o.stdout?.on(`data`,e=>{s+=e}),o.stderr?.on(`data`,e=>{c+=e}),o.on(`error`,e=>{p({stdout:s,stderr:c,code:null,timedOut:u,spawnError:e.message})}),o.on(`close`,e=>{p({stdout:s,stderr:c,code:e,timedOut:u})}),o.stdin&&(t.input===void 0?o.stdin.end():o.stdin.end(t.input))})}async function Ul(e,t,n){let{argv:r,usesPlaceholder:i}=Ll(e,t);return Hl(r,{input:i?void 0:t,timeoutMs:n})}async function Wl(e,t){let n=Date.now(),r=Rl(t.skillBody,e.prompt),i=await Ul(t.agent,r,t.timeoutMs),a=i.stdout.trim(),o={id:e.id,prompt:e.prompt,reply:a,agentDurationMs:i.durationMs};if(i.spawnError)return{...o,status:`errored`,error:`Agent command failed to start: ${i.spawnError}`,durationMs:Date.now()-n,assertions:Gl(e.assertions)};if(i.timedOut)return{...o,status:`errored`,error:`Agent timed out after ${Math.round(t.timeoutMs/1e3)}s.`,durationMs:Date.now()-n,assertions:Gl(e.assertions)};if(a.length===0)return{...o,status:`errored`,error:`Agent returned no output on stdout.`,durationMs:Date.now()-n,assertions:Gl(e.assertions)};if(!t.judge)return{...o,status:`unjudged`,durationMs:Date.now()-n,assertions:Gl(e.assertions)};let s=0,c=``;for(let r=0;r<2;r+=1){let i=zl(e.prompt,a,e.assertions,r>0),l=await Ul(t.judge,i,t.timeoutMs);if(s+=l.durationMs,l.spawnError)return{...o,status:`errored`,error:`Judge command failed to start: ${l.spawnError}`,judgeDurationMs:s,durationMs:Date.now()-n,assertions:Gl(e.assertions)};if(l.timedOut)return{...o,status:`errored`,error:`Judge timed out after ${Math.round(t.timeoutMs/1e3)}s.`,judgeDurationMs:s,durationMs:Date.now()-n,assertions:Gl(e.assertions)};let u=Vl(l.stdout,e.assertions);if(`verdicts`in u){let e=u.verdicts.some(e=>e.verdict===`fail`);return{...o,status:e?`failed`:`passed`,judgeDurationMs:s,durationMs:Date.now()-n,assertions:u.verdicts}}c=u.error}return{...o,status:`errored`,error:`Judge output could not be parsed after a retry: ${c}`,judgeDurationMs:s,durationMs:Date.now()-n,assertions:Gl(e.assertions)}}function Gl(e){return e.map(e=>({assertion:e,verdict:`unjudged`}))}async function Kl(e,t,n){let r=Array(e.length),i=0,a=async()=>{for(;;){let t=i;if(i+=1,t>=e.length)return;r[t]=await n(e[t],t)}},o=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:o},()=>a())),r}function ql(e){let t={passed:0,failed:0,errored:0,unjudged:0};for(let n of e)t[n.status]+=1;return t}function Jl(e){let t=[],n=T(e.subject);n&&t.push(n);let r=e._;if(Array.isArray(r))for(let e of r)typeof e==`string`&&e.length>0&&t.push(e);return[...new Set(t)]}function Yl(e){let t=Nl();if(e.length===0)return t;let n=new Map(t.map(e=>[e.subject,e]));return e.map(e=>{let r=n.get(e);if(!r){let n=t.map(e=>e.subject).join(`, `);throw new d(`INVALID_INPUT`,`Unknown eval subject: ${e}.${n?` Known subjects: ${n}.`:``}`)}return r})}function Xl(e){let t=Nl().map(e=>{let t=Pl(e.subject,e.path);return{subject:e.subject,evals:t.evals.length}});if(e){L({schemaVersion:1,subjects:t});return}if(t.length===0){process.stdout.write(`No eval subjects found.
110
+ `);return r?`${i}\n\nYour previous reply could not be parsed as the required JSON with one result per assertion. Reply again with STRICT JSON only, in the exact shape shown, and nothing else.`:i}function Ql(e){let t=e.indexOf(`{`);if(t===-1)return;let n=0,r=!1,i=!1;for(let a=t;a<e.length;a+=1){let o=e[a];if(r)i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1);else if(o===`"`)r=!0;else if(o===`{`)n+=1;else if(o===`}`&&(--n,n===0))try{return JSON.parse(e.slice(t,a+1))}catch{return}}}function $l(e,t){let n=Ql(e);if(!n||typeof n!=`object`)return{error:`Judge reply did not contain a JSON object.`};let r=n.results;return Array.isArray(r)?r.length===t.length?{verdicts:t.map((e,t)=>{let n=r[t];return{assertion:e,verdict:n?.pass===!0?`pass`:`fail`,reason:typeof n?.reason==`string`&&n.reason.trim().length>0?n.reason.trim():`No reason given.`,source:`judge verdict`}})}:{error:`Judge returned ${r.length} results for ${t.length} assertions.`}:{error:`Judge reply had no results array.`}}function eu(e,t){return new Promise(n=>{let r=Date.now(),[i,...a]=e,o;try{o=Wr(i,a,{stdio:[`pipe`,`pipe`,`pipe`]})}catch(e){n({stdout:``,stderr:``,code:null,timedOut:!1,spawnError:e instanceof Error?e.message:String(e),durationMs:Date.now()-r});return}let s=``,c=``,l=!1,u=!1,d,f=setTimeout(()=>{u=!0,o.kill(`SIGTERM`),d=setTimeout(()=>{try{o.kill(`SIGKILL`)}catch{}},2e3),d.unref()},t.timeoutMs),ee=e=>{l||(l=!0,clearTimeout(f),d&&clearTimeout(d),n({...e,durationMs:Date.now()-r}))};o.stdout?.on(`data`,e=>{s+=e}),o.stderr?.on(`data`,e=>{c+=e}),o.on(`error`,e=>{ee({stdout:s,stderr:c,code:null,timedOut:u,spawnError:e.message})}),o.on(`close`,e=>{ee({stdout:s,stderr:c,code:e,timedOut:u})}),o.stdin&&(t.input===void 0?o.stdin.end():o.stdin.end(t.input))})}async function tu(e,t,n){let{argv:r,usesPlaceholder:i}=Yl(e,t);return eu(r,{input:i?void 0:t,timeoutMs:n})}async function nu(e,t){let n=Date.now(),r=Xl(t.skillBody,e.prompt),i=await tu(t.agent,r,t.timeoutMs),a=i.stdout.trim(),o={id:e.id,prompt:e.prompt,reply:a,agentDurationMs:i.durationMs};if(i.spawnError)return{...o,status:`errored`,error:`Agent command failed to start: ${i.spawnError}`,durationMs:Date.now()-n,assertions:ru(e.assertions)};if(i.timedOut)return{...o,status:`errored`,error:`Agent timed out after ${Math.round(t.timeoutMs/1e3)}s.`,durationMs:Date.now()-n,assertions:ru(e.assertions)};if(a.length===0)return{...o,status:`errored`,error:`Agent returned no output on stdout.`,durationMs:Date.now()-n,assertions:ru(e.assertions)};if(!t.judge)return{...o,status:`unjudged`,durationMs:Date.now()-n,assertions:ru(e.assertions)};let s=0,c=``;for(let r=0;r<2;r+=1){let i=Zl(e.prompt,a,e.assertions,r>0),l=await tu(t.judge,i,t.timeoutMs);if(s+=l.durationMs,l.spawnError)return{...o,status:`errored`,error:`Judge command failed to start: ${l.spawnError}`,judgeDurationMs:s,durationMs:Date.now()-n,assertions:ru(e.assertions)};if(l.timedOut)return{...o,status:`errored`,error:`Judge timed out after ${Math.round(t.timeoutMs/1e3)}s.`,judgeDurationMs:s,durationMs:Date.now()-n,assertions:ru(e.assertions)};let u=$l(l.stdout,e.assertions);if(`verdicts`in u){let e=u.verdicts.some(e=>e.verdict===`fail`);return{...o,status:e?`failed`:`passed`,judgeDurationMs:s,durationMs:Date.now()-n,assertions:u.verdicts}}c=u.error}return{...o,status:`errored`,error:`Judge output could not be parsed after a retry: ${c}`,judgeDurationMs:s,durationMs:Date.now()-n,assertions:ru(e.assertions)}}function ru(e){return e.map(e=>({assertion:e,verdict:`unjudged`}))}async function iu(e,t,n){let r=Array(e.length),i=0,a=async()=>{for(;;){let t=i;if(i+=1,t>=e.length)return;r[t]=await n(e[t],t)}},o=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:o},()=>a())),r}function au(e){let t={passed:0,failed:0,errored:0,unjudged:0};for(let n of e)t[n.status]+=1;return t}function ou(e){let t=[],n=w(e.subject);n&&t.push(n);let r=e._;if(Array.isArray(r))for(let e of r)typeof e==`string`&&e.length>0&&t.push(e);return[...new Set(t)]}function su(e){let t=Gl();if(e.length===0)return t;let n=new Map(t.map(e=>[e.subject,e]));return e.map(e=>{let r=n.get(e);if(!r){let n=t.map(e=>e.subject).join(`, `);throw new g(`INVALID_INPUT`,`Unknown eval subject: ${e}.${n?` Known subjects: ${n}.`:``}`)}return r})}function cu(e){let t=Gl().map(e=>{let t=Kl(e.subject,e.path);return{subject:e.subject,evals:t.evals.length}});if(e){I({schemaVersion:1,subjects:t});return}if(t.length===0){process.stdout.write(`No eval subjects found.
110
111
  `);return}let n=Math.max(...t.map(e=>e.subject.length));process.stdout.write(`Eval subjects
111
- `);for(let e of t){let t=e.evals===1?`eval`:`evals`;process.stdout.write(` ${e.subject.padEnd(n)} ${e.evals} ${t}\n`)}}function Zl(e){return e===`passed`?`PASS`:e===`failed`?`FAIL`:e===`errored`?`ERROR`:`UNJUDGED`}function Ql(e,t){t.judged?process.stdout.write(`Assertion verdicts below are judge verdicts, model judgments from the judge agent, not ground truth.
112
+ `);for(let e of t){let t=e.evals===1?`eval`:`evals`;process.stdout.write(` ${e.subject.padEnd(n)} ${e.evals} ${t}\n`)}}function lu(e){return e===`passed`?`PASS`:e===`failed`?`FAIL`:e===`errored`?`ERROR`:`UNJUDGED`}function uu(e,t){t.judged?process.stdout.write(`Assertion verdicts below are judge verdicts, model judgments from the judge agent, not ground truth.
112
113
 
113
114
  `):process.stdout.write(`Judging was skipped. Review each agent reply against the assertion checklist by hand.
114
115
 
115
- `);for(let n of e){process.stdout.write(`# ${n.subject}\n`);for(let e of n.evals)if(process.stdout.write(`\n[${Zl(e.status)}] eval ${e.id} (${e.durationMs}ms)\n`),process.stdout.write(` prompt: ${eu(e.prompt,100)}\n`),e.error&&process.stdout.write(` error: ${e.error}\n`),!t.judged){process.stdout.write(` reply: ${eu(e.reply,200)}\n`),process.stdout.write(` assertions to review:
116
- `);for(let t of e.assertions)process.stdout.write(` - [ ] ${t.assertion}\n`)}else for(let t of e.assertions){let e=t.verdict===`pass`?`pass`:t.verdict===`fail`?`fail`:`unjudged`;process.stdout.write(` - ${e}: ${t.assertion}\n`),t.reason&&process.stdout.write(` judge verdict: ${t.reason}\n`)}let e=ql(n.evals);process.stdout.write(`\nSubject ${n.subject}: ${e.passed} passed, ${e.failed} failed, ${e.errored} errored${e.unjudged?`, ${e.unjudged} unjudged`:``}.\n\n`)}let n=$l(e);process.stdout.write(`Totals: ${n.passed} passed, ${n.failed} failed, ${n.errored} errored${n.unjudged?`, ${n.unjudged} unjudged`:``} across ${n.evals} evals.\n`)}function $l(e){let t={passed:0,failed:0,errored:0,unjudged:0,evals:0};for(let n of e)t.passed+=n.passed,t.failed+=n.failed,t.errored+=n.errored,t.unjudged+=n.unjudged,t.evals+=n.evals.length;return t}function eu(e,t){let n=e.replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t-1)}…`:n}const tu=x({meta:{name:`eval`,description:`Run behaviour evals for the seo skill against a local agent and judge the results`},args:{subject:{type:`positional`,required:!1,description:`Eval subject (report id or job). Omit to run every subject.`},list:{type:`boolean`,default:!1,description:`List eval subjects with their eval counts and exit.`},id:{type:`string`,description:`Run one eval id within a single subject.`},agent:{type:`string`,default:Ml,description:`Agent command. Use {prompt} to place the prompt in argv, otherwise it is sent on stdin.`},"judge-agent":{type:`string`,description:`Judge command. Defaults to the same command as --agent.`},judge:pi(`Judge assertions with an agent.`,`Skip judging and print replies with an assertion checklist.`),skill:pi(`Send the seo router skill as context before the prompt.`,`Omit the seo router skill context.`),timeout:{type:`string`,default:`300`,description:`Timeout in seconds per agent or judge call.`},concurrency:{type:`string`,default:`1`,description:`Evals to run in parallel (max 4).`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=j(e);if(e.list===!0){Xl(t);return}let n=Yl(Jl(e)),r=O(e.id);if(r!==void 0&&n.length!==1)throw new d(`INVALID_INPUT`,`--id needs exactly one subject. Name the subject to filter.`);let i=O(e.timeout)??300;if(!(i>0))throw new d(`INVALID_INPUT`,`--timeout must be a positive number of seconds.`);let a=Math.max(1,Math.min(4,O(e.concurrency)??1)),o=T(e.agent)??Ml,s=e.judge===!1?null:T(e[`judge-agent`])??o,c=e.skill===!1?null:Fl(),l={agent:o,judge:s,skillBody:c,timeoutMs:i*1e3},u=[];for(let e of n){let n=Pl(e.subject,e.path).evals;if(r!==void 0&&(n=n.filter(e=>e.id===r),n.length===0))throw new d(`INVALID_INPUT`,`No eval with id ${r} in subject ${e.subject}.`);t||process.stderr.write(`Running ${n.length} eval${n.length===1?``:`s`} for ${e.subject}...\n`);let i=await Kl(n,a,e=>Wl(e,l)),o=ql(i);u.push({subject:e.subject,...o,evals:i})}let f=$l(u),p=f.failed>0||f.errored>0;t?L({schemaVersion:1,agent:o,judge:s,judged:s!==null,skillContext:c!==null,timeoutSeconds:i,concurrency:a,subjects:u,totals:f}):Ql(u,{judged:s!==null,agent:o,judge:s}),p&&(process.exitCode=1)}});function nu(){let e=pl();return Sr(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&y(v(e,t.name,`SKILL.md`))).map(t=>({name:t.name,description:_l(v(e,t.name)),path:v(e,t.name)})).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))}function ru(e){let t=nu();if(!e)return t;let n=t.find(t=>t.name===e);if(!n)throw new d(`INVALID_INPUT`,`Unknown skill: ${e}.`);return[n]}const iu=x({meta:{name:`list`,description:`Show the packaged SEO skill`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:({args:e})=>{let t=nu();if(j(e))L({skills:t});else{ra(`SEO skill`,`Packaged with this CLI.`),process.stdout.write(`
117
- `);for(let e of t)R([[`Name`,e.name],[`Purpose`,`Helps agents choose and run the right SEO audit or report.`],[`Path`,e.path]]);process.stdout.write(`
118
- `),na({title:`Add it to an agent`,body:`Run setup to install the skill and connect your first site.`,command:`seo start`})}}}),au=x({meta:{name:`path`,description:`Print a packaged agent skill path`},args:{name:{type:`positional`,description:`Skill name. Omit it for the skill directory.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:({args:e})=>{let t=T(e.name),n=t?ru(t)[0]?.path:pl();j(e)?L({name:t,path:n}):process.stdout.write(`${n}\n`)}}),ou=x({meta:{name:`install`,description:`Install the SEO skill for coding agents`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:({args:e})=>{let t=j(e),n=zs({quiet:t});if(t)L(n),n.status===`failed`&&(process.exitCode=1);else{if(n.status===`failed`)throw new d(`INTERNAL_ERROR`,`Skill install failed: ${n.error}`);process.stdout.write(`SEO skill installed. Agents that support skills can discover it now.
119
- `)}}}),su=x({meta:{name:`skill`,description:`Inspect the packaged SEO skill and run its evals`},subCommands:{list:iu,path:au,install:ou,eval:tu}}),cu=x({meta:{name:`privacy`,description:`Show local config, token, cache, and log storage paths`},run:async()=>{let e=et(),t=ie();R(e.map(e=>[e.label,`${e.path} · ${da(e.sizeBytes)} · ${e.mode}`])),process.stdout.write(`
120
- `),R(Object.entries(t.counts).map(([e,t])=>[e,String(t)]))}}),lu=x({meta:{name:`reset`,description:`Delete saved credentials and all local data`},args:{yes:{type:`boolean`,default:!1,description:`Confirm deletion without prompting.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=j(e);if(!e.yes&&!I({json:t}))throw new d(`INVALID_INPUT`,`Cannot prompt here. Pass --yes to confirm reset.`);e.yes||B(await Ur({message:`Delete saved credentials and all local data?`,initialValue:!1}))?(await Rn(),t?L({reset:!0}):process.stdout.write(`Reset complete.
121
- `)):Hr(`Reset aborted.`)}}),uu=x({meta:{name:`sites`,description:`List Search Console properties available to this Google login`},args:{json:{type:`boolean`,default:!1},refresh:{type:`boolean`,default:!1},account:{type:`string`,description:`Saved Google account email.`}},run:async({args:e})=>{let t=await u(E(e.refresh),T(e.account));j(e)?L({sites:t}):z([`Property`,`Permission`],t.map(e=>[e.siteUrl,e.permissionLevel??`unknown`]))}}),du=x({meta:{name:`updates`,description:`List official Google Search Status ranking updates`},args:{product:{type:`string`,default:`Ranking`},limit:{type:`string`,default:`10`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=await de({product:T(e.product),limit:O(e.limit)});j(e)?L({updates:t}):sa(t.map(e=>({title:e.name,meta:[e.type,e.status,`${e.start.slice(0,10)} to ${e.end?.slice(0,10)??`present`}`]})),{empty:`No matching Google Search updates.`})}}),fu={ci:`disabled automatically in CI or tests`,do_not_track:`disabled by DO_NOT_TRACK`,environment:`disabled by a telemetry environment variable`,local_setting:`disabled in local settings`,invalid_state:`disabled because the local state file is invalid`};function pu(e){return{enabled:e.enabled,...e.reason?{reason:e.reason}:{},stateFile:e.stateFile,...e.state?{firstRunAt:e.state.firstRunAt,cohort:e.state.cohort,sentMilestones:e.state.sentMilestones}:{}}}function mu(e,t){let n=pu(e);t?L(n):(R([[`Anonymous telemetry`,e.enabled?`enabled`:`disabled`],[`Reason`,e.reason?fu[e.reason]:`local setting`],[`State file`,e.stateFile],[`Install cohort`,e.state?.cohort??`not created`]]),process.stdout.write(`
116
+ `);for(let n of e){process.stdout.write(`# ${n.subject}\n`);for(let e of n.evals)if(process.stdout.write(`\n[${lu(e.status)}] eval ${e.id} (${e.durationMs}ms)\n`),process.stdout.write(` prompt: ${fu(e.prompt,100)}\n`),e.error&&process.stdout.write(` error: ${e.error}\n`),!t.judged){process.stdout.write(` reply: ${fu(e.reply,200)}\n`),process.stdout.write(` assertions to review:
117
+ `);for(let t of e.assertions)process.stdout.write(` - [ ] ${t.assertion}\n`)}else for(let t of e.assertions){let e=t.verdict===`pass`?`pass`:t.verdict===`fail`?`fail`:`unjudged`;process.stdout.write(` - ${e}: ${t.assertion}\n`),t.reason&&process.stdout.write(` judge verdict: ${t.reason}\n`)}let e=au(n.evals);process.stdout.write(`\nSubject ${n.subject}: ${e.passed} passed, ${e.failed} failed, ${e.errored} errored${e.unjudged?`, ${e.unjudged} unjudged`:``}.\n\n`)}let n=du(e);process.stdout.write(`Totals: ${n.passed} passed, ${n.failed} failed, ${n.errored} errored${n.unjudged?`, ${n.unjudged} unjudged`:``} across ${n.evals} evals.\n`)}function du(e){let t={passed:0,failed:0,errored:0,unjudged:0,evals:0};for(let n of e)t.passed+=n.passed,t.failed+=n.failed,t.errored+=n.errored,t.unjudged+=n.unjudged,t.evals+=n.evals.length;return t}function fu(e,t){let n=e.replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t-1)}…`:n}const pu=b({meta:{name:`eval`,description:`Run behaviour evals for the seo skill against a local agent and judge the results`},args:{subject:{type:`positional`,required:!1,description:`Eval subject (report id or job). Omit to run every subject.`},list:{type:`boolean`,default:!1,description:`List eval subjects with their eval counts and exit.`},id:{type:`string`,description:`Run one eval id within a single subject.`},agent:{type:`string`,default:Wl,description:`Agent command. Use {prompt} to place the prompt in argv, otherwise it is sent on stdin.`},"judge-agent":{type:`string`,description:`Judge command. Defaults to the same command as --agent.`},judge:yi(`Judge assertions with an agent.`,`Skip judging and print replies with an assertion checklist.`),skill:yi(`Send the seo router skill as context before the prompt.`,`Omit the seo router skill context.`),timeout:{type:`string`,default:`300`,description:`Timeout in seconds per agent or judge call.`},concurrency:{type:`string`,default:`1`,description:`Evals to run in parallel (max 4).`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=A(e);if(e.list===!0){cu(t);return}let n=su(ou(e)),r=D(e.id);if(r!==void 0&&n.length!==1)throw new g(`INVALID_INPUT`,`--id needs exactly one subject. Name the subject to filter.`);let i=D(e.timeout)??300;if(!(i>0))throw new g(`INVALID_INPUT`,`--timeout must be a positive number of seconds.`);let a=Math.max(1,Math.min(4,D(e.concurrency)??1)),o=w(e.agent)??Wl,s=e.judge===!1?null:w(e[`judge-agent`])??o,c=e.skill===!1?null:ql(),l={agent:o,judge:s,skillBody:c,timeoutMs:i*1e3},u=[];for(let e of n){let n=Kl(e.subject,e.path).evals;if(r!==void 0&&(n=n.filter(e=>e.id===r),n.length===0))throw new g(`INVALID_INPUT`,`No eval with id ${r} in subject ${e.subject}.`);t||process.stderr.write(`Running ${n.length} eval${n.length===1?``:`s`} for ${e.subject}...\n`);let i=await iu(n,a,e=>nu(e,l)),o=au(i);u.push({subject:e.subject,...o,evals:i})}let d=du(u),f=d.failed>0||d.errored>0;t?I({schemaVersion:1,agent:o,judge:s,judged:s!==null,skillContext:c!==null,timeoutSeconds:i,concurrency:a,subjects:u,totals:d}):uu(u,{judged:s!==null,agent:o,judge:s}),f&&(process.exitCode=1)}});function mu(){let e=Tl();return Or(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&v(_(e,t.name,`SKILL.md`))).map(t=>({name:t.name,description:kl(_(e,t.name)),path:_(e,t.name)})).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))}function hu(e){let t=mu();if(!e)return t;let n=t.find(t=>t.name===e);if(!n)throw new g(`INVALID_INPUT`,`Unknown skill: ${e}.`);return[n]}const gu=b({meta:{name:`list`,description:`Show the packaged SEO skill`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:({args:e})=>{let t=mu();if(A(e))I({skills:t});else{la(`SEO skill`,`Packaged with this CLI.`),process.stdout.write(`
118
+ `);for(let e of t)L([[`Name`,e.name],[`Purpose`,`Helps agents choose and run the right SEO audit or report.`],[`Path`,e.path]]);process.stdout.write(`
119
+ `),ca({title:`Add it to an agent`,body:`Run setup to install the skill and connect your first site.`,command:`seo start`})}}}),_u=b({meta:{name:`path`,description:`Print a packaged agent skill path`},args:{name:{type:`positional`,description:`Skill name. Omit it for the skill directory.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:({args:e})=>{let t=w(e.name),n=t?hu(t)[0]?.path:Tl();A(e)?I({name:t,path:n}):process.stdout.write(`${n}\n`)}}),vu=b({meta:{name:`install`,description:`Install the SEO skill for coding agents`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:({args:e})=>{let t=A(e),n=Zs({quiet:t});if(t)I(n),n.status===`failed`&&(process.exitCode=1);else{if(n.status===`failed`)throw new g(`INTERNAL_ERROR`,`Skill install failed: ${n.error}`);process.stdout.write(`SEO skill installed. Agents that support skills can discover it now.
120
+ `)}}}),yu=b({meta:{name:`skill`,description:`Inspect the packaged SEO skill and run its evals`},subCommands:{list:gu,path:_u,install:vu,eval:pu}}),bu=b({meta:{name:`privacy`,description:`Show local config, token, cache, and log storage paths`},run:async()=>{let e=Se(),t=c();L(e.map(e=>[e.label,`${e.path} · ${_a(e.sizeBytes)} · ${e.mode}`])),process.stdout.write(`
121
+ `),L(Object.entries(t.counts).map(([e,t])=>[e,String(t)]))}}),xu=b({meta:{name:`reset`,description:`Delete saved credentials and all local data`},args:{yes:{type:`boolean`,default:!1,description:`Confirm deletion without prompting.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=A(e);if(!e.yes&&!F({json:t}))throw new g(`INVALID_INPUT`,`Cannot prompt here. Pass --yes to confirm reset.`);e.yes||z(await Yr({message:`Delete saved credentials and all local data?`,initialValue:!1}))?(await Un(),t?I({reset:!0}):process.stdout.write(`Reset complete.
122
+ `)):Jr(`Reset aborted.`)}}),Su=b({meta:{name:`sites`,description:`List Search Console properties available to this Google login`},args:{json:{type:`boolean`,default:!1},refresh:{type:`boolean`,default:!1},account:{type:`string`,description:`Saved Google account email.`}},run:async({args:e})=>{let t=await Fe(T(e.refresh),w(e.account));A(e)?I({sites:t}):R([`Property`,`Permission`],t.map(e=>[e.siteUrl,e.permissionLevel??`unknown`]))}}),Cu=b({meta:{name:`updates`,description:`List official Google Search Status ranking updates`},args:{product:{type:`string`,default:`Ranking`},limit:{type:`string`,default:`10`},json:{type:`boolean`,default:!1}},run:async({args:e})=>{let t=await Mn({product:w(e.product),limit:D(e.limit)});A(e)?I({updates:t}):pa(t.map(e=>({title:e.name,meta:[e.type,e.status,`${e.start.slice(0,10)} to ${e.end?.slice(0,10)??`present`}`]})),{empty:`No matching Google Search updates.`})}}),wu={ci:`disabled automatically in CI or tests`,do_not_track:`disabled by DO_NOT_TRACK`,environment:`disabled by a telemetry environment variable`,local_setting:`disabled in local settings`,invalid_state:`disabled because the local state file is invalid`};function Tu(e){return{enabled:e.enabled,...e.reason?{reason:e.reason}:{},stateFile:e.stateFile,...e.state?{firstRunAt:e.state.firstRunAt,cohort:e.state.cohort,sentMilestones:e.state.sentMilestones}:{}}}function Eu(e,t){let n=Tu(e);t?I(n):(L([[`Anonymous telemetry`,e.enabled?`enabled`:`disabled`],[`Reason`,e.reason?wu[e.reason]:`local setting`],[`State file`,e.stateFile],[`Install cohort`,e.state?.cohort??`not created`]]),process.stdout.write(`
122
123
  Only tool usage is sent. URLs, report data, Google data, and identifiers are never sent.
123
124
  `),process.stdout.write(`Details: https://seoskill.dev/telemetry
124
- `))}const hu={type:`boolean`,default:!1,description:`Print machine-readable JSON.`},gu=x({meta:{name:`telemetry`,description:`Check or change anonymous usage telemetry`},subCommands:{status:x({meta:{name:`status`,description:`Show whether anonymous usage telemetry is enabled`},args:{json:hu},run:async({args:e})=>mu(Zt(),j(e))}),enable:x({meta:{name:`enable`,description:`Enable anonymous usage telemetry in local settings`},args:{json:hu},run:async({args:e})=>{mu(Mn(!0),j(e))}}),disable:x({meta:{name:`disable`,description:`Disable anonymous usage telemetry in local settings`},args:{json:hu},run:async({args:e})=>{mu(Mn(!1),j(e))}})}});function _u(e){let t=e.toLowerCase();return[`pass`,`passed`,`complete`,`completed`,`joined`].includes(t)?`pass`:[`warn`,`warning`,`partial`,`review`].includes(t)?`warning`:[`fail`,`failed`,`error`].includes(t)?`fail`:[`unknown`,`unavailable`].includes(t)?`unknown`:`info`}function vu(e){let t=e.steps.map(e=>_u(e.status)),n=t.includes(`fail`)?`fail`:t.includes(`warning`)?`warning`:t.includes(`unknown`)?`unknown`:`pass`;aa({title:e.workflow,target:e.site,status:n,summary:e.summary,metrics:[{label:`Completed`,value:t.filter(e=>e===`pass`).length,status:`pass`},{label:`Review`,value:t.filter(e=>e===`warning`).length,status:`warning`},{label:`Unknown`,value:t.filter(e=>e===`unknown`).length,status:`unknown`}],sections:[{title:`Evidence collection`,diagnostics:e.steps.map(e=>({status:_u(e.status),title:e.tool,explanation:e.summary,evidence:[`Status: ${e.status}`]}))},{title:`Priority actions`,diagnostics:e.actions.map(e=>({status:`warning`,title:e.title,explanation:`Confidence: ${e.confidence}.`,fix:e.action}))}]})}const yu=x({meta:{name:`crawl-queue`,description:`Run a crawl and return a ranked implementation queue`},args:{crawlUrl:{type:`positional`,required:!1,description:`Start URL to crawl.`},url:{type:`string`,description:`Start URL to crawl. Defaults to the --site home page.`},site:{type:`string`,description:`GSC property URL for joining page metrics.`},...vo,mode:{type:`string`,description:`Crawl mode: site, page, list, or sitemap. Defaults to site.`},urls:{type:`string`,description:`Comma-separated URLs for list mode.`},"urls-file":{type:`string`,description:`File with one URL per line for list mode.`},"max-pages":{type:`string`,description:`Maximum pages to crawl. Defaults to 500.`},"max-depth":{type:`string`,description:`Maximum click depth. Defaults to 16.`},concurrency:{type:`string`,description:`Parallel page fetches. Defaults to 8.`},"fetch-interval-cap":{type:`string`,description:`Maximum page fetches per interval per host.`},"fetch-interval-ms":{type:`string`,description:`Fetch rate interval in milliseconds.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache and fetch fresh pages.`},include:{type:`string`,description:`Comma-separated URL patterns to include.`},exclude:{type:`string`,description:`Comma-separated URL patterns to exclude.`},limit:{type:`string`,description:`Maximum queue items to print. Defaults to 25.`},"no-sitemap":{type:`boolean`,default:!1,description:`Do not seed URLs from sitemap.xml.`},"no-robots":{type:`boolean`,default:!1,description:`Do not skip URLs disallowed by robots.txt.`},"no-external":{type:`boolean`,default:!1,description:`Do not check external links.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering when Playwright is installed.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=j(e),n=await Su(e),r=xu(e),i=T(e.site),a=r??(i?Eo(i):void 0)??n[0];if(!a)throw new d(`INVALID_INPUT`,"No crawl URL given. Pass a URL, --url or --site. Run `seo sites` to list your Search Console properties.");let o=await Ee({url:a,site:i,mode:bu(e.mode)??(n.length?`list`:void 0),urls:n,maxPages:O(e[`max-pages`]),maxDepth:O(e[`max-depth`]),concurrency:O(e.concurrency),refresh:E(e.refresh),fetchRate:vi({...e,"fetch-concurrency":e.concurrency}),include:A(e.include),exclude:A(e.exclude),googleAnalyticsPropertyId:T(e[`google-analytics-property`]),analyticsConnection:yo(e),useSitemap:!D(e,`sitemap`),respectRobots:!D(e,`robots`),checkExternal:!D(e,`external`),js:!!E(e.js),limit:O(e.limit)});t?L(o):(vu(o),z([`Rank`,`Score`,`Rule`,`Severity`,`Affected`,`Target`,`Action`],o.output.queue.map((e,t)=>[t+1,e.score,e.ruleId,e.severity,e.affectedUrls,e.target,e.action])),J(`Implementation queue details`,o.output.queue.map(e=>({label:`${e.ruleId} (${e.affectedUrls} URLs)`,context:`${e.severity}, score ${e.score}`,action:`${e.action} Verify with: ${e.verification.command}`}))))}});function bu(e){let t=T(e);if(t){if([`site`,`page`,`list`,`sitemap`].includes(t))return t;throw Error(`Mode must be one of: site, page, list, sitemap.`)}}function xu(e){let t=T(e.crawlUrl),n=T(e.url);if(t&&n&&t!==n)throw Error(`Use either a URL argument or --url, not both.`);return t??n}async function Su(e){let t=A(e.urls)??[],n=T(e[`urls-file`]);return n&&t.push(...Cu(await b(n,`utf8`))),[...new Set(t)]}function Cu(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`))}const wu=x({meta:{name:`refresh-priorities`,description:`Agent workflow for a ranked SEO action queue`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},...X([`days`,`recentDays`,`limit`,`includeBrand`,`refresh`],{days:{description:`Diagnosis window length in days. Defaults to 90.`},limit:{description:`Maximum queue items to print. Defaults to 25.`}}),...vo,"verify-content":pi(`Verify top opportunities against page title, meta, and content. Defaults to true.`,`Skip page content verification.`),"verify-limit":{type:`string`,description:`Maximum opportunity URLs to verify. Defaults to 5.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=j(e),n=M(T(e.site)),r=await tn({site:n,days:O(e.days),recentDays:O(e.recent),limit:O(e.limit),includeBrand:E(e[`include-brand`]),googleAnalyticsPropertyId:T(e[`google-analytics-property`]),analyticsConnection:yo(e),verifyContent:E(e[`verify-content`]),verifyLimit:O(e[`verify-limit`]),refresh:E(e.refresh)});t?L(r):(vu(r),z([`Source`,`Category`,`Score`,`Findings`,`Template`,`Analytics`,`Target`,`Action`],r.output.queue.map(e=>[e.source,e.category,e.score,e.grouped?.count??1,e.template?.label??`-`,e.analytics?.sessions??`-`,e.target,e.action])),J(`Queue action details`,r.output.queue.map(e=>({label:e.target,context:`${e.category}, score ${e.score}`,action:e.action}))))}});function Tu(e){return e===null?`-`:e.toLocaleString(`en-GB`,{maximumFractionDigits:e>=100?0:1})}function Eu(e){return[...e.winners.map(e=>({direction:`winner`,item:e})),...e.losers.map(e=>({direction:`loser`,item:e}))]}function Du(e,t){let n=Eu(t);n.length&&(process.stdout.write(`\n${e}\n`),z([`Direction`,`Key`,`Clicks`,`Impr.`,`Position`],n.map(({direction:e,item:t})=>[e,t.key,Tu(t.clickDelta),Tu(t.impressionDelta),Tu(t.positionDelta)])))}function Ou(e){process.stdout.write(`
125
+ `))}const Du={type:`boolean`,default:!1,description:`Print machine-readable JSON.`},Ou=b({meta:{name:`telemetry`,description:`Check or change anonymous usage telemetry`},subCommands:{status:b({meta:{name:`status`,description:`Show whether anonymous usage telemetry is enabled`},args:{json:Du},run:async({args:e})=>Eu(pn(),A(e))}),enable:b({meta:{name:`enable`,description:`Enable anonymous usage telemetry in local settings`},args:{json:Du},run:async({args:e})=>{Eu(Ht(!0),A(e))}}),disable:b({meta:{name:`disable`,description:`Disable anonymous usage telemetry in local settings`},args:{json:Du},run:async({args:e})=>{Eu(Ht(!1),A(e))}})}});function ku(e){let t=e.toLowerCase();return[`pass`,`passed`,`complete`,`completed`,`joined`].includes(t)?`pass`:[`warn`,`warning`,`partial`,`review`].includes(t)?`warning`:[`fail`,`failed`,`error`].includes(t)?`fail`:[`unknown`,`unavailable`].includes(t)?`unknown`:`info`}function Au(e){let t=e.steps.map(e=>ku(e.status)),n=t.includes(`fail`)?`fail`:t.includes(`warning`)?`warning`:t.includes(`unknown`)?`unknown`:`pass`;da({title:e.workflow,target:e.site,status:n,summary:e.summary,metrics:[{label:`Completed`,value:t.filter(e=>e===`pass`).length,status:`pass`},{label:`Review`,value:t.filter(e=>e===`warning`).length,status:`warning`},{label:`Unknown`,value:t.filter(e=>e===`unknown`).length,status:`unknown`}],sections:[{title:`Evidence collection`,diagnostics:e.steps.map(e=>({status:ku(e.status),title:e.tool,explanation:e.summary,evidence:[`Status: ${e.status}`]}))},{title:`Priority actions`,diagnostics:e.actions.map(e=>({status:`warning`,title:e.title,explanation:`Confidence: ${e.confidence}.`,fix:e.action}))}]})}const ju=b({meta:{name:`crawl-queue`,description:`Run a crawl and return a ranked implementation queue`},args:{crawlUrl:{type:`positional`,required:!1,description:`Start URL to crawl.`},url:{type:`string`,description:`Start URL to crawl. Defaults to the --site home page.`},site:{type:`string`,description:`GSC property URL for joining page metrics.`},...Ao,mode:{type:`string`,description:`Crawl mode: site, page, list, or sitemap. Defaults to site.`},urls:{type:`string`,description:`Comma-separated URLs for list mode.`},"urls-file":{type:`string`,description:`File with one URL per line for list mode.`},"max-pages":{type:`string`,description:`Maximum pages to crawl. Defaults to 500.`},"max-depth":{type:`string`,description:`Maximum click depth. Defaults to 16.`},concurrency:{type:`string`,description:`Parallel page fetches. Defaults to 8.`},"fetch-interval-cap":{type:`string`,description:`Maximum page fetches per interval per host.`},"fetch-interval-ms":{type:`string`,description:`Fetch rate interval in milliseconds.`},refresh:{type:`boolean`,default:!1,description:`Bypass local HTTP cache and fetch fresh pages.`},include:{type:`string`,description:`Comma-separated URL patterns to include.`},exclude:{type:`string`,description:`Comma-separated URL patterns to exclude.`},limit:{type:`string`,description:`Maximum queue items to print. Defaults to 25.`},"no-sitemap":{type:`boolean`,default:!1,description:`Do not seed URLs from sitemap.xml.`},"no-robots":{type:`boolean`,default:!1,description:`Do not skip URLs disallowed by robots.txt.`},"no-external":{type:`boolean`,default:!1,description:`Do not check external links.`},js:{type:`boolean`,default:!1,description:`Force JavaScript rendering when Playwright is installed.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=A(e),n=await Pu(e),r=Nu(e),i=w(e.site),a=r??(i?Ro(i):void 0)??n[0];if(!a)throw new g(`INVALID_INPUT`,"No crawl URL given. Pass a URL, --url or --site. Run `seo sites` to list your Search Console properties.");let o=await Ee({url:a,site:i,mode:Mu(e.mode)??(n.length?`list`:void 0),urls:n,maxPages:D(e[`max-pages`]),maxDepth:D(e[`max-depth`]),concurrency:D(e.concurrency),refresh:T(e.refresh),fetchRate:wi({...e,"fetch-concurrency":e.concurrency}),include:k(e.include),exclude:k(e.exclude),googleAnalyticsPropertyId:w(e[`google-analytics-property`]),analyticsConnection:jo(e),useSitemap:!E(e,`sitemap`),respectRobots:!E(e,`robots`),checkExternal:!E(e,`external`),js:!!T(e.js),limit:D(e.limit)});t?I(o):(Au(o),R([`Rank`,`Score`,`Rule`,`Severity`,`Affected`,`Target`,`Action`],o.output.queue.map((e,t)=>[t+1,e.score,e.ruleId,e.severity,e.affectedUrls,e.target,e.action])),J(`Implementation queue details`,o.output.queue.map(e=>({label:`${e.ruleId} (${e.affectedUrls} URLs)`,context:`${e.severity}, score ${e.score}`,action:`${e.action} Verify with: ${e.verification.command}`}))))}});function Mu(e){let t=w(e);if(t){if([`site`,`page`,`list`,`sitemap`].includes(t))return t;throw Error(`Mode must be one of: site, page, list, sitemap.`)}}function Nu(e){let t=w(e.crawlUrl),n=w(e.url);if(t&&n&&t!==n)throw Error(`Use either a URL argument or --url, not both.`);return t??n}async function Pu(e){let t=k(e.urls)??[],n=w(e[`urls-file`]);return n&&t.push(...Fu(await y(n,`utf8`))),[...new Set(t)]}function Fu(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`))}const Iu=b({meta:{name:`refresh-priorities`,description:`Agent workflow for a ranked SEO action queue`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},...X([`days`,`recentDays`,`limit`,`includeBrand`,`refresh`],{days:{description:`Diagnosis window length in days. Defaults to 90.`},limit:{description:`Maximum queue items to print. Defaults to 25.`}}),...Ao,"verify-content":yi(`Verify top opportunities against page title, meta, and content. Defaults to true.`,`Skip page content verification.`),"verify-limit":{type:`string`,description:`Maximum opportunity URLs to verify. Defaults to 5.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=A(e),n=j(w(e.site)),r=await _e({site:n,days:D(e.days),recentDays:D(e.recent),limit:D(e.limit),includeBrand:T(e[`include-brand`]),googleAnalyticsPropertyId:w(e[`google-analytics-property`]),analyticsConnection:jo(e),verifyContent:T(e[`verify-content`]),verifyLimit:D(e[`verify-limit`]),refresh:T(e.refresh)});t?I(r):(Au(r),R([`Source`,`Category`,`Score`,`Findings`,`Template`,`Analytics`,`Target`,`Action`],r.output.queue.map(e=>[e.source,e.category,e.score,e.grouped?.count??1,e.template?.label??`-`,e.analytics?.sessions??`-`,e.target,e.action])),J(`Queue action details`,r.output.queue.map(e=>({label:e.target,context:`${e.category}, score ${e.score}`,action:e.action}))))}});function Lu(e){return e===null?`-`:e.toLocaleString(`en-GB`,{maximumFractionDigits:e>=100?0:1})}function Ru(e){return[...e.winners.map(e=>({direction:`winner`,item:e})),...e.losers.map(e=>({direction:`loser`,item:e}))]}function zu(e,t){let n=Ru(t);n.length&&(process.stdout.write(`\n${e}\n`),R([`Direction`,`Key`,`Clicks`,`Impr.`,`Position`],n.map(({direction:e,item:t})=>[e,t.key,Lu(t.clickDelta),Lu(t.impressionDelta),Lu(t.positionDelta)])))}function Bu(e){process.stdout.write(`
125
126
  Segment coverage
126
- `),z([`Dimension`,`Eligible`,`Returned`,`Limited`,`Result cap`,`Source cap`,`Source capped`],[`page`,`query`,`device`,`country`].map(t=>{let n=e[t].coverage;return[t,n.eligibleRows,n.returnedRows,n.limitedRows,n.resultLimit,n.sourceRowLimit,n.sourcePossiblyTruncated?`yes`:`no`]}))}function ku(e){e.length&&(process.stdout.write(`
127
+ `),R([`Dimension`,`Eligible`,`Returned`,`Limited`,`Result cap`,`Source cap`,`Source capped`],[`page`,`query`,`device`,`country`].map(t=>{let n=e[t].coverage;return[t,n.eligibleRows,n.returnedRows,n.limitedRows,n.resultLimit,n.sourceRowLimit,n.sourcePossiblyTruncated?`yes`:`no`]}))}function Vu(e){e.length&&(process.stdout.write(`
127
128
  Template movement
128
- `),z([`Direction`,`Template`,`Pattern confidence`,`URLs`,`Clicks`,`Returned share`,`Common terms`],e.map(e=>[e.direction,e.signature,e.confidence,e.urlCount,Tu(e.clickDelta),`${Math.round(e.movementShare*100)}%`,e.commonTerms.join(`, `)||`-`])),Y(`Template actions`,e.map(e=>e.summary)),Y(`Template evidence scope`,[`Shares use returned directional page click movement. Pattern confidence applies only to returned matched-retained page segments.`]))}const Au=x({meta:{name:`update-postmortem`,description:`Agent workflow for Google update winner/loser analysis`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},...X([`days`,`recentDays`,`limit`,`includeBrand`,`refresh`],{days:{description:`Diagnosis window length in days. Defaults to 90.`},limit:{description:`Maximum winners/losers per segment. Defaults to 20.`}}),"known-change":{type:`string`,description:`Manual site-side change to treat as a confounder, for example pruning pages or blocking traffic.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=j(e),n=M(T(e.site)),r=await a({site:n,days:O(e.days),recentDays:O(e.recent),limit:O(e.limit),includeBrand:E(e[`include-brand`]),knownConfounders:T(e[`known-change`])?[T(e[`known-change`])??``]:void 0,refresh:E(e.refresh)});t?L(r):(K({title:`Update postmortem`,target:r.site,status:`unknown`,summary:r.summary,metrics:[{label:`Attribution`,value:r.output.update.attribution.replaceAll(`-`,` `)},{label:`Confidence`,value:r.output.update.confidence},{label:`Known confounders`,value:r.output.update.confounders.length}]}),Y(`Recommended actions`,r.actions.map(e=>`${e.title} (${e.confidence}): ${e.action}`)),Y(`Postmortem findings`,r.output.insights.map(e=>e.summary)),Y(`Segment evidence warnings`,[...r.output.segments.page.warnings,...r.output.segments.query.warnings,...r.output.segments.device.warnings,...r.output.segments.country.warnings].filter((e,t,n)=>n.indexOf(e)===t)),ku(r.output.templateMovement),Y(`Update evidence`,r.output.update.evidence),Ou(r.output.segments),Du(`Page winners and losers`,r.output.segments.page),Du(`Query winners and losers`,r.output.segments.query),Du(`Device winners and losers`,r.output.segments.device),Du(`Country winners and losers`,r.output.segments.country),no(`seo export update-postmortem --site ${JSON.stringify(n)}`))}}),ju=/* @__PURE__ */ new Set([`database`,`filesystem`,`internal`,`unknown`]);function Mu(e){return e.replace(/^v/,``).split(`.`)[0]||`unknown`}function Nu(e){return qt(e[0])?e[0]:void 0}function Pu(e,t){return yn(e)?`seo ${e}`:t?`seo ${t}`:`seo command`}function Fu(e){let t=fn(e.error);if(!ju.has(t.errorCategory))return;let n=Nu(e.args),r=Pu(e.report,n),i=[Je(e.error).code,t.errorCategory,t.failureReason,t.failureContext].filter(Boolean).join(` | `),a=new URL(`https://github.com/iannuttall/seo/issues/new`);return a.searchParams.set(`template`,`bug.yml`),a.searchParams.set(`title`,`bug: ${r} failed`),a.searchParams.set(`version`,e.version??Cn),a.searchParams.set(`runtime`,`Node ${Mu(e.nodeVersion??process.version)} on ${e.processPlatform??ur()} (${e.processArch??cr()})`),a.searchParams.set(`diagnostics`,i),a.toString()}const Iu={"refresh-priorities":`seo report`,"query-cluster":`seo report`,"quick-wins":`seo report --section quick-wins`,"ctr-underperformers":`seo report --section low-ctr`,"striking-distance":`seo report --section striking-distance`,"second-page":`seo report --section second-page`,decaying:`seo report --section content-decay`,cannibal:`seo report --section cannibalization`,"traffic-anomaly":`seo report --section traffic-drop`,"page-opportunities":`seo page --url <url>`,"audit-page":`seo page --url <url>`,"url-inspect":`seo page --url <url>`,"segment-impact":`seo compare --date <date>`,"update-correlate":`seo compare --date <date>`,"update-postmortem":`seo compare --date <date>`,"link-recover":`seo index`,"gsc-query":`seo data`},Lu={"agent-readiness":null,"ai-readiness":null,"community-intent":null,"entity-readiness":null,llms:null,"monthly-report":`seo report`,okf:null,pseo:null,"report-narrative":`seo report`,"seo-to-ai-query":null,"server-logs":null,links:`seo research backlinks --target <domain>`,"export knowledge":null,"export monthly":`seo report --json`,"export narrative":`seo report --json`,"export pseo":null,indexnow:null,"providers semrush":`seo providers`,"providers limits":null,"providers spend":null,"providers dataforseo limits":null,"providers dataforseo spend":null,"providers ahrefs limits":null,"change-log":null,client:null,project:null,projects:null,"content-groups":null,"crawl-diff":`seo crawl`,"crawl-reports":`seo crawl`,diagnose:`seo report`,"diagnose-property":`seo report`,"export diagnose":`seo report --json`,"index-watch":`seo page --url <url>`,monitoring:`seo crawl`,schedule:null,"technical-watch":`seo crawl`,tests:`seo compare --date <date>`},Z=`It saved history between runs. Your agent keeps its own notes now.`,Ru=`Commands take --site now instead of a saved project.`,zu=`Spend is controlled in your provider account. Set limits in DataForSEO, Ahrefs or the other provider.`,Bu={"providers limits":zu,"providers spend":zu,"providers dataforseo limits":zu,"providers dataforseo spend":zu,"providers ahrefs limits":zu,"change-log":Z,client:Ru,project:Ru,projects:Ru,"content-groups":Z,"crawl-diff":Z,"crawl-reports":Z,diagnose:Z,"diagnose-property":Z,"export diagnose":Z,"index-watch":Z,monitoring:Z,schedule:Z,"technical-watch":Z,tests:Z},Vu=/* @__PURE__ */ new Set([`client`,`project`,`projects`]);function Hu(e){let t=e.findIndex(e=>e.startsWith(`-`)),n=t===-1?e:e.slice(0,t),r=+(n[0]===`help`);for(let e=3;e>=1;--e){let t=n.slice(r,r+e).join(` `);if(n.length-r>=e&&Object.hasOwn(Lu,t))return t}return null}function Uu(e){let t=Object.hasOwn(Iu,e)?Iu[e]:void 0;return t?`\`seo ${e}\` is now \`${t}\`. The old name stops working in 1.0.0.`:null}function Wu(e){let t=Hu(e);if(!t)return null;let n=Lu[t],r=t.split(` `)[0]??``,i=n?`Use \`${n}\` instead.`:Vu.has(r)?"Run `seo sites` to list your Search Console properties.":r===`providers`?"Run `seo providers --help` for the provider commands.":"Run `seo help` for the commands.";return`\`seo ${t}\` was removed. ${Object.hasOwn(Bu,t)?Bu[t]:`SEO Skill now focuses on Search Console, analytics and keyword data.`} ${i}`}const Gu={"internal-links":[`--days`,`--limit`,`--check-limit`,`--min-impressions`,`--brand-terms`,`--include-brand`,`--no-include-brand`,`--js`,`--no-js`,`--fetch-concurrency`,`--fetch-interval-cap`,`--fetch-interval-ms`]},Ku=e=>e.split(`=`)[0]??``;function qu(e){let t=e.find(e=>[`--project`,`--client`].includes(Ku(e)));if(t)return`\`${Ku(t)}\` was removed. ${Ru} Pass --site with a domain, URL or sc-domain: property, or run \`seo sites\` to list your Search Console properties.`;let n=e[0]??``,r=Object.hasOwn(Gu,n)?e.find(e=>Gu[n]?.includes(Ku(e))):void 0;if(!r)return null;let i=Ku(r);return`\`${i}\` was removed from \`seo ${n}\`. It now sets its own limits, brand terms and page fetching, and shows them in the output.${i===`--days`?` Pass --start-date and --end-date for other dates.`:``}`}function Ju(e){return e.replaceAll(`\\`,`/`).toLowerCase()}function Yu(e,t){return t===`win32`?`${e}.cmd`:e}function Xu(e,t=process.platform){let n=Ju(e);if(!(n.includes(`/_npx/`)||n.includes(`/.npm/_npx/`)||n.includes(`/.cache/pnpm/dlx/`)||n.includes(`/.volta/`))){if(n.includes(`/.pnpm/`)||n.includes(`/pnpm/global/`))return{command:Yu(`pnpm`,t),args:[`add`,`--global`,`seo@latest`]};if(n.includes(`/.bun/install/global/`))return{command:Yu(`bun`,t),args:[`add`,`--global`,`seo@latest`]};if(n.includes(`/.config/yarn/global/`))return{command:Yu(`yarn`,t),args:[`global`,`add`,`seo@latest`]};if(n.includes(`/node_modules/seo/`))return{command:Yu(`npm`,t),args:[`install`,`--global`,`seo@latest`]}}}function Zu(e){return!(!e.stdinIsTty||!e.stdoutIsTty||e.env.CI||e.env.NO_UPDATE_NOTIFIER||e.env.NODE_ENV===`test`||e.env.npm_lifecycle_event||e.env.npm_execpath||e.env.TERM===`dumb`||e.argv.includes(`--json`)||e.argv.some(e=>[`--help`,`-h`,`--version`,`-v`].includes(e))||[`help`,`mcp`].includes(e.argv[0]??``))}function Qu(e){if(e)try{return Cr(e)}catch{return e}}async function $u(e){let t=await Yr({message:`seo ${e.update.latest} is available. You have ${e.update.current}.`,options:[{value:`update`,label:`Update now`,hint:[e.command.command,...e.command.args].join(` `)},{value:`later`,label:`Later`}],initialValue:`later`});return Gr(t)?`later`:t}function ed(e){return ts(e.command,e.args,{stdio:`inherit`}).status}async function td(e,t={}){if(!Zu({argv:t.argv??process.argv.slice(2),env:t.env??process.env,stdinIsTty:t.stdinIsTty??!!process.stdin.isTTY,stdoutIsTty:t.stdoutIsTty??!!process.stdout.isTTY}))return;let n=Qu(t.cliPath??process.argv[1]),r=n?Xu(n,t.platform??process.platform):void 0;if(!r)return;let i=(t.createNotifier??(e=>ai({pkg:e,shouldNotifyInNpmScript:!1})))(e).update;if(i&&Et(i.current,i.latest)&&await(t.prompt??$u)({command:r,update:i})!==`later`)return(t.run??ed)(r)===0?(Kr.success(`Updated seo to ${i.latest}. Run your command again.`),0):(Kr.error(`The update failed. Your current version is unchanged.`),1)}function nd(e){if(process.stderr.isTTY&&!process.env.CI&&!(e.includes(`--json`)||e[0]===`mcp`))try{let{configDir:e,configFile:t}=gt();if(!y(t))return;let n=v(e,`notices.json`),r=y(n)?JSON.parse(xr(n,`utf8`)):[];if(r.includes(`0.4`))return;process.stderr.write(`
129
+ `),R([`Direction`,`Template`,`Pattern confidence`,`URLs`,`Clicks`,`Returned share`,`Common terms`],e.map(e=>[e.direction,e.signature,e.confidence,e.urlCount,Lu(e.clickDelta),`${Math.round(e.movementShare*100)}%`,e.commonTerms.join(`, `)||`-`])),Y(`Template actions`,e.map(e=>e.summary)),Y(`Template evidence scope`,[`Shares use returned directional page click movement. Pattern confidence applies only to returned matched-retained page segments.`]))}const Hu=b({meta:{name:`update-postmortem`,description:`Agent workflow for Google update winner/loser analysis`},args:{site:{type:`string`,description:`GSC property URL, for example sc-domain:example.com.`},...X([`days`,`recentDays`,`limit`,`includeBrand`,`refresh`],{days:{description:`Diagnosis window length in days. Defaults to 90.`},limit:{description:`Maximum winners/losers per segment. Defaults to 20.`}}),"known-change":{type:`string`,description:`Manual site-side change to treat as a confounder, for example pruning pages or blocking traffic.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=A(e),n=j(w(e.site)),r=await ce({site:n,days:D(e.days),recentDays:D(e.recent),limit:D(e.limit),includeBrand:T(e[`include-brand`]),knownConfounders:w(e[`known-change`])?[w(e[`known-change`])??``]:void 0,refresh:T(e.refresh)});t?I(r):(K({title:`Update postmortem`,target:r.site,status:`unknown`,summary:r.summary,metrics:[{label:`Attribution`,value:r.output.update.attribution.replaceAll(`-`,` `)},{label:`Confidence`,value:r.output.update.confidence},{label:`Known confounders`,value:r.output.update.confounders.length}]}),Y(`Recommended actions`,r.actions.map(e=>`${e.title} (${e.confidence}): ${e.action}`)),Y(`Postmortem findings`,r.output.insights.map(e=>e.summary)),Y(`Segment evidence warnings`,[...r.output.segments.page.warnings,...r.output.segments.query.warnings,...r.output.segments.device.warnings,...r.output.segments.country.warnings].filter((e,t,n)=>n.indexOf(e)===t)),Vu(r.output.templateMovement),Y(`Update evidence`,r.output.update.evidence),Bu(r.output.segments),zu(`Page winners and losers`,r.output.segments.page),zu(`Query winners and losers`,r.output.segments.query),zu(`Device winners and losers`,r.output.segments.device),zu(`Country winners and losers`,r.output.segments.country),ho(`seo export update-postmortem --site ${JSON.stringify(n)}`))}}),Uu=/* @__PURE__ */ new Set([`database`,`filesystem`,`internal`,`unknown`]);function Wu(e){return e.replace(/^v/,``).split(`.`)[0]||`unknown`}function Gu(e){return Dt(e[0])?e[0]:void 0}function Ku(e,t){return Ft(e)?`seo ${e}`:t?`seo ${t}`:`seo command`}function qu(e){let t=sr(e.error);if(!Uu.has(t.errorCategory))return;let n=Gu(e.args),r=Ku(e.report,n),i=[a(e.error).code,t.errorCategory,t.failureReason,t.failureContext].filter(Boolean).join(` | `),o=new URL(`https://github.com/iannuttall/seo/issues/new`);return o.searchParams.set(`template`,`bug.yml`),o.searchParams.set(`title`,`bug: ${r} failed`),o.searchParams.set(`version`,e.version??Yn),o.searchParams.set(`runtime`,`Node ${Wu(e.nodeVersion??process.version)} on ${e.processPlatform??hr()} (${e.processArch??pr()})`),o.searchParams.set(`diagnostics`,i),o.toString()}const Ju={"refresh-priorities":`seo report`,"query-cluster":`seo report`,"quick-wins":`seo report --section quick-wins`,"ctr-underperformers":`seo report --section low-ctr`,"striking-distance":`seo report --section striking-distance`,"second-page":`seo report --section second-page`,decaying:`seo report --section content-decay`,cannibal:`seo report --section cannibalization`,"traffic-anomaly":`seo report --section traffic-drop`,"page-opportunities":`seo page --url <url>`,"audit-page":`seo page --url <url>`,"url-inspect":`seo page --url <url>`,"segment-impact":`seo compare --date <date>`,"update-correlate":`seo compare --date <date>`,"update-postmortem":`seo compare --date <date>`,"link-recover":`seo index`,"gsc-query":`seo data`},Yu={"agent-readiness":null,"ai-readiness":null,"community-intent":null,"entity-readiness":null,llms:null,"monthly-report":`seo report`,okf:null,pseo:null,"report-narrative":`seo report`,"seo-to-ai-query":null,"server-logs":null,links:`seo research backlinks --target <domain>`,"export knowledge":null,"export monthly":`seo report --json`,"export narrative":`seo report --json`,"export pseo":null,indexnow:null,"providers semrush":`seo providers`,"providers limits":null,"providers spend":null,"providers dataforseo limits":null,"providers dataforseo spend":null,"providers ahrefs limits":null,"change-log":null,client:null,project:null,projects:null,"content-groups":null,"crawl-diff":`seo crawl`,"crawl-reports":`seo crawl`,diagnose:`seo report`,"diagnose-property":`seo report`,"export diagnose":`seo report --json`,"index-watch":`seo page --url <url>`,monitoring:`seo crawl`,schedule:null,"technical-watch":`seo crawl`,tests:`seo compare --date <date>`},Z=`It saved history between runs. Your agent keeps its own notes now.`,Xu=`Commands take --site now instead of a saved project.`,Zu=`Spend is controlled in your provider account. Set limits in DataForSEO, Ahrefs or the other provider.`,Qu={"providers limits":Zu,"providers spend":Zu,"providers dataforseo limits":Zu,"providers dataforseo spend":Zu,"providers ahrefs limits":Zu,"change-log":Z,client:Xu,project:Xu,projects:Xu,"content-groups":Z,"crawl-diff":Z,"crawl-reports":Z,diagnose:Z,"diagnose-property":Z,"export diagnose":Z,"index-watch":Z,monitoring:Z,schedule:Z,"technical-watch":Z,tests:Z},$u=/* @__PURE__ */ new Set([`client`,`project`,`projects`]);function ed(e){let t=e.findIndex(e=>e.startsWith(`-`)),n=t===-1?e:e.slice(0,t),r=+(n[0]===`help`);for(let e=3;e>=1;--e){let t=n.slice(r,r+e).join(` `);if(n.length-r>=e&&Object.hasOwn(Yu,t))return t}return null}function td(e){let t=Object.hasOwn(Ju,e)?Ju[e]:void 0;return t?`\`seo ${e}\` is now \`${t}\`. The old name stops working in 1.0.0.`:null}function nd(e){let t=ed(e);if(!t)return null;let n=Yu[t],r=t.split(` `)[0]??``,i=n?`Use \`${n}\` instead.`:$u.has(r)?"Run `seo sites` to list your Search Console properties.":r===`providers`?"Run `seo providers --help` for the provider commands.":"Run `seo help` for the commands.";return`\`seo ${t}\` was removed. ${Object.hasOwn(Qu,t)?Qu[t]:`SEO Skill now focuses on Search Console, analytics and keyword data.`} ${i}`}const rd={"internal-links":[`--days`,`--limit`,`--check-limit`,`--min-impressions`,`--brand-terms`,`--include-brand`,`--no-include-brand`,`--js`,`--no-js`,`--fetch-concurrency`,`--fetch-interval-cap`,`--fetch-interval-ms`]},id=e=>e.split(`=`)[0]??``;function ad(e){let t=e.find(e=>[`--project`,`--client`].includes(id(e)));if(t)return`\`${id(t)}\` was removed. ${Xu} Pass --site with a domain, URL or sc-domain: property, or run \`seo sites\` to list your Search Console properties.`;let n=e[0]??``,r=Object.hasOwn(rd,n)?e.find(e=>rd[n]?.includes(id(e))):void 0;if(!r)return null;let i=id(r);return`\`${i}\` was removed from \`seo ${n}\`. It now sets its own limits, brand terms and page fetching, and shows them in the output.${i===`--days`?` Pass --start-date and --end-date for other dates.`:``}`}function od(e){return e.replaceAll(`\\`,`/`).toLowerCase()}function sd(e,t){return t===`win32`?`${e}.cmd`:e}function cd(e,t=process.platform){let n=od(e);if(!(n.includes(`/_npx/`)||n.includes(`/.npm/_npx/`)||n.includes(`/.cache/pnpm/dlx/`)||n.includes(`/.volta/`))){if(n.includes(`/.pnpm/`)||n.includes(`/pnpm/global/`))return{command:sd(`pnpm`,t),args:[`add`,`--global`,`seo@latest`]};if(n.includes(`/.bun/install/global/`))return{command:sd(`bun`,t),args:[`add`,`--global`,`seo@latest`]};if(n.includes(`/.config/yarn/global/`))return{command:sd(`yarn`,t),args:[`global`,`add`,`seo@latest`]};if(n.includes(`/node_modules/seo/`))return{command:sd(`npm`,t),args:[`install`,`--global`,`seo@latest`]}}}function ld(e){return!(!e.stdinIsTty||!e.stdoutIsTty||e.env.CI||e.env.NO_UPDATE_NOTIFIER||e.env.NODE_ENV===`test`||e.env.npm_lifecycle_event||e.env.npm_execpath||e.env.TERM===`dumb`||e.argv.includes(`--json`)||e.argv.some(e=>[`--help`,`-h`,`--version`,`-v`].includes(e))||[`help`,`mcp`].includes(e.argv[0]??``))}function ud(e){if(e)try{return kr(e)}catch{return e}}async function dd(e){let t=await ti({message:`seo ${e.update.latest} is available. You have ${e.update.current}.`,options:[{value:`update`,label:`Update now`,hint:[e.command.command,...e.command.args].join(` `)},{value:`later`,label:`Later`}],initialValue:`later`});return Zr(t)?`later`:t}function fd(e){return ps(e.command,e.args,{stdio:`inherit`}).status}async function pd(e,t={}){if(!ld({argv:t.argv??process.argv.slice(2),env:t.env??process.env,stdinIsTty:t.stdinIsTty??!!process.stdin.isTTY,stdoutIsTty:t.stdoutIsTty??!!process.stdout.isTTY}))return;let n=ud(t.cliPath??process.argv[1]),r=n?cd(n,t.platform??process.platform):void 0;if(!r)return;let i=(t.createNotifier??(e=>di({pkg:e,shouldNotifyInNpmScript:!1})))(e).update;if(i&&kt(i.current,i.latest)&&await(t.prompt??dd)({command:r,update:i})!==`later`)return(t.run??fd)(r)===0?(Qr.success(`Updated seo to ${i.latest}. Run your command again.`),0):(Qr.error(`The update failed. Your current version is unchanged.`),1)}function md(e){if(process.stderr.isTTY&&!process.env.CI&&!(e.includes(`--json`)||e[0]===`mcp`))try{let{configDir:e,configFile:t}=qe();if(!v(t))return;let n=_(e,`notices.json`),r=v(n)?JSON.parse(Dr(n,`utf8`)):[];if(r.includes(`0.4`))return;process.stderr.write(`
129
130
  SEO Skill 0.4: eight commands replace the old reports, and projects are gone: every command takes --site (run \`seo sites\` to list yours). Old command names print what to use instead.
130
131
  Free hosted MCP server, nothing to install: https://seoskill.dev/docs/mcp
131
132
  To stay on the old version: npm i -g seo@0.2.41
132
133
  What changed: https://github.com/iannuttall/seo/blob/main/CHANGELOG.md
133
134
 
134
- `),Dr(n,JSON.stringify([...r,`0.4`]),{mode:384})}catch{}}const rd={name:`seo`,version:Cn},id=[{title:`Start here`,commands:[[`seo start`,`Sign in with Google, then add the MCP server and skill`],[`seo report`,`Last week across your audited sites (after seo login)`],[`seo report --site <site>`,`One site: overview and every section`],[`seo report --site <site> --section quick-wins`,`One section of the report, with live page checks`]]},{title:`Commands`,commands:[[`seo page --url <url>`,`One page: live facts, index status, queries`],[`seo compare --date <date>`,`Before and after a date`],[`seo index`,`Pages that lost most of their clicks`],[`seo research <action>`,`Keyword, SERP, competitor and backlink data from your key`],[`seo data`,`Raw Search Console, Bing or Clicky rows`],[`seo crawl`,`Crawl a site and list technical issues`],[`seo internal-links`,`Pages that could link to a target page`],[`seo lint <files>`,`Check copy for AI writing patterns and length`],[`seo site new <folder>`,`Start a data-driven site on Astro and Cloudflare`]]},{title:`Setup`,commands:[[`seo login`,`Use your seoskill.dev account on this machine`],[`seo sites`,`List Search Console properties`],[`seo mcp install`,`Add the local MCP server to your agents`],[`seo providers`,`Connect DataForSEO or Ahrefs`],[`seo doctor`,`Check local auth and config`]]}],ad=[...id,{title:`More commands`,commands:[[`seo crawl-queue`,`Run a crawl and rank the fix queue`],[`seo rules`,`List crawler rule ids`],[`seo explain --rule missing_title`,`Explain a crawler rule`],[`seo redirect-trace`,`Trace redirects`],[`seo perf audit`,`Run a page performance audit`],[`seo index-coverage`,`Choose pages for URL Inspection`],[`seo ai-referrals`,`AI referral traffic in Google Analytics`],[`seo analytics google report`,`Google Analytics landing pages for visits from search`],[`seo updates`,`List official Google ranking updates`],[`seo export`,`Export report data to CSV`],[`seo reports list`,`List every structured report`],[`seo skill list`,`Show the packaged SEO skill`],[`seo auth`,`Manage Google auth`],[`seo cache`,`Manage local cache`],[`seo privacy`,`Show local storage paths`],[`seo telemetry status`,`Check anonymous usage telemetry`],[`seo reset`,`Delete saved credentials and all local data`]]}];function od(e){ra(`seo v${rd.version}`,`Your own Search Console, Google Analytics and Bing data, as facts for your agent.`),process.stdout.write(`
135
- `),oa(e.flatMap(e=>e.commands.map(([t,n])=>({category:e.title,id:t,name:n}))),{noun:`command`,categoryLabels:Object.fromEntries(e.map(e=>[e.title,e.title]))}),process.stdout.write(`
136
- `),ca(`More help`,"Use `seo help <command>` or `seo <command> --help` for command help.","Use `seo help all` for the longer command list.")}const sd=x({meta:{name:`seo`,version:rd.version,description:`Local-first SEO CLI and MCP server`},subCommands:{init:tc,analytics:Va,auth:Ja,mcp:ac,doctor:Oc,status:Oc,privacy:cu,telemetry:gu,reset:lu,cache:Za,logs:nc,crawl:Ao,"crawl-queue":yu,content:ro,providers:tl,export:es,"index-coverage":oc,"link-recover":sc,rules:dl,explain:fl,"refresh-priorities":wu,"redirect-trace":cc,skill:su,start:ec,setup:$s,site:jl,login:Fs,logout:Rs,report:ba,page:xa,compare:Sa,index:Ca,data:Ta,research:Ea,lint:Da,reports:ul,"segment-impact":Ac,"striking-distance":Mc,"update-postmortem":Au,sites:uu,"gsc-query":zo,"url-inspect":Bo,updates:du,"traffic-anomaly":Wo,"update-correlate":Go,"ai-referrals":pc,"audit-page":Cc,"second-page":Sc,cannibal:mc,decaying:_c,"quick-wins":xc,"page-opportunities":yc,perf:Dc,"internal-links":vc,"ctr-underperformers":hc,"query-cluster":bc},run:async()=>{process.argv.slice(2).length===0&&process.stdout.write("Use `seo start` to set up, then `seo report` for the main report.\n")}}),cd={cannibal:`cannibalisation`,crawl:`site-crawl`,"crawl-queue":`top-fixes`,decaying:`decaying-pages`,doctor:`setup-check`,status:`setup-check`,explain:`explain-crawl-issue`,"link-recover":`link-recovery`,"query-cluster":`query-clusters`,report:`search-performance-overview`,rules:`crawler-rules`,"update-correlate":`update-correlation`},ld=/* @__PURE__ */ new Set([`ai-referrals`,`audit-page`,`ctr-underperformers`,`index-coverage`,`internal-links`,`page-opportunities`,`quick-wins`,`redirect-trace`,`refresh-priorities`,`second-page`,`segment-impact`,`striking-distance`,`traffic-anomaly`,`update-postmortem`]),ud=new Set(_n().map(e=>e.id));function dd(e,t){let n=e.indexOf(t);return n>=0?e[n+1]:e.find(e=>e.startsWith(`${t}=`))?.slice(t.length+1)}function fd(e){let[t,n,r]=e;if(t)return t in wt?Tn(t,{section:dd(e,`--section`),action:n})??void 0:t===`reports`&&n===`run`?r&&ud.has(r)?r:void 0:t===`content`&&n===`optimize`?`content-optimization`:t===`perf`&&n===`audit`?`performance-audit`:cd[t]??(ld.has(t)?t:void 0)}const pd=process.argv.slice(2);function md(e){let t=e[1];return t&&[`list`,`describe`,`run`,`-h`,`--help`].includes(t)?e:t===void 0?[`reports`,`list`]:t.startsWith(`-`)?(process.stderr.write("Running `seo report`: `seo reports` lists reports.\n"),[`report`,...e.slice(1)]):[`reports`,`run`,...e.slice(1)]}const Q=pd[0]===`mcp`&&(pd[1]===void 0||/^-(?!h$|-help$)/.test(pd[1]))&&!process.stdin.isTTY?[`mcp`,`serve`,...pd.slice(1)]:pd[0]===`reports`?md(pd):pd;nd(Q);const hd=Wu(Q)??qu(Q);hd&&(process.stderr.write(`${hd}\n`),process.exit(2));const gd=Uu(Q[0]??``);gd&&!Q.some(e=>[`--help`,`-h`].includes(e))&&process.stderr.write(`${gd}\n`);const _d={agent:kn()},vd=Q[0]===`telemetry`,yd=Q[0]===`mcp`&&Q[1]===`serve`;!vd&&!yd&&bt(_d),yd||on();const bd=await td(rd,{argv:Q});bd!==void 0&&process.exit(bd),(Q.length===0||Q.length===1&&[`help`,`--help`,`-h`].includes(Q[0]??``))&&(od(id),process.exit(0)),Q[0]===`help`&&Q[1]===`all`&&(od(ad),process.exit(0));const $=Q[0]===`help`&&Q.length>1?[...Q.slice(1),`--help`]:Q;$!==Q&&(process.argv=[process.argv[0]??`node`,process.argv[1]??`seo`,...$]);const xd=$.some(e=>[`--help`,`-h`].includes(e)),Sd=Q.length===1&&[`--version`,`-v`].includes(Q[0]??``),Cd=xd||Sd?void 0:fd($);if(xd||Sd)await Vr(sd);else{Cd&&Mt(Cd,_d);let e=Q.includes(`--json`);try{await Br(sd,{rawArgs:$}),Cd&&cn(Cd,_d),[`init`,`setup`,`start`].includes($[0]??``)&&!$.includes(`--dry-run`)&&zt(_d)}catch(t){if(t?.code===`E_NO_COMMAND`&&await Vr(sd,{rawArgs:[...$,`--help`]}),Cd)Bn(Cd,t,_d);else if(!vd){let e=Nu($);e&&Ot(e,t,_d)}let n=Je(t);if(e){let e=on();process.stdout.write(`${JSON.stringify({...Jn(n),...e?{updateNotice:e}:{}},null,2)}\n`)}else{process.stderr.write(`Error: ${n.message}\n`);let e=Fu({args:$,error:t,report:Cd});e&&process.stderr.write(`Report this bug: ${e}\n`)}process.exitCode=n.exitCode}let t=e||yd?void 0:on();t&&process.stderr.write(`\n${t}\n`)}export{};
135
+ `),Nr(n,JSON.stringify([...r,`0.4`]),{mode:384})}catch{}}const hd={name:`seo`,version:Yn},gd=[{title:`Start here`,commands:[[`seo start`,`Sign in with Google, then add the MCP server and skill`],[`seo report`,`Last week across your audited sites (after seo login)`],[`seo report --site <site>`,`One site: overview and every section`],[`seo report --site <site> --section quick-wins`,`One section of the report, with live page checks`]]},{title:`Commands`,commands:[[`seo page --url <url>`,`One page: live facts, index status, queries`],[`seo compare --date <date>`,`Before and after a date`],[`seo index`,`Pages that lost most of their clicks`],[`seo research <action>`,`Keyword, SERP, competitor and backlink data from your key`],[`seo data`,`Raw Search Console, Bing, Clicky or Simple Analytics rows`],[`seo crawl`,`Crawl a site and list technical issues`],[`seo internal-links`,`Pages that could link to a target page`],[`seo lint <files>`,`Check copy for AI writing patterns and length`],[`seo site new <folder>`,`Start a data-driven site on Astro and Cloudflare`]]},{title:`Setup`,commands:[[`seo login`,`Use your seoskill.dev account on this machine`],[`seo sites`,`List Search Console properties`],[`seo mcp install`,`Add the local MCP server to your agents`],[`seo providers`,`Connect DataForSEO or Ahrefs`],[`seo doctor`,`Check local auth and config`]]}],_d=[...gd,{title:`More commands`,commands:[[`seo crawl-queue`,`Run a crawl and rank the fix queue`],[`seo rules`,`List crawler rule ids`],[`seo explain --rule missing_title`,`Explain a crawler rule`],[`seo redirect-trace`,`Trace redirects`],[`seo perf audit`,`Run a page performance audit`],[`seo index-coverage`,`Choose pages for URL Inspection`],[`seo ai-referrals`,`AI referral traffic in Google Analytics`],[`seo analytics google report`,`Google Analytics landing pages for visits from search`],[`seo updates`,`List official Google ranking updates`],[`seo export`,`Export report data to CSV`],[`seo reports list`,`List every structured report`],[`seo skill list`,`Show the packaged SEO skill`],[`seo auth`,`Manage Google auth`],[`seo cache`,`Manage local cache`],[`seo privacy`,`Show local storage paths`],[`seo telemetry status`,`Check anonymous usage telemetry`],[`seo reset`,`Delete saved credentials and all local data`]]}];function vd(e){la(`seo v${hd.version}`,`Your own Search Console, Google Analytics and Bing data, as facts for your agent.`),process.stdout.write(`
136
+ `),fa(e.flatMap(e=>e.commands.map(([t,n])=>({category:e.title,id:t,name:n}))),{noun:`command`,categoryLabels:Object.fromEntries(e.map(e=>[e.title,e.title]))}),process.stdout.write(`
137
+ `),ma(`More help`,"Use `seo help <command>` or `seo <command> --help` for command help.","Use `seo help all` for the longer command list.")}const yd=b({meta:{name:`seo`,version:hd.version,description:`Local-first SEO CLI and MCP server`},subCommands:{init:pc,analytics:$a,auth:oo,mcp:_c,doctor:Bc,status:Bc,privacy:bu,telemetry:Ou,reset:xu,cache:lo,logs:mc,crawl:Ho,"crawl-queue":ju,content:go,providers:pl,export:fs,"index-coverage":vc,"link-recover":yc,rules:Cl,explain:wl,"refresh-priorities":Iu,"redirect-trace":bc,skill:yu,start:fc,setup:dc,site:Ul,login:qs,logout:Xs,report:Ta,page:Ea,compare:Oa,index:ka,data:Aa,research:ja,lint:Ma,reports:Sl,"segment-impact":Hc,"striking-distance":Wc,"update-postmortem":Hu,sites:Su,"gsc-query":Zo,"url-inspect":Qo,updates:Cu,"traffic-anomaly":ns,"update-correlate":rs,"ai-referrals":Tc,"audit-page":Fc,"second-page":Pc,cannibal:Ec,decaying:kc,"quick-wins":Nc,"page-opportunities":jc,perf:zc,"internal-links":Ac,"ctr-underperformers":Dc,"query-cluster":Mc},run:async()=>{process.argv.slice(2).length===0&&process.stdout.write("Use `seo start` to set up, then `seo report` for the main report.\n")}}),bd={cannibal:`cannibalisation`,crawl:`site-crawl`,"crawl-queue":`top-fixes`,decaying:`decaying-pages`,doctor:`setup-check`,status:`setup-check`,explain:`explain-crawl-issue`,"link-recover":`link-recovery`,"query-cluster":`query-clusters`,report:`search-performance-overview`,rules:`crawler-rules`,"update-correlate":`update-correlation`},xd=/* @__PURE__ */ new Set([`ai-referrals`,`audit-page`,`ctr-underperformers`,`index-coverage`,`internal-links`,`page-opportunities`,`quick-wins`,`redirect-trace`,`refresh-priorities`,`second-page`,`segment-impact`,`striking-distance`,`traffic-anomaly`,`update-postmortem`]),Sd=new Set(Sn().map(e=>e.id));function Cd(e,t){let n=e.indexOf(t);return n>=0?e[n+1]:e.find(e=>e.startsWith(`${t}=`))?.slice(t.length+1)}function wd(e){let[t,n,r]=e;if(t)return t in Ze?mt(t,{section:Cd(e,`--section`),action:n})??void 0:t===`reports`&&n===`run`?r&&Sd.has(r)?r:void 0:t===`content`&&n===`optimize`?`content-optimization`:t===`perf`&&n===`audit`?`performance-audit`:bd[t]??(xd.has(t)?t:void 0)}const Td=process.argv.slice(2);function Ed(e){let t=e[1];return t&&[`list`,`describe`,`run`,`-h`,`--help`].includes(t)?e:t===void 0?[`reports`,`list`]:t.startsWith(`-`)?(process.stderr.write("Running `seo report`: `seo reports` lists reports.\n"),[`report`,...e.slice(1)]):[`reports`,`run`,...e.slice(1)]}const Q=Td[0]===`mcp`&&(Td[1]===void 0||/^-(?!h$|-help$)/.test(Td[1]))&&!process.stdin.isTTY?[`mcp`,`serve`,...Td.slice(1)]:Td[0]===`reports`?Ed(Td):Td;md(Q);const Dd=nd(Q)??ad(Q);Dd&&(process.stderr.write(`${Dd}\n`),process.exit(2));const Od=td(Q[0]??``);Od&&!Q.some(e=>[`--help`,`-h`].includes(e))&&process.stderr.write(`${Od}\n`);const kd={agent:jt()},Ad=Q[0]===`telemetry`,jd=Q[0]===`mcp`&&Q[1]===`serve`;!Ad&&!jd&&Gn(kd),jd||dn();const Md=await pd(hd,{argv:Q});Md!==void 0&&process.exit(Md),(Q.length===0||Q.length===1&&[`help`,`--help`,`-h`].includes(Q[0]??``))&&(vd(gd),process.exit(0)),Q[0]===`help`&&Q[1]===`all`&&(vd(_d),process.exit(0));const $=Q[0]===`help`&&Q.length>1?[...Q.slice(1),`--help`]:Q;$!==Q&&(process.argv=[process.argv[0]??`node`,process.argv[1]??`seo`,...$]);const Nd=$.some(e=>[`--help`,`-h`].includes(e)),Pd=Q.length===1&&[`--version`,`-v`].includes(Q[0]??``),Fd=Nd||Pd?void 0:wd($);if(Nd||Pd)await qr(yd);else{Fd&&Kt(Fd,kd);let e=Q.includes(`--json`);try{await Kr(yd,{rawArgs:$}),Fd&&_n(Fd,kd),[`init`,`setup`,`start`].includes($[0]??``)&&!$.includes(`--dry-run`)&&yt(kd)}catch(t){if(t?.code===`E_NO_COMMAND`&&await qr(yd,{rawArgs:[...$,`--help`]}),Fd)Xt(Fd,t,kd);else if(!Ad){let e=Gu($);e&&On(e,t,kd)}let n=a(t);if(e){let e=dn();process.stdout.write(`${JSON.stringify({...ln(n),...e?{updateNotice:e}:{}},null,2)}\n`)}else{process.stderr.write(`Error: ${n.message}\n`);let e=qu({args:$,error:t,report:Fd});e&&process.stderr.write(`Report this bug: ${e}\n`)}process.exitCode=n.exitCode}let t=e||jd?void 0:dn();t&&process.stderr.write(`\n${t}\n`)}export{};
137
138
  //# sourceMappingURL=cli.js.map