seo 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,131 +1,131 @@
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,Ct as d,D as f,Dn as ee,Dt as te,E as p,En as ne,Et as m,F as h,Fn as re,Ft as ie,G as ae,Gn as oe,Gt as se,H as ce,Hn as le,Ht as ue,I as de,In as fe,It as pe,J as me,Jn as he,Jt as ge,K as _e,Kn as ve,Kt as ye,L as be,Ln as xe,Lt as Se,M as Ce,Mn as we,Mt as Te,N as Ee,Nn as De,Nt as Oe,O as ke,On as Ae,Ot as je,P as Me,Pn as Ne,Pt as Pe,Q as Fe,Qn as Ie,Qt as Le,R as Re,Rn as ze,Rt as Be,S as Ve,Sn as He,St as Ue,T as We,Tn as Ge,Tt as Ke,U as qe,Un as Je,Ut as Ye,V as Xe,Vn as Ze,Vt as Qe,W as $e,Wn as et,Wt as tt,X as nt,Xn as rt,Xt as it,Y as at,Yn as ot,Yt as st,Z as ct,Zn as lt,Zt as ut,_ as dt,_n as ft,_t as pt,a as mt,an as ht,ar as gt,at as _t,b as vt,bn as yt,bt,c as xt,cn as St,ct as Ct,d as wt,dn as Tt,dt as Et,en as Dt,er as Ot,et as kt,f as At,fn as jt,ft as Mt,g as Nt,gn as Pt,gt as Ft,h as It,hn as Lt,ht as Rt,i as zt,in as Bt,ir as Vt,it as Ht,j as Ut,jn as Wt,jt as Gt,k as Kt,kn as qt,kt as Jt,l as Yt,ln as Xt,lt as Zt,m as Qt,mn as $t,mt as en,nn as tn,nr as nn,nt as rn,o as an,on,ot as sn,p as cn,pn as ln,pt as un,q as dn,qn as fn,qt as pn,rn as mn,rr as hn,rt as gn,sn as _n,st as vn,t as yn,tn as bn,tr as g,tt as xn,u as Sn,un as Cn,ut as wn,v as Tn,vn as En,vt as Dn,w as On,wn as kn,wt as An,x as jn,xn as Mn,xt as Nn,y as Pn,yn as Fn,yt as In,z as Ln,zn as Rn,zt as zn}from"./dist-B_2zww72.js";import{randomBytes as Bn}from"node:crypto";import{arch as Vn,homedir as Hn,platform as Un}from"node:os";import{basename as Wn,dirname as Gn,join as _,posix as Kn,relative as qn,resolve as Jn,sep as Yn,win32 as Xn}from"node:path";import{constants as Zn,copyFileSync as Qn,createWriteStream as $n,existsSync as v,mkdirSync as er,readFileSync as tr,readdirSync as nr,realpathSync as rr,renameSync as ir,rmSync as ar,statSync as or,writeFileSync as sr}from"node:fs";import{fileURLToPath as cr}from"node:url";import{cp as lr,mkdir as ur,readFile as y,readdir as dr,rename as fr,writeFile as pr}from"node:fs/promises";import{isDeepStrictEqual as mr,stripVTControlCharacters as hr}from"node:util";import{spawn as gr,spawnSync as _r}from"node:child_process";import{defineCommand as b,runCommand as vr,runMain as yr}from"citty";import{cancel as br,confirm as xr,intro as Sr,isCancel as Cr,log as wr,multiselect as Tr,note as x,outro as S,password as Er,select as Dr,text as Or}from"@clack/prompts";import kr from"picocolors";import Ar from"string-width";import jr from"cli-table3";import{finished as Mr}from"node:stream/promises";import{applyEdits as Nr,modify as Pr,parse as Fr,printParseErrorCode as Ir}from"jsonc-parser";import Lr 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 Rr(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 zr(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 Br(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:Rr(e,t)})),...[`page`,`query`,`device`,`country`].map(t=>({filename:`postmortem-segment-${t}-unmatched.csv`,headers:[...C.unmatchedSegment],rows:zr(e,t)}))]}function Vr(e){return v(e)?nr(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.log`)).map(t=>{let n=_(e,t.name),r=or(n);return{path:n,size:r.size,modifiedAt:r.mtimeMs}}):[]}function Hr(e,t){let n=Gn(e),r=Wn(e,`.log`),i=0;for(;;){let e=_(n,`${r}.${t}${i?`-${i}`:``}.log`);if(!v(e))return e;i+=1}}function Ur(e={}){let t=e.directory??ot().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 Vr(t))e.size<=r||(ir(e.path,Hr(e.path,n)),o+=1);for(let e of Vr(t))e.modifiedAt>=n-a||(ar(e.path,{force:!0}),s+=1);let c=Vr(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;ar(e.path,{force:!0}),l-=e.size,s+=1}return{rotated:o,removed:s,sizeBytes:l}}function Wr(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 Gr(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 Kr(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 qr(e,t){let n=T(e[t]);if(n===!1)return!0;if(n===!0)return!1;let r=T(e[Jr(t)]);if(r===!1)return!0;if(r===!0)return!1;if(T(e[`no-${t}`])===!0||T(e[`no${Yr(t)}`])===!0)return!0}function Jr(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function Yr(e){let t=Jr(e);return t?`${t[0]?.toUpperCase()}${t.slice(1)}`:``}function E(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 D(e,t){if(e===void 0||e===``)return;let n=E(e);if(n===void 0)throw new g(`INVALID_INPUT`,`${t} must be a number.`);return n}function O(e){if(typeof e!=`string`)return;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t.length?t:void 0}function Xr(e){return O(e)??[]}function Zr(e){let t={concurrency:E(e[`fetch-concurrency`]),intervalCap:E(e[`fetch-interval-cap`]),intervalMs:E(e[`fetch-interval-ms`])};return Object.values(t).some(e=>e!==void 0)?t:void 0}function k(e){return e.json===!0}async function Qr(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 A(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 $r(e,t={}){let n=A(e),r=(await on(t.refresh,t.account)).map(e=>e.siteUrl),i=lt(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 ei(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 ti(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 ni(e={}){let t=e.env??process.env,n=ti(e.columns)??ti(e.streamColumns)??ti(t.COLUMNS)??80;return Math.min(200,Math.max(40,n))}function j(e={}){let t=e.env??process.env,n=e.isTTY??!!process.stdout.isTTY,r=e.color??!!(n&&t.NO_COLOR===void 0);return{columns:ni({...e,env:t,streamColumns:e.streamColumns??process.stdout.columns}),colors:kr.createColors(r),hasColor:r,isInteractive:n&&!t.CI}}function M(e){return Ar(hr(e))}function ri(e,t){let n=[],r=``;for(let i of e)r&&M(`${r}${i}`)>t?(n.push(r),r=i):r+=i;return r&&n.push(r),n}function ii(e,t){if(!e)return[``];let n=e.trim().split(/\s+/u),r=[],i=``;for(let e of n){let n=M(e)>t?ri(e,t):[e];for(let e of n)i?M(`${i} ${e}`)<=t?i+=` ${e}`:(r.push(i),i=e):i=e}return i&&r.push(i),r.length>0?r:[``]}function N(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,At as a,B as o,Bn as s,Bt as c,C as l,Cn as u,Ct as d,D as f,Dn as ee,Dt as te,E as ne,En as p,Et as re,F as m,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,St as We,T as Ge,Tn as Ke,Tt as qe,U as Je,Un as Ye,Ut as Xe,V as Ze,Vn as Qe,Vt as $e,W as et,Wn as tt,Wt as nt,X as rt,Xn as it,Xt as at,Y as ot,Yn as st,Yt as ct,Z as lt,Zn as ut,Zt as dt,_ as ft,_n as pt,_t as mt,a as ht,an as gt,ar as h,at as _t,b as vt,bn as yt,bt,c as xt,cn as St,cr as Ct,ct as wt,d as Tt,dn as Et,dt as Dt,en as Ot,er as kt,et as At,f as jt,fn as Mt,ft as Nt,g as Pt,gn as Ft,gt as It,h as Lt,hn as Rt,ht as zt,i as Bt,in as Vt,ir as Ht,it as Ut,j as Wt,jn as Gt,jt as Kt,k as qt,kn as Jt,kt as Yt,l as Xt,ln as Zt,lr as Qt,lt as $t,m as en,mn as tn,mt as nn,nn as rn,nr as an,nt as on,o as sn,on as cn,or as ln,ot as un,p as dn,pn as fn,pt as pn,q as mn,qn as hn,qt as gn,rn as _n,rr as vn,rt as yn,sn as bn,sr as xn,st as Sn,t as Cn,tn as wn,tr as Tn,tt as En,u as Dn,un as On,ut as kn,v as An,vn as jn,vt as Mn,w as Nn,wn as Pn,wt as Fn,x as In,xn as Ln,xt as Rn,y as zn,yn as Bn,yt as Vn,z as Hn,zn as Un,zt as Wn}from"./dist-pwGymked.js";import{randomBytes as Gn}from"node:crypto";import{arch as Kn,homedir as qn,platform as Jn}from"node:os";import{basename as Yn,dirname as Xn,join as g,posix as Zn,relative as Qn,resolve as $n,sep as er,win32 as tr}from"node:path";import{constants as nr,copyFileSync as rr,createWriteStream as ir,existsSync as _,mkdirSync as ar,readFileSync as or,readdirSync as sr,realpathSync as cr,renameSync as lr,rmSync as ur,statSync as dr,writeFileSync as fr}from"node:fs";import{fileURLToPath as pr}from"node:url";import{cp as mr,mkdir as hr,readFile as v,readdir as gr,rename as _r,writeFile as vr}from"node:fs/promises";import{isDeepStrictEqual as yr,stripVTControlCharacters as br}from"node:util";import{spawn as xr,spawnSync as Sr}from"node:child_process";import{defineCommand as y,runCommand as Cr,runMain as wr}from"citty";import{cancel as Tr,confirm as Er,intro as Dr,isCancel as Or,log as kr,multiselect as Ar,note as b,outro as x,password as jr,select as Mr,text as Nr}from"@clack/prompts";import Pr from"picocolors";import Fr from"string-width";import Ir from"cli-table3";import{finished as Lr}from"node:stream/promises";import{applyEdits as Rr,modify as zr,parse as Br,printParseErrorCode as Vr}from"jsonc-parser";import Hr from"update-notifier";const S={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 Ur(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 Wr(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 Gr(e){return[{filename:`postmortem-summary.csv`,headers:[...S.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:[...S.steps],rows:e.steps.map((e,t)=>({rank:t+1,tool:e.tool,status:e.status,summary:e.summary}))},{filename:`workflow-actions.csv`,headers:[...S.actions],rows:e.actions.map((e,t)=>({rank:t+1,title:e.title,confidence:e.confidence,action:e.action}))},{filename:`postmortem-findings.csv`,headers:[...S.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:[...S.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:[...S.evidence],rows:e.output.update.evidence.map((e,t)=>({rank:t+1,evidence:e}))},{filename:`postmortem-confounders.csv`,headers:[...S.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:[...S.segment],rows:Ur(e,t)})),...[`page`,`query`,`device`,`country`].map(t=>({filename:`postmortem-segment-${t}-unmatched.csv`,headers:[...S.unmatchedSegment],rows:Wr(e,t)}))]}function Kr(e){return _(e)?sr(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.log`)).map(t=>{let n=g(e,t.name),r=dr(n);return{path:n,size:r.size,modifiedAt:r.mtimeMs}}):[]}function qr(e,t){let n=Xn(e),r=Yn(e,`.log`),i=0;for(;;){let e=g(n,`${r}.${t}${i?`-${i}`:``}.log`);if(!_(e))return e;i+=1}}function Jr(e={}){let n=e.directory??t().logDir,r=e.now??Date.now(),i=e.maxFileBytes??8388608,a=e.maxTotalBytes??67108864,o=e.maxAgeMs??12096e5;ar(n,{recursive:!0,mode:448});let s=0,c=0;for(let e of Kr(n))e.size<=i||(lr(e.path,qr(e.path,r)),s+=1);for(let e of Kr(n))e.modifiedAt>=r-o||(ur(e.path,{force:!0}),c+=1);let l=Kr(n).sort((e,t)=>e.modifiedAt-t.modifiedAt||(e.path<t.path?-1:+(e.path>t.path))),u=l.reduce((e,t)=>e+t.size,0);for(let e of l){if(u<=a)break;ur(e.path,{force:!0}),u-=e.size,c+=1}return{rotated:s,removed:c,sizeBytes:u}}function Yr(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 Xr(e,t){return{type:`boolean`,default:!0,description:e,negativeDescription:t}}function C(e){return typeof e==`string`?e:void 0}function w(e){return typeof e==`boolean`?e:void 0}function Zr(e){let t=C(e.rendering);if(t!==void 0&&t!==`auto`&&t!==`on`&&t!==`off`)throw new h(`INVALID_INPUT`,`--rendering must be auto, on, or off.`);if(w(e.js)===!0&&t&&t!==`on`)throw new h(`INVALID_INPUT`,`Use either --js or --rendering on, not both with different modes.`);return t??(w(e.js)?`on`:`auto`)}function Qr(e,t){let n=w(e[t]);if(n===!1)return!0;if(n===!0)return!1;let r=w(e[$r(t)]);if(r===!1)return!0;if(r===!0)return!1;if(w(e[`no-${t}`])===!0||w(e[`no${ei(t)}`])===!0)return!0}function $r(e){return e.replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function ei(e){let t=$r(e);return t?`${t[0]?.toUpperCase()}${t.slice(1)}`:``}function T(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 E(e,t){if(e===void 0||e===``)return;let n=T(e);if(n===void 0)throw new h(`INVALID_INPUT`,`${t} must be a number.`);return n}function D(e){if(typeof e!=`string`)return;let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t.length?t:void 0}function ti(e){return D(e)??[]}function ni(e){let t={concurrency:T(e[`fetch-concurrency`]),intervalCap:T(e[`fetch-interval-cap`]),intervalMs:T(e[`fetch-interval-ms`])};return Object.values(t).some(e=>e!==void 0)?t:void 0}function O(e){return e.json===!0}async function ri(e,t){let n=C(e),r=C(t);if(n&&r)throw Error(`Use either --body or --body-file, not both.`);if(!n&&!r)return;let i=n??await v(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 k(e){if(e)return e;throw new h(`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 ii(e,t={}){let n=k(e),r=(await On(t.refresh,t.account)).map(e=>e.siteUrl),i=Tn(r,n);if(!i)throw new h(`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 ai(e){if(e)return e;throw new h(`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 si(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 A(e={}){let t=e.env??process.env,n=e.isTTY??!!process.stdout.isTTY,r=e.color??!!(n&&t.NO_COLOR===void 0);return{columns:si({...e,env:t,streamColumns:e.streamColumns??process.stdout.columns}),colors:Pr.createColors(r),hasColor:r,isInteractive:n&&!t.CI}}function j(e){return Fr(br(e))}function ci(e,t){let n=[],r=``;for(let i of e)r&&j(`${r}${i}`)>t?(n.push(r),r=i):r+=i;return r&&n.push(r),n}function li(e,t){if(!e)return[``];let n=e.trim().split(/\s+/u),r=[],i=``;for(let e of n){let n=j(e)>t?ci(e,t):[e];for(let e of n)i?j(`${i} ${e}`)<=t?i+=` ${e}`:(r.push(i),i=e):i=e}return i&&r.push(i),r.length>0?r:[``]}function M(e,t){let n=Math.max(1,t);return e.replaceAll(`\r
4
4
  `,`
5
5
  `).split(`
6
- `).flatMap(e=>ii(e,n))}function ai(e,t){if(M(e)<=t)return e;let n=Math.max(1,t-M(`...`)),r=``;for(let t of e){if(M(`${r}${t}`)>n)break;r+=t}return`${r}...`}const oi={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 si(e){return e===void 0?``:String(e)}function ci(e,t){return e.map((e,n)=>{let r=t.map(e=>si(e[n]));return Math.min(42,Math.max(M(e),...r.map(M),4))})}function li(e,t,n){return e.length===0||e.length>4||!e.map((e,n)=>t.every(e=>/^-?(?:\d+(?:\.\d+)?|\d+(?:\.\d+)?%)$/u.test(si(e[n]).trim()))).some(Boolean)?!1:ci(e,t).reduce((e,t)=>e+t+2,0)<=n.columns}function ui(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 di(e,t,n){let r=ci(e,t).map(e=>e+2),i=new jr({chars:oi,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)=>N(ui(e,si(a[t]),n),Math.max(1,(r[t]??3)-2)).join(`
7
- `)));return i.toString()}function fi(e,t,n,r){let i=r.columns-n-2;return i<24?[r.colors.dim(e),...N(t,r.columns-2).map(e=>` ${e}`)]:N(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=>M(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(...fi(a,ui(a,si(t[r]),n),i,n));return s.join(`
6
+ `).flatMap(e=>li(e,n))}function ui(e,t){if(j(e)<=t)return e;let n=Math.max(1,t-j(`...`)),r=``;for(let t of e){if(j(`${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 fi(e){return e===void 0?``:String(e)}function pi(e,t){return e.map((e,n)=>{let r=t.map(e=>fi(e[n]));return Math.min(42,Math.max(j(e),...r.map(j),4))})}function mi(e,t,n){return e.length===0||e.length>4||!e.map((e,n)=>t.every(e=>/^-?(?:\d+(?:\.\d+)?|\d+(?:\.\d+)?%)$/u.test(fi(e[n]).trim()))).some(Boolean)?!1:pi(e,t).reduce((e,t)=>e+t+2,0)<=n.columns}function hi(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 gi(e,t,n){let r=pi(e,t).map(e=>e+2),i=new Ir({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)=>M(hi(e,fi(a[t]),n),Math.max(1,(r[t]??3)-2)).join(`
7
+ `)));return i.toString()}function _i(e,t,n,r){let i=r.columns-n-2;return i<24?[r.colors.dim(e),...M(t,r.columns-2).map(e=>` ${e}`)]:M(t,i).map((t,i)=>{let a=i===0?e.padEnd(n):``.padEnd(n);return`${r.colors.dim(a)}${` `.repeat(2)}${t}`})}function vi(e,t,n,r={}){let i=Math.min(28,Math.max(...e.map(e=>j(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(..._i(a,hi(a,fi(t[r]),n),i,n));return s.join(`
8
8
  `)}).join(`
9
9
 
10
- `)}function mi(e,t,n,r={}){return t.length===0?n.colors.dim(`No results.`):r.layout===`table`||r.layout!==`records`&&li(e,t,n)?di(e,t,n):pi(e,t,n,r)}function hi(e,t){if(e.length===0)return``;let n=Math.min(28,Math.max(...e.map(([e])=>M(e))));return e.flatMap(([e,r])=>{let i=fi(e,r,n,t);return i.length>0&&(i[0]=(i[0]??``).replace(e,t.colors.bold(e))),i}).join(`
11
- `)}function gi(e,t){let n=[t.colors.bold(e.title)];return e.body&&n.push(...N(e.body,t.columns)),e.command&&n.push(t.colors.cyan(ai(e.command,t.columns))),n.join(`
12
- `)}function _i(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 vi(e){return e===`warning`?`WARN`:e===`notApplicable`?`N/A`:e.toUpperCase()}function yi(e,t,n){let r=` `.repeat(t);return N(e,Math.max(1,n-t)).map(e=>`${r}${e}`)}function bi(e,t){let n=_i(e.status,t)(`[${vi(e.status)}]`.padEnd(10)),r=Math.max(1,t.columns-10),i=N(e.title,r).map((e,r)=>`${r===0?n:` `.repeat(10)}${t.colors.bold(e)}`);i.push(...yi(e.explanation,10,t.columns));for(let n of e.evidence??[]){let e=N(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=N(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 xi(e,t){return N(e.map(e=>{let n=String(e.value),r=e.status?_i(e.status,t)(n):t.colors.bold(n);return`${e.label} ${r}`}).join(t.colors.dim(` · `)),t.columns).join(`
14
- `)}function Si(e,t){let n=_i(e.status,t),r=[t.colors.bold(e.title)];e.target&&r.push(t.colors.dim(e.target)),r.push(``),r.push(`${n(vi(e.status))} ${N(e.summary,Math.max(1,t.columns-6)).join(`
15
- `)}`),e.metrics?.length&&r.push(xi(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=>bi(e,t)).join(`
10
+ `)}function yi(e,t,n,r={}){return t.length===0?n.colors.dim(`No results.`):r.layout===`table`||r.layout!==`records`&&mi(e,t,n)?gi(e,t,n):vi(e,t,n,r)}function bi(e,t){if(e.length===0)return``;let n=Math.min(28,Math.max(...e.map(([e])=>j(e))));return e.flatMap(([e,r])=>{let i=_i(e,r,n,t);return i.length>0&&(i[0]=(i[0]??``).replace(e,t.colors.bold(e))),i}).join(`
11
+ `)}function xi(e,t){let n=[t.colors.bold(e.title)];return e.body&&n.push(...M(e.body,t.columns)),e.command&&n.push(t.colors.cyan(ui(e.command,t.columns))),n.join(`
12
+ `)}function Si(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 Ci(e){return e===`warning`?`WARN`:e===`notApplicable`?`N/A`:e.toUpperCase()}function wi(e,t,n){let r=` `.repeat(t);return M(e,Math.max(1,n-t)).map(e=>`${r}${e}`)}function Ti(e,t){let n=Si(e.status,t)(`[${Ci(e.status)}]`.padEnd(10)),r=Math.max(1,t.columns-10),i=M(e.title,r).map((e,r)=>`${r===0?n:` `.repeat(10)}${t.colors.bold(e)}`);i.push(...wi(e.explanation,10,t.columns));for(let n of e.evidence??[]){let e=M(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=M(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 Ei(e,t){return M(e.map(e=>{let n=String(e.value),r=e.status?Si(e.status,t)(n):t.colors.bold(n);return`${e.label} ${r}`}).join(t.colors.dim(` · `)),t.columns).join(`
14
+ `)}function Di(e,t){let n=Si(e.status,t),r=[t.colors.bold(e.title)];e.target&&r.push(t.colors.dim(e.target)),r.push(``),r.push(`${n(Ci(e.status))} ${M(e.summary,Math.max(1,t.columns-6)).join(`
15
+ `)}`),e.metrics?.length&&r.push(Ei(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=>Ti(e,t)).join(`
16
16
 
17
- `));if(e.notes?.length){r.push(``,t.colors.bold(`Notes`));for(let n of e.notes){let e=N(n,Math.max(1,t.columns-2));r.push(...e.map((e,t)=>`${t===0?`- `:` `}${e}`))}}return r.join(`
18
- `)}function Ci(e,t,n=`${t}s`){return e===1?t:n}function wi(e,t,n){let r=` `.repeat(t);return N(e,Math.max(1,n-t)).map(e=>`${r}${e}`)}function Ti(e,t,n){return[t.colors.bold(e),...n?N(n,t.columns):[]].join(`
19
- `)}function Ei(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(...wi(e.detail,6,t.columns)),e.fix){let n=N(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=M(n,Math.max(1,t.columns-2));r.push(...e.map((e,t)=>`${t===0?`- `:` `}${e}`))}}return r.join(`
18
+ `)}function Oi(e,t,n=`${t}s`){return e===1?t:n}function ki(e,t,n){let r=` `.repeat(t);return M(e,Math.max(1,n-t)).map(e=>`${r}${e}`)}function Ai(e,t,n){return[t.colors.bold(e),...n?M(n,t.columns):[]].join(`
19
+ `)}function ji(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(...ki(e.detail,6,t.columns)),e.fix){let n=M(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 Di(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} ${Ci(t,`check`)} passed, ${n} ${Ci(n,`warning`)}, ${r} failed.`}function Oi(e,t,n){let r=n.columns-t-2-2;return r<24||M(e.id)>t?[...wi(e.id,2,n.columns).map(e=>n.colors.cyan(e)),...wi(e.name,4,n.columns)].join(`
23
- `):N(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 ki(e){let t=e.replaceAll(`-`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Ai(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} ${Ci(e.length,n.noun)} across ${r.size} ${Ci(r.size,`category`,`categories`)}.`,a=Math.min(30,Math.max(...e.map(e=>M(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]??ki(e);return[t.colors.bold(`${o} (${i.length})`),...i.map(e=>Oi(e,a,t))].join(`
22
+ `)}function Mi(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} ${Oi(t,`check`)} passed, ${n} ${Oi(n,`warning`)}, ${r} failed.`}function Ni(e,t,n){let r=n.columns-t-2-2;return r<24||j(e.id)>t?[...ki(e.id,2,n.columns).map(e=>n.colors.cyan(e)),...ki(e.name,4,n.columns)].join(`
23
+ `):M(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 Pi(e){let t=e.replaceAll(`-`,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Fi(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} ${Oi(e.length,n.noun)} across ${r.size} ${Oi(r.size,`category`,`categories`)}.`,a=Math.min(30,Math.max(...e.map(e=>j(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]??Pi(e);return[t.colors.bold(`${o} (${i.length})`),...i.map(e=>Ni(e,a,t))].join(`
25
25
  `)})].join(`
26
26
 
27
- `)}function ji(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(...wi(e.description,2,t.columns));let r=e.meta?.filter(Boolean).join(` · `);return r&&n.push(...wi(r,2,t.columns).map(e=>t.colors.dim(e))),n.join(`
27
+ `)}function Ii(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(...ki(e.description,2,t.columns));let r=e.meta?.filter(Boolean).join(` · `);return r&&n.push(...ki(r,2,t.columns).map(e=>t.colors.dim(e))),n.join(`
28
28
  `)}).join(`
29
29
 
30
- `)}function Mi(e,t,n){let r=t.filter(e=>e.trim().length>0).flatMap(e=>N(e,n.columns));return[n.colors.bold(e),...r].join(`
31
- `)}function Ni(e,t,n){let r=t.flatMap(e=>N(e,Math.max(1,n.columns-2)).map((e,t)=>`${t===0?`- `:` `}${e}`));return[n.colors.bold(e),...r].join(`
32
- `)}function Pi(e,t){return e.length===0?t.colors.dim(`No parameters.`):ji(e.map(e=>({title:e.name,description:e.description,meta:[e.type,e.required?`required`:`optional`]})),t,{empty:`No parameters.`})}function P(e={}){return!(e.json||!process.stdin.isTTY||!process.stdout.isTTY||process.env.CI)}function F(e){let t=e&&typeof e==`object`&&!Array.isArray(e)?Yt():void 0,n=t?{...e,updateNotice:t}:e;process.stdout.write(`${JSON.stringify(n,null,2)}\n`)}function I(e){let t=hi(e,j());t&&process.stdout.write(`${t}\n`)}function L(e,t){process.stdout.write(`${mi(e,t,j())}\n`)}function R(e){process.stdout.write(`${gi(e,j())}\n`)}function Fi(e,t){process.stdout.write(`${Ti(e,j(),t)}\n`)}function Ii(e){process.stdout.write(`${Ei(e,j())}\n`)}function Li(e){process.stdout.write(`${Si(e,j())}\n`)}function Ri(e,t){process.stdout.write(`${Ai(e,j(),t)}\n`)}function zi(e,t){process.stdout.write(`${ji(e,j(),t)}\n`)}function z(e,...t){process.stdout.write(`${Mi(e,t,j())}\n`)}function Bi(e,t){process.stdout.write(`${Ni(e,t,j())}\n`)}function Vi(e){process.stdout.write(`${Pi(e,j())}\n`)}function Hi(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}const Ui={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`},Wi=e=>/^[\w:/.,<>@#?=&%+-]+$/.test(String(e))?String(e):`"${e}"`,Gi=(e,t)=>[`seo ${e}`,...Object.entries(t??{}).filter(([,e])=>e!==void 0).map(([e,t])=>`${Ui[e]??`--${e}`} ${Wi(t??``)}`)].join(` `),Ki={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.`}},qi={"start-date":{type:`string`,description:`Optional YYYY-MM-DD.`},"end-date":{type:`string`,description:`Optional YYYY-MM-DD.`}},Ji={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 Yi(e,t){return $r(t,{refresh:T(e.refresh),account:w(e.account)})}async function H(e,t){try{let n=await t(Kt({call:Gi,account:w(e.account),refresh:T(e.refresh)}));k(e)?F(n.data):process.stdout.write(`${n.text}\n`)}catch(e){throw We(e)}}const Xi=b({meta:{name:`report`,description:"Start here. No --site: last week across your audited sites (beta, 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 (beta, after `seo login`)."},section:{type:`string`,description:`Optional, needs --site. One of ${[...ct,kt].join(`, `)}. issues keeps a list of what was found for the site, on this machine.`},mark:{type:`string`,description:`With --site and --issues: ${xn.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.`},...qi,...Ji,...Ki},run:async({args:t})=>{let n=w(t.section),r=[...ct,kt];if(n&&!r.includes(n))throw new g(`INVALID_INPUT`,`--section is one of ${r.join(`, `)}.`);let i=w(t.site),a=w(t.mark),o=w(t.issues);if(a||o){if(a&&!xn.includes(a))throw new g(`INVALID_INPUT`,`--mark is one of ${xn.join(`, `)}.`);let r=await Yi(t,A(i));await H(t,i=>e({site:r,section:n,mark:a,issues:o?.split(`,`),note:w(t.note)},i));return}if(!i&&!n&&Ae()){await H(t,e=>qe(e));return}let s=n===`bing`?await Yi(t,i).catch(()=>A(i)):await Yi(t,i).catch(async e=>{if(n||!i)throw e;return await H(t,n=>Fe({site:A(i),startDate:w(t[`start-date`]),endDate:w(t[`end-date`])},n).catch(()=>{throw e})),null});s!==null&&await H(t,r=>e({site:s,section:n,startDate:w(t[`start-date`]),endDate:w(t[`end-date`]),detail:V(t),offset:E(t.offset)},r))}}),Zi=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},...qi,...Ji,...Ki},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 Yi(e,t);await H(e,r=>dn({site:n,url:t,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),detail:V(e),offset:E(e.offset)},r))}}),Qi=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/.`},...Ki},run:async({args:e})=>{let t=await Yi(e,w(e.site));await H(e,n=>ae({site:t,date:w(e.date)??``,pages:w(e.pages)},n))}}),$i=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.`},...qi,...Ji,...Ki},run:async({args:e})=>{let t=await Yi(e,w(e.site)),n=E(e[`max-urls`]);if(n!==void 0&&(!Number.isInteger(n)||n<1||n>2e3))throw new g(`INVALID_INPUT`,`--max-urls is a whole number from 1 to ${gn}.`);await H(e,r=>_e({site:t,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),detail:V(e),offset:E(e.offset),maxUrls:n},r))}}),ea=b({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: ${wn.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.`},...qi,...Ji,...Ki},run:async({args:e})=>{let t=O(e.dimensions)??[`query`],n=t.filter(e=>!wn.includes(e));if(n.length)throw new g(`INVALID_INPUT`,`Unknown dimensions: ${n.join(`, `)}. Use ${wn.join(`, `)}.`);let r=w(e.source)??`search_console`;if(![`search_console`,`bing`,`clicky`].includes(r))throw new g(`INVALID_INPUT`,`--source is search_console, bing or clicky.`);if(r===`clicky`){let t=A(w(e.site));await H(e,async()=>_t({site:t,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),detail:V(e),offset:E(e.offset)},await ke(),{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:f,call:e=>Gi(`data`,{source:`clicky`,site:t,detail:`rows`,offset:e})}));return}if(r===`bing`){let n=A(w(e.site));await H(e,r=>sn({site:n,dimension:t[0]===`page`?`page`:`query`,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),detail:V(e),offset:E(e.offset)},r));return}let i=await Yi(e,w(e.site)),a=w(e.page),o=w(e.query);await H(e,n=>Et({site:i,dimensions:t,filters:[...a?[{dimension:`page`,operator:`contains`,expression:a}]:[],...o?[{dimension:`query`,operator:`contains`,expression:o}]:[]],startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),detail:V(e),offset:E(e.offset)},n))}}),ta=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:me.join(`, `)},provider:{type:`string`,description:`${at.join(`, `)}. Default: the first one with a saved key.`},keywords:{type:`string`,description:`Comma-separated keywords.`},target:{type:`string`,description:`Domain or URL.`},country:{type:`string`,description:`Two-letter country code. Default us.`},...Ji,account:Ki.account,json:Ki.json},run:async({args:e})=>{let t=w(e.action);if(!me.includes(t))throw new g(`INVALID_INPUT`,`The action is one of ${me.join(`, `)}.`);let n=await ke(),r={dataforseo:`x-dataforseo-login`,ahrefs:`x-ahrefs-key`},i=w(e.provider)??(t===`ai_answers`?`dataforseo`:at.find(e=>n.has(r[e])))??`dataforseo`;if(!at.includes(i))throw new g(`INVALID_INPUT`,`--provider is one of ${at.join(`, `)}.`);if(!n.has(r[i]))throw new g(`AUTH_CONFIG_REQUIRED`,`No ${i} key. Save it at https://seoskill.dev/account#keys and run \`seo login\`, or run \`seo providers ${i} connect\` to keep it on this machine only.`);let a=O(e.keywords)??[],o=w(e.target),s=w(e.country);if(t===`ai_answers`){if(i!==`dataforseo`)throw new g(`INVALID_INPUT`,`ai_answers uses dataforseo.`);let r=await Yi(e,o);await H(e,i=>Zt({site:r,country:s??`us`,detail:V(e),offset:E(e.offset)??0},n,i,e=>Gi(`research`,{action:t,target:o,country:s,detail:`rows`,offset:e}).replace(`--action `,``)))}else await H(e,()=>nt({provider:i,action:t,keywords:a,target:o,country:s,detail:V(e),offset:E(e.offset)},n,{call:e=>Gi(`research`,{action:t,provider:i,keywords:a.join(`,`)||void 0,target:o,country:s,detail:`rows`,offset:e}).replace(`--action `,``)}))}});function na(e){return e===`keychain`?`system keychain`:e===`file`?`private local file`:e===`environment`?ue:e??`missing`}function ra(e){if(e&&en(e))return e.trim();throw new g(`INVALID_INPUT`,`No Clicky site given. Pass --site-id with the numeric Clicky site ID.`)}async function ia(e,t){return un({siteId:e,sitekey:t}).catch(e=>{throw new g(e instanceof Mt&&e.code===`auth`?`AUTH_REQUIRED`:`PROVIDER_UNAVAILABLE`,e instanceof Error?e.message:String(e))})}const aa={type:`boolean`,default:!1,description:`Print machine-readable JSON.`},oa={type:`string`,description:`Numeric Clicky site ID.`},sa=b({meta:{name:`connect`,description:`Check and save a Clicky site on this machine`},args:{"site-id":oa,json:aa},run:async({args:e})=>{let t=k(e),n=P({json:t});n&&Sr(`Connect Clicky`);let r=ra(w(e[`site-id`])??(n?B(await Or({message:`Clicky site ID`,validate:e=>en(e??``)?void 0:`Enter the numeric site ID from Clicky`})):void 0)),i=process.env.SEO_CLICKY_SITEKEY?.trim()||(n?B(await Er({message:`Clicky sitekey`,validate:e=>Rt(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 ${ue}.`);let a=await ia(r,i.trim()),o=await ye(r,i.trim()),s={siteId:r,domain:a,connected:!0,credentialSource:o};if(t){F(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`)}}),ca=b({meta:{name:`status`,description:`Show a Clicky site saved on this machine`},args:{"site-id":oa,check:{type:`boolean`,default:!1,description:`Check the saved sitekey with Clicky.`},json:aa},run:async({args:e})=>{let t=ra(w(e[`site-id`])),n=await se(t),r=T(e.check);r&&n&&await ia(t,n.siteKey);let i={siteId:t,connected:!!n,credentialSource:n?.source,liveCheck:r?n?`passed`:`unavailable`:`not-requested`};k(e)?F(i):I([[`Site ID`,t],[`Connected`,i.connected?`yes`:`no`],[`Credential`,na(i.credentialSource)],[`Live check`,i.liveCheck]])}}),la=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.`},...qi,...Ji,json:aa},run:async({args:e})=>{let t=A(w(e.site));await H(e,async()=>_t({site:t,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),detail:V(e),offset:E(e.offset)},await ke(),{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:f,call:e=>`seo analytics clicky report --site ${t} --detail rows --offset ${e}`}))}}),ua=b({meta:{name:`disconnect`,description:`Remove a Clicky site saved on this machine`},args:{"site-id":oa,json:aa},run:async({args:e})=>{let t=ra(w(e[`site-id`]));await Ye(t);let n=!!process.env[ue],r={siteId:t,savedCredentialRemoved:!0,environmentCredential:n?`active`:`missing`};k(e)?F(r):process.stdout.write(n?`Saved sitekey removed. ${ue} is still active.\n`:`Clicky is disconnected for this site.
33
- `)}}),da=b({meta:{name:`clicky`,description:`Read Clicky, or save a Clicky site on this machine only`},subCommands:{connect:sa,status:ca,report:la,disconnect:ua}}),fa=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 Tt(w(e.account)),n=t.flatMap(e=>e.propertySummaries.map(t=>({account:e.displayName??e.account,property:Cn(t.property),displayName:t.displayName??t.property})));k(e)?F({accountSummaries:t,properties:n}):L([`Property`,`Name`,`Account`],n.map(e=>[e.property,e.displayName,e.account]))}}),pa=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."},...qi,...Ji,json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=ei(w(e.property));await H(e,async()=>Ct({property:t,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),detail:V(e),offset:E(e.offset)},await vn(await On(),t,$t.signIn),{signIn:$t.signIn,call:e=>`seo analytics google report --property ${t} --detail rows --offset ${e}`}))}}),ma=b({meta:{name:`google`,description:`Read Google Analytics properties and reports`},subCommands:{properties:fa,report:pa}}),ha=b({meta:{name:`analytics`,description:`Read analytics data from connected providers`},subCommands:{clicky:da,google:ma}});function ga(){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 _a(){return x(ga(),`Google sign-in`),Lt()}function va(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 ya(e){return e.active===`keychain`?`system keychain`:e.configured===`keychain`?`private file fallback`:`private file`}function ba(e){return e===`shared`?`SEO Skill app`:`Local OAuth config`}function xa(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`,ba(e.clientSource)],[`Expires`,Wr(e.expiresAt)]),t}const Sa=b({meta:{name:`auth`,description:`Authentication commands`},subCommands:{login:b({meta:{name:`login`,description:`Run Google OAuth flow`},run:async()=>{if((await Pt()).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 _a();I(xa({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 Pt(),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 En(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 Pt();if(t.activeMode===`service-account`){let n={mode:`service-account`,account:t.identity??null,source:va(t.serviceAccount.source)};if(k(e)){F(n);return}I([[`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 He(n):t.tokens;if(n&&!r)throw new g(`AUTH_REQUIRED`,`Google account ${n} is not connected.`);if(r)k(e)?F({mode:`oauth`,account:r.account_email,scopes:r.scope.split(/\s+/u).filter(Boolean),clientSource:r.client_source,expiresAt:r.expires_at}):I(xa({accountEmail:r.account_email,clientSource:r.client_source,expiresAt:r.expires_at,scope:r.scope}));else{if(k(e)){F({mode:`oauth`,account:null});return}process.stdout.write(`Not logged in.
34
- `)}}}),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 Pt(),n=w(e.account),r=n?await He(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 yt():void 0;if(k(e)){F({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`,va(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]),I(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 yt();I([[`Account`,r.account_email],[`Connected accounts`,String(t.accounts.length)],[`Scopes`,r.scope],[`Client`,ba(r.client_source)],[`Expires`,Wr(r.expires_at)],[`Tokens file`,ot().tokensFile],[`Token storage`,ya(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 kn(e.keychain?`keychain`:`file`):await yt();k(e)?F(t):I([[`Configured storage`,t.configured],[`Active storage`,ya(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 Pt()).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 ft(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=Mn();k(e)?F({accounts:t}):t.length===0?process.stdout.write(`No Google accounts are connected.
36
- `):I(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.`);u(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(!P({json:k(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.");Sr(`Local Google OAuth client`),x(`This is the advanced path.
30
+ `)}function Li(e,t,n){let r=t.filter(e=>e.trim().length>0).flatMap(e=>M(e,n.columns));return[n.colors.bold(e),...r].join(`
31
+ `)}function Ri(e,t,n){let r=t.flatMap(e=>M(e,Math.max(1,n.columns-2)).map((e,t)=>`${t===0?`- `:` `}${e}`));return[n.colors.bold(e),...r].join(`
32
+ `)}function zi(e,t){return e.length===0?t.colors.dim(`No parameters.`):Ii(e.map(e=>({title:e.name,description:e.description,meta:[e.type,e.required?`required`:`optional`]})),t,{empty:`No parameters.`})}function N(e={}){return!(e.json||!process.stdin.isTTY||!process.stdout.isTTY||process.env.CI)}function P(e){let t=e&&typeof e==`object`&&!Array.isArray(e)?Xt():void 0,n=t?{...e,updateNotice:t}:e;process.stdout.write(`${JSON.stringify(n,null,2)}\n`)}function F(e){let t=bi(e,A());t&&process.stdout.write(`${t}\n`)}function I(e,t){process.stdout.write(`${yi(e,t,A())}\n`)}function L(e){process.stdout.write(`${xi(e,A())}\n`)}function Bi(e,t){process.stdout.write(`${Ai(e,A(),t)}\n`)}function Vi(e){process.stdout.write(`${ji(e,A())}\n`)}function Hi(e){process.stdout.write(`${Di(e,A())}\n`)}function Ui(e,t){process.stdout.write(`${Fi(e,A(),t)}\n`)}function Wi(e,t){process.stdout.write(`${Ii(e,A(),t)}\n`)}function R(e,...t){process.stdout.write(`${Li(e,t,A())}\n`)}function Gi(e,t){process.stdout.write(`${Ri(e,t,A())}\n`)}function Ki(e){process.stdout.write(`${zi(e,A())}\n`)}function qi(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}const Ji={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`},Yi=e=>/^[\w:/.,<>@#?=&%+-]+$/.test(String(e))?String(e):`"${e}"`,Xi=(e,t)=>[`seo ${e}`,...Object.entries(t??{}).filter(([,e])=>e!==void 0).map(([e,t])=>`${Ji[e]??`--${e}`} ${Yi(t??``)}`)].join(` `),Zi={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.`}},Qi={"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=C(e.detail)??`summary`;if(![`summary`,`rows`,`full`].includes(t))throw new h(`INVALID_INPUT`,`--detail is summary, rows or full.`);return t}function $i(e,t){return ii(t,{refresh:w(e.refresh),account:C(e.account)})}async function H(e,t){try{let n=await t(r({call:Xi,account:C(e.account),refresh:w(e.refresh)}));O(e)?P(n.data):process.stdout.write(`${n.text}\n`)}catch(e){throw ne(e)}}const ea=y({meta:{name:`report`,description:"Start here. No --site: last week across your audited sites (beta, 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 (beta, after `seo login`)."},section:{type:`string`,description:`Optional, needs --site. One of ${[...Ie,on].join(`, `)}. issues keeps a list of what was found for the site, on this machine.`},mark:{type:`string`,description:`With --site and --issues: ${yn.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.`},...Qi,...B,...Zi},run:async({args:t})=>{let n=C(t.section),r=[...Ie,on];if(n&&!r.includes(n))throw new h(`INVALID_INPUT`,`--section is one of ${r.join(`, `)}.`);let i=C(t.site),a=C(t.mark),o=C(t.issues);if(a||o){if(a&&!yn.includes(a))throw new h(`INVALID_INPUT`,`--mark is one of ${yn.join(`, `)}.`);let e=await $i(t,k(i));await H(t,r=>At({site:e,section:n,mark:a,issues:o?.split(`,`),note:C(t.note)},r));return}if(!i&&!n&&Te()){await H(t,e=>et(e));return}let s=n===`bing`?await $i(t,i).catch(()=>k(i)):await $i(t,i).catch(async r=>{if(n||!i)throw r;return await H(t,n=>e({site:k(i),startDate:C(t[`start-date`]),endDate:C(t[`end-date`])},n).catch(()=>{throw r})),null});s!==null&&await H(t,e=>At({site:s,section:n,startDate:C(t[`start-date`]),endDate:C(t[`end-date`]),detail:V(t),offset:T(t.offset)},e))}}),ta=y({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},...Qi,...B,...Zi},run:async({args:e})=>{let t=C(e.url)??``;if(!/^https?:\/\/\S+$/.test(t))throw new h(`INVALID_INPUT`,`--url must be a full http(s) URL.`);let n=await $i(e,t);await H(e,r=>he({site:n,url:t,startDate:C(e[`start-date`]),endDate:C(e[`end-date`]),detail:V(e),offset:T(e.offset)},r))}}),na=y({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/.`},...Zi},run:async({args:e})=>{let t=await $i(e,C(e.site));await H(e,n=>ve({site:t,date:C(e.date)??``,pages:C(e.pages)},n))}}),ra=y({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.`},...Qi,...B,...Zi},run:async({args:e})=>{let t=await $i(e,C(e.site)),n=T(e[`max-urls`]);if(n!==void 0&&(!Number.isInteger(n)||n<1||n>2e3))throw new h(`INVALID_INPUT`,`--max-urls is a whole number from 1 to ${_t}.`);await H(e,r=>mn({site:t,startDate:C(e[`start-date`]),endDate:C(e[`end-date`]),detail:V(e),offset:T(e.offset),maxUrls:n},r))}}),ia=y({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: ${Nt.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.`},...Qi,...B,...Zi},run:async({args:e})=>{let t=D(e.dimensions)??[`query`],n=t.filter(e=>!Nt.includes(e));if(n.length)throw new h(`INVALID_INPUT`,`Unknown dimensions: ${n.join(`, `)}. Use ${Nt.join(`, `)}.`);let r=C(e.source)??`search_console`;if(![`search_console`,`bing`,`clicky`].includes(r))throw new h(`INVALID_INPUT`,`--source is search_console, bing or clicky.`);if(r===`clicky`){let t=k(C(e.site));await H(e,async()=>Sn({site:t,startDate:C(e[`start-date`]),endDate:C(e[`end-date`]),detail:V(e),offset:T(e.offset)},await qt(),{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:Ae,call:e=>Xi(`data`,{source:`clicky`,site:t,detail:`rows`,offset:e})}));return}if(r===`bing`){let n=k(C(e.site));await H(e,r=>wt({site:n,dimension:t[0]===`page`?`page`:`query`,startDate:C(e[`start-date`]),endDate:C(e[`end-date`]),detail:V(e),offset:T(e.offset)},r));return}let i=await $i(e,C(e.site)),a=C(e.page),o=C(e.query);await H(e,n=>pn({site:i,dimensions:t,filters:[...a?[{dimension:`page`,operator:`contains`,expression:a}]:[],...o?[{dimension:`query`,operator:`contains`,expression:o}]:[]],startDate:C(e[`start-date`]),endDate:C(e[`end-date`]),detail:V(e),offset:T(e.offset)},n))}}),aa=y({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:ot.join(`, `)},provider:{type:`string`,description:`${rt.join(`, `)}. Default: the first one with a saved key.`},keywords:{type:`string`,description:`Comma-separated keywords.`},target:{type:`string`,description:`Domain or URL.`},country:{type:`string`,description:`Two-letter country code. Default us.`},...B,account:Zi.account,json:Zi.json},run:async({args:e})=>{let t=C(e.action);if(!ot.includes(t))throw new h(`INVALID_INPUT`,`The action is one of ${ot.join(`, `)}.`);let n=await qt(),r={dataforseo:`x-dataforseo-login`,ahrefs:`x-ahrefs-key`},i=C(e.provider)??(t===`ai_answers`?`dataforseo`:rt.find(e=>n.has(r[e])))??`dataforseo`;if(!rt.includes(i))throw new h(`INVALID_INPUT`,`--provider is one of ${rt.join(`, `)}.`);if(!n.has(r[i]))throw new h(`AUTH_CONFIG_REQUIRED`,`No ${i} key. Save it at https://seoskill.dev/account#keys and run \`seo login\`, or run \`seo providers ${i} connect\` to keep it on this machine only.`);let a=D(e.keywords)??[],o=C(e.target),s=C(e.country);if(t===`ai_answers`){if(i!==`dataforseo`)throw new h(`INVALID_INPUT`,`ai_answers uses dataforseo.`);let r=await $i(e,o);await H(e,i=>Dt({site:r,country:s??`us`,detail:V(e),offset:T(e.offset)??0},n,i,e=>Xi(`research`,{action:t,target:o,country:s,detail:`rows`,offset:e}).replace(`--action `,``)))}else await H(e,()=>lt({provider:i,action:t,keywords:a,target:o,country:s,detail:V(e),offset:T(e.offset)},n,{call:e=>Xi(`research`,{action:t,provider:i,keywords:a.join(`,`)||void 0,target:o,country:s,detail:`rows`,offset:e}).replace(`--action `,``)}))}}),oa=y({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:!0,description:`Files, folders or globs: .md, .mdx, .html, .astro or .txt. Up to 100 files.`},preset:{type:`string`,description:`${zt.join(`, `)}. Default blog for Markdown and text, landing for HTML and Astro. meta reads one title or description per line.`},format:{type:`string`,description:`${nn.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.`},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:Zi.json},run:async({args:e})=>{let t=C(e.preset);if(t&&!zt.includes(t))throw new h(`INVALID_INPUT`,`--preset is one of ${zt.join(`, `)}.`);let n=C(e.format);if(n&&!nn.includes(n))throw new h(`INVALID_INPUT`,`--format is one of ${nn.join(`, `)}.`);let r=C(e[`fail-on`])??`error`;if(r!==`error`&&r!==`warning`)throw new h(`INVALID_INPUT`,`--fail-on is error or warning.`);let i=(e._??[]).filter(e=>typeof e==`string`),a=[].concat(e[`ignore-phrase`]??[]).filter(e=>typeof e==`string`);try{let o=await En({paths:i,preset:t,format:n,ignoreRules:D(e.ignore),ignorePhrases:a},e=>l(e));O(e)?P(o.data):process.stdout.write(`${o.text}\n`);let{errors:s,warnings:c}=o.data;(s>0||r===`warning`&&c>0)&&(process.exitCode=1)}catch(e){throw ne(e)}}});function sa(e){return e===`keychain`?`system keychain`:e===`file`?`private local file`:e===`environment`?be:e??`missing`}function ca(e){if(e&&Mn(e))return e.trim();throw new h(`INVALID_INPUT`,`No Clicky site given. Pass --site-id with the numeric Clicky site ID.`)}async function la(e,t){return mt({siteId:e,sitekey:t}).catch(e=>{throw new h(e instanceof It&&e.code===`auth`?`AUTH_REQUIRED`:`PROVIDER_UNAVAILABLE`,e instanceof Error?e.message:String(e))})}const ua={type:`boolean`,default:!1,description:`Print machine-readable JSON.`},da={type:`string`,description:`Numeric Clicky site ID.`},fa=y({meta:{name:`connect`,description:`Check and save a Clicky site on this machine`},args:{"site-id":da,json:ua},run:async({args:e})=>{let t=O(e),n=N({json:t});n&&Dr(`Connect Clicky`);let r=ca(C(e[`site-id`])??(n?z(await Nr({message:`Clicky site ID`,validate:e=>Mn(e??``)?void 0:`Enter the numeric site ID from Clicky`})):void 0)),i=process.env.SEO_CLICKY_SITEKEY?.trim()||(n?z(await jr({message:`Clicky sitekey`,validate:e=>Vn(e??``)?void 0:`Enter the sitekey from Clicky (Preferences, Info)`})):void 0);if(!i)throw new h(`AUTH_REQUIRED`,`Run this command in a terminal or set ${be}.`);let a=await la(r,i.trim()),o=await at(r,i.trim()),s={siteId:r,domain:a,connected:!0,credentialSource:o};if(t){P(s);return}let c=`Clicky site ${r}${a?` (${a})`:``} saved in the ${sa(o)}. Next: seo analytics clicky report --site ${r}`;n?x(c):process.stdout.write(`${c}\n`)}}),pa=y({meta:{name:`status`,description:`Show a Clicky site saved on this machine`},args:{"site-id":da,check:{type:`boolean`,default:!1,description:`Check the saved sitekey with Clicky.`},json:ua},run:async({args:e})=>{let t=ca(C(e[`site-id`])),n=await ct(t),r=w(e.check);r&&n&&await la(t,n.siteKey);let i={siteId:t,connected:!!n,credentialSource:n?.source,liveCheck:r?n?`passed`:`unavailable`:`not-requested`};O(e)?P(i):F([[`Site ID`,t],[`Connected`,i.connected?`yes`:`no`],[`Credential`,sa(i.credentialSource)],[`Live check`,i.liveCheck]])}}),ma=y({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.`},...Qi,...B,json:ua},run:async({args:e})=>{let t=k(C(e.site));await H(e,async()=>Sn({site:t,startDate:C(e[`start-date`]),endDate:C(e[`end-date`]),detail:V(e),offset:T(e.offset)},await qt(),{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:Ae,call:e=>`seo analytics clicky report --site ${t} --detail rows --offset ${e}`}))}}),ha=y({meta:{name:`disconnect`,description:`Remove a Clicky site saved on this machine`},args:{"site-id":da,json:ua},run:async({args:e})=>{let t=ca(C(e[`site-id`]));await gn(t);let n=!!process.env[be],r={siteId:t,savedCredentialRemoved:!0,environmentCredential:n?`active`:`missing`};O(e)?P(r):process.stdout.write(n?`Saved sitekey removed. ${be} is still active.\n`:`Clicky is disconnected for this site.
33
+ `)}}),ga=y({meta:{name:`clicky`,description:`Read Clicky, or save a Clicky site on this machine only`},subCommands:{connect:fa,status:pa,report:ma,disconnect:ha}}),_a=y({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 Rt(C(e.account)),n=t.flatMap(e=>e.propertySummaries.map(t=>({account:e.displayName??e.account,property:tn(t.property),displayName:t.displayName??t.property})));O(e)?P({accountSummaries:t,properties:n}):I([`Property`,`Name`,`Account`],n.map(e=>[e.property,e.displayName,e.account]))}}),va=y({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."},...Qi,...B,json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=ai(C(e.property));await H(e,async()=>kn({property:t,startDate:C(e[`start-date`]),endDate:C(e[`end-date`]),detail:V(e),offset:T(e.offset)},await $t(await Ge(),t,jn.signIn),{signIn:jn.signIn,call:e=>`seo analytics google report --property ${t} --detail rows --offset ${e}`}))}}),ya=y({meta:{name:`google`,description:`Read Google Analytics properties and reports`},subCommands:{properties:_a,report:va}}),ba=y({meta:{name:`analytics`,description:`Read analytics data from connected providers`},subCommands:{clicky:ga,google:ya}});function xa(){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 Sa(){return b(xa(),`Google sign-in`),Bn()}function Ca(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 wa(e){return e.active===`keychain`?`system keychain`:e.configured===`keychain`?`private file fallback`:`private file`}function Ta(e){return e===`shared`?`SEO Skill app`:`Local OAuth config`}function Ea(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`,Ta(e.clientSource)],[`Expires`,Yr(e.expiresAt)]),t}const Da=y({meta:{name:`auth`,description:`Authentication commands`},subCommands:{login:y({meta:{name:`login`,description:`Run Google OAuth flow`},run:async()=>{if((await yt()).activeMode===`service-account`)throw new h(`AUTH_CONFIG_REQUIRED`,`A service account is active from the environment. Unset its credential variable before running browser OAuth.`);let e=await Sa();F(Ea({accountEmail:e.account_email,clientSource:e.client_source,expiresAt:e.expires_at,scope:e.scope}))}}),logout:y({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 yt(),n=C(e.account);if(n&&e.all)throw new h(`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:y({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 yt();if(t.activeMode===`service-account`){let n={mode:`service-account`,account:t.identity??null,source:Ca(t.serviceAccount.source)};if(O(e)){P(n);return}F([[`Account type`,`Service account`],[`Account`,t.identity??`Invalid configuration`],[`Credentials`,n.source],[`Access`,`Search Console and Google Analytics, read only`]]);return}let n=C(e.account),r=n?await p(n):t.tokens;if(n&&!r)throw new h(`AUTH_REQUIRED`,`Google account ${n} is not connected.`);if(r)O(e)?P({mode:`oauth`,account:r.account_email,scopes:r.scope.split(/\s+/u).filter(Boolean),clientSource:r.client_source,expiresAt:r.expires_at}):F(Ea({accountEmail:r.account_email,clientSource:r.client_source,expiresAt:r.expires_at,scope:r.scope}));else{if(O(e)){P({mode:`oauth`,account:null});return}process.stdout.write(`Not logged in.
34
+ `)}}}),status:y({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 n=await yt(),r=C(e.account),i=r?await p(r):n.tokens;if(r&&!i&&n.activeMode!==`service-account`)throw new h(`AUTH_REQUIRED`,`Google account ${r} is not connected.`);let a=n.activeMode===`oauth`?await Pn():void 0;if(O(e)){P({authenticated:n.activeMode===`oauth`?!!i:n.serviceAccount.configured,mode:n.activeMode,identity:n.identity,account:n.activeMode===`oauth`?i?.account_email:void 0,scopes:n.activeMode===`oauth`?i?.scope:void 0,clientSource:n.activeMode===`oauth`?i?.client_source:void 0,expiresAt:n.activeMode===`oauth`?i?.expires_at:void 0,sharedConfigured:n.sharedConfigured,byoConfigured:n.byoConfigured,serviceAccount:{configured:n.serviceAccount.configured,identity:n.serviceAccount.identity,source:n.serviceAccount.source,error:n.serviceAccount.error},accounts:n.accounts,...a?{tokenStorage:a}:{}});return}if(n.activeMode===`service-account`){let e=[[`Mode`,`service account`],[`Identity`,n.identity??`unavailable`],[`Source`,Ca(n.serviceAccount.source)],[`Scopes`,`Search Console readonly, Google Analytics readonly`],[`Storage`,`credentials stay in the environment`]];n.serviceAccount.error&&e.push([`Status`,n.serviceAccount.error]),F(e);return}if(!i){let e=n.serviceAccount.error?n.serviceAccount.error:n.sharedConfigured?`Shared seo app available`:n.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 o=a??await Pn();F([[`Account`,i.account_email],[`Connected accounts`,String(n.accounts.length)],[`Scopes`,i.scope],[`Client`,Ta(i.client_source)],[`Expires`,Yr(i.expires_at)],[`Tokens file`,t().tokensFile],[`Token storage`,wa(o)],...o.reason?[[`Storage note`,o.reason]]:[],[`OAuth mode`,n.sharedConfigured?`SEO Skill app available`:n.byoConfigured?`Local OAuth config available`:`missing`],[`Revoke at`,`https://myaccount.google.com/permissions`]])}}),storage:y({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 h(`INVALID_INPUT`,`Choose either --keychain or --file, not both.`);let t=e.keychain||e.file?await je(e.keychain?`keychain`:`file`):await Pn();O(e)?P(t):F([[`Configured storage`,t.configured],[`Active storage`,wa(t)],...t.reason?[[`Note`,t.reason]]:[]])}}),refresh:y({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 yt()).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 Ln(C(e.account));process.stdout.write(`Refreshed. New expiry ${new Date(t.expires_at).toISOString()}.\n`)}}),accounts:y({meta:{name:`accounts`,description:`List saved Google accounts`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:({args:e})=>{let t=Ke();O(e)?P({accounts:t}):t.length===0?process.stdout.write(`No Google accounts are connected.
36
+ `):F(t.map(e=>[e.active?`Active account`:`Account`,e.accountEmail]))}}),use:y({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=C(e.account);if(!t)throw new h(`INVALID_INPUT`,`Google account is required.`);ee(t),process.stdout.write(`Default Google account: ${t}\n`)}}),"setup-client":y({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(!N({json:O(e)}))throw new h(`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.");Dr(`Local Google OAuth client`),b(`This is the advanced path.
37
37
  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 Or({message:`Google Desktop OAuth client ID`,validate:e=>e?void 0:`Client ID is required`})),n=B(await Er({message:`Google Desktop OAuth client secret`,validate:e=>e?void 0:`Client secret is required`}));Ge({clientId:t,clientSecret:n}),S(`Saved local OAuth config to ${ot().oauthClientFile}`)}})}}),Ca=[`gsc`,`google-analytics`,`dataforseo`,`ahrefs`,`clicky`,`http`];function wa(e){if(e!==void 0){if(typeof e==`string`&&Ca.includes(e))return e;throw new g(`INVALID_INPUT`,`--provider must be one of: ${Ca.join(`, `)}.`)}}const Ta=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=ln();I([[`DB`,e.dbPath],[`Size`,Hi(e.sizeBytes)],[`Cached data`,`${Hi(e.logicalSizeBytes)} of ${Hi(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=jt(wa(e.provider));process.stdout.write(`Removed ${t} cached rows.\n`)}})}});function U(e){return Math.round(e).toLocaleString(`en-GB`)}function Ea(e){return e.toFixed(1)}function W(e){return`${(e*100).toFixed(1)}%`}function G(e,t=72){return ai(e,t)}function Da(e){return e.verification?.requested?`${e.verification.verified} checked, ${e.verification.failed} failed`:`off`}function Oa(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){Li(Oa(e))}function q(e,t){L(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=ka(e,r);i&&(process.stdout.write(`
39
- `),Li(i),t.length>r.length&&process.stdout.write(`Showing ${r.length} of ${t.length}. Use --json for full data.\n`))}function ka(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 Aa(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 ja=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":Gr(`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=k(e),n=A(w(e.site)),r=await mn({site:n,url:w(e.url)??``,days:E(e.days),limit:E(e.limit),minImpressions:E(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?F(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(`
38
+ Your actual sensitive data is the local refresh token, not the desktop app client secret.`,`Advanced`);let n=z(await Nr({message:`Google Desktop OAuth client ID`,validate:e=>e?void 0:`Client ID is required`})),r=z(await jr({message:`Google Desktop OAuth client secret`,validate:e=>e?void 0:`Client secret is required`}));Jt({clientId:n,clientSecret:r}),x(`Saved local OAuth config to ${t().oauthClientFile}`)}})}}),Oa=[`gsc`,`google-analytics`,`dataforseo`,`ahrefs`,`clicky`,`http`];function ka(e){if(e!==void 0){if(typeof e==`string`&&Oa.includes(e))return e;throw new h(`INVALID_INPUT`,`--provider must be one of: ${Oa.join(`, `)}.`)}}const Aa=y({meta:{name:`cache`,description:`Cache helpers`},subCommands:{stats:y({meta:{name:`stats`,description:`Show local cache size and row counts`},run:async()=>{let e=pt();F([[`DB`,e.dbPath],[`Size`,qi(e.sizeBytes)],[`Cached data`,`${qi(e.logicalSizeBytes)} of ${qi(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:y({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=Ft(ka(e.provider));process.stdout.write(`Removed ${t} cached rows.\n`)}})}});function U(e){return Math.round(e).toLocaleString(`en-GB`)}function ja(e){return e.toFixed(1)}function W(e){return`${(e*100).toFixed(1)}%`}function G(e,t=72){return ui(e,t)}function Ma(e){return e.verification?.requested?`${e.verification.verified} checked, ${e.verification.failed} failed`:`off`}function Na(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){Hi(Na(e))}function q(e,t){I(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=Pa(e,r);i&&(process.stdout.write(`
39
+ `),Hi(i),t.length>r.length&&process.stdout.write(`Showing ${r.length} of ${t.length}. Use --json for full data.\n`))}function Pa(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 Fa(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 Ia=y({meta:{name:`content`,description:`Optimize page content from real GSC queries`},subCommands:{optimize:y({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":Xr(`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=O(e),n=k(C(e.site)),r=await bn({site:n,url:C(e.url)??``,days:T(e.days),limit:T(e.limit),minImpressions:T(e[`min-impressions`]),includeBrand:w(e[`include-brand`]),verifyContent:w(e[`verify-content`])!==!1,js:w(e.js)?!0:`auto`,refresh:w(e.refresh)});t?P(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
40
  Suggested sections
41
41
  `),q([`Heading`,`Queries`],r.brief.sections.map(e=>[G(e.heading,48),G(e.queries.join(`, `),80)]))),r.intentMix.length&&(process.stdout.write(`
42
42
  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 Ma=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 Na(e){return` `.repeat(e)}function Pa(e){return e&&typeof e==`object`&&`toJSON`in e&&typeof e.toJSON==`function`?e.toJSON():e}async function Fa(e,t,n,r,i=!1){let a=Pa(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(`[
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 La=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 Ra(e){return` `.repeat(e)}function za(e){return e&&typeof e==`object`&&`toJSON`in e&&typeof e.toJSON==`function`?e.toJSON():e}async function Ba(e,t,n,r,i=!1){let a=za(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
44
  `);for(let t=0;t<a.length;t+=1)t>0&&await e.write(`,
45
- `),await e.write(Na(n+1)),await Fa(e,a[t],n+1,r,!0);return await e.write(`\n${Na(n)}]`),!0}let t=Object.entries(a).filter(([,e])=>{let t=Pa(e);return![`undefined`,`function`,`symbol`].includes(typeof t)});if(t.length===0)return await e.write(`{}`),!0;await e.write(`{
45
+ `),await e.write(Ra(n+1)),await Ba(e,a[t],n+1,r,!0);return await e.write(`\n${Ra(n)}]`),!0}let t=Object.entries(a).filter(([,e])=>{let t=za(e);return![`undefined`,`function`,`symbol`].includes(typeof t)});if(t.length===0)return await e.write(`{}`),!0;await e.write(`{
46
46
  `);for(let i=0;i<t.length;i+=1){let[a,o]=t[i];i>0&&await e.write(`,
47
- `),await e.write(`${Na(n+1)}${JSON.stringify(a)}: `),await Fa(e,o,n+1,r)}return await e.write(`\n${Na(n)}}`),!0}finally{r.delete(a)}}async function Ia(e,t){let n=new Ma(e);await Fa(n,t,0,/* @__PURE__ */ new Set)||await n.write(`undefined`),await n.write(`
48
- `),await n.flush()}async function La(e,t){if(!e){await Ia(process.stdout,t);return}await ur(Gn(e),{recursive:!0});let n=$n(e);try{await Ia(n,t),n.end(),await Mr(n)}catch(e){throw n.destroy(),e}process.stdout.write(`Wrote ${e}\n`)}function Ra(e){return e.length?e.join(`, `):`none`}function za(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:`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: ${Ra(a.map(e=>e.userAgent))}.`:`Checked: ${Ra(r.map(e=>e.userAgent))}.`}}function Ba(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 Va(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 Ha(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[za(e,`search`),za(e,`training`),Ba(e),Va(e),{status:`info`,title:`Agent files`,explanation:`Found: ${Ra(t)}.`},{status:`info`,title:`Content-Signal and Link header`,explanation:`Content-Signal: ${Ra([...new Set(n)])}. Link header relations on the start page: ${Ra(e.startPageHeaders?.linkRelations??[])}.`}]}function Ua(e){return e===`high`?`fail`:`warning`}function Wa(e,t=Dt(e)){let r=n(e),i=e.status===`failed`||e.summary.highIssues>0?`fail`:e.status===`partial`?`unknown`:e.summary.mediumIssues>0||e.summary.lowIssues>0?`warning`:`pass`,a=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})),o=t.slice(0,10).map(e=>({status:Ua(e.severity),title:`${e.title} on ${e.count} ${e.count===1?`URL`:`URLs`}`,explanation:Vt(e.ruleId)?.whyItMatters??e.whyThisRanks,evidence:e.sampleUrls.slice(0,5),fix:e.howToFix})),s=r.slice(0,10).map(e=>({status:`warning`,title:`${e.title} on ${e.count} ${e.count===1?`URL`:`URLs`}`,explanation:Vt(e.ruleId)?.whyItMatters??e.whyThisRanks,evidence:e.sampleUrls.slice(0,5),fix:e.howToFix}));Li({title:e.config.strategy===`health`?`Sitemap health pass`:`Site crawl`,target:e.config.url,status:i,summary: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:a},{title:`Prioritised fixes`,diagnostics:o},{title:`Review before changing anything`,diagnostics:s},{title:`Agent access`,diagnostics:Ha(e.ai)},...!a.length&&!o.length&&!s.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 Ga={"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 Ka(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:tt(n)}}function qa(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 Ja(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 Ya(e){return e?e===`serp-framing`?`wording gap`:e===`content-gap`?`content gap`:e===`technical-check`?`technical check`:`covered`:`-`}const Xa={high:3,medium:2,low:1},Za=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.`},...Ga,mode:{type:`string`,description:`Crawl mode: site, page, list, or sitemap. Start with sitemap --health for large sites.`},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.`},"urls-file":{type:`string`,description:`File with one URL per line for list 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.`},"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.`},format:{type:`string`,description:`Output format: pretty, json, csv, html, markdown, or junit. JUnit requires --health.`},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=k(e),r=to(e.format,t),i=w(e.output),a=no(e.csv),o=$a(e.severity),s=$a(e[`fail-on`]),c=await ro(e),l=eo(e),u=w(e[`sitemap-url`]),d=T(e.health),f=Qa(e.mode);if(r===`junit`&&!d)throw new g(`INVALID_INPUT`,`--format junit requires --health.`);if((d||u)&&f&&f!==`sitemap`)throw new g(`INVALID_INPUT`,`--health and --sitemap-url require sitemap mode.`);if(d&&qr(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 ee=w(e.site),te=(l?qa(l)??l:void 0)??(ee?qa(ee):void 0)??(u?new URL(`/`,u).toString():void 0)??c[0];if(!te)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 pe({url:te,site:ee,mode:f??(d||u?`sitemap`:c.length?`list`:void 0),strategy:d?`health`:`full`,sitemapUrl:u,urls:c,maxPages:E(e[`max-pages`]),maxDepth:E(e[`max-depth`]),concurrency:E(e.concurrency),refresh:T(e.refresh),fetchRate:Zr({...e,"fetch-concurrency":e.concurrency}),include:O(e.include),exclude:O(e.exclude),googleAnalyticsPropertyId:w(e[`google-analytics-property`]),analyticsConnection:Ka(e),useSitemap:!qr(e,`sitemap`),respectRobots:!qr(e,`robots`),checkExternal:!qr(e,`external`),js:Kr(e)}),ne=Dt(p,{severity:o}),m=s?p.issues.some(e=>Xa[e.severity]>=Xa[s]):!1,h=p.status===`failed`,re={...p,topFixes:ne,reviewObservations:n(p,{severity:o}),...s?{failOn:s,failedThreshold:m}:{}};r===`json`?(await La(i,re),(h||m)&&(process.exitCode=1)):r===`csv`?(await ao(i,a===`pages`?ut(p):pn(p)),(h||m)&&(process.exitCode=1)):r===`html`?(await ao(i,ge(p,ne)),(h||m)&&(process.exitCode=1)):r===`junit`?(await ao(i,st(p)),(h||m)&&(process.exitCode=1)):r===`markdown`?(await ao(i,it(p,ne)),(h||m)&&(process.exitCode=1)):i?(await ao(i,Le(p,ne)),(h||m)&&(process.exitCode=1)):(Wa(p,ne),s&&(process.stdout.write(`
47
+ `),await e.write(`${Ra(n+1)}${JSON.stringify(a)}: `),await Ba(e,o,n+1,r)}return await e.write(`\n${Ra(n)}}`),!0}finally{r.delete(a)}}async function Va(e,t){let n=new La(e);await Ba(n,t,0,/* @__PURE__ */ new Set)||await n.write(`undefined`),await n.write(`
48
+ `),await n.flush()}async function Ha(e,t){if(!e){await Va(process.stdout,t);return}await hr(Xn(e),{recursive:!0});let n=ir(e);try{await Va(n,t),n.end(),await Lr(n)}catch(e){throw n.destroy(),e}process.stdout.write(`Wrote ${e}\n`)}function Ua(e){return e.length?e.join(`, `):`none`}function Wa(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:`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: ${Ua(a.map(e=>e.userAgent))}.`:`Checked: ${Ua(r.map(e=>e.userAgent))}.`}}function Ga(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 Ka(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 qa(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[Wa(e,`search`),Wa(e,`training`),Ga(e),Ka(e),{status:`info`,title:`Agent files`,explanation:`Found: ${Ua(t)}.`},{status:`info`,title:`Content-Signal and Link header`,explanation:`Content-Signal: ${Ua([...new Set(n)])}. Link header relations on the start page: ${Ua(e.startPageHeaders?.linkRelations??[])}.`}]}function Ja(e){return e===`high`?`fail`:`warning`}function Ya(e,t=Vt(e)){let n=_n(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:Ja(e.severity),title:`${e.title} on ${e.count} ${e.count===1?`URL`:`URLs`}`,explanation:Ct(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:Ct(e.ruleId)?.whyItMatters??e.whyThisRanks,evidence:e.sampleUrls.slice(0,5),fix:e.howToFix}));Hi({title:e.config.strategy===`health`?`Sitemap health pass`:`Site crawl`,target:e.config.url,status:r,summary: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:qa(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 Xa={"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 Za(e){let t=C(e[`google-analytics-property`]),n=C(e[`clicky-site-id`]);if(t&&n)throw new h(`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:_e(n)}}function Qa(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 $a(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 eo(e){return e?e===`serp-framing`?`wording gap`:e===`content-gap`?`content gap`:e===`technical-check`?`technical check`:`covered`:`-`}const to={high:3,medium:2,low:1},no=y({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.`},...Xa,mode:{type:`string`,description:`Crawl mode: site, page, list, or sitemap. Start with sitemap --health for large sites.`},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.`},"urls-file":{type:`string`,description:`File with one URL per line for list 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.`},"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.`},format:{type:`string`,description:`Output format: pretty, json, csv, html, markdown, or junit. JUnit requires --health.`},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=O(e),r=oo(e.format,t),i=C(e.output),a=so(e.csv),o=io(e.severity),s=io(e[`fail-on`]),l=await co(e),u=ao(e),d=C(e[`sitemap-url`]),f=w(e.health),ee=ro(e.mode);if(r===`junit`&&!f)throw new h(`INVALID_INPUT`,`--format junit requires --health.`);if((f||d)&&ee&&ee!==`sitemap`)throw new h(`INVALID_INPUT`,`--health and --sitemap-url require sitemap mode.`);if(f&&Qr(e,`sitemap`))throw new h(`INVALID_INPUT`,`--health cannot be combined with --no-sitemap.`);if((f||d)&&l.length)throw new h(`INVALID_INPUT`,`--health and --sitemap-url cannot be combined with URL list input.`);let te=C(e.site),ne=(u?Qa(u)??u:void 0)??(te?Qa(te):void 0)??(d?new URL(`/`,d).toString():void 0)??l[0];if(!ne)throw new h(`INVALID_INPUT`,"No crawl URL given. Pass a URL, --url or --site. Run `seo sites` to list your Search Console properties.");let p=await c({url:ne,site:te,mode:ee??(f||d?`sitemap`:l.length?`list`:void 0),strategy:f?`health`:`full`,sitemapUrl:d,urls:l,maxPages:T(e[`max-pages`]),maxDepth:T(e[`max-depth`]),concurrency:T(e.concurrency),refresh:w(e.refresh),fetchRate:ni({...e,"fetch-concurrency":e.concurrency}),include:D(e.include),exclude:D(e.exclude),googleAnalyticsPropertyId:C(e[`google-analytics-property`]),analyticsConnection:Za(e),useSitemap:!Qr(e,`sitemap`),respectRobots:!Qr(e,`robots`),checkExternal:!Qr(e,`external`),js:Zr(e)}),re=Vt(p,{severity:o}),m=s?p.issues.some(e=>to[e.severity]>=to[s]):!1,ie=p.status===`failed`,ae={...p,topFixes:re,reviewObservations:_n(p,{severity:o}),...s?{failOn:s,failedThreshold:m}:{}};r===`json`?(await Ha(i,ae),(ie||m)&&(process.exitCode=1)):r===`csv`?(await uo(i,a===`pages`?wn(p):dt(p)),(ie||m)&&(process.exitCode=1)):r===`html`?(await uo(i,Re(p,re)),(ie||m)&&(process.exitCode=1)):r===`junit`?(await uo(i,n(p)),(ie||m)&&(process.exitCode=1)):r===`markdown`?(await uo(i,Ot(p,re)),(ie||m)&&(process.exitCode=1)):i?(await uo(i,rn(p,re)),(ie||m)&&(process.exitCode=1)):(Ya(p,re),s&&(process.stdout.write(`
49
49
  Run metadata
50
- `),I([[`Fail threshold`,s]])),(h||m)&&(process.exitCode=1))}});function Qa(e){let t=w(e);if(t){if([`site`,`page`,`list`,`sitemap`].includes(t))return t;throw new g(`INVALID_INPUT`,`Mode must be one of: site, page, list, sitemap.`)}}function $a(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 eo(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 to(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 no(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 ro(e){let t=O(e.urls)??[],n=w(e[`urls-file`]);return n&&t.push(...io(await y(n,`utf8`))),[...new Set(t)]}function io(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`))}async function ao(e,t){e?(await ur(Gn(e),{recursive:!0}),await pr(e,t),process.stdout.write(`Wrote ${e}\n`)):process.stdout.write(t)}const oo=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 Qr(e.body,e[`body-file`])??{startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),dimensions:O(e.dimensions)??[`query`,`page`],type:w(e.type)??`web`,rowLimit:E(e.limit),dataState:`final`};try{Object.assign(t,rt({startDate:w(t.startDate),endDate:w(t.endDate)},28))}catch(e){throw We(e)}let n=k(e),r=A(w(e.site)??w(t.siteUrl));delete t.siteUrl;let i=await _n(r,t,{refresh:T(e.refresh),accountEmail:w(e.account)}),a=E(e.limit),o=a?i.rows.slice(0,a):i.rows;n?F({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}]}),L([`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)])))}}),so=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=k(e),n=A(w(e.site)),r=w(e.url);if(!r)throw Error(`Pass --url.`);let i=await St({siteUrl:n,inspectionUrl:r,accountEmail:w(e.account),languageCode:w(e.language)});if(t){F(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`}]})}}),co={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=co[e];return[n.cli,{...n.arg,...t[e]}]}))}function lo(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 fo=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=k(e),n=await m({site:A(w(e.site)),days:E(e.days),recentDays:E(e.recent),refresh:T(e.refresh)});t?F(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,lo(e.baselineMean),lo(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]))}}),po=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=k(e),n=A(w(e.site)),r=await te({site:n,days:E(e.days),recentDays:E(e.recent),paddingDays:E(e[`padding-days`]),knownConfounders:w(e[`known-change`])?[w(e[`known-change`])??``]:void 0,refresh:T(e.refresh)});t?F(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,lo(e.baselineMean),lo(e.comparisonMean),uo(e.percentChange),e.zScore??`n/a`])),r.overlappingUpdates.length&&(process.stdout.write(`
50
+ `),F([[`Fail threshold`,s]])),(ie||m)&&(process.exitCode=1))}});function ro(e){let t=C(e);if(t){if([`site`,`page`,`list`,`sitemap`].includes(t))return t;throw new h(`INVALID_INPUT`,`Mode must be one of: site, page, list, sitemap.`)}}function io(e){let t=C(e);if(t){if([`low`,`medium`,`high`].includes(t))return t;throw new h(`INVALID_INPUT`,`Severity must be one of: low, medium, high.`)}}function ao(e){let t=C(e.crawlUrl),n=C(e.url);if(t&&n&&t!==n)throw new h(`INVALID_INPUT`,`Use either a URL argument or --url, not both.`);return t??n}function oo(e,t){let n=C(e);if(t&&n&&n!==`json`)throw new h(`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 h(`INVALID_INPUT`,`Format must be one of: pretty, json, csv, html, markdown, junit.`)}function so(e){let t=C(e);if(!t)return`issues`;if([`issues`,`pages`].includes(t))return t;throw new h(`INVALID_INPUT`,`CSV table must be one of: issues, pages.`)}async function co(e){let t=D(e.urls)??[],n=C(e[`urls-file`]);return n&&t.push(...lo(await v(n,`utf8`))),[...new Set(t)]}function lo(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`))}async function uo(e,t){e?(await hr(Xn(e),{recursive:!0}),await vr(e,t),process.stdout.write(`Wrote ${e}\n`)):process.stdout.write(t)}const fo=y({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 ri(e.body,e[`body-file`])??{startDate:C(e[`start-date`]),endDate:C(e[`end-date`]),dimensions:D(e.dimensions)??[`query`,`page`],type:C(e.type)??`web`,rowLimit:T(e.limit),dataState:`final`};try{Object.assign(t,kt({startDate:C(t.startDate),endDate:C(t.endDate)},28))}catch(e){throw ne(e)}let n=O(e),r=k(C(e.site)??C(t.siteUrl));delete t.siteUrl;let i=await Et(r,t,{refresh:w(e.refresh),accountEmail:C(e.account)}),a=T(e.limit),o=a?i.rows.slice(0,a):i.rows;n?P({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}]}),I([`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)])))}}),po=y({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=O(e),n=k(C(e.site)),r=C(e.url);if(!r)throw Error(`Pass --url.`);let i=await Mt({siteUrl:n,inspectionUrl:r,accountEmail:C(e.account),languageCode:C(e.language)});if(t){P(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`}]})}}),mo={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=mo[e];return[n.cli,{...n.arg,...t[e]}]}))}function ho(e){return e.toLocaleString(`en-GB`,{maximumFractionDigits:e>=100?0:1})}function go(e){if(e===null)return`n/a`;let t=Math.abs(e)>=10?e.toFixed(0):e.toFixed(1);return`${e>0?`+`:``}${t}%`}const _o=y({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=O(e),n=await a({site:k(C(e.site)),days:T(e.days),recentDays:T(e.recent),refresh:w(e.refresh)});t?P(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),go(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]))}}),vo=y({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=O(e),n=k(C(e.site)),r=await Kt({site:n,days:T(e.days),recentDays:T(e.recent),paddingDays:T(e[`padding-days`]),knownConfounders:C(e[`known-change`])?[C(e[`known-change`])??``]:void 0,refresh:w(e.refresh)});t?P(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),go(e.percentChange),e.zScore??`n/a`])),r.overlappingUpdates.length&&(process.stdout.write(`
51
51
  Updates
52
- `),L([`Start`,`End`,`Type`,`Name`],r.overlappingUpdates.map(e=>[e.start.slice(0,10),e.end?.slice(0,10)??`open`,e.type,e.name]))),Aa(`seo segment-impact --site ${JSON.stringify(n)} --dimension page`))}}),mo={site:{type:`string`,description:`Search Console property, for example sc-domain:example.com.`}};function ho(e){return{type:`string`,description:`Output folder. Defaults to ./seo-export/<site>-${e}-YYYY-MM-DD.`}}function go(e){return e.toLowerCase().replace(/^sc-domain:/,``).replace(/^https?:\/\//,``).replace(/[^a-z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``)}function _o(e){let t=(/* @__PURE__ */ new Date()).toISOString().slice(0,10),n=go(e.site);return Jn(process.cwd(),`seo-export`,`${n}-${e.report}-${t}`)}async function vo(e,t){await ur(e,{recursive:!0});let n=[];for(let r of t){let t=Jn(e,r.filename);await pr(t,tn(r.rows,r.headers),`utf8`),n.push(t)}return n}function yo(e,t){process.stdout.write(`Wrote ${Pe(t.length,`CSV file`)} to ${e}\n`);for(let e of t)process.stdout.write(`- ${e}\n`)}const bo=b({meta:{name:`refresh-priorities`,description:`Export the ranked SEO priority queue, score breakdowns, grouped findings, and diagnosis detail CSVs.`},args:{...mo,out:ho(`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.`}}),...Ga,"verify-content":Gr(`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=A(w(e.site)),n=await pt({site:t,days:E(e.days),recentDays:E(e.recent),limit:E(e.limit),includeBrand:T(e[`include-brand`]),googleAnalyticsPropertyId:w(e[`google-analytics-property`]),analyticsConnection:Ka(e),verifyContent:T(e[`verify-content`]),verifyLimit:E(e[`verify-limit`]),refresh:T(e.refresh)}),r=w(e.out)??_o({report:`refresh-priorities`,site:t});yo(r,await vo(r,bn(n)))}}),xo=b({meta:{name:`update-postmortem`,description:`Export update postmortem attribution, findings, template movement, and segment movers.`},args:{...mo,out:ho(`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=A(w(e.site)),n=await Ft({site:t,days:E(e.days),recentDays:E(e.recent),limit:E(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)??_o({report:`update-postmortem`,site:t});yo(r,await vo(r,Br(n)))}}),So=b({meta:{name:`export`,description:`Export full report data to CSV files`},subCommands:{"update-postmortem":xo,"refresh-priorities":bo}});function Co(e,t,n={}){if(process.platform!==`win32`)return _r(e,t,n);let r=e=>/^[\w./:=@\\-]+$/.test(e)?e:`"${e.replaceAll(`"`,`""`)}"`;return _r([e,...t].map(r).join(` `),{...n,shell:!0})}function wo(e){let t=e.platform===`win32`?Xn:Kn;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 To(e={}){let t=e.home??Hn(),n=e.platform??process.platform,r=wo({home:t,platform:n,env:e.env??process.env}),i=n===`win32`?Xn:Kn,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 Eo(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=_(Gn(i),e);if(r(t))return t}return e}function Do(e){return Eo(e)!==e}function Oo(e={}){let t=e.targets??To(),n=e.hasCommand??Do,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 ko={insertSpaces:!0,tabSize:2,eol:`
53
- `};function Ao(){return(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g,`-`)}function jo(e,t){er(Gn(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.${Date.now()}.tmp`,r=v(e)?or(e).mode&511:384;sr(n,t,{encoding:`utf8`,mode:r}),ir(n,e)}function Mo(e){let t=`${e}.bak-${Ao()}`,n=t,r=2;for(;v(n);)n=`${t}-${r}`,r+=1;Qn(e,n,Zn.COPYFILE_EXCL)}function No(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Po(e){if(!v(e.path))return{source:`{}
54
- `,config:{}};let t=tr(e.path,`utf8`),n=[],r=Fr(t,n,{allowTrailingComma:!0});if(n.length>0){let t=n[0],r=t?`${Ir(t.error)} at offset ${t.offset}`:`unknown parse error`;throw Error(`Cannot update ${e.path}: invalid JSONC (${r}).`)}if(!No(r))throw Error(`Cannot update ${e.path}: config root must be an object.`);if(r.mcpServers!==void 0&&!No(r.mcpServers))throw Error(`Cannot update ${e.path}: mcpServers must be an object.`);return{source:t,config:r}}function Fo(e){return e.includes(`mcp`)&&e.includes(`serve`)&&e.some(e=>e===`seo`||e.startsWith(`seo@`)||e===`@seo/cli`)}function Io(e,t){return typeof e.command!=`string`||t.length!==3||t[1]!==`mcp`||t[2]!==`serve`||!No(e.env)?!1:e.env.SEO_MCP_CONFIGURED_BY===`seo`}function Lo(e){if(!No(e)||!Array.isArray(e.args))return!1;let t=e.args.filter(e=>typeof e==`string`);return Fo(t)||Io(e,t)}function Ro(e){let t=Nr(e.source,Pr(e.source,[`mcpServers`,e.name??`seo`],e.value,{formattingOptions:ko}));v(e.target.path)&&Mo(e.target.path),jo(e.target.path,t)}function zo(e,t){let n=Co(e,t,{encoding:`utf8`});return{status:n.status,stdout:String(n.stdout??``),stderr:String(n.stderr??``),error:n.error}}function Bo(e){let t=e.replaceAll(`\\`,`/`).toLowerCase();return t.includes(`/_npx/`)||t.includes(`/.npm/_npx/`)||t.includes(`/.cache/pnpm/dlx/`)}function Vo(e){if(!e||!v(e))return;let t=rr(e);return Bo(t)?void 0:t}function Ho(e={}){let t=Vo(e.cliPath??process.argv[1]);if(t)return{command:e.nodePath??process.execPath,args:[t,`mcp`,`serve`]};let n=`seo@${e.version??oe}`;return(e.platform??process.platform)===`win32`?{command:`cmd`,args:[`/c`,`npx`,`-y`,n,`mcp`,`serve`]}:{command:`npx`,args:[`-y`,n,`mcp`,`serve`]}}function Uo(e=!1,t=Ho()){let n=ot(),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 Wo(e){return e.includes(`SEO_MCP_CONFIGURED_BY`)||/args:\s+-y\s+(?:seo(?:@\S+)?|@seo\/cli)\s+mcp\s+serve\b/.test(e)}function Go(e,t,n){let r=Eo(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&&!Wo(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=ot(),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 Ko(e,t={}){let n={runCommand:t.runCommand??zo,reinstall:t.reinstall??!1,serverCommand:t.serverCommand??Ho()};if(e.kind===`native`)return Go(e,`install`,n);let{source:r,config:i}=Po(e),a=i.mcpServers?.seo,o=Uo(e.includeType,n.serverCommand);if(mr(a,o)&&!n.reinstall)return{client:e.client,path:e.path,changed:!1};if(a!==void 0&&!Lo(a))throw Error(`Cannot install SEO MCP: ${e.path} already has an unmanaged mcpServers.seo entry.`);return Ro({target:e,source:r,value:o}),{client:e.client,path:e.path,changed:!0}}function qo(e,t={}){if(e.kind===`native`)return Go(e,`uninstall`,{runCommand:t.runCommand??zo,reinstall:!1,serverCommand:Ho()});if(!v(e.path))return{client:e.client,path:e.path,changed:!1};let{source:n,config:r}=Po(e),i=r.mcpServers;if(i?.seo===void 0)return{client:e.client,path:e.path,changed:!1};if(!Lo(i.seo))throw Error(`Cannot uninstall SEO MCP: ${e.path} has an unmanaged mcpServers.seo entry.`);return Ro({target:e,source:n,value:void 0}),{client:e.client,path:e.path,changed:!0}}const Jo=`https://seoskill.dev/mcp`,Yo=`seoskill`;function Xo(e){return e.client!==`claude-desktop`}function Zo(e){return e.includeType?{type:`http`,url:Jo}:{url:Jo}}function Qo(e){return No(e)&&e.url===`https://seoskill.dev/mcp`}function $o(e,t={}){if(!Xo(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??zo,r=Eo(e.executable),i=n(r,[`mcp`,`get`,Yo]);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.${Yo} entry.`)}let a=n(r,[`mcp`,`add`,Yo,`--url`,Jo]);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}=Po(e),i=r.mcpServers?.[Yo];if(Qo(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.${Yo} entry.`);return Ro({target:e,source:n,value:Zo(e),name:Yo}),{client:e.client,path:e.path,changed:!0}}const es=e=>process.stdout.write(`${e}\n`);async function ts(){let{google:e,bing:t,keys:n}=await ee();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(Ht)).length}}function ns(e){return[`Linked to your seoskill.dev account.`,`Google: ${e.google.join(`, `)||`none`}.`,`Bing: ${e.bing?`${e.bing} linked`:`not connected (add it at ${ne}/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(`
55
- `)}const rs=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=k(e),n=async()=>{let e=await ts();t?F(e):es(ns(e))};if(process.env.SEO_TOKEN?.trim()){await n();return}if(De()){let e=await i();if(e===`linked`)return n();if(e===`pending`&&!P({json:t})){let e=De();t?F({status:`pending`,...as(e)}):es(`Waiting for approval. Open ${e?.url} and click "Link this machine", then run \`seo login\` again.`);return}}else if(Ae()){await n();return}let r=De()??await Ne();if(!P({json:t}))t?F({status:`pending`,...as(r)}):es([`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(`
56
- `));else{if(await is())return n();es("The login expired. Run `seo login` again."),process.exitCode=1}}});async function is(){let e=De()??await Ne();for(es(`Opening ${e.url}\nApprove code ${e.code} there. Waiting…`),await we(e.url);De();){await new Promise(e=>setTimeout(e,3e3));let e=await i();if(e===`linked`)return!0;if(e===`expired`)break}return!1}const as=e=>({url:e?.url,code:e?.code}),os=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 qt();k(e)?F({unlinked:t}):es(t?`This machine is no longer linked to your seoskill.dev account.`:`This machine was not linked.`)}});function ss(e={}){let t=Co(`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 cs(e){let t=async()=>{let{google:e}=await ee().catch(()=>({google:[]}));return{status:`linked`,accountEmail:e.map(e=>e.email).join(`, `)||void 0}};if(process.env.SEO_TOKEN?.trim()||Ae())return t();if(!e.interactive)return null;let n=B(await Dr({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():(x("The link expired. Run `seo login` to try again.",`Not signed in`),{status:`skipped`})}function ls(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 us(){let e=await _a();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 ds(e){let t=await Pt();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`,Wt())}let n=Mn();if(n.length>0){let e=B(await Dr({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 u(e.accountEmail),{status:`already-connected`,accountEmail:e.accountEmail};if(t.sharedConfigured||t.byoConfigured)return us()}let r=B(await Dr({message:`Connect Google now?`,options:ls({sharedConfigured:t.sharedConfigured,byoConfigured:t.byoConfigured})}));if(r===`skip`)return{status:`skipped`};if(r===`setup`){let e=B(await Or({message:`Google Desktop OAuth client ID`,validate:e=>e?void 0:`Client ID is required`})),t=B(await Er({message:`Google Desktop OAuth client secret`,validate:e=>e?void 0:`Client secret is required`}));Ge({clientId:e,clientSecret:t})}return us()}async function fs(){return B(await xr({message:`Install the SEO skill so your agents know how to use seo?`,initialValue:!0}))?ss():{status:`declined`}}async function ps(){let e=Oo();if(e.length===0)return[];let t=B(await Dr({message:`Add an MCP server to your agents?`,options:[{value:`hosted`,label:`Free hosted server (recommended)`,hint:`${Jo}, 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 Tr({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`&&Xo(e)?`hosted`:`local`;try{return{...n===`hosted`?$o(e):Ko(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 ${Jo} as a custom connector.`,`Claude Desktop`),r}const ms=[`seo sites`,`seo report --site <site>`],hs=[`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 (${Jo}) or a local one to your agents.`,`Install the SEO skill for your agents.`];function gs(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 _s(e){return e.status===`installed`?`installed`:e.status===`failed`?`install failed`:`not installed`}function vs(e){return e.length===0?`not added`:e.map(e=>e.error?`${e.client} skipped`:`${e.client} (${e.server})`).join(`, `)}function ys(){process.stdout.write(`
57
- `),R({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 bs(e){let t=k(e);if(t||Sr(process.argv[2]===`setup`?`seo setup`:`seo start`),e[`dry-run`]){t?F({dryRun:!0,steps:hs,next:ms}):(x(hs.map((e,t)=>`${t+1}. ${e}`).join(`
58
- `),`Setup will`),x(ms.join(`
59
- `),`Then run`),S(`Dry run complete. Nothing was changed.`));return}he();let n=P({json:t}),r=await cs({interactive:n})??await ds({interactive:n}),i=n?await ps():[],a=n?await fs():{status:`skipped`};if(t){F({auth:r,mcp:i,skill:a,next:ms});return}I([[`Sign-in`,gs(r)],[`MCP server`,vs(i)],[`SEO skill`,_s(a)]]);let o=i.filter(e=>e.error);o.length&&x(o.map(e=>`${e.client}: ${e.error}`).join(`
60
- `),`MCP setup skipped`),a.error&&x(a.error,`SEO skill install failed`),x(`seo sites list your Search Console properties
61
- seo report --site <site> run the main report for one of them`,`Try next`),S(`Setup complete.`),ys()}const xs=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})=>bs(e)}),Ss=b({...xs,meta:{name:`start`,description:`Start here: sign in with Google, then add the MCP server and skill to your agents`}}),Cs=b({...Ss,meta:{name:`init`,description:"Legacy alias for `seo start`."}}),ws=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=Ur();k(e)?F(t):e.quiet||process.stdout.write(`Rotated ${t.rotated} and removed ${t.removed} log files. ${Hi(t.sizeBytes)} retained.\n`)}})}}),Ts=[{client:`claude-desktop`,flag:`claude-desktop`},{client:`claude-code`,flag:`claude-code`},{client:`codex`,flag:`codex`},{client:`cursor`,flag:`cursor`}];function Es(e,t){return T(e.all)?t:Ts.filter(({flag:t})=>T(e[t])).map(({client:e})=>e)}const Ds=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-4Yam8ps7.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=To(),n=Oo({targets:t}),r=k(e),i=Es(e,n.map(e=>e.client));if(i.length===0){if(!P({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=B(await Tr({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)?qo(t):Ko(t,{reinstall:T(e.reinstall)}));if(r)F({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`)}})}}),Os=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=k(e),n=A(w(e.site)),r=Xr(e.sitemaps),i=await An({site:n,url:w(e.url),sitemaps:r.length?r:void 0,days:E(e.days),rowLimit:E(e[`row-limit`]),maxSitemapUrls:E(e[`max-sitemap-urls`]),itemsPerSection:E(e.limit),refresh:T(e.refresh)});t?F(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(`
52
+ `),I([`Start`,`End`,`Type`,`Name`],r.overlappingUpdates.map(e=>[e.start.slice(0,10),e.end?.slice(0,10)??`open`,e.type,e.name]))),Fa(`seo segment-impact --site ${JSON.stringify(n)} --dimension page`))}}),yo={site:{type:`string`,description:`Search Console property, for example sc-domain:example.com.`}};function bo(e){return{type:`string`,description:`Output folder. Defaults to ./seo-export/<site>-${e}-YYYY-MM-DD.`}}function xo(e){return e.toLowerCase().replace(/^sc-domain:/,``).replace(/^https?:\/\//,``).replace(/[^a-z0-9._-]+/g,`-`).replace(/^-+|-+$/g,``)}function So(e){let t=(/* @__PURE__ */ new Date()).toISOString().slice(0,10),n=xo(e.site);return $n(process.cwd(),`seo-export`,`${n}-${e.report}-${t}`)}async function Co(e,t){await hr(e,{recursive:!0});let n=[];for(let r of t){let t=$n(e,r.filename);await vr(t,cn(r.rows,r.headers),`utf8`),n.push(t)}return n}function wo(e,t){process.stdout.write(`Wrote ${Ve(t.length,`CSV file`)} to ${e}\n`);for(let e of t)process.stdout.write(`- ${e}\n`)}const To=y({meta:{name:`refresh-priorities`,description:`Export the ranked SEO priority queue, score breakdowns, grouped findings, and diagnosis detail CSVs.`},args:{...yo,out:bo(`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.`}}),...Xa,"verify-content":Xr(`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=k(C(e.site)),n=await Rn({site:t,days:T(e.days),recentDays:T(e.recent),limit:T(e.limit),includeBrand:w(e[`include-brand`]),googleAnalyticsPropertyId:C(e[`google-analytics-property`]),analyticsConnection:Za(e),verifyContent:w(e[`verify-content`]),verifyLimit:T(e[`verify-limit`]),refresh:w(e.refresh)}),r=C(e.out)??So({report:`refresh-priorities`,site:t});wo(r,await Co(r,gt(n)))}}),Eo=y({meta:{name:`update-postmortem`,description:`Export update postmortem attribution, findings, template movement, and segment movers.`},args:{...yo,out:bo(`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=k(C(e.site)),n=await bt({site:t,days:T(e.days),recentDays:T(e.recent),limit:T(e.limit),includeBrand:w(e[`include-brand`]),knownConfounders:C(e[`known-change`])?[C(e[`known-change`])??``]:void 0,refresh:w(e.refresh)}),r=C(e.out)??So({report:`update-postmortem`,site:t});wo(r,await Co(r,Gr(n)))}}),Do=y({meta:{name:`export`,description:`Export full report data to CSV files`},subCommands:{"update-postmortem":Eo,"refresh-priorities":To}});function Oo(e,t,n={}){if(process.platform!==`win32`)return Sr(e,t,n);let r=e=>/^[\w./:=@\\-]+$/.test(e)?e:`"${e.replaceAll(`"`,`""`)}"`;return Sr([e,...t].map(r).join(` `),{...n,shell:!0})}function ko(e){let t=e.platform===`win32`?tr:Zn;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 Ao(e={}){let t=e.home??qn(),n=e.platform??process.platform,r=ko({home:t,platform:n,env:e.env??process.env}),i=n===`win32`?tr:Zn,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 jo(e,t={}){let n=t.platform??process.platform,r=t.exists??_,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=g(e,t);if(r(n))return n}for(let e of a){let t=g(Xn(i),e);if(r(t))return t}return e}function Mo(e){return jo(e)!==e}function No(e={}){let t=e.targets??Ao(),n=e.hasCommand??Mo,r=e.hasPath??_;return t.filter(e=>e.kind===`native`?e.commandNames.some(n):r(e.path)||e.detectionPaths.some(r)||e.commandNames.some(n))}const Po={insertSpaces:!0,tabSize:2,eol:`
53
+ `};function Fo(){return(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g,`-`)}function Io(e,t){ar(Xn(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.${Date.now()}.tmp`,r=_(e)?dr(e).mode&511:384;fr(n,t,{encoding:`utf8`,mode:r}),lr(n,e)}function Lo(e){let t=`${e}.bak-${Fo()}`,n=t,r=2;for(;_(n);)n=`${t}-${r}`,r+=1;rr(e,n,nr.COPYFILE_EXCL)}function Ro(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function zo(e){if(!_(e.path))return{source:`{}
54
+ `,config:{}};let t=or(e.path,`utf8`),n=[],r=Br(t,n,{allowTrailingComma:!0});if(n.length>0){let t=n[0],r=t?`${Vr(t.error)} at offset ${t.offset}`:`unknown parse error`;throw Error(`Cannot update ${e.path}: invalid JSONC (${r}).`)}if(!Ro(r))throw Error(`Cannot update ${e.path}: config root must be an object.`);if(r.mcpServers!==void 0&&!Ro(r.mcpServers))throw Error(`Cannot update ${e.path}: mcpServers must be an object.`);return{source:t,config:r}}function Bo(e){return e.includes(`mcp`)&&e.includes(`serve`)&&e.some(e=>e===`seo`||e.startsWith(`seo@`)||e===`@seo/cli`)}function Vo(e,t){return typeof e.command!=`string`||t.length!==3||t[1]!==`mcp`||t[2]!==`serve`||!Ro(e.env)?!1:e.env.SEO_MCP_CONFIGURED_BY===`seo`}function Ho(e){if(!Ro(e)||!Array.isArray(e.args))return!1;let t=e.args.filter(e=>typeof e==`string`);return Bo(t)||Vo(e,t)}function Uo(e){let t=Rr(e.source,zr(e.source,[`mcpServers`,e.name??`seo`],e.value,{formattingOptions:Po}));_(e.target.path)&&Lo(e.target.path),Io(e.target.path,t)}function Wo(e,t){let n=Oo(e,t,{encoding:`utf8`});return{status:n.status,stdout:String(n.stdout??``),stderr:String(n.stderr??``),error:n.error}}function Go(e){let t=e.replaceAll(`\\`,`/`).toLowerCase();return t.includes(`/_npx/`)||t.includes(`/.npm/_npx/`)||t.includes(`/.cache/pnpm/dlx/`)}function Ko(e){if(!e||!_(e))return;let t=cr(e);return Go(t)?void 0:t}function qo(e={}){let t=Ko(e.cliPath??process.argv[1]);if(t)return{command:e.nodePath??process.execPath,args:[t,`mcp`,`serve`]};let n=`seo@${e.version??st}`;return(e.platform??process.platform)===`win32`?{command:`cmd`,args:[`/c`,`npx`,`-y`,n,`mcp`,`serve`]}:{command:`npx`,args:[`-y`,n,`mcp`,`serve`]}}function Jo(e=!1,n=qo()){let r=t(),i={command:n.command,args:n.args,env:{SEO_CONFIG_DIR:r.configDir,SEO_MCP_CONFIGURED_BY:`seo`}};return e&&(i.type=`stdio`),i}function Yo(e){return e.includes(`SEO_MCP_CONFIGURED_BY`)||/args:\s+-y\s+(?:seo(?:@\S+)?|@seo\/cli)\s+mcp\s+serve\b/.test(e)}function Xo(e,n,r){let i=jo(e.executable),a=r.runCommand(i,[`mcp`,`get`,`seo`]);if(a.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 o=a.status===0;if(o&&!Yo(a.stdout))throw Error(`Cannot ${n} SEO MCP: ${e.path} already has an unmanaged mcp_servers.seo entry.`);if(n===`install`&&o&&!r.reinstall||n===`uninstall`&&!o)return{client:e.client,path:e.path,changed:!1};if(n===`install`&&o){let e=r.runCommand(i,[`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 s=t(),c=n===`install`?[`mcp`,`add`,`seo`,`--env`,`SEO_CONFIG_DIR=${s.configDir}`,`--env`,`SEO_MCP_CONFIGURED_BY=seo`,`--`,r.serverCommand.command,...r.serverCommand.args]:[`mcp`,`remove`,`seo`],l=r.runCommand(i,c);if(l.error||l.status!==0){let e=l.error?.message??l.stderr.trim()??`unknown error`;throw Error(`Cannot ${n} SEO MCP for Codex: ${e}`)}return{client:e.client,path:e.path,changed:!0}}function Zo(e,t={}){let n={runCommand:t.runCommand??Wo,reinstall:t.reinstall??!1,serverCommand:t.serverCommand??qo()};if(e.kind===`native`)return Xo(e,`install`,n);let{source:r,config:i}=zo(e),a=i.mcpServers?.seo,o=Jo(e.includeType,n.serverCommand);if(yr(a,o)&&!n.reinstall)return{client:e.client,path:e.path,changed:!1};if(a!==void 0&&!Ho(a))throw Error(`Cannot install SEO MCP: ${e.path} already has an unmanaged mcpServers.seo entry.`);return Uo({target:e,source:r,value:o}),{client:e.client,path:e.path,changed:!0}}function Qo(e,t={}){if(e.kind===`native`)return Xo(e,`uninstall`,{runCommand:t.runCommand??Wo,reinstall:!1,serverCommand:qo()});if(!_(e.path))return{client:e.client,path:e.path,changed:!1};let{source:n,config:r}=zo(e),i=r.mcpServers;if(i?.seo===void 0)return{client:e.client,path:e.path,changed:!1};if(!Ho(i.seo))throw Error(`Cannot uninstall SEO MCP: ${e.path} has an unmanaged mcpServers.seo entry.`);return Uo({target:e,source:n,value:void 0}),{client:e.client,path:e.path,changed:!0}}const $o=`https://seoskill.dev/mcp`,es=`seoskill`;function ts(e){return e.client!==`claude-desktop`}function ns(e){return e.includeType?{type:`http`,url:$o}:{url:$o}}function rs(e){return Ro(e)&&e.url===`https://seoskill.dev/mcp`}function is(e,t={}){if(!ts(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??Wo,r=jo(e.executable),i=n(r,[`mcp`,`get`,es]);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.${es} entry.`)}let a=n(r,[`mcp`,`add`,es,`--url`,$o]);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}=zo(e),i=r.mcpServers?.[es];if(rs(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.${es} entry.`);return Uo({target:e,source:n,value:ns(e),name:es}),{client:e.client,path:e.path,changed:!0}}const as=e=>process.stdout.write(`${e}\n`);async function os(){let{google:e,bing:t,keys:n}=await Gt();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(un)).length}}function ss(e){return[`Linked to your seoskill.dev account.`,`Google: ${e.google.join(`, `)||`none`}.`,`Bing: ${e.bing?`${e.bing} linked`:`not connected (add it at ${i}/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(`
55
+ `)}const cs=y({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=O(e),n=async()=>{let e=await os();t?P(e):as(ss(e))};if(process.env.SEO_TOKEN?.trim()){await n();return}if(Se()){let e=await Pe();if(e===`linked`)return n();if(e===`pending`&&!N({json:t})){let e=Se();t?P({status:`pending`,...us(e)}):as(`Waiting for approval. Open ${e?.url} and click "Link this machine", then run \`seo login\` again.`);return}}else if(Te()){await n();return}let r=Se()??await Be();if(!N({json:t}))t?P({status:`pending`,...us(r)}):as([`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(`
56
+ `));else{if(await ls())return n();as("The login expired. Run `seo login` again."),process.exitCode=1}}});async function ls(){let e=Se()??await Be();for(as(`Opening ${e.url}\nApprove code ${e.code} there. Waiting…`),await pe(e.url);Se();){await new Promise(e=>setTimeout(e,3e3));let e=await Pe();if(e===`linked`)return!0;if(e===`expired`)break}return!1}const us=e=>({url:e?.url,code:e?.code}),ds=y({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 Oe();O(e)?P({unlinked:t}):as(t?`This machine is no longer linked to your seoskill.dev account.`:`This machine was not linked.`)}});function fs(e={}){let t=Oo(`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 ps(e){let t=async()=>{let{google:e}=await Gt().catch(()=>({google:[]}));return{status:`linked`,accountEmail:e.map(e=>e.email).join(`, `)||void 0}};if(process.env.SEO_TOKEN?.trim()||Te())return t();if(!e.interactive)return null;let n=z(await Mr({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 ls()?t():(b("The link expired. Run `seo login` to try again.",`Not signed in`),{status:`skipped`})}function ms(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 Sa();return b(`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 gs(e){let t=await yt();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 h(`AUTH_REQUIRED`,ie())}let n=Ke();if(n.length>0){let e=z(await Mr({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 ee(e.accountEmail),{status:`already-connected`,accountEmail:e.accountEmail};if(t.sharedConfigured||t.byoConfigured)return hs()}let r=z(await Mr({message:`Connect Google now?`,options:ms({sharedConfigured:t.sharedConfigured,byoConfigured:t.byoConfigured})}));if(r===`skip`)return{status:`skipped`};if(r===`setup`){let e=z(await Nr({message:`Google Desktop OAuth client ID`,validate:e=>e?void 0:`Client ID is required`})),t=z(await jr({message:`Google Desktop OAuth client secret`,validate:e=>e?void 0:`Client secret is required`}));Jt({clientId:e,clientSecret:t})}return hs()}async function _s(){return z(await Er({message:`Install the SEO skill so your agents know how to use seo?`,initialValue:!0}))?fs():{status:`declined`}}async function vs(){let e=No();if(e.length===0)return[];let t=z(await Mr({message:`Add an MCP server to your agents?`,options:[{value:`hosted`,label:`Free hosted server (recommended)`,hint:`${$o}, 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 Ar({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`&&ts(e)?`hosted`:`local`;try{return{...n===`hosted`?is(e):Zo(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`)&&b(`Claude Desktop got the local server. To use the hosted one there, open Settings, then Connectors, and add ${$o} as a custom connector.`,`Claude Desktop`),r}const ys=[`seo sites`,`seo report --site <site>`],bs=[`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 (${$o}) or a local one to your agents.`,`Install the SEO skill for your agents.`];function xs(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 Ss(e){return e.status===`installed`?`installed`:e.status===`failed`?`install failed`:`not installed`}function Cs(e){return e.length===0?`not added`:e.map(e=>e.error?`${e.client} skipped`:`${e.client} (${e.server})`).join(`, `)}function ws(){process.stdout.write(`
57
+ `),L({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 Ts(e){let t=O(e);if(t||Dr(process.argv[2]===`setup`?`seo setup`:`seo start`),e[`dry-run`]){t?P({dryRun:!0,steps:bs,next:ys}):(b(bs.map((e,t)=>`${t+1}. ${e}`).join(`
58
+ `),`Setup will`),b(ys.join(`
59
+ `),`Then run`),x(`Dry run complete. Nothing was changed.`));return}Le();let n=N({json:t}),r=await ps({interactive:n})??await gs({interactive:n}),i=n?await vs():[],a=n?await _s():{status:`skipped`};if(t){P({auth:r,mcp:i,skill:a,next:ys});return}F([[`Sign-in`,xs(r)],[`MCP server`,Cs(i)],[`SEO skill`,Ss(a)]]);let o=i.filter(e=>e.error);o.length&&b(o.map(e=>`${e.client}: ${e.error}`).join(`
60
+ `),`MCP setup skipped`),a.error&&b(a.error,`SEO skill install failed`),b(`seo sites list your Search Console properties
61
+ seo report --site <site> run the main report for one of them`,`Try next`),x(`Setup complete.`),ws()}const Es=y({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})=>Ts(e)}),Ds=y({...Es,meta:{name:`start`,description:`Start here: sign in with Google, then add the MCP server and skill to your agents`}}),Os=y({...Ds,meta:{name:`init`,description:"Legacy alias for `seo start`."}}),ks=y({meta:{name:`logs`,description:`Manage local log retention`},subCommands:{prune:y({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=Jr();O(e)?P(t):e.quiet||process.stdout.write(`Rotated ${t.rotated} and removed ${t.removed} log files. ${qi(t.sizeBytes)} retained.\n`)}})}}),As=[{client:`claude-desktop`,flag:`claude-desktop`},{client:`claude-code`,flag:`claude-code`},{client:`codex`,flag:`codex`},{client:`cursor`,flag:`cursor`}];function js(e,t){return w(e.all)?t:As.filter(({flag:t})=>w(e[t])).map(({client:e})=>e)}const Ms=y({meta:{name:`mcp`,description:`MCP server helpers`},subCommands:{serve:y({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-Dik5MNDk.js`);await t({test:w(e.test)})}}),install:y({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(w(e.uninstall)&&w(e.reinstall))throw new h(`INVALID_INPUT`,`Use either --uninstall or --reinstall, not both.`);let t=Ao(),n=No({targets:t}),r=O(e),i=js(e,n.map(e=>e.client));if(i.length===0){if(!N({json:r}))throw new h(`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 Ar({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 h(`INVALID_INPUT`,`MCP setup is not supported for ${a.join(`, `)} on ${process.platform}.`);let o=t.filter(e=>i.includes(e.client)).map(t=>w(e.uninstall)?Qo(t):Zo(t,{reinstall:w(e.reinstall)}));if(r)P({operation:w(e.uninstall)?`uninstall`:`install`,results:o});else for(let e of o)process.stdout.write(`${e.changed?`updated`:`skipped`} ${e.client} · ${e.path}\n`)}})}}),Ns=y({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=O(e),n=k(C(e.site)),r=ti(e.sitemaps),i=await Me({site:n,url:C(e.url),sitemaps:r.length?r:void 0,days:T(e.days),rowLimit:T(e[`row-limit`]),maxSitemapUrls:T(e[`max-sitemap-urls`]),itemsPerSection:T(e.limit),refresh:w(e.refresh)});t?P(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(`
62
62
  Representative URL Inspection candidates
63
- `),L([`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))}}),ks=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=k(e),n=await Ue({site:A(w(e.site)),days:E(e.days),limit:E(e.limit),minClicks:E(e[`min-clicks`]),minImpressions:E(e[`min-impressions`]),refresh:T(e.refresh),js:T(e.js)?!0:`auto`});t?F(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)))}}),As=b({meta:{name:`redirect-trace`,description:`Trace redirects and report final indexability/canonical issues`},args:{url:{type:`string`,required:!0,description:`URL to trace.`},"max-hops":{type:`string`,description:`Maximum redirect hops to follow. 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=await d({url:w(e.url)??``,maxHops:E(e[`max-hops`]),refresh:T(e.refresh),js:T(e.js)?!0:`auto`});k(e)?F(t):(K({title:`Redirect trace`,target:t.url,status:t.summary.issues.length>0?`warning`:t.summary.finalIndexable===void 0?`unknown`:`pass`,summary:t.summary.issues.length>0?t.summary.issues.join(`, `):`${t.summary.hops} redirect hops ended at HTTP ${t.summary.finalStatus}.`,metrics:[{label:`Final URL`,value:t.finalUrl},{label:`Final status`,value:t.summary.finalStatus},{label:`Indexable`,value:t.summary.finalIndexable===void 0?`Unknown`:t.summary.finalIndexable?`Yes`:`No`},{label:`Hops`,value:t.summary.hops}]}),L([`#`,`Status`,`URL`,`Next`],t.chain.map((e,t)=>[t+1,e.status,G(e.url,72),G(e.nextUrl??`-`,72)])),t.finalPage&&(process.stdout.write(`
63
+ `),I([`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))}}),Ps=y({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=O(e),n=await re({site:k(C(e.site)),days:T(e.days),limit:T(e.limit),minClicks:T(e[`min-clicks`]),minImpressions:T(e[`min-impressions`]),refresh:w(e.refresh),js:w(e.js)?!0:`auto`});t?P(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)))}}),Fs=y({meta:{name:`redirect-trace`,description:`Trace redirects and report final indexability/canonical issues`},args:{url:{type:`string`,required:!0,description:`URL to trace.`},"max-hops":{type:`string`,description:`Maximum redirect hops to follow. 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=await te({url:C(e.url)??``,maxHops:T(e[`max-hops`]),refresh:w(e.refresh),js:w(e.js)?!0:`auto`});O(e)?P(t):(K({title:`Redirect trace`,target:t.url,status:t.summary.issues.length>0?`warning`:t.summary.finalIndexable===void 0?`unknown`:`pass`,summary:t.summary.issues.length>0?t.summary.issues.join(`, `):`${t.summary.hops} redirect hops ended at HTTP ${t.summary.finalStatus}.`,metrics:[{label:`Final URL`,value:t.finalUrl},{label:`Final status`,value:t.summary.finalStatus},{label:`Indexable`,value:t.summary.finalIndexable===void 0?`Unknown`:t.summary.finalIndexable?`Yes`:`No`},{label:`Hops`,value:t.summary.hops}]}),I([`#`,`Status`,`URL`,`Next`],t.chain.map((e,t)=>[t+1,e.status,G(e.url,72),G(e.nextUrl??`-`,72)])),t.finalPage&&(process.stdout.write(`
64
64
  Final page
65
- `),I([[`Title`,t.finalPage.title??`-`],[`Canonical`,t.finalPage.canonical??`-`],[`Meta robots`,t.finalPage.metaRobots??`-`]])),Y(`Warnings`,t.warnings.slice(0,10)))}}),js=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=k(e),n=ei(w(e.property)),r=await Xt({property:n,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),maxRows:D(e[`max-rows`],`--max-rows`),resultLimit:D(e[`result-limit`],`--result-limit`),limit:D(e.limit,`--limit`),refresh:e.refresh===!0});if(t)F(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(`
65
+ `),F([[`Title`,t.finalPage.title??`-`],[`Canonical`,t.finalPage.canonical??`-`],[`Meta robots`,t.finalPage.metaRobots??`-`]])),Y(`Warnings`,t.warnings.slice(0,10)))}}),Is=y({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=O(e),n=ai(C(e.property)),r=await fn({property:n,startDate:C(e[`start-date`]),endDate:C(e[`end-date`]),maxRows:E(e[`max-rows`],`--max-rows`),resultLimit:E(e[`result-limit`],`--result-limit`),limit:E(e.limit,`--limit`),refresh:e.refresh===!0});if(t)P(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(`
66
66
  AI sources
67
67
  `),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(`
68
68
  Landing pages
69
69
  `),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(`
70
70
  Evidence warnings
71
- `);for(let e of r.dataSource.partialReasons)process.stdout.write(`- ${e}\n`)}process.stdout.write(`\nNote: ${r.summary.caveat}\n`)}}}),Ms=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=k(e),n=T(e.refresh),r=A(w(e.site)),i=await Te({site:r,days:D(e.days,`--days`),limit:D(e.limit,`--limit`),minImpressions:D(e[`min-impressions`],`--min-impressions`),brandTerms:[...O(e[`brand-terms`])??[]],includeBrand:T(e[`include-brand`]),refresh:n});t?F(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]))}}),Ns=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=k(e),n=A(w(e.site)),r=await ie({site:n,minImpressions:E(e[`min-impressions`]),includeBrand:T(e[`include-brand`])});t?F(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),Ea(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 Ps(e){return e>0?Ea(e):`n/a`}const Fs=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=k(e),n=T(e.refresh),r=w(e.comparison),i=D(e.days,`--days`),a=D(e.limit,`--limit`),o=D(e[`min-drop-pct`],`--min-drop-pct`),s=D(e[`min-previous-clicks`],`--min-previous-clicks`),c=D(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=A(w(e.site)),u=await Gt({site:l,days:i,limit:a,comparison:r,brandTerms:[...O(e[`brand-terms`])??[]],includeBrand:T(e[`include-brand`]),minDropPct:o,minPreviousClicks:s,minClickLoss:c,refresh:n});t?F(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)}`,`${Ps(e.previous.position)} -> ${Ps(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})))))}});function Is(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 Ls=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.`},...qi,...Ji,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=k(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:E(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 Ke({site:s,targetUrl:r,maxPages:o,startDate:w(e[`start-date`]),endDate:w(e[`end-date`]),refresh:n},{...await p({site:s,refresh:n}),progress:Is(!t&&process.stderr.isTTY)});if(t){F(c);return}let l={...r?{url:r}:{site:i},...o===void 0?{}:{"max-pages":o}};process.stdout.write(`${rn(c,{detail:V(e),offset:E(e.offset)??0,more:(e,t)=>Gi(`internal-links`,{...l,detail:e,offset:t})})}\n`)}}),Rs=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":Gr(`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=k(e),n=A(w(e.site)),r=await Bt({site:n,url:w(e.url)??``,days:E(e.days),limit:E(e.limit),minImpressions:E(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?F(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:Ja(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.
71
+ `);for(let e of r.dataSource.partialReasons)process.stdout.write(`- ${e}\n`)}process.stdout.write(`\nNote: ${r.summary.caveat}\n`)}}}),Ls=y({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=O(e),n=w(e.refresh),r=k(C(e.site)),i=await me({site:r,days:E(e.days,`--days`),limit:E(e.limit,`--limit`),minImpressions:E(e[`min-impressions`],`--min-impressions`),brandTerms:[...D(e[`brand-terms`])??[]],includeBrand:w(e[`include-brand`]),refresh:n});t?P(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:w(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]))}}),Rs=y({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=O(e),n=k(C(e.site)),r=await Wn({site:n,minImpressions:T(e[`min-impressions`]),includeBrand:w(e[`include-brand`])});t?P(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),ja(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 zs(e){return e>0?ja(e):`n/a`}const Bs=y({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=O(e),n=w(e.refresh),r=C(e.comparison),i=E(e.days,`--days`),a=E(e.limit,`--limit`),o=E(e[`min-drop-pct`],`--min-drop-pct`),s=E(e[`min-previous-clicks`],`--min-previous-clicks`),c=E(e[`min-click-loss`],`--min-click-loss`);if(r!==void 0&&r!==`previous-period`&&r!==`year-over-year`)throw new h(`INVALID_INPUT`,`--comparison must be previous-period or year-over-year.`);let l=k(C(e.site)),u=await ae({site:l,days:i,limit:a,comparison:r,brandTerms:[...D(e[`brand-terms`])??[]],includeBrand:w(e[`include-brand`]),minDropPct:o,minPreviousClicks:s,minClickLoss:c,refresh:n});t?P(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)}`,`${zs(e.previous.position)} -> ${zs(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})))))}});function Vs(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 Hs=y({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.`},...Qi,...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=O(e),n=w(e.refresh),r=C(e.url),i=C(e.site);if(!!r==!!i)throw new h(`INVALID_INPUT`,`Send --site to audit a whole site, or --url to find links to one page.`);let a=C(e[`max-pages`]),o=a===void 0?void 0:T(a);if(a!==void 0&&o===void 0)throw new h(`INVALID_INPUT`,`--max-pages is a whole number.`);let s=r??i,c=await Yt({site:s,targetUrl:r,maxPages:o,startDate:C(e[`start-date`]),endDate:C(e[`end-date`]),refresh:n},{...await f({site:s,refresh:n}),progress:Vs(!t&&process.stderr.isTTY)});if(t){P(c);return}let l={...r?{url:r}:{site:i},...o===void 0?{}:{"max-pages":o}};process.stdout.write(`${Ut(c,{detail:V(e),offset:T(e.offset)??0,more:(e,t)=>Xi(`internal-links`,{...l,detail:e,offset:t})})}\n`)}}),Us=y({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":Xr(`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=O(e),n=k(C(e.site)),r=await St({site:n,url:C(e.url)??``,days:T(e.days),limit:T(e.limit),minImpressions:T(e[`min-impressions`]),includeBrand:w(e[`include-brand`]),verifyContent:w(e[`verify-content`])!==!1,js:w(e.js)?!0:`auto`,refresh:w(e.refresh)});t?P(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:$a(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.
72
72
  `:`GSC rows were found, but none met the report criteria.
73
- `))}}),zs=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=k(e),n=A(w(e.site)),r=await bt({site:n,scope:w(e.scope),includeBrand:T(e[`include-brand`]),minImpressions:E(e[`min-impressions`]),limit:E(e.limit)});t?F(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??``}))))}}),Bs=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=k(e),n=E(e[`verify-limit`]),r=T(e[`verify-content`])===!0||n!==void 0,i=A(w(e.site)),o=await a({site:i,days:E(e.days),limit:E(e.limit),minImpressions:E(e[`min-impressions`]),brandTerms:[...O(e[`brand-terms`])??[]],includeBrand:T(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:T(e.js)?!0:void 0,rate:Zr(e),refresh:T(e.refresh)});t?F(o):(K({title:`Quick wins`,target:o.site,status:o.source.possiblyTruncated?`unknown`:`info`,summary:o.summary.verdict,metrics:[{label:`Eligible rows`,value:U(o.summary.eligibleRows)},{label:`Returned rows`,value:U(o.summary.returnedRows)},{label:`Query clusters`,value:U(o.summary.repeatedQueryGroups)},{label:`Template patterns`,value:U(o.summary.templatePatterns)},{label:`CTR click shortfall`,value:U(o.summary.returnedEstimatedCtrClickShortfall)},{label:`Brand queries`,value:o.summary.brandFiltering},{label:`Evidence`,value:o.dataStatus},{label:`Verification`,value:Da(o)}]}),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`,o.recommendations),Y(`Report caveats`,o.caveats),o.items.length&&(o.templateRecommendations.length&&(q([`Template`,`URLs`,`Rows`,`Shortfall`,`Impr`,`Action`],o.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`,o.templateRecommendations.map(e=>({label:e.templateLabel,context:`${U(e.urlCount)} URLs, ${U(e.totalEstimatedCtrClickShortfall)} heuristic CTR click shortfall`,action:`${e.action} ${e.evidence}`})))),o.groups.length&&(q([`Cluster`,`URLs`,`Rows`,`Shortfall`,`Impr`,`Sample URL`,`Action`],o.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`,o.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`],o.items.map(e=>[G(e.query,36),G(e.template.label,24),G(e.url,48),Ea(e.position),U(e.impressions),`${W(e.ctr)} / ${W(e.targetCtr)}`,U(e.estimatedCtrClickShortfall),Ja(e.contentVerification?.fetchDiagnostics),Ya(e.contentVerification?.classification),G(e.recommendation.action,64)])),J(`Top opportunity actions`,o.items.map(e=>({label:e.query,context:`${e.template.label}, pos ${Ea(e.position)}, ${U(e.impressions)} impressions`,action:e.recommendation.action})))))}}),Vs=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=k(e),n=E(e[`verify-limit`]),r=T(e[`verify-content`])===!0||n!==void 0,i=A(w(e.site)),a=await In({site:i,range:E(e.days),minImpressions:E(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:Zr(e),refresh:T(e.refresh)});t?F(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:Da(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),Ja(e.fetchDiagnostics),Ya(e.contentVerification?.classification),e.recommendation.action])),J(`Top second-page actions`,a.items.map(e=>({label:e.primaryQuery,context:`${e.template.label}, pos ${Ea(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.
74
- `),process.stdout.write(`${a.ledgerSummary}\n`)))}}),Hs=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 ht({url:w(e.url)??``,site:w(e.site),js:T(e.js)?!0:`auto`,refresh:T(e.refresh)});k(e)?F(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??`Missing`},{label:`Meta description`,value:t.page.metaDescription??`Missing`},{label:`Words`,value:t.page.wordCount},{label:`Fetch`,value:Ja(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 Us(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 Ws(e){return e?e.displayValue??String(e.value??`not measured`):`not measured`}function Gs(e){if(!e)return`not available`;let t=e.unit===`milliseconds`?`ms`:``;return`${e.p75}${t} (${e.rating})`}const Ks=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=k(e),n=w(e.url);if(!n)throw new g(`INVALID_INPUT`,`No URL given. Pass --url.`);let r=await Nn({url:n,strategy:Us(e.strategy),lighthouseBin:w(e[`lighthouse-bin`]),cruxApiKey:w(e[`crux-key`]),refresh:T(e.refresh),includeRaw:t&&T(e.raw)});t?F(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:Ws(r.metrics.firstContentfulPaint)},{label:`LCP`,value:Ws(r.metrics.largestContentfulPaint)},{label:`TBT`,value:Ws(r.metrics.totalBlockingTime)},{label:`CLS`,value:Ws(r.metrics.cumulativeLayoutShift)},{label:`INP`,value:Ws(r.metrics.interactionToNextPaint)},{label:`Server response`,value:Ws(r.metrics.serverResponseTime)},{label:`Fallback fetch`,value:Ws(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:Gs(r.fieldData?.metrics.largestContentfulPaint)},{label:`Field INP p75`,value:Gs(r.fieldData?.metrics.interactionToNextPaint)},{label:`Field CLS p75`,value:Gs(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))}})}}),qs=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 l();k(e)?(F(t),t.ok||(process.exitCode=1)):(Fi(`SEO doctor`,Di(t.checks)),process.stdout.write(`
75
- `),Ii(t.checks),process.stdout.write(`\nChecked ${t.generatedAt}\n`),t.ok||(process.exitCode=1))}}),Js=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},Ys=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=k(e),n=Js(e.dimension),r=D(e.days,`--days`),i=D(e.compare,`--compare`),a=D(e.limit,`--limit`),o=D(e[`unmatched-limit`],`--unmatched-limit`),s=D(e[`max-rows`],`--max-rows`),c=A(w(e.site)),l=await Oe({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?F(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}`}]}),L([`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(`
73
+ `))}}),Ws=y({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=O(e),n=k(C(e.site)),r=await Fn({site:n,scope:C(e.scope),includeBrand:w(e[`include-brand`]),minImpressions:T(e[`min-impressions`]),limit:T(e.limit)});t?P(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??``}))))}}),Gs=y({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=O(e),n=T(e[`verify-limit`]),r=w(e[`verify-content`])===!0||n!==void 0,i=k(C(e.site)),a=await Fe({site:i,days:T(e.days),limit:T(e.limit),minImpressions:T(e[`min-impressions`]),brandTerms:[...D(e[`brand-terms`])??[]],includeBrand:w(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:w(e.js)?!0:void 0,rate:ni(e),refresh:w(e.refresh)});t?P(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:Ma(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),ja(e.position),U(e.impressions),`${W(e.ctr)} / ${W(e.targetCtr)}`,U(e.estimatedCtrClickShortfall),$a(e.contentVerification?.fetchDiagnostics),eo(e.contentVerification?.classification),G(e.recommendation.action,64)])),J(`Top opportunity actions`,a.items.map(e=>({label:e.query,context:`${e.template.label}, pos ${ja(e.position)}, ${U(e.impressions)} impressions`,action:e.recommendation.action})))))}}),Ks=y({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=O(e),n=T(e[`verify-limit`]),r=w(e[`verify-content`])===!0||n!==void 0,i=k(C(e.site)),a=await d({site:i,range:T(e.days),minImpressions:T(e[`min-impressions`]),limit:C(e.limit)?Number(C(e.limit)):10,includeBrand:w(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:w(e.js)?!0:void 0,rate:ni(e),refresh:w(e.refresh)});t?P(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:Ma(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),$a(e.fetchDiagnostics),eo(e.contentVerification?.classification),e.recommendation.action])),J(`Top second-page actions`,a.items.map(e=>({label:e.primaryQuery,context:`${e.template.label}, pos ${ja(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.
74
+ `),process.stdout.write(`${a.ledgerSummary}\n`)))}}),qs=y({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 Zt({url:C(e.url)??``,site:C(e.site),js:w(e.js)?!0:`auto`,refresh:w(e.refresh)});O(e)?P(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??`Missing`},{label:`Meta description`,value:t.page.metaDescription??`Missing`},{label:`Words`,value:t.page.wordCount},{label:`Fetch`,value:$a(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 Js(e){let t=C(e)??`mobile`;if(t!==`mobile`&&t!==`desktop`)throw new h(`INVALID_INPUT`,`Invalid --strategy. Use mobile or desktop.`);return t}function Ys(e){return e?e.displayValue??String(e.value??`not measured`):`not measured`}function Xs(e){if(!e)return`not available`;let t=e.unit===`milliseconds`?`ms`:``;return`${e.p75}${t} (${e.rating})`}const Zs=y({meta:{name:`perf`,description:`Audit lab performance and field Core Web Vitals`},subCommands:{audit:y({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=O(e),n=C(e.url);if(!n)throw new h(`INVALID_INPUT`,`No URL given. Pass --url.`);let r=await qe({url:n,strategy:Js(e.strategy),lighthouseBin:C(e[`lighthouse-bin`]),cruxApiKey:C(e[`crux-key`]),refresh:w(e.refresh),includeRaw:t&&w(e.raw)});t?P(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:Ys(r.metrics.firstContentfulPaint)},{label:`LCP`,value:Ys(r.metrics.largestContentfulPaint)},{label:`TBT`,value:Ys(r.metrics.totalBlockingTime)},{label:`CLS`,value:Ys(r.metrics.cumulativeLayoutShift)},{label:`INP`,value:Ys(r.metrics.interactionToNextPaint)},{label:`Server response`,value:Ys(r.metrics.serverResponseTime)},{label:`Fallback fetch`,value:Ys(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:Xs(r.fieldData?.metrics.largestContentfulPaint)},{label:`Field INP p75`,value:Xs(r.fieldData?.metrics.interactionToNextPaint)},{label:`Field CLS p75`,value:Xs(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))}})}}),Qs=y({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 Nn();O(e)?(P(t),t.ok||(process.exitCode=1)):(Bi(`SEO doctor`,Mi(t.checks)),process.stdout.write(`
75
+ `),Vi(t.checks),process.stdout.write(`\nChecked ${t.generatedAt}\n`),t.ok||(process.exitCode=1))}}),$s=e=>{let t=C(e)??`page`;if(t!==`page`&&t!==`query`&&t!==`country`&&t!==`device`)throw Error(`Invalid --dimension. Use page, query, country, or device.`);return t},ec=y({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=O(e),n=$s(e.dimension),r=E(e.days,`--days`),i=E(e.compare,`--compare`),a=E(e.limit,`--limit`),o=E(e[`unmatched-limit`],`--unmatched-limit`),s=E(e[`max-rows`],`--max-rows`),c=k(C(e.site)),l=await Ce({site:c,dimension:n,days:r,compareDays:i,startDate:C(e[`start-date`]),endDate:C(e[`end-date`]),limit:a,unmatchedLimit:o,maxRows:s,refresh:w(e.refresh)});t?P(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}`}]}),I([`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(`
76
76
  One-window evidence (not treated as zero)
77
- `),L([`Segment`,`Retained in`,`Clicks`,`Impressions`],l.unmatchedSegments.map(e=>[e.key,e.retainedIn,e.clicks,e.impressions]))),Y(`Warnings`,l.warnings))}});function Xs(e){return`${U(e)} ${e===1?`row`:`rows`}`}const Zs=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=k(e),n=E(e[`verify-limit`]),r=T(e[`verify-content`])===!0||n!==void 0,i=A(w(e.site)),a=await Jt({site:i,days:E(e.days),minImpressions:E(e[`min-impressions`]),limit:E(e.limit),includeBrand:T(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:T(e.js)?!0:void 0,rate:Zr(e),refresh:T(e.refresh)});t?F(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),Ea(e.impressionWeightedPosition),e.actionScope,G(e.recommendation.action,72)])),J(`Top striking-distance group actions`,a.groups.map(e=>({label:e.label,context:`${Xs(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),Ea(e.position),e.priority.score,Ja(e.contentVerification?.fetchDiagnostics),Ya(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 ${Ea(e.position)}, ${U(e.impressions)} impressions`,action:e.recommendation.action})))):process.stdout.write(`No striking-distance opportunities matched these filters.
78
- `))}});function Qs(e){return e===`keychain`?`system keychain`:e===`file`?`private local file`:e??`missing`}function $s(e){return e===null?`unavailable`:`$${(e/1e6).toFixed(2)}`}function ec(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 tc=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(!P({json:k(e)}))throw new g(`AUTH_REQUIRED`,`Run \`seo providers ahrefs connect\` in a terminal. Agents and CI can set ${Ln}.`);Sr(`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=B(await Er({message:`Ahrefs API v3 key`,validate:e=>e?.trim()?void 0:`API key is required`})),n=await new cn({apiKey:t}).limitsAndUsage(),r=await ce(t);x(`${n.subscription} subscription. API key units: ${ec(n.apiKeyUnits)}.`,`Connection verified`),S(`Saved in the ${Qs(r)}. Run seo providers ahrefs status --check to verify it again.`)}}),nc=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 Xe(),n=!!e.check,r=n&&t?await new cn().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`}};k(e)?F(i):I([[`Connected`,i.connected?`yes`:`no`],[`API version`,i.apiVersion?`Version 3`:`not connected`],[`Credential`,Qs(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`,ec(r.apiKeyUnits)],[`Workspace units`,ec(r.workspaceUnits)],[`Usage resets`,r.usageResetsAt],[`Key expires`,r.apiKeyExpiresAt]]:[]])}}),rc=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 o();let t=!!process.env[Ln]?.trim(),n={savedCredentialRemoved:!0,environmentCredential:t?`active`:`missing`,note:t?`The environment variable was not changed. Clear ${Ln} to fully disconnect.`:`Ahrefs is disconnected.`};k(e)?F(n):process.stdout.write(`${n.note}\n`)}}),ic=b({meta:{name:`ahrefs`,description:`Connect Ahrefs for optional search and link data`},subCommands:{connect:tc,status:nc,disconnect:rc}}),ac="Run `seo providers bing connect` with a new API key.",oc=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(!P({json:k(e)}))throw new g(`AUTH_REQUIRED`,`Run \`seo providers bing connect\` in a terminal. Agents and CI can set ${h}.`);Sr(`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 n=B(await Er({message:`Bing Webmaster API key`,validate:e=>e?.trim()?void 0:`API key is required`})),r=await Ot(t({apiKey:n},{signIn:ac})),i=await Re(n);x(`${r.filter(e=>e.verified).length} verified sites.`,`Connection verified`),S(`Saved in the ${Qs(i)}.`)}}),sc=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 n=await be(),r=n?await Ot(t({apiKey:n.apiKey},{signIn:ac})):null,i={connected:!!n,credentialSource:n?.source??null,sites:r?.filter(e=>e.verified).map(e=>e.url)??[]};k(e)?F(i):process.stdout.write(n?`Connected (${Qs(n.source)}). Verified sites: ${i.sites.join(`, `)||`none`}.\n`:"Not connected. Run `seo providers bing connect`.\n")}}),cc=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 de();let t=!!process.env[h]?.trim(),n=t?`The saved key is removed. Clear ${h} to fully disconnect.`:`Bing is disconnected.`;k(e)?F({removed:!0,environment:t}):process.stdout.write(`${n}\n`)}}),lc=b({meta:{name:`bing`,description:`Connect Bing Webmaster Tools for Bing search data`},subCommands:{connect:oc,status:sc,disconnect:cc}}),uc=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(!P({json:k(e)}))throw new g(`AUTH_REQUIRED`,`Run \`seo providers dataforseo connect\` in a terminal. Agents and CI can set ${r} and ${Ut}.`);Sr(`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=B(await Or({message:`DataForSEO API login`,validate:e=>e?.trim()?void 0:`API login is required`})),n=B(await Er({message:`DataForSEO API password`,validate:e=>e?void 0:`API password is required`})),i={login:t.trim(),password:n},a=await new At({credentials:()=>i}).userData(),o=await Me(i);x(`${a.login} is connected with an account balance of ${$s(a.balanceMicros)}.`,`Connection verified`),S(`Saved in the ${Qs(o)}. Run seo providers dataforseo status --check to verify it again.`)}}),dc=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 Ee(),n=!!e.check,r=n&&t?await new At().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`}};k(e)?F(i):I([[`Connected`,i.connected?`yes`:`no`],[`Credential`,Qs(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`,$s(r.balanceMicros)]]:[]])}}),fc=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 Ce();let t=!!process.env[r]?.trim(),n=!!process.env[Ut],i={savedCredentialsRemoved:!0,environmentCredentials:t&&n?`active`:t||n?`partial`:`missing`,note:t||n?`Environment variables were not changed. Clear ${r} and ${Ut} to fully disconnect.`:`DataForSEO is disconnected.`};k(e)?F(i):process.stdout.write(`${i.note}\n`)}}),pc=b({meta:{name:`dataforseo`,description:`Connect DataForSEO for optional search data`},subCommands:{connect:uc,status:dc,disconnect:fc}});function mc(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 hc(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 gc(e){let t=await Be(),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 _c(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 vc(){return Tn()}const yc={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 vc();k(e)?F(t):t.installed.length>0?L([`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.
79
- `)}}),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 dt(t);k(e)?F(n):I([[`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=k(e),r=T(e.yes),i=P({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 Qt(t)}catch(e){throw new g(`INVALID_INPUT`,e instanceof Error?e.message:String(e))}if(!r&&(Sr(`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(`
80
- `),`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`),!B(await xr({message:`Install ${a.package}@${a.version}?`,initialValue:!1})))){S(`Provider was not installed.`);return}let o;try{o=await It(a)}catch(e){throw new g(`PROVIDER_UNAVAILABLE`,e instanceof Error?e.message:String(e))}n?F({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=k(e),r=T(e.yes),i=P({json:n});if(!r&&!i)throw new g(`INVALID_INPUT`,`Pass --yes to remove a provider extension in JSON or CI mode.`);if(!r&&!B(await xr({message:`Remove provider ${t}?`,initialValue:!1})))return;let a=await Nt(t);if(!a)throw new g(`INVALID_INPUT`,`Provider ${t} is not installed.`);n?F({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=k(e),r=P({json:n}),i=await gc(t),a={...vt(t),...mc(w(e.account))},o={};if(r){Sr(`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=B(await Or({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=B(await Er({message:e.label,validate:t=>e.required!==!1&&!t?.trim()?`${e.label} is required`:void 0}));t?.trim()&&(o[e.id]=t.trim())}}a=_c(i,a);let s={...o};Object.keys(s).length===0&&(s=await c({providerId:t,account:a,fields:i.connection.fields})),await Se({providerId:t,account:a,credentials:s}),Object.keys(o).length>0&&await Qe({providerId:t,account:a,credentials:o}),jn(t,a);let l={provider:t,connected:!0,account:a,capabilities:(i.capabilities??[]).map(e=>e.id),actions:(i.actions??[]).map(e=>e.id)};n?F(l):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 gc(t),r=vt(t),i;try{i=await c({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 Se({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`};k(e)?F(s):L([`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 gc(t);let n=vt(t);await zn({providerId:t,account:n}),Pn(t);let r={provider:t,disconnected:!0,note:`Environment variables were not changed.`};k(e)?F(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 gc(t);let r={...vt(t),...mc(w(e.account))};F(await Ve({providerId:t,actionId:n,account:r,params:hc(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 vc(),n={ok:t.installed.every(e=>e.loadStatus===`ready`),installed:t.installed};k(e)?F(n):n.installed.length===0?process.stdout.write(`No provider extensions are installed.
81
- `):L([`Provider`,`Package`,`Version`,`Status`],n.installed.map(e=>[e.id,e.package,e.version,e.error??e.loadStatus]))}})},bc=b({meta:{name:`providers`,description:`Connect optional data providers`},subCommands:{...yc,ahrefs:ic,bing:lc,dataforseo:pc}}),xc={"ai-search":`AI search`,crawl:`Crawling and technical checks`,diagnosis:`Diagnosis`,monitoring:`Monitoring`,opportunities:`Opportunities`,reporting:`Reporting`,setup:`Setup`,workflows:`Workflows`};function Sc(e){let t=w(e);if(t){if(!yn.includes(t))throw new g(`INVALID_INPUT`,`Unknown report category: ${t}. Choose ${yn.join(`, `)}.`);return t}}async function Cc(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 wc(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 Tc(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 Ec=b({meta:{name:`list`,description:`List report ids available to the CLI and MCP server`},args:{category:{type:`string`,description:`Filter by category: ${yn.join(`, `)}.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=Sc(e.category),n=an(t);k(e)?F({reports:n,categories:yn}):(Ri(n,{noun:`report`,categoryLabels:xc}),process.stdout.write(`
82
- `),R({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>`}))}}),Dc=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=zt(w(e.id)??``);k(e)?F({report:t}):(Fi(t.name,t.description),process.stdout.write(`
83
- `),I([[`ID`,t.id],[`Category`,t.category],[`Outcome`,t.outcome]]),process.stdout.write(`
84
- `),Bi(`Use when`,t.useWhen),process.stdout.write(`
85
- `),Bi(`Avoid when`,t.avoidWhen),process.stdout.write(`
86
- `),Bi(`Read in order`,t.readOrder),process.stdout.write(`
87
- `),Bi(`Do not claim`,t.doNotClaim),process.stdout.write(`
88
- `),z(`Verify`,t.verify),process.stdout.write(`
89
- `),R({title:`Implement findings`,body:t.agentWorkflow.completion,command:t.agentWorkflow.actionView.cli}),t.related.length>0&&(process.stdout.write(`
90
- `),Bi(`Related reports`,t.related.map(e=>`${e.id}: ${e.reason}`))),process.stdout.write(`
77
+ `),I([`Segment`,`Retained in`,`Clicks`,`Impressions`],l.unmatchedSegments.map(e=>[e.key,e.retainedIn,e.clicks,e.impressions]))),Y(`Warnings`,l.warnings))}});function tc(e){return`${U(e)} ${e===1?`row`:`rows`}`}const nc=y({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=O(e),n=T(e[`verify-limit`]),r=w(e[`verify-content`])===!0||n!==void 0,i=k(C(e.site)),a=await ke({site:i,days:T(e.days),minImpressions:T(e[`min-impressions`]),limit:T(e.limit),includeBrand:w(e[`include-brand`]),verifyContent:r,verifyLimit:n,js:w(e.js)?!0:void 0,rate:ni(e),refresh:w(e.refresh)});t?P(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),ja(e.impressionWeightedPosition),e.actionScope,G(e.recommendation.action,72)])),J(`Top striking-distance group actions`,a.groups.map(e=>({label:e.label,context:`${tc(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),ja(e.position),e.priority.score,$a(e.contentVerification?.fetchDiagnostics),eo(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 ${ja(e.position)}, ${U(e.impressions)} impressions`,action:e.recommendation.action})))):process.stdout.write(`No striking-distance opportunities matched these filters.
78
+ `))}});function rc(e){return e===`keychain`?`system keychain`:e===`file`?`private local file`:e??`missing`}function ic(e){return e===null?`unavailable`:`$${(e/1e6).toFixed(2)}`}function ac(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 oc=y({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(!N({json:O(e)}))throw new h(`AUTH_REQUIRED`,`Run \`seo providers ahrefs connect\` in a terminal. Agents and CI can set ${o}.`);Dr(`Connect Ahrefs`),b(`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 jr({message:`Ahrefs API v3 key`,validate:e=>e?.trim()?void 0:`API key is required`})),n=await new dn({apiKey:t}).limitsAndUsage(),r=await Je(t);b(`${n.subscription} subscription. API key units: ${ac(n.apiKeyUnits)}.`,`Connection verified`),x(`Saved in the ${rc(r)}. Run seo providers ahrefs status --check to verify it again.`)}}),sc=y({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 le(),n=!!e.check,r=n&&t?await new dn().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`}};O(e)?P(i):F([[`Connected`,i.connected?`yes`:`no`],[`API version`,i.apiVersion?`Version 3`:`not connected`],[`Credential`,rc(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`,ac(r.apiKeyUnits)],[`Workspace units`,ac(r.workspaceUnits)],[`Usage resets`,r.usageResetsAt],[`Key expires`,r.apiKeyExpiresAt]]:[]])}}),cc=y({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 Ze();let t=!!process.env[o]?.trim(),n={savedCredentialRemoved:!0,environmentCredential:t?`active`:`missing`,note:t?`The environment variable was not changed. Clear ${o} to fully disconnect.`:`Ahrefs is disconnected.`};O(e)?P(n):process.stdout.write(`${n.note}\n`)}}),lc=y({meta:{name:`ahrefs`,description:`Connect Ahrefs for optional search and link data`},subCommands:{connect:oc,status:sc,disconnect:cc}}),uc="Run `seo providers bing connect` with a new API key.",dc=y({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(!N({json:O(e)}))throw new h(`AUTH_REQUIRED`,`Run \`seo providers bing connect\` in a terminal. Agents and CI can set ${fe}.`);Dr(`Connect Bing Webmaster Tools`),b(`In Bing Webmaster Tools, open Settings, then API access, and copy the API key. Bing data is free.`,`API key`);let t=z(await jr({message:`Bing Webmaster API key`,validate:e=>e?.trim()?void 0:`API key is required`})),n=await Ht(vn({apiKey:t},{signIn:uc})),r=await Hn(t);b(`${n.filter(e=>e.verified).length} verified sites.`,`Connection verified`),x(`Saved in the ${rc(r)}.`)}}),fc=y({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 ze(),n=t?await Ht(vn({apiKey:t.apiKey},{signIn:uc})):null,r={connected:!!t,credentialSource:t?.source??null,sites:n?.filter(e=>e.verified).map(e=>e.url)??[]};O(e)?P(r):process.stdout.write(t?`Connected (${rc(t.source)}). Verified sites: ${r.sites.join(`, `)||`none`}.\n`:"Not connected. Run `seo providers bing connect`.\n")}}),pc=y({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 xe();let t=!!process.env[fe]?.trim(),n=t?`The saved key is removed. Clear ${fe} to fully disconnect.`:`Bing is disconnected.`;O(e)?P({removed:!0,environment:t}):process.stdout.write(`${n}\n`)}}),mc=y({meta:{name:`bing`,description:`Connect Bing Webmaster Tools for Bing search data`},subCommands:{connect:dc,status:fc,disconnect:pc}}),hc=y({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(!N({json:O(e)}))throw new h(`AUTH_REQUIRED`,`Run \`seo providers dataforseo connect\` in a terminal. Agents and CI can set ${Wt} and ${we}.`);Dr(`Connect DataForSEO`),b(`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 Nr({message:`DataForSEO API login`,validate:e=>e?.trim()?void 0:`API login is required`})),n=z(await jr({message:`DataForSEO API password`,validate:e=>e?void 0:`API password is required`})),r={login:t.trim(),password:n},i=await new jt({credentials:()=>r}).userData(),a=await m(r);b(`${i.login} is connected with an account balance of ${ic(i.balanceMicros)}.`,`Connection verified`),x(`Saved in the ${rc(a)}. Run seo providers dataforseo status --check to verify it again.`)}}),gc=y({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 Ne(),n=!!e.check,r=n&&t?await new jt().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`}};O(e)?P(i):F([[`Connected`,i.connected?`yes`:`no`],[`Credential`,rc(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`,ic(r.balanceMicros)]]:[]])}}),_c=y({meta:{name:`disconnect`,description:`Remove saved DataForSEO credentials`},args:{json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{await De();let t=!!process.env[Wt]?.trim(),n=!!process.env[we],r={savedCredentialsRemoved:!0,environmentCredentials:t&&n?`active`:t||n?`partial`:`missing`,note:t||n?`Environment variables were not changed. Clear ${Wt} and ${we} to fully disconnect.`:`DataForSEO is disconnected.`};O(e)?P(r):process.stdout.write(`${r.note}\n`)}}),vc=y({meta:{name:`dataforseo`,description:`Connect DataForSEO for optional search data`},subCommands:{connect:hc,status:gc,disconnect:_c}});function yc(e){if(!e)return{};let t;try{t=JSON.parse(e)}catch{throw new h(`INVALID_INPUT`,`--account must be a JSON object.`)}if(!t||Array.isArray(t)||typeof t!=`object`)throw new h(`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 h(`INVALID_INPUT`,`--account must contain at most 20 bounded string fields.`);return Object.fromEntries(n.map(([e,t])=>[e,t.trim()]))}function bc(e){if(!e)return{};let t;try{t=JSON.parse(e)}catch{throw new h(`INVALID_INPUT`,`--params must be a JSON object.`)}if(!t||Array.isArray(t)||typeof t!=`object`)throw new h(`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 h(`INVALID_INPUT`,`--params must be a JSON object smaller than 64 KiB.`);return Object.fromEntries(n)}async function xc(e){let t=await de(),n=t.registry.get(e);if(n)return n;let r=t.failures.find(t=>t.id===e);throw r?new h(`INVALID_INPUT`,`Provider ${e} could not load: ${r.message}`):new h(`INVALID_INPUT`,`Provider ${e} is not installed.`)}function Sc(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 h(`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 h(`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 h(`INVALID_INPUT`,`${t.label} is required.`);return i}async function Cc(){return An()}const wc={list:y({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 Cc();O(e)?P(t):t.installed.length>0?I([`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.
79
+ `)}}),describe:y({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=C(e.id)??``,n=await ft(t);O(e)?P(n):F([[`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:y({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=C(e.package)??``,n=O(e),r=w(e.yes),i=N({json:n});if(!r&&!i)throw new h(`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 en(t)}catch(e){throw new h(`INVALID_INPUT`,e instanceof Error?e.message:String(e))}if(!r&&(Dr(`Install provider package`),b([`${a.package}@${a.version}`,`Publisher: ${a.publisher??`not supplied by npm`}`,`Repository: ${a.repository??`not supplied by npm`}`,`Integrity: ${a.integrity}`].join(`
80
+ `),`Package`),b(`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 Er({message:`Install ${a.package}@${a.version}?`,initialValue:!1})))){x(`Provider was not installed.`);return}let o;try{o=await Lt(a)}catch(e){throw new h(`PROVIDER_UNAVAILABLE`,e instanceof Error?e.message:String(e))}n?P({installed:o,package:a}):x(`Installed provider ${o.id} from ${o.package}@${o.version}.`)}}),remove:y({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=C(e.id)??``,n=O(e),r=w(e.yes),i=N({json:n});if(!r&&!i)throw new h(`INVALID_INPUT`,`Pass --yes to remove a provider extension in JSON or CI mode.`);if(!r&&!z(await Er({message:`Remove provider ${t}?`,initialValue:!1})))return;let a=await Pt(t);if(!a)throw new h(`INVALID_INPUT`,`Provider ${t} is not installed.`);n?P({removed:a}):process.stdout.write(`Removed ${t}.\n`)}}),connect:y({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=C(e.id)??``,n=O(e),r=N({json:n}),i=await xc(t),a={...vt(t),...yc(C(e.account))},o={};if(r){Dr(`Connect ${i.displayName}`),i.connection.verificationNotice&&b(i.connection.verificationNotice,`Connection check`);for(let e of i.connection.fields){if(e.kind===`account`){let t=z(await Nr({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 jr({message:e.label,validate:t=>e.required!==!1&&!t?.trim()?`${e.label} is required`:void 0}));t?.trim()&&(o[e.id]=t.trim())}}a=Sc(i,a);let s={...o};Object.keys(s).length===0&&(s=await nt({providerId:t,account:a,fields:i.connection.fields})),await $e({providerId:t,account:a,credentials:s}),Object.keys(o).length>0&&await ce({providerId:t,account:a,credentials:o}),In(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?P(c):x(`Connected ${i.displayName}. Run seo providers describe ${t} to see what it can do.`)}}),status:y({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=C(e.id)??``,n=await xc(t),r=vt(t),i;try{i=await nt({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=w(e.check);if(o&&!a)throw new h(`AUTH_REQUIRED`,`Provider ${t} is not connected. Run \`seo providers connect ${t}\`.`);o&&i&&await $e({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`};O(e)?P(s):I([`Provider`,`Connected`,`Capabilities`,`Check`],[[n.displayName,a?`yes`:`no`,s.capabilities.join(`, `),s.check]])}}),disconnect:y({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=C(e.id)??``;await xc(t);let n=vt(t);await Xe({providerId:t,account:n}),zn(t);let r={provider:t,disconnected:!0,note:`Environment variables were not changed.`};O(e)?P(r):process.stdout.write(`Disconnected ${t}. ${r.note}\n`)}}),run:y({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=C(e.id)??``,n=C(e.action)??``;await xc(t);let r={...vt(t),...yc(C(e.account))};P(await He({providerId:t,actionId:n,account:r,params:bc(C(e.params)),refresh:w(e.refresh)}))}}),doctor:y({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 Cc(),n={ok:t.installed.every(e=>e.loadStatus===`ready`),installed:t.installed};O(e)?P(n):n.installed.length===0?process.stdout.write(`No provider extensions are installed.
81
+ `):I([`Provider`,`Package`,`Version`,`Status`],n.installed.map(e=>[e.id,e.package,e.version,e.error??e.loadStatus]))}})},Tc=y({meta:{name:`providers`,description:`Connect optional data providers`},subCommands:{...wc,ahrefs:lc,bing:mc,dataforseo:vc}}),Ec={"ai-search":`AI search`,crawl:`Crawling and technical checks`,diagnosis:`Diagnosis`,monitoring:`Monitoring`,opportunities:`Opportunities`,reporting:`Reporting`,setup:`Setup`,workflows:`Workflows`};function Dc(e){let t=C(e);if(t){if(!Cn.includes(t))throw new h(`INVALID_INPUT`,`Unknown report category: ${t}. Choose ${Cn.join(`, `)}.`);return t}}async function Oc(e,t){let n=C(e),r=C(t);if(n&&r)throw new h(`INVALID_INPUT`,`Use either --params or --params-file, not both.`);if(!n&&!r)return{};let i=n??await v(r??``,`utf8`),a;try{a=JSON.parse(i)}catch{throw new h(`INVALID_INPUT`,`Report parameters must be valid JSON.`)}if(!a||typeof a!=`object`||Array.isArray(a))throw new h(`INVALID_INPUT`,`Report parameters must be an object.`);return a}function kc(e){if(!e.isError)return;let t=e.structuredContent;throw new h(t?.error?.code??`INTERNAL_ERROR`,t?.error?.message??`The report could not be completed.`)}function Ac(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 jc=y({meta:{name:`list`,description:`List report ids available to the CLI and MCP server`},args:{category:{type:`string`,description:`Filter by category: ${Cn.join(`, `)}.`},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=Dc(e.category),n=sn(t);O(e)?P({reports:n,categories:Cn}):(Ui(n,{noun:`report`,categoryLabels:Ec}),process.stdout.write(`
82
+ `),L({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>`}))}}),Mc=y({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=Bt(C(e.id)??``);O(e)?P({report:t}):(Bi(t.name,t.description),process.stdout.write(`
83
+ `),F([[`ID`,t.id],[`Category`,t.category],[`Outcome`,t.outcome]]),process.stdout.write(`
84
+ `),Gi(`Use when`,t.useWhen),process.stdout.write(`
85
+ `),Gi(`Avoid when`,t.avoidWhen),process.stdout.write(`
86
+ `),Gi(`Read in order`,t.readOrder),process.stdout.write(`
87
+ `),Gi(`Do not claim`,t.doNotClaim),process.stdout.write(`
88
+ `),R(`Verify`,t.verify),process.stdout.write(`
89
+ `),L({title:`Implement findings`,body:t.agentWorkflow.completion,command:t.agentWorkflow.actionView.cli}),t.related.length>0&&(process.stdout.write(`
90
+ `),Gi(`Related reports`,t.related.map(e=>`${e.id}: ${e.reason}`))),process.stdout.write(`
91
91
  Parameters
92
- `),Vi(Tc(t.inputSchema)),process.stdout.write(`
93
- `),R({title:`Need the exact schema?`,command:`seo reports describe ${t.id} --json`}))}}),Oc=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 Cc(e.params,e[`params-file`]),r=await mt(t,n,{view:T(e[`actions-only`])?`actions`:`full`});if(wc(r),k(e))F(r.structuredContent??{});else for(let e of r.content)process.stdout.write(`${e.text}\n`)}}),kc=b({meta:{name:`reports`,description:`Discover and run the complete report catalog`},subCommands:{list:Ec,describe:Dc,run:Oc}}),Ac=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=gt().filter(e=>!t||e.category===t);k(e)?F({rules:n}):Ri(n.map(e=>({id:e.id,category:e.category,name:`${e.title} · ${e.defaultSeverity}`})),{noun:`rule`})}}),jc=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=Vt(t);if(!n)throw Error(`Unknown rule: ${t}`);k(e)?F(n):(I([[`Rule`,n.id],[`Title`,n.title],[`Category`,n.category],[`Severity`,n.defaultSeverity]]),process.stdout.write(`
94
- `),z(`Why it matters`,n.whyItMatters),process.stdout.write(`
95
- `),z(`How to fix`,n.howToFix),process.stdout.write(`
96
- `),z(`Impact if ignored`,n.impactIfIgnored),process.stdout.write(`
97
- `),z(`How to verify`,n.howToVerify))}});function Mc(){return Fc(`skills`,process.env.SEO_SKILLS_DIR)}function Nc(){return Fc(`evals`,process.env.SEO_EVALS_DIR)}function Pc(){return Fc(`site-kit`)}function Fc(e,t){if(t)return Jn(t);let n=Gn(cr(import.meta.url));for(let t=0;t<6;t+=1){let t=_(n,e);if(v(_(t,`README.md`)))return t;n=Gn(n)}throw new g(`INTERNAL_ERROR`,`Packaged ${e} could not be found. Reinstall \`seo\` and try again.`)}function Ic(e){return tr(_(e,`SKILL.md`),`utf8`).match(/^description:\s*(.+)$/m)?.[1]?.trim()??``}const Lc=[[`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`]],Rc=/* @__PURE__ */ new Set([`node_modules`,`dist`,`.astro`,`.wrangler`]);function zc(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``)}function Bc(e){return zc(Wn(e)).split(`-`).filter(Boolean).map(e=>`${e[0]?.toUpperCase()}${e.slice(1)}`).join(` `)}function Vc(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 Hc(e,t){let n=JSON.parse(await y(e,`utf8`));t(n),await pr(e,`${JSON.stringify(n,null,2)}\n`)}function Uc(){return Co(`pnpm`,[`--version`],{stdio:`ignore`}).status===0?`pnpm`:`npm`}const Wc=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=k(e),n=Jn(String(e.folder));if(v(n)&&(await dr(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()||Bc(n),i=Vc(w(e.domain)),a=zc(Wn(n))||`site`,o=Bn(16).toString(`hex`),s=_(Pc(),`starter`);await lr(s,n,{recursive:!0,filter:e=>!qn(s,e).split(Yn).some(e=>Rc.has(e))}),await fr(_(n,`gitignore`),_(n,`.gitignore`)),await Hc(_(n,`site.config.json`),e=>{e.name=r,e.domain=i,e.indexNowKey=o}),await pr(_(n,`public`,`${o}.txt`),o),await Hc(_(n,`package.json`),e=>{e.name=a;let t=e.devDependencies;t.seo=`^${oe}`});let c=_(n,`wrangler.jsonc`);await pr(c,(await y(c,`utf8`)).replace(`"name": "example-site"`,`"name": ${JSON.stringify(a)}`));let l=_(n,`README.md`);await pr(l,(await y(l,`utf8`)).replace(/^# .*$/m,`# ${r}`));let u=qr(e,`install`)===!0?void 0:Uc(),d=!1;u&&(t||process.stdout.write(`Installing packages with ${u}...\n`),d=Co(u,[`install`],{cwd:n,stdio:t?`ignore`:`inherit`}).status===0);let f=[`cd ${qn(process.cwd(),n)||`.`}`,`seo site guide setup`];t?F({folder:n,name:r,domain:i,installed:d,packageManager:u??null,next:f}):(Fi(`Created ${r}`,n),I([[`Domain`,i],[`Packages`,d?`installed with ${u}`:u?`${u} install failed. Run it in the folder.`:`not installed`]]),process.stdout.write(`
98
- `),z(`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.`),R({title:`Next`,body:`Read the first step. Each step ends with the next one.`,command:f.join(` && `)}))}});function Gc(e){let t=zc(e.join(` `));return Lc.find(([e])=>e===t)?.[0]}const Kc=b({meta:{name:`guide`,description:`Print the instructions for one step of building the site`},args:{step:{type:`positional`,required:!1,description:Lc.map(([e])=>e).join(`, `)},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=k(e),n=e._?.length?e._:[w(e.step)??``];if(!n.join(``).trim()){if(t){F({steps:Lc.map(([e,t])=>({step:e,summary:t}))});return}Fi(`Build a site, one step at a time`,"Run `seo site guide <step>` and follow it before the next step."),Bi(`Steps`,Lc.map(([e,t])=>`${e}: ${t}`)),R({title:`Start here`,command:`seo site guide setup`});return}let r=Gc(n);if(!r)throw new g(`INVALID_INPUT`,`Unknown step "${n.join(` `)}". Steps: ${Lc.map(([e])=>e).join(`, `)}.`);let i=await y(_(Pc(),`guide`,`${r}.md`),`utf8`),a=Lc.findIndex(([e])=>e===r),o=Lc[a+1]?.[0];t?F({step:r,number:a+1,of:Lc.length,markdown:i,next:o?`seo site guide ${o}`:null}):process.stdout.write(i.endsWith(`
99
- `)?i:`${i}\n`)}});async function qc(e){return(await dr(e,{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(t=>qn(e,_(t.parentPath,t.name)).split(Yn).join(`/`))}function Jc(e){Fi(e.status===`passed`?`Site check passed`:e.status===`partial`?`Site check stopped early`:`Site check failed`,e.origin),I([[`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(`
100
- `);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);Bi(`${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`&&z(`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.`),R(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 Yc=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=k(e),n=Jn(w(e.dir)??`.`),r=Jn(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 wt({origin:`https://${Vc(o)}`,files:await qc(r),readText:e=>y(_(r,e),`utf8`),readBytes:e=>y(_(r,e)),allowWords:a.allowWords??[],sources:v(_(n,`src`))?{files:(await qc(_(n,`src`))).map(e=>`src/${e}`),readText:e=>y(_(n,e),`utf8`)}:void 0});t?F(s):Jc(s),s.status!==`passed`&&(process.exitCode=1)}}),Xc=b({meta:{name:`site`,description:`Build a data-driven site on Astro and Cloudflare`},subCommands:{new:Wc,guide:Kc,check:Yc}}),Zc=`claude -p`;function Qc(){let e=Nc();return nr(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(t=>({subject:Wn(t.name,`.json`),path:_(e,t.name)})).sort((e,t)=>e.subject<t.subject?-1:+(e.subject>t.subject))}function $c(e,t){let n;try{n=tr(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 el(){let e=_(Mc(),`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 tr(e,`utf8`)}function tl(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===`
101
- `||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 nl(e,t){let n=tl(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 rl(e,t){return e?`${e.trim()}\n\n---\n\nUser request:\n${t}`:t}function il(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(`
92
+ `),Ki(Ac(t.inputSchema)),process.stdout.write(`
93
+ `),L({title:`Need the exact schema?`,command:`seo reports describe ${t.id} --json`}))}}),Nc=y({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=C(e.id)??``,n=await Oc(e.params,e[`params-file`]),r=await ht(t,n,{view:w(e[`actions-only`])?`actions`:`full`});if(kc(r),O(e))P(r.structuredContent??{});else for(let e of r.content)process.stdout.write(`${e.text}\n`)}}),Pc=y({meta:{name:`reports`,description:`Discover and run the complete report catalog`},subCommands:{list:jc,describe:Mc,run:Nc}}),Fc=y({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=C(e.category),n=Qt().filter(e=>!t||e.category===t);O(e)?P({rules:n}):Ui(n.map(e=>({id:e.id,category:e.category,name:`${e.title} · ${e.defaultSeverity}`})),{noun:`rule`})}}),Ic=y({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=C(e.rule)??``,n=Ct(t);if(!n)throw Error(`Unknown rule: ${t}`);O(e)?P(n):(F([[`Rule`,n.id],[`Title`,n.title],[`Category`,n.category],[`Severity`,n.defaultSeverity]]),process.stdout.write(`
94
+ `),R(`Why it matters`,n.whyItMatters),process.stdout.write(`
95
+ `),R(`How to fix`,n.howToFix),process.stdout.write(`
96
+ `),R(`Impact if ignored`,n.impactIfIgnored),process.stdout.write(`
97
+ `),R(`How to verify`,n.howToVerify))}});function Lc(){return Bc(`skills`,process.env.SEO_SKILLS_DIR)}function Rc(){return Bc(`evals`,process.env.SEO_EVALS_DIR)}function zc(){return Bc(`site-kit`)}function Bc(e,t){if(t)return $n(t);let n=Xn(pr(import.meta.url));for(let t=0;t<6;t+=1){let t=g(n,e);if(_(g(t,`README.md`)))return t;n=Xn(n)}throw new h(`INTERNAL_ERROR`,`Packaged ${e} could not be found. Reinstall \`seo\` and try again.`)}function Vc(e){return or(g(e,`SKILL.md`),`utf8`).match(/^description:\s*(.+)$/m)?.[1]?.trim()??``}const Hc=[[`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`]],Uc=/* @__PURE__ */ new Set([`node_modules`,`dist`,`.astro`,`.wrangler`]);function Wc(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``)}function Gc(e){return Wc(Yn(e)).split(`-`).filter(Boolean).map(e=>`${e[0]?.toUpperCase()}${e.slice(1)}`).join(` `)}function Kc(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 h(`INVALID_INPUT`,`--domain must be a domain such as example.com, not ${e}.`);return t}async function qc(e,t){let n=JSON.parse(await v(e,`utf8`));t(n),await vr(e,`${JSON.stringify(n,null,2)}\n`)}function Jc(){return Oo(`pnpm`,[`--version`],{stdio:`ignore`}).status===0?`pnpm`:`npm`}const Yc=y({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=O(e),n=$n(String(e.folder));if(_(n)&&(await gr(n)).some(e=>e!==`.git`))throw new h(`INVALID_INPUT`,`${n} is not empty. Choose a new folder for the site.`);let r=C(e.name)?.trim()||Gc(n),i=Kc(C(e.domain)),a=Wc(Yn(n))||`site`,o=Gn(16).toString(`hex`),s=g(zc(),`starter`);await mr(s,n,{recursive:!0,filter:e=>!Qn(s,e).split(er).some(e=>Uc.has(e))}),await _r(g(n,`gitignore`),g(n,`.gitignore`)),await qc(g(n,`site.config.json`),e=>{e.name=r,e.domain=i,e.indexNowKey=o}),await vr(g(n,`public`,`${o}.txt`),o),await qc(g(n,`package.json`),e=>{e.name=a;let t=e.devDependencies;t.seo=`^${st}`});let c=g(n,`wrangler.jsonc`);await vr(c,(await v(c,`utf8`)).replace(`"name": "example-site"`,`"name": ${JSON.stringify(a)}`));let l=g(n,`README.md`);await vr(l,(await v(l,`utf8`)).replace(/^# .*$/m,`# ${r}`));let u=Qr(e,`install`)===!0?void 0:Jc(),d=!1;u&&(t||process.stdout.write(`Installing packages with ${u}...\n`),d=Oo(u,[`install`],{cwd:n,stdio:t?`ignore`:`inherit`}).status===0);let f=[`cd ${Qn(process.cwd(),n)||`.`}`,`seo site guide setup`];t?P({folder:n,name:r,domain:i,installed:d,packageManager:u??null,next:f}):(Bi(`Created ${r}`,n),F([[`Domain`,i],[`Packages`,d?`installed with ${u}`:u?`${u} install failed. Run it in the folder.`:`not installed`]]),process.stdout.write(`
98
+ `),R(`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.`),L({title:`Next`,body:`Read the first step. Each step ends with the next one.`,command:f.join(` && `)}))}});function Xc(e){let t=Wc(e.join(` `));return Hc.find(([e])=>e===t)?.[0]}const Zc=y({meta:{name:`guide`,description:`Print the instructions for one step of building the site`},args:{step:{type:`positional`,required:!1,description:Hc.map(([e])=>e).join(`, `)},json:{type:`boolean`,default:!1,description:`Print machine-readable JSON.`}},run:async({args:e})=>{let t=O(e),n=e._?.length?e._:[C(e.step)??``];if(!n.join(``).trim()){if(t){P({steps:Hc.map(([e,t])=>({step:e,summary:t}))});return}Bi(`Build a site, one step at a time`,"Run `seo site guide <step>` and follow it before the next step."),Gi(`Steps`,Hc.map(([e,t])=>`${e}: ${t}`)),L({title:`Start here`,command:`seo site guide setup`});return}let r=Xc(n);if(!r)throw new h(`INVALID_INPUT`,`Unknown step "${n.join(` `)}". Steps: ${Hc.map(([e])=>e).join(`, `)}.`);let i=await v(g(zc(),`guide`,`${r}.md`),`utf8`),a=Hc.findIndex(([e])=>e===r),o=Hc[a+1]?.[0];t?P({step:r,number:a+1,of:Hc.length,markdown:i,next:o?`seo site guide ${o}`:null}):process.stdout.write(i.endsWith(`
99
+ `)?i:`${i}\n`)}});async function Qc(e){return(await gr(e,{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(t=>Qn(e,g(t.parentPath,t.name)).split(er).join(`/`))}function $c(e){Bi(e.status===`passed`?`Site check passed`:e.status===`partial`?`Site check stopped early`:`Site check failed`,e.origin),F([[`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(`
100
+ `);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);Gi(`${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`&&R(`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.`),L(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 el=y({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=O(e),n=$n(C(e.dir)??`.`),r=$n(n,C(e.dist)??`dist`),i=g(n,`site.config.json`),a=_(i)?JSON.parse(await v(i,`utf8`)):{},o=C(e.domain)??a.domain;if(!o)throw new h(`INVALID_INPUT`,"No domain. Run this in a folder made by `seo site new`, or pass --domain.");if(!_(r))throw new h(`INVALID_INPUT`,`${r} does not exist. Build the site first with \`pnpm build\`.`);let s=await Tt({origin:`https://${Kc(o)}`,files:await Qc(r),readText:e=>v(g(r,e),`utf8`),readBytes:e=>v(g(r,e)),allowWords:a.allowWords??[],sources:_(g(n,`src`))?{files:(await Qc(g(n,`src`))).map(e=>`src/${e}`),readText:e=>v(g(n,e),`utf8`)}:void 0});t?P(s):$c(s),s.status!==`passed`&&(process.exitCode=1)}}),tl=y({meta:{name:`site`,description:`Build a data-driven site on Astro and Cloudflare`},subCommands:{new:Yc,guide:Zc,check:el}}),nl=`claude -p`;function rl(){let e=Rc();return sr(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.json`)).map(t=>({subject:Yn(t.name,`.json`),path:g(e,t.name)})).sort((e,t)=>e.subject<t.subject?-1:+(e.subject>t.subject))}function il(e,t){let n;try{n=or(t,`utf8`)}catch{throw new h(`INVALID_INPUT`,`Cannot read eval file for ${e}.`)}let r;try{r=JSON.parse(n)}catch{throw new h(`INVALID_INPUT`,`Eval file ${e}.json is not valid JSON.`)}if(!r||typeof r!=`object`||Array.isArray(r))throw new h(`INVALID_INPUT`,`Eval file ${e}.json must be an object.`);let i=r;if(i.subject!==e)throw new h(`INVALID_INPUT`,`Eval file ${e}.json must set subject to "${e}".`);if(!Array.isArray(i.evals)||i.evals.length===0)throw new h(`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 h(`INVALID_INPUT`,`${i}: id must be an integer.`);let o=r.id;if(a.has(o))throw new h(`INVALID_INPUT`,`${i}: duplicate id ${o}.`);if(a.add(o),typeof r.prompt!=`string`||r.prompt.trim().length===0)throw new h(`INVALID_INPUT`,`${i}: prompt must be a non-empty string.`);if(typeof r.expected_output!=`string`||r.expected_output.trim().length===0)throw new h(`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 h(`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 h(`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 al(){let e=g(Lc(),`seo`,`SKILL.md`);if(!_(e))throw new h(`INTERNAL_ERROR`,"The seo router skill could not be found. Reinstall `seo` or use --no-skill.");return or(e,`utf8`)}function ol(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===`
101
+ `||s===`\r`?r&&=(t.push(n),n=``,!1):(n+=s,r=!0)}if(i||a)throw new h(`INVALID_INPUT`,`Unbalanced quote in agent command.`);return r&&t.push(n),t}function sl(e,t){let n=ol(e);if(n.length===0)throw new h(`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 cl(e,t){return e?`${e.trim()}\n\n---\n\nUser request:\n${t}`:t}function ll(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(`
102
102
  `),`</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(`
103
- `);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 al(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 ol(e,t){let n=al(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 sl(e,t){return new Promise(n=>{let r=Date.now(),[i,...a]=e,o;try{o=gr(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 cl(e,t,n){let{argv:r,usesPlaceholder:i}=nl(e,t);return sl(r,{input:i?void 0:t,timeoutMs:n})}async function ll(e,t){let n=Date.now(),r=rl(t.skillBody,e.prompt),i=await cl(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:ul(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:ul(e.assertions)};if(a.length===0)return{...o,status:`errored`,error:`Agent returned no output on stdout.`,durationMs:Date.now()-n,assertions:ul(e.assertions)};if(!t.judge)return{...o,status:`unjudged`,durationMs:Date.now()-n,assertions:ul(e.assertions)};let s=0,c=``;for(let r=0;r<2;r+=1){let i=il(e.prompt,a,e.assertions,r>0),l=await cl(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:ul(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:ul(e.assertions)};let u=ol(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:ul(e.assertions)}}function ul(e){return e.map(e=>({assertion:e,verdict:`unjudged`}))}async function dl(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 fl(e){let t={passed:0,failed:0,errored:0,unjudged:0};for(let n of e)t[n.status]+=1;return t}function pl(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 ml(e){let t=Qc();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 hl(e){let t=Qc().map(e=>{let t=$c(e.subject,e.path);return{subject:e.subject,evals:t.evals.length}});if(e){F({schemaVersion:1,subjects:t});return}if(t.length===0){process.stdout.write(`No eval subjects found.
103
+ `);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 ul(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 dl(e,t){let n=ul(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 fl(e,t){return new Promise(n=>{let r=Date.now(),[i,...a]=e,o;try{o=xr(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 pl(e,t,n){let{argv:r,usesPlaceholder:i}=sl(e,t);return fl(r,{input:i?void 0:t,timeoutMs:n})}async function ml(e,t){let n=Date.now(),r=cl(t.skillBody,e.prompt),i=await pl(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:hl(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:hl(e.assertions)};if(a.length===0)return{...o,status:`errored`,error:`Agent returned no output on stdout.`,durationMs:Date.now()-n,assertions:hl(e.assertions)};if(!t.judge)return{...o,status:`unjudged`,durationMs:Date.now()-n,assertions:hl(e.assertions)};let s=0,c=``;for(let r=0;r<2;r+=1){let i=ll(e.prompt,a,e.assertions,r>0),l=await pl(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:hl(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:hl(e.assertions)};let u=dl(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:hl(e.assertions)}}function hl(e){return e.map(e=>({assertion:e,verdict:`unjudged`}))}async function gl(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 _l(e){let t={passed:0,failed:0,errored:0,unjudged:0};for(let n of e)t[n.status]+=1;return t}function vl(e){let t=[],n=C(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=rl();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 h(`INVALID_INPUT`,`Unknown eval subject: ${e}.${n?` Known subjects: ${n}.`:``}`)}return r})}function bl(e){let t=rl().map(e=>{let t=il(e.subject,e.path);return{subject:e.subject,evals:t.evals.length}});if(e){P({schemaVersion:1,subjects:t});return}if(t.length===0){process.stdout.write(`No eval subjects found.
104
104
  `);return}let n=Math.max(...t.map(e=>e.subject.length));process.stdout.write(`Eval subjects
105
- `);for(let e of t){let t=e.evals===1?`eval`:`evals`;process.stdout.write(` ${e.subject.padEnd(n)} ${e.evals} ${t}\n`)}}function gl(e){return e===`passed`?`PASS`:e===`failed`?`FAIL`:e===`errored`?`ERROR`:`UNJUDGED`}function _l(e,t){t.judged?process.stdout.write(`Assertion verdicts below are judge verdicts, model judgments from the judge agent, not ground truth.
105
+ `);for(let e of t){let t=e.evals===1?`eval`:`evals`;process.stdout.write(` ${e.subject.padEnd(n)} ${e.evals} ${t}\n`)}}function xl(e){return e===`passed`?`PASS`:e===`failed`?`FAIL`:e===`errored`?`ERROR`:`UNJUDGED`}function Sl(e,t){t.judged?process.stdout.write(`Assertion verdicts below are judge verdicts, model judgments from the judge agent, not ground truth.
106
106
 
107
107
  `):process.stdout.write(`Judging was skipped. Review each agent reply against the assertion checklist by hand.
108
108
 
109
- `);for(let n of e){process.stdout.write(`# ${n.subject}\n`);for(let e of n.evals)if(process.stdout.write(`\n[${gl(e.status)}] eval ${e.id} (${e.durationMs}ms)\n`),process.stdout.write(` prompt: ${yl(e.prompt,100)}\n`),e.error&&process.stdout.write(` error: ${e.error}\n`),!t.judged){process.stdout.write(` reply: ${yl(e.reply,200)}\n`),process.stdout.write(` assertions to review:
110
- `);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=fl(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=vl(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 vl(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 yl(e,t){let n=e.replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t-1)}…`:n}const bl=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:Zc,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:Gr(`Judge assertions with an agent.`,`Skip judging and print replies with an assertion checklist.`),skill:Gr(`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=k(e);if(e.list===!0){hl(t);return}let n=ml(pl(e)),r=E(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=E(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,E(e.concurrency)??1)),o=w(e.agent)??Zc,s=e.judge===!1?null:w(e[`judge-agent`])??o,c=e.skill===!1?null:el(),l={agent:o,judge:s,skillBody:c,timeoutMs:i*1e3},u=[];for(let e of n){let n=$c(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 dl(n,a,e=>ll(e,l)),o=fl(i);u.push({subject:e.subject,...o,evals:i})}let d=vl(u),f=d.failed>0||d.errored>0;t?F({schemaVersion:1,agent:o,judge:s,judged:s!==null,skillContext:c!==null,timeoutSeconds:i,concurrency:a,subjects:u,totals:d}):_l(u,{judged:s!==null,agent:o,judge:s}),f&&(process.exitCode=1)}});function xl(){let e=Mc();return nr(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&v(_(e,t.name,`SKILL.md`))).map(t=>({name:t.name,description:Ic(_(e,t.name)),path:_(e,t.name)})).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))}function Sl(e){let t=xl();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 Cl=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=xl();if(k(e))F({skills:t});else{Fi(`SEO skill`,`Packaged with this CLI.`),process.stdout.write(`
111
- `);for(let e of t)I([[`Name`,e.name],[`Purpose`,`Helps agents choose and run the right SEO audit or report.`],[`Path`,e.path]]);process.stdout.write(`
112
- `),R({title:`Add it to an agent`,body:`Run setup to install the skill and connect your first site.`,command:`seo start`})}}}),wl=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?Sl(t)[0]?.path:Mc();k(e)?F({name:t,path:n}):process.stdout.write(`${n}\n`)}}),Tl=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=k(e),n=ss({quiet:t});if(t)F(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.
113
- `)}}}),El=b({meta:{name:`skill`,description:`Inspect the packaged SEO skill and run its evals`},subCommands:{list:Cl,path:wl,install:Tl,eval:bl}}),Dl=b({meta:{name:`privacy`,description:`Show local config, token, cache, and log storage paths`},run:async()=>{let e=Fn(),t=ln();I(e.map(e=>[e.label,`${e.path} · ${Hi(e.sizeBytes)} · ${e.mode}`])),process.stdout.write(`
114
- `),I(Object.entries(t.counts).map(([e,t])=>[e,String(t)]))}}),Ol=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=k(e);if(!e.yes&&!P({json:t}))throw new g(`INVALID_INPUT`,`Cannot prompt here. Pass --yes to confirm reset.`);e.yes||B(await xr({message:`Delete saved credentials and all local data?`,initialValue:!1}))?(await Sn(),t?F({reset:!0}):process.stdout.write(`Reset complete.
115
- `)):br(`Reset aborted.`)}}),kl=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 on(T(e.refresh),w(e.account));k(e)?F({sites:t}):L([`Property`,`Permission`],t.map(e=>[e.siteUrl,e.permissionLevel??`unknown`]))}}),Al=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 je({product:w(e.product),limit:E(e.limit)});k(e)?F({updates:t}):zi(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.`})}}),jl={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 Ml(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 Nl(e,t){let n=Ml(e);t?F(n):(I([[`Anonymous telemetry`,e.enabled?`enabled`:`disabled`],[`Reason`,e.reason?jl[e.reason]:`local setting`],[`State file`,e.stateFile],[`Install cohort`,e.state?.cohort??`not created`]]),process.stdout.write(`
109
+ `);for(let n of e){process.stdout.write(`# ${n.subject}\n`);for(let e of n.evals)if(process.stdout.write(`\n[${xl(e.status)}] eval ${e.id} (${e.durationMs}ms)\n`),process.stdout.write(` prompt: ${wl(e.prompt,100)}\n`),e.error&&process.stdout.write(` error: ${e.error}\n`),!t.judged){process.stdout.write(` reply: ${wl(e.reply,200)}\n`),process.stdout.write(` assertions to review:
110
+ `);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=_l(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=Cl(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 Cl(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 wl(e,t){let n=e.replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t-1)}…`:n}const Tl=y({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:nl,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:Xr(`Judge assertions with an agent.`,`Skip judging and print replies with an assertion checklist.`),skill:Xr(`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=O(e);if(e.list===!0){bl(t);return}let n=yl(vl(e)),r=T(e.id);if(r!==void 0&&n.length!==1)throw new h(`INVALID_INPUT`,`--id needs exactly one subject. Name the subject to filter.`);let i=T(e.timeout)??300;if(!(i>0))throw new h(`INVALID_INPUT`,`--timeout must be a positive number of seconds.`);let a=Math.max(1,Math.min(4,T(e.concurrency)??1)),o=C(e.agent)??nl,s=e.judge===!1?null:C(e[`judge-agent`])??o,c=e.skill===!1?null:al(),l={agent:o,judge:s,skillBody:c,timeoutMs:i*1e3},u=[];for(let e of n){let n=il(e.subject,e.path).evals;if(r!==void 0&&(n=n.filter(e=>e.id===r),n.length===0))throw new h(`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 gl(n,a,e=>ml(e,l)),o=_l(i);u.push({subject:e.subject,...o,evals:i})}let d=Cl(u),f=d.failed>0||d.errored>0;t?P({schemaVersion:1,agent:o,judge:s,judged:s!==null,skillContext:c!==null,timeoutSeconds:i,concurrency:a,subjects:u,totals:d}):Sl(u,{judged:s!==null,agent:o,judge:s}),f&&(process.exitCode=1)}});function El(){let e=Lc();return sr(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&_(g(e,t.name,`SKILL.md`))).map(t=>({name:t.name,description:Vc(g(e,t.name)),path:g(e,t.name)})).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))}function Dl(e){let t=El();if(!e)return t;let n=t.find(t=>t.name===e);if(!n)throw new h(`INVALID_INPUT`,`Unknown skill: ${e}.`);return[n]}const Ol=y({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=El();if(O(e))P({skills:t});else{Bi(`SEO skill`,`Packaged with this CLI.`),process.stdout.write(`
111
+ `);for(let e of t)F([[`Name`,e.name],[`Purpose`,`Helps agents choose and run the right SEO audit or report.`],[`Path`,e.path]]);process.stdout.write(`
112
+ `),L({title:`Add it to an agent`,body:`Run setup to install the skill and connect your first site.`,command:`seo start`})}}}),kl=y({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=C(e.name),n=t?Dl(t)[0]?.path:Lc();O(e)?P({name:t,path:n}):process.stdout.write(`${n}\n`)}}),Al=y({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=O(e),n=fs({quiet:t});if(t)P(n),n.status===`failed`&&(process.exitCode=1);else{if(n.status===`failed`)throw new h(`INTERNAL_ERROR`,`Skill install failed: ${n.error}`);process.stdout.write(`SEO skill installed. Agents that support skills can discover it now.
113
+ `)}}}),jl=y({meta:{name:`skill`,description:`Inspect the packaged SEO skill and run its evals`},subCommands:{list:Ol,path:kl,install:Al,eval:Tl}}),Ml=y({meta:{name:`privacy`,description:`Show local config, token, cache, and log storage paths`},run:async()=>{let e=u(),t=pt();F(e.map(e=>[e.label,`${e.path} · ${qi(e.sizeBytes)} · ${e.mode}`])),process.stdout.write(`
114
+ `),F(Object.entries(t.counts).map(([e,t])=>[e,String(t)]))}}),Nl=y({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=O(e);if(!e.yes&&!N({json:t}))throw new h(`INVALID_INPUT`,`Cannot prompt here. Pass --yes to confirm reset.`);e.yes||z(await Er({message:`Delete saved credentials and all local data?`,initialValue:!1}))?(await Dn(),t?P({reset:!0}):process.stdout.write(`Reset complete.
115
+ `)):Tr(`Reset aborted.`)}}),Pl=y({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 On(w(e.refresh),C(e.account));O(e)?P({sites:t}):I([`Property`,`Permission`],t.map(e=>[e.siteUrl,e.permissionLevel??`unknown`]))}}),Fl=y({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 Ee({product:C(e.product),limit:T(e.limit)});O(e)?P({updates:t}):Wi(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.`})}}),Il={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 Ll(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 Rl(e,t){let n=Ll(e);t?P(n):(F([[`Anonymous telemetry`,e.enabled?`enabled`:`disabled`],[`Reason`,e.reason?Il[e.reason]:`local setting`],[`State file`,e.stateFile],[`Install cohort`,e.state?.cohort??`not created`]]),process.stdout.write(`
116
116
  Only tool usage is sent. URLs, report data, Google data, and identifiers are never sent.
117
117
  `),process.stdout.write(`Details: https://seoskill.dev/telemetry
118
- `))}const Pl={type:`boolean`,default:!1,description:`Print machine-readable JSON.`},Fl=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:Pl},run:async({args:e})=>Nl(fe(),k(e))}),enable:b({meta:{name:`enable`,description:`Enable anonymous usage telemetry in local settings`},args:{json:Pl},run:async({args:e})=>{Nl(Rn(!0),k(e))}}),disable:b({meta:{name:`disable`,description:`Disable anonymous usage telemetry in local settings`},args:{json:Pl},run:async({args:e})=>{Nl(Rn(!1),k(e))}})}});function Il(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 Ll(e){let t=e.steps.map(e=>Il(e.status)),n=t.includes(`fail`)?`fail`:t.includes(`warning`)?`warning`:t.includes(`unknown`)?`unknown`:`pass`;Li({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:Il(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 Rl=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.`},...Ga,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=k(e),n=await Vl(e),r=Bl(e),i=w(e.site),a=r??(i?qa(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 Dn({url:a,site:i,mode:zl(e.mode)??(n.length?`list`:void 0),urls:n,maxPages:E(e[`max-pages`]),maxDepth:E(e[`max-depth`]),concurrency:E(e.concurrency),refresh:T(e.refresh),fetchRate:Zr({...e,"fetch-concurrency":e.concurrency}),include:O(e.include),exclude:O(e.exclude),googleAnalyticsPropertyId:w(e[`google-analytics-property`]),analyticsConnection:Ka(e),useSitemap:!qr(e,`sitemap`),respectRobots:!qr(e,`robots`),checkExternal:!qr(e,`external`),js:!!T(e.js),limit:E(e.limit)});t?F(o):(Ll(o),L([`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 zl(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 Bl(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 Vl(e){let t=O(e.urls)??[],n=w(e[`urls-file`]);return n&&t.push(...Hl(await y(n,`utf8`))),[...new Set(t)]}function Hl(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`))}const Ul=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.`}}),...Ga,"verify-content":Gr(`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=k(e),n=A(w(e.site)),r=await pt({site:n,days:E(e.days),recentDays:E(e.recent),limit:E(e.limit),includeBrand:T(e[`include-brand`]),googleAnalyticsPropertyId:w(e[`google-analytics-property`]),analyticsConnection:Ka(e),verifyContent:T(e[`verify-content`]),verifyLimit:E(e[`verify-limit`]),refresh:T(e.refresh)});t?F(r):(Ll(r),L([`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 Wl(e){return e===null?`-`:e.toLocaleString(`en-GB`,{maximumFractionDigits:e>=100?0:1})}function Gl(e){return[...e.winners.map(e=>({direction:`winner`,item:e})),...e.losers.map(e=>({direction:`loser`,item:e}))]}function Kl(e,t){let n=Gl(t);n.length&&(process.stdout.write(`\n${e}\n`),L([`Direction`,`Key`,`Clicks`,`Impr.`,`Position`],n.map(({direction:e,item:t})=>[e,t.key,Wl(t.clickDelta),Wl(t.impressionDelta),Wl(t.positionDelta)])))}function ql(e){process.stdout.write(`
118
+ `))}const zl={type:`boolean`,default:!1,description:`Print machine-readable JSON.`},Bl=y({meta:{name:`telemetry`,description:`Check or change anonymous usage telemetry`},subCommands:{status:y({meta:{name:`status`,description:`Show whether anonymous usage telemetry is enabled`},args:{json:zl},run:async({args:e})=>Rl(s(),O(e))}),enable:y({meta:{name:`enable`,description:`Enable anonymous usage telemetry in local settings`},args:{json:zl},run:async({args:e})=>{Rl(Ye(!0),O(e))}}),disable:y({meta:{name:`disable`,description:`Disable anonymous usage telemetry in local settings`},args:{json:zl},run:async({args:e})=>{Rl(Ye(!1),O(e))}})}});function Vl(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 Hl(e){let t=e.steps.map(e=>Vl(e.status)),n=t.includes(`fail`)?`fail`:t.includes(`warning`)?`warning`:t.includes(`unknown`)?`unknown`:`pass`;Hi({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:Vl(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 Ul=y({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.`},...Xa,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=O(e),n=await Kl(e),r=Gl(e),i=C(e.site),a=r??(i?Qa(i):void 0)??n[0];if(!a)throw new h(`INVALID_INPUT`,"No crawl URL given. Pass a URL, --url or --site. Run `seo sites` to list your Search Console properties.");let o=await We({url:a,site:i,mode:Wl(e.mode)??(n.length?`list`:void 0),urls:n,maxPages:T(e[`max-pages`]),maxDepth:T(e[`max-depth`]),concurrency:T(e.concurrency),refresh:w(e.refresh),fetchRate:ni({...e,"fetch-concurrency":e.concurrency}),include:D(e.include),exclude:D(e.exclude),googleAnalyticsPropertyId:C(e[`google-analytics-property`]),analyticsConnection:Za(e),useSitemap:!Qr(e,`sitemap`),respectRobots:!Qr(e,`robots`),checkExternal:!Qr(e,`external`),js:!!w(e.js),limit:T(e.limit)});t?P(o):(Hl(o),I([`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 Wl(e){let t=C(e);if(t){if([`site`,`page`,`list`,`sitemap`].includes(t))return t;throw Error(`Mode must be one of: site, page, list, sitemap.`)}}function Gl(e){let t=C(e.crawlUrl),n=C(e.url);if(t&&n&&t!==n)throw Error(`Use either a URL argument or --url, not both.`);return t??n}async function Kl(e){let t=D(e.urls)??[],n=C(e[`urls-file`]);return n&&t.push(...ql(await v(n,`utf8`))),[...new Set(t)]}function ql(e){return e.split(/[\n,]/).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`#`))}const Jl=y({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.`}}),...Xa,"verify-content":Xr(`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=O(e),n=k(C(e.site)),r=await Rn({site:n,days:T(e.days),recentDays:T(e.recent),limit:T(e.limit),includeBrand:w(e[`include-brand`]),googleAnalyticsPropertyId:C(e[`google-analytics-property`]),analyticsConnection:Za(e),verifyContent:w(e[`verify-content`]),verifyLimit:T(e[`verify-limit`]),refresh:w(e.refresh)});t?P(r):(Hl(r),I([`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 Yl(e){return e===null?`-`:e.toLocaleString(`en-GB`,{maximumFractionDigits:e>=100?0:1})}function Xl(e){return[...e.winners.map(e=>({direction:`winner`,item:e})),...e.losers.map(e=>({direction:`loser`,item:e}))]}function Zl(e,t){let n=Xl(t);n.length&&(process.stdout.write(`\n${e}\n`),I([`Direction`,`Key`,`Clicks`,`Impr.`,`Position`],n.map(({direction:e,item:t})=>[e,t.key,Yl(t.clickDelta),Yl(t.impressionDelta),Yl(t.positionDelta)])))}function Ql(e){process.stdout.write(`
119
119
  Segment coverage
120
- `),L([`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 Jl(e){e.length&&(process.stdout.write(`
120
+ `),I([`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 $l(e){e.length&&(process.stdout.write(`
121
121
  Template movement
122
- `),L([`Direction`,`Template`,`Pattern confidence`,`URLs`,`Clicks`,`Returned share`,`Common terms`],e.map(e=>[e.direction,e.signature,e.confidence,e.urlCount,Wl(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 Yl=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=k(e),n=A(w(e.site)),r=await Ft({site:n,days:E(e.days),recentDays:E(e.recent),limit:E(e.limit),includeBrand:T(e[`include-brand`]),knownConfounders:w(e[`known-change`])?[w(e[`known-change`])??``]:void 0,refresh:T(e.refresh)});t?F(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)),Jl(r.output.templateMovement),Y(`Update evidence`,r.output.update.evidence),ql(r.output.segments),Kl(`Page winners and losers`,r.output.segments.page),Kl(`Query winners and losers`,r.output.segments.query),Kl(`Device winners and losers`,r.output.segments.device),Kl(`Country winners and losers`,r.output.segments.country),Aa(`seo export update-postmortem --site ${JSON.stringify(n)}`))}}),Xl=/* @__PURE__ */ new Set([`database`,`filesystem`,`internal`,`unknown`]);function Zl(e){return e.replace(/^v/,``).split(`.`)[0]||`unknown`}function Ql(e){return fn(e[0])?e[0]:void 0}function $l(e,t){return ze(e)?`seo ${e}`:t?`seo ${t}`:`seo command`}function eu(e){let t=ve(e.error);if(!Xl.has(t.errorCategory))return;let n=Ql(e.args),r=$l(e.report,n),i=[hn(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??oe),a.searchParams.set(`runtime`,`Node ${Zl(e.nodeVersion??process.version)} on ${e.processPlatform??Un()} (${e.processArch??Vn()})`),a.searchParams.set(`diagnostics`,i),a.toString()}const tu={"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`},nu={"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.`,iu=`Spend is controlled in your provider account. Set limits in DataForSEO, Ahrefs or the other provider.`,au={"providers limits":iu,"providers spend":iu,"providers dataforseo limits":iu,"providers dataforseo spend":iu,"providers ahrefs limits":iu,"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},ou=/* @__PURE__ */ new Set([`client`,`project`,`projects`]);function su(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(nu,t))return t}return null}function cu(e){let t=Object.hasOwn(tu,e)?tu[e]:void 0;return t?`\`seo ${e}\` is now \`${t}\`. The old name stops working in 1.0.0.`:null}function lu(e){let t=su(e);if(!t)return null;let n=nu[t],r=t.split(` `)[0]??``,i=n?`Use \`${n}\` instead.`:ou.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(au,t)?au[t]:`SEO Skill now focuses on Search Console, analytics and keyword data.`} ${i}`}const uu={"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`]},du=e=>e.split(`=`)[0]??``;function fu(e){let t=e.find(e=>[`--project`,`--client`].includes(du(e)));if(t)return`\`${du(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(uu,n)?e.find(e=>uu[n]?.includes(du(e))):void 0;if(!r)return null;let i=du(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 pu(e){return e.replaceAll(`\\`,`/`).toLowerCase()}function mu(e,t){return t===`win32`?`${e}.cmd`:e}function hu(e,t=process.platform){let n=pu(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:mu(`pnpm`,t),args:[`add`,`--global`,`seo@latest`]};if(n.includes(`/.bun/install/global/`))return{command:mu(`bun`,t),args:[`add`,`--global`,`seo@latest`]};if(n.includes(`/.config/yarn/global/`))return{command:mu(`yarn`,t),args:[`global`,`add`,`seo@latest`]};if(n.includes(`/node_modules/seo/`))return{command:mu(`npm`,t),args:[`install`,`--global`,`seo@latest`]}}}function gu(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 _u(e){if(e)try{return rr(e)}catch{return e}}async function vu(e){let t=await Dr({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 Cr(t)?`later`:t}function yu(e){return Co(e.command,e.args,{stdio:`inherit`}).status}async function bu(e,t={}){if(!gu({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=_u(t.cliPath??process.argv[1]),r=n?hu(n,t.platform??process.platform):void 0;if(!r)return;let i=(t.createNotifier??(e=>Lr({pkg:e,shouldNotifyInNpmScript:!1})))(e).update;if(i&&xt(i.current,i.latest)&&await(t.prompt??vu)({command:r,update:i})!==`later`)return(t.run??yu)(r)===0?(wr.success(`Updated seo to ${i.latest}. Run your command again.`),0):(wr.error(`The update failed. Your current version is unchanged.`),1)}function xu(e){if(process.stderr.isTTY&&!process.env.CI&&!(e.includes(`--json`)||e[0]===`mcp`))try{let{configDir:e,configFile:t}=ot();if(!v(t))return;let n=_(e,`notices.json`),r=v(n)?JSON.parse(tr(n,`utf8`)):[];if(r.includes(`0.4`))return;process.stderr.write(`
122
+ `),I([`Direction`,`Template`,`Pattern confidence`,`URLs`,`Clicks`,`Returned share`,`Common terms`],e.map(e=>[e.direction,e.signature,e.confidence,e.urlCount,Yl(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 eu=y({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=O(e),n=k(C(e.site)),r=await bt({site:n,days:T(e.days),recentDays:T(e.recent),limit:T(e.limit),includeBrand:w(e[`include-brand`]),knownConfounders:C(e[`known-change`])?[C(e[`known-change`])??``]:void 0,refresh:w(e.refresh)});t?P(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)),$l(r.output.templateMovement),Y(`Update evidence`,r.output.update.evidence),Ql(r.output.segments),Zl(`Page winners and losers`,r.output.segments.page),Zl(`Query winners and losers`,r.output.segments.query),Zl(`Device winners and losers`,r.output.segments.device),Zl(`Country winners and losers`,r.output.segments.country),Fa(`seo export update-postmortem --site ${JSON.stringify(n)}`))}}),tu=/* @__PURE__ */ new Set([`database`,`filesystem`,`internal`,`unknown`]);function nu(e){return e.replace(/^v/,``).split(`.`)[0]||`unknown`}function ru(e){return ut(e[0])?e[0]:void 0}function iu(e,t){return ue(e)?`seo ${e}`:t?`seo ${t}`:`seo command`}function au(e){let t=it(e.error);if(!tu.has(t.errorCategory))return;let n=ru(e.args),r=iu(e.report,n),i=[xn(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??st),a.searchParams.set(`runtime`,`Node ${nu(e.nodeVersion??process.version)} on ${e.processPlatform??Jn()} (${e.processArch??Kn()})`),a.searchParams.set(`diagnostics`,i),a.toString()}const ou={"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`},su={"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.`,cu=`Commands take --site now instead of a saved project.`,lu=`Spend is controlled in your provider account. Set limits in DataForSEO, Ahrefs or the other provider.`,uu={"providers limits":lu,"providers spend":lu,"providers dataforseo limits":lu,"providers dataforseo spend":lu,"providers ahrefs limits":lu,"change-log":Z,client:cu,project:cu,projects:cu,"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},du=/* @__PURE__ */ new Set([`client`,`project`,`projects`]);function fu(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(su,t))return t}return null}function pu(e){let t=Object.hasOwn(ou,e)?ou[e]:void 0;return t?`\`seo ${e}\` is now \`${t}\`. The old name stops working in 1.0.0.`:null}function mu(e){let t=fu(e);if(!t)return null;let n=su[t],r=t.split(` `)[0]??``,i=n?`Use \`${n}\` instead.`:du.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(uu,t)?uu[t]:`SEO Skill now focuses on Search Console, analytics and keyword data.`} ${i}`}const hu={"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`]},gu=e=>e.split(`=`)[0]??``;function _u(e){let t=e.find(e=>[`--project`,`--client`].includes(gu(e)));if(t)return`\`${gu(t)}\` was removed. ${cu} 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(hu,n)?e.find(e=>hu[n]?.includes(gu(e))):void 0;if(!r)return null;let i=gu(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 vu(e){return e.replaceAll(`\\`,`/`).toLowerCase()}function yu(e,t){return t===`win32`?`${e}.cmd`:e}function bu(e,t=process.platform){let n=vu(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 xu(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 Su(e){if(e)try{return cr(e)}catch{return e}}async function Cu(e){let t=await Mr({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 Or(t)?`later`:t}function wu(e){return Oo(e.command,e.args,{stdio:`inherit`}).status}async function Tu(e,t={}){if(!xu({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=Su(t.cliPath??process.argv[1]),r=n?bu(n,t.platform??process.platform):void 0;if(!r)return;let i=(t.createNotifier??(e=>Hr({pkg:e,shouldNotifyInNpmScript:!1})))(e).update;if(i&&xt(i.current,i.latest)&&await(t.prompt??Cu)({command:r,update:i})!==`later`)return(t.run??wu)(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 Eu(e){if(process.stderr.isTTY&&!process.env.CI&&!(e.includes(`--json`)||e[0]===`mcp`))try{let{configDir:e,configFile:n}=t();if(!_(n))return;let r=g(e,`notices.json`),i=_(r)?JSON.parse(or(r,`utf8`)):[];if(i.includes(`0.4`))return;process.stderr.write(`
123
123
  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.
124
124
  Free hosted MCP server, nothing to install: https://seoskill.dev/docs/mcp
125
125
  To stay on the old version: npm i -g seo@0.2.41
126
126
  What changed: https://github.com/iannuttall/seo/blob/main/CHANGELOG.md
127
127
 
128
- `),sr(n,JSON.stringify([...r,`0.4`]),{mode:384})}catch{}}const Su={name:`seo`,version:oe},Cu=[{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 (beta, 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 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`]]}],wu=[...Cu,{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 Tu(e){Fi(`seo v${Su.version}`,`Your own Search Console, Google Analytics and Bing data, as facts for your agent.`),process.stdout.write(`
129
- `),Ri(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(`
130
- `),z(`More help`,"Use `seo help <command>` or `seo <command> --help` for command help.","Use `seo help all` for the longer command list.")}const Eu=b({meta:{name:`seo`,version:Su.version,description:`Local-first SEO CLI and MCP server`},subCommands:{init:Cs,analytics:ha,auth:Sa,mcp:Ds,doctor:qs,privacy:Dl,telemetry:Fl,reset:Ol,cache:Ta,logs:ws,crawl:Za,"crawl-queue":Rl,content:ja,providers:bc,export:So,"index-coverage":Os,"link-recover":ks,rules:Ac,explain:jc,"refresh-priorities":Ul,"redirect-trace":As,skill:El,start:Ss,setup:xs,site:Xc,login:rs,logout:os,report:Xi,page:Zi,compare:Qi,index:$i,data:ea,research:ta,reports:kc,"segment-impact":Ys,"striking-distance":Zs,"update-postmortem":Yl,sites:kl,"gsc-query":oo,"url-inspect":so,updates:Al,"traffic-anomaly":fo,"update-correlate":po,"ai-referrals":js,"audit-page":Hs,"second-page":Vs,cannibal:Ms,decaying:Fs,"quick-wins":Bs,"page-opportunities":Rs,perf:Ks,"internal-links":Ls,"ctr-underperformers":Ns,"query-cluster":zs},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")}}),Du={cannibal:`cannibalisation`,crawl:`site-crawl`,"crawl-queue":`top-fixes`,decaying:`decaying-pages`,doctor:`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`},Ou=/* @__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`]),ku=new Set(an().map(e=>e.id));function Au(e,t){let n=e.indexOf(t);return n>=0?e[n+1]:e.find(e=>e.startsWith(`${t}=`))?.slice(t.length+1)}function ju(e){let[t,n,r]=e;if(t)return t in Ie?$e(t,{section:Au(e,`--section`),action:n})??void 0:t===`reports`&&n===`run`?r&&ku.has(r)?r:void 0:t===`content`&&n===`optimize`?`content-optimization`:t===`perf`&&n===`audit`?`performance-audit`:Du[t]??(Ou.has(t)?t:void 0)}const Mu=process.argv.slice(2);function Nu(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=Mu[0]===`mcp`&&(Mu[1]===void 0||/^-(?!h$|-help$)/.test(Mu[1]))&&!process.stdin.isTTY?[`mcp`,`serve`,...Mu.slice(1)]:Mu[0]===`reports`?Nu(Mu):Mu;xu(Q);const Pu=lu(Q)??fu(Q);Pu&&(process.stderr.write(`${Pu}\n`),process.exit(2));const Fu=cu(Q[0]??``);Fu&&!Q.some(e=>[`--help`,`-h`].includes(e))&&process.stderr.write(`${Fu}\n`);const Iu={agent:re()},Lu=Q[0]===`telemetry`,Ru=Q[0]===`mcp`&&Q[1]===`serve`;!Lu&&!Ru&&xe(Iu),Ru||Yt();const zu=await bu(Su,{argv:Q});zu!==void 0&&process.exit(zu),(Q.length===0||Q.length===1&&[`help`,`--help`,`-h`].includes(Q[0]??``))&&(Tu(Cu),process.exit(0)),Q[0]===`help`&&Q[1]===`all`&&(Tu(wu),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 Bu=$.some(e=>[`--help`,`-h`].includes(e)),Vu=Q.length===1&&[`--version`,`-v`].includes(Q[0]??``),Hu=Bu||Vu?void 0:ju($);if(Bu||Vu)await yr(Eu);else{Hu&&Je(Hu,Iu);let e=Q.includes(`--json`);try{await vr(Eu,{rawArgs:$}),Hu&&Ze(Hu,Iu),[`init`,`setup`,`start`].includes($[0]??``)&&!$.includes(`--dry-run`)&&et(Iu)}catch(t){if(t?.code===`E_NO_COMMAND`&&await yr(Eu,{rawArgs:[...$,`--help`]}),Hu)le(Hu,t,Iu);else if(!Lu){let e=Ql($);e&&s(e,t,Iu)}let n=hn(t);if(e){let e=Yt();process.stdout.write(`${JSON.stringify({...nn(n),...e?{updateNotice:e}:{}},null,2)}\n`)}else{process.stderr.write(`Error: ${n.message}\n`);let e=eu({args:$,error:t,report:Hu});e&&process.stderr.write(`Report this bug: ${e}\n`)}process.exitCode=n.exitCode}let t=e||Ru?void 0:Yt();t&&process.stderr.write(`\n${t}\n`)}export{};
128
+ `),fr(r,JSON.stringify([...i,`0.4`]),{mode:384})}catch{}}const Du={name:`seo`,version:st},Ou=[{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 (beta, 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`]]}],ku=[...Ou,{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 Au(e){Bi(`seo v${Du.version}`,`Your own Search Console, Google Analytics and Bing data, as facts for your agent.`),process.stdout.write(`
129
+ `),Ui(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(`
130
+ `),R(`More help`,"Use `seo help <command>` or `seo <command> --help` for command help.","Use `seo help all` for the longer command list.")}const ju=y({meta:{name:`seo`,version:Du.version,description:`Local-first SEO CLI and MCP server`},subCommands:{init:Os,analytics:ba,auth:Da,mcp:Ms,doctor:Qs,privacy:Ml,telemetry:Bl,reset:Nl,cache:Aa,logs:ks,crawl:no,"crawl-queue":Ul,content:Ia,providers:Tc,export:Do,"index-coverage":Ns,"link-recover":Ps,rules:Fc,explain:Ic,"refresh-priorities":Jl,"redirect-trace":Fs,skill:jl,start:Ds,setup:Es,site:tl,login:cs,logout:ds,report:ea,page:ta,compare:na,index:ra,data:ia,research:aa,lint:oa,reports:Pc,"segment-impact":ec,"striking-distance":nc,"update-postmortem":eu,sites:Pl,"gsc-query":fo,"url-inspect":po,updates:Fl,"traffic-anomaly":_o,"update-correlate":vo,"ai-referrals":Is,"audit-page":qs,"second-page":Ks,cannibal:Ls,decaying:Bs,"quick-wins":Gs,"page-opportunities":Us,perf:Zs,"internal-links":Hs,"ctr-underperformers":Rs,"query-cluster":Ws},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")}}),Mu={cannibal:`cannibalisation`,crawl:`site-crawl`,"crawl-queue":`top-fixes`,decaying:`decaying-pages`,doctor:`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`},Nu=/* @__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`]),Pu=new Set(sn().map(e=>e.id));function Fu(e,t){let n=e.indexOf(t);return n>=0?e[n+1]:e.find(e=>e.startsWith(`${t}=`))?.slice(t.length+1)}function Iu(e){let[t,n,r]=e;if(t)return t in an?oe(t,{section:Fu(e,`--section`),action:n})??void 0:t===`reports`&&n===`run`?r&&Pu.has(r)?r:void 0:t===`content`&&n===`optimize`?`content-optimization`:t===`perf`&&n===`audit`?`performance-audit`:Mu[t]??(Nu.has(t)?t:void 0)}const Lu=process.argv.slice(2);function Ru(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=Lu[0]===`mcp`&&(Lu[1]===void 0||/^-(?!h$|-help$)/.test(Lu[1]))&&!process.stdin.isTTY?[`mcp`,`serve`,...Lu.slice(1)]:Lu[0]===`reports`?Ru(Lu):Lu;Eu(Q);const zu=mu(Q)??_u(Q);zu&&(process.stderr.write(`${zu}\n`),process.exit(2));const Bu=pu(Q[0]??``);Bu&&!Q.some(e=>[`--help`,`-h`].includes(e))&&process.stderr.write(`${Bu}\n`);const Vu={agent:Un()},Hu=Q[0]===`telemetry`,Uu=Q[0]===`mcp`&&Q[1]===`serve`;!Hu&&!Uu&&Qe(Vu),Uu||Xt();const Wu=await Tu(Du,{argv:Q});Wu!==void 0&&process.exit(Wu),(Q.length===0||Q.length===1&&[`help`,`--help`,`-h`].includes(Q[0]??``))&&(Au(Ou),process.exit(0)),Q[0]===`help`&&Q[1]===`all`&&(Au(ku),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 Gu=$.some(e=>[`--help`,`-h`].includes(e)),Ku=Q.length===1&&[`--version`,`-v`].includes(Q[0]??``),qu=Gu||Ku?void 0:Iu($);if(Gu||Ku)await wr(ju);else{qu&&hn(qu,Vu);let e=Q.includes(`--json`);try{await Cr(ju,{rawArgs:$}),qu&&se(qu,Vu),[`init`,`setup`,`start`].includes($[0]??``)&&!$.includes(`--dry-run`)&&ge(Vu)}catch(t){if(t?.code===`E_NO_COMMAND`&&await wr(ju,{rawArgs:[...$,`--help`]}),qu)ye(qu,t,Vu);else if(!Hu){let e=ru($);e&&tt(e,t,Vu)}let n=xn(t);if(e){let e=Xt();process.stdout.write(`${JSON.stringify({...ln(n),...e?{updateNotice:e}:{}},null,2)}\n`)}else{process.stderr.write(`Error: ${n.message}\n`);let e=au({args:$,error:t,report:qu});e&&process.stderr.write(`Report this bug: ${e}\n`)}process.exitCode=n.exitCode}let t=e||Uu?void 0:Xt();t&&process.stderr.write(`\n${t}\n`)}export{};
131
131
  //# sourceMappingURL=cli.js.map