seo 0.8.2 → 0.8.3

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.
@@ -10,7 +10,7 @@ import{createRequire as e}from"node:module";import t,{createHash as n,randomUUID
10
10
  `),data:{summary:Ln(t.summary)?t.summary:null,path:i?.path??null,total:a.length,columns:u,rows:l,limits:c}}}function Zn(e,t,n){let r=zn(e);if(!r)return{total:0,text:``};let i=r.rows.map(Bn);return{total:i.length,text:Un(i.slice(0,n),Vn(i,6),t)}}async function Qn(e,t){return(await Rt(e,{signIn:t})).filter(e=>e.permissionLevel!==`siteUnverifiedUser`).map(e=>({siteUrl:e.siteUrl,permissionLevel:e.permissionLevel??``})).sort((e,t)=>e.siteUrl.localeCompare(t.siteUrl))}const $n=e=>{try{return new URL(e.includes(`://`)?e:`https://${e.replace(/^sc-domain:/,``)}`).hostname.replace(/^www\./,``)}catch{return e}};async function er(e){let t=e.accounts.length>1,[n,r]=await Promise.all([Promise.all(e.accounts.map(async t=>{let[n,r]=await Promise.all([Qn(t.google,e.signIn).catch(e=>e instanceof Error?e:Error(String(e))),Bt(t.google,{signIn:e.signIn}).catch(()=>null)]);return{email:t.email,properties:n,analytics:r}})),e.bing?qt(e.bing).catch(e=>e instanceof Error?e:Error(String(e))):Promise.resolve(null)]),i=Array.isArray(r)?r.filter(e=>e.verified):[],a=new Map(i.map(e=>[$n(e.url),e])),o=n.flatMap(e=>e.properties instanceof Error?[]:e.properties.map(n=>({...n,...t?{account:e.email??``}:{},...Array.isArray(r)?{bing:a.get($n(n.siteUrl))?.url??``}:{}}))),s=new Set(o.map(e=>$n(e.siteUrl))),c=i.filter(e=>!s.has($n(e.url))),l=n.filter(e=>e.properties instanceof Error),u=n.flatMap(e=>(e.analytics??[]).flatMap(n=>n.propertySummaries.map(r=>({property:r.property.replace(`properties/`,``),name:r.displayName??``,account:n.displayName??``,...t?{signIn:e.email??``}:{}})))),d=[[`dataforseo`,`x-dataforseo-login`],[`ahrefs`,`x-ahrefs-key`]].filter(([,t])=>e.keys.get(t??``)).map(([e])=>e),f=[`siteUrl`,`permissionLevel`,...t?[`account`]:[],...Array.isArray(r)?[`bing`]:[]];return{text:[t?`Google accounts: ${e.accounts.map(e=>e.email).join(`, `)}.`:null,`Search Console properties (${o.length}):`,o.length?Un(o,f,null):`None. These Google sign-ins have no Search Console access, so the reports cannot run.`,...l.map(e=>`${e.email??`Google`}: could not list properties. ${e.properties.message}`),u.length?`Google Analytics properties (${u.length}):\n${Un(u,[`property`,`name`,`account`,...t?[`signIn`]:[]],null)}`:`Google Analytics: no properties readable with these sign-ins.`,e.bing===void 0?null:r===null?`Bing Webmaster: not connected.`:r instanceof Error?`Bing Webmaster: could not list sites. ${r.message}`:c.length?`Bing Webmaster sites with no Search Console property here (${c.length}): ${c.map(e=>e.url).join(`, `)}.`:`Bing Webmaster: ${i.length} verified sites; the bing column shows each one.`,`Research keys: ${d.length?d.join(`, `):`none`}.`,e.clicky?.length?`Clicky sites (seo_data with source "clicky"): ${e.clicky.join(`, `)}.`:null,`Add a Google account${e.bing===void 0?``:`, Bing`} or a key: ${e.connect}`,`Next: seo_report with a site.`].filter(Boolean).join(`
11
11
 
12
12
  `),data:{searchConsole:o,googleAnalytics:u,bing:Array.isArray(r)?i:null,research:d,clicky:e.clicky??[]}}}const tr={siteOwner:0,siteFullUser:1,siteRestrictedUser:2};function nr(e){if(e.length===0)return null;let t=e[0];if(e.length===1&&t)return t;let n,r=()=>(n??=Promise.all(e.map(async e=>({call:e,sites:await e(`GetUserSites`).then(e=>Array.isArray(e)?e:[]).catch(()=>[])}))),n);return async(e,n={})=>{let i=await r();return e===`GetUserSites`?i.flatMap(e=>e.sites):(i.find(e=>e.sites.some(e=>e.IsVerified===!0&&e.Url===n.siteUrl))?.call??t)(e,n)}}var rr=class{hint;google;bing;sites=new Map;owners;constructor(e,t){this.hint=t,this.google=e.google.map(e=>({email:e.email,google:Mt(e.token)})),this.bing=nr(e.bing)}accounts(){return this.google.map(e=>({email:e.email,google:e.google}))}sitesOf(e){let t=this.sites.get(e);return t||(t=Qn(e.google,this.hint.signIn),this.sites.set(e,t)),t}ownerMap(){return this.owners??=(async()=>{let e=await Promise.all(this.google.map(async e=>({linked:e,sites:await this.sitesOf(e).catch(e=>{if(this.google.length===1)throw e;return[]})}))),t=new Map;for(let{linked:n,sites:r}of e)for(let e of r){let r=tr[e.permissionLevel]??3,i=t.get(e.siteUrl);(!i||r<i.rank)&&t.set(e.siteUrl,{linked:n,rank:r})}return new Map([...t].map(([e,{linked:t}])=>[e,t]))})(),this.owners}async resolve(e){if(this.google.length===0)throw new yn(`NOT_CONNECTED`,`No Google account is connected. ${this.hint.signIn}`);let t=Mn([...(await this.ownerMap()).keys()],e);if(t)return t;throw new yn(`NO_ACCESS`,`None of the connected Google accounts (${this.google.map(e=>e.email).join(`, `)}) has a Search Console property for ${e}. ${this.hint.addGoogle}`)}async owner(e){let t=(await this.ownerMap()).get(await this.resolve(e));if(!t)throw new yn(`NO_ACCESS`,`No access to ${e}.`);return t}searchAnalytics(){return async(e,t)=>Lt((await this.owner(e)).google,e,{...t,maxRows:t.maxRows??t.rowLimit??1e5},{signIn:this.hint.signIn})}async inspect(e,t){return zt((await this.owner(e)).google,e,t,{signIn:this.hint.signIn,languageCode:`en-US`})}};let ir;function ar(e){return e.platform===`win32`?g(e.env.APPDATA??g(e.home,`AppData`,`Roaming`),`seo`,`Config`):g(e.env.XDG_CONFIG_HOME??g(e.home,`.config`),`seo`)}function or(e){return e.platform===`darwin`?g(e.home,`Library`,`Caches`,`seo`):e.platform===`win32`?g(e.env.LOCALAPPDATA??g(e.home,`AppData`,`Local`),`seo`,`Cache`):g(e.env.XDG_CACHE_HOME??g(e.home,`.cache`),`seo`)}function sr(e){return e.platform===`darwin`?g(e.home,`Library`,`Logs`,`seo`):e.platform===`win32`?g(e.env.LOCALAPPDATA??g(e.home,`AppData`,`Local`),`seo`,`Log`):g(e.env.XDG_STATE_HOME??g(e.home,`.local`,`state`),`seo`)}function cr(e){return{env:e.env??process.env,home:e.home??c(),platform:e.platform??process.platform}}function lr(e={}){let t=cr(e),n=t.env.SEO_CONFIG_DIR??ar(t),r=t.env.SEO_CACHE_DIR??or(t);return{configDir:n,cacheDir:r,logDir:t.env.SEO_LOG_DIR??sr(t),providerPackagesDir:g(n,`providers`),installedProviderPackagesFile:g(n,`provider-packages.json`),configFile:g(n,`config.json`),tokensFile:g(n,`tokens.json`),oauthClientFile:g(n,`oauth-client.json`),providerSecretsFile:g(n,`provider-secrets.json`),telemetryStateFile:g(n,`telemetry.json`),cacheDbFile:g(r,`cache.db`)}}function ur(e){let t=cr(e);if(!(t.platform!==`darwin`||t.env.SEO_CONFIG_DIR||t.env.XDG_CONFIG_HOME))return g(t.home,`Library`,`Preferences`,`seo`)}function dr(e={}){let t=ur(e);if(!t)return;let n=lr(e);if(!(!S(t)||S(n.configDir)))try{C(p(n.configDir),{recursive:!0,mode:448}),E(t,n.configDir)}catch(e){let t=e.code;if(t!==`EEXIST`&&t!==`ENOENT`)throw e}}function fr(){return ir||(ir=lr(),ir)}function pr(){let e=fr();return dr(),C(e.configDir,{recursive:!0,mode:448}),C(e.cacheDir,{recursive:!0,mode:448}),C(e.logDir,{recursive:!0,mode:448}),C(e.providerPackagesDir,{recursive:!0,mode:448}),e}function mr(e){try{return O(e).size}catch{return 0}}function hr(e,t=448){C(p(e),{recursive:!0,mode:t})}function gr(e){try{return JSON.parse(w(e,`utf8`))}catch{return}}function _r(e,t,n){hr(e);let r=`${e}.${process.pid}.${Date.now()}.tmp`;te(r,JSON.stringify(t,null,2),{encoding:`utf8`,mode:n}),b(r,n),E(r,e),b(e,n)}function vr(e){try{return`0${(O(e).mode&511).toString(8)}`}catch{return`missing`}}function yr(e){D(e,{recursive:!0,force:!0})}const br=[`auth`,`crawl_timeout`,`network`,`config`,`data`,`database`,`filesystem`,`internal`,`unknown`],xr=[`access_denied`,`auth_config_required`,`auth_expired`,`auth_required`,`crawl_timeout`,`database_constraint`,`database_corrupt`,`database_locked`,`database_read_only`,`database_unique_constraint`,`filesystem_full`,`filesystem_not_found`,`filesystem_permission`,`insufficient_data`,`internal_error`,`invalid_input`,`network_connection`,`network_dns`,`network_timeout`,`network_tls`,`optional_provider_unavailable`,`property_not_found`,`provider_unavailable`,`rate_limited`,`unknown`],Sr=[`crawl_pages_run_id_url`],Cr=`analytics.auth.cache.change-log.client.content.content-groups.crawl-reports.diagnose.export.gsc-query.indexnow.init.llms.logs.mcp.monitoring.okf.perf.privacy.project.projects.providers.pseo.reports.reset.schedule.server-logs.setup.skill.sites.start.telemetry.tests.updates.url-inspect`.split(`.`),wr={ACCESS_DENIED:{errorCategory:`auth`,failureReason:`access_denied`},AUTH_CONFIG_REQUIRED:{errorCategory:`auth`,failureReason:`auth_config_required`},AUTH_EXPIRED:{errorCategory:`auth`,failureReason:`auth_expired`},AUTH_REQUIRED:{errorCategory:`auth`,failureReason:`auth_required`},INSUFFICIENT_DATA:{errorCategory:`data`,failureReason:`insufficient_data`},INTERNAL_ERROR:{errorCategory:`internal`,failureReason:`internal_error`},INVALID_INPUT:{errorCategory:`config`,failureReason:`invalid_input`},OPTIONAL_PROVIDER_UNAVAILABLE:{errorCategory:`network`,failureReason:`optional_provider_unavailable`},PROPERTY_NOT_FOUND:{errorCategory:`config`,failureReason:`property_not_found`},PROVIDER_UNAVAILABLE:{errorCategory:`network`,failureReason:`provider_unavailable`},RATE_LIMITED:{errorCategory:`network`,failureReason:`rate_limited`}},Tr=new Set([`EAI_AGAIN`,`ENODATA`,`ENOTFOUND`]),Er=new Set([`ECONNREFUSED`,`ECONNRESET`,`ECONNABORTED`,`EPIPE`,`EHOSTUNREACH`,`ENETUNREACH`,`UND_ERR_SOCKET`,`UND_ERR_CONNECT`]),Dr=new Set([`ETIMEDOUT`,`UND_ERR_CONNECT_TIMEOUT`,`UND_ERR_BODY_TIMEOUT`,`UND_ERR_HEADERS_TIMEOUT`]);function Or(e,t){try{return e[t]}catch{return}}function kr(e){if(typeof e!=`string`&&typeof e!=`number`)return;let t=String(e);return t.length>2048?t.slice(0,2048):t}function Ar(e){let t=[e],n=new Set,r=[];for(;t.length>0&&r.length<4;){let e=t.shift();if(typeof e==`string`){r.push({message:kr(e)});continue}!e||typeof e!=`object`||n.has(e)||(n.add(e),r.push({code:kr(Or(e,`code`)),message:kr(Or(e,`message`)),name:kr(Or(e,`name`))}),t.push(Or(e,`cause`),Or(e,`error`)))}return r}function jr(e,t){if(e.has(`SQLITE_CONSTRAINT_PRIMARYKEY`)||e.has(`SQLITE_CONSTRAINT_UNIQUE`)||/unique constraint failed/i.test(t)){let e=/unique constraint failed:\s*crawl_pages\.run_id\s*,\s*crawl_pages\.url/i.test(t)?`crawl_pages_run_id_url`:void 0;return{errorCategory:`database`,failureReason:`database_unique_constraint`,...e?{failureContext:e}:{}}}if([...e].some(e=>e.startsWith(`SQLITE_CONSTRAINT`))||/constraint failed/i.test(t))return{errorCategory:`database`,failureReason:`database_constraint`};if([...e].some(e=>e.startsWith(`SQLITE_BUSY`)||e.startsWith(`SQLITE_LOCKED`))||/database is locked/i.test(t))return{errorCategory:`database`,failureReason:`database_locked`};if([...e].some(e=>e.startsWith(`SQLITE_CORRUPT`))||e.has(`SQLITE_NOTADB`)||/database disk image is malformed|file is not a database/i.test(t))return{errorCategory:`database`,failureReason:`database_corrupt`};if([...e].some(e=>e.startsWith(`SQLITE_READONLY`))||/attempt to write a readonly database/i.test(t))return{errorCategory:`database`,failureReason:`database_read_only`}}function Mr(e){if(e.has(`EACCES`)||e.has(`EPERM`)||e.has(`EROFS`))return{errorCategory:`filesystem`,failureReason:`filesystem_permission`};if(e.has(`ENOENT`))return{errorCategory:`filesystem`,failureReason:`filesystem_not_found`};if(e.has(`ENOSPC`)||e.has(`EDQUOT`)||e.has(`SQLITE_FULL`))return{errorCategory:`filesystem`,failureReason:`filesystem_full`};if([...e].some(e=>Tr.has(e)))return{errorCategory:`network`,failureReason:`network_dns`};if([...e].some(e=>Dr.has(e)))return{errorCategory:`network`,failureReason:`network_timeout`};if([...e].some(e=>Er.has(e)))return{errorCategory:`network`,failureReason:`network_connection`};if([...e].some(e=>/^(?:CERT_|DEPTH_ZERO_SELF_SIGNED_CERT$|ERR_SSL_|ERR_TLS_|SELF_SIGNED_CERT_IN_CHAIN$|UNABLE_TO_VERIFY_LEAF_SIGNATURE$)/.test(e)))return{errorCategory:`network`,failureReason:`network_tls`}}function Nr(e){let t=Ar(e),n=new Set(t.map(e=>e.code?.toUpperCase()).filter(e=>!!e)),r=jr(n,t.map(e=>e.message).filter(e=>!!e).join(`
13
- `));if(r)return r;let i=Mr(n);if(i)return i;if(t.some(e=>e.name===`AbortError`||e.name===`TimeoutError`))return{errorCategory:`crawl_timeout`,failureReason:`crawl_timeout`};for(let e of n){let t=wr[e];if(t)return t}return t.some(e=>e.name===`CLIError`)?{errorCategory:`config`,failureReason:`invalid_input`}:{errorCategory:`unknown`,failureReason:`unknown`}}function Pr(e){try{return Nr(e)}catch{return{errorCategory:`unknown`,failureReason:`unknown`}}}function Fr(e){return typeof e==`string`&&Cr.includes(e)}function Ir(e){let t=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),n=t.getUTCDay()||7;t.setUTCDate(t.getUTCDate()+4-n);let r=new Date(Date.UTC(t.getUTCFullYear(),0,1)),i=Math.ceil(((t.getTime()-r.getTime())/864e5+1)/7);return`${t.getUTCFullYear()}-W${String(i).padStart(2,`0`)}`}function Lr(e){let t=e?.toLowerCase()??``;return t?t.includes(`claude`)?`claude-code`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)||t.includes(`openai`)?`codex`:`unknown`:null}const Rr=`0.8.2`,zr=`affected-urls.ai-referrals.audit-page.audit-urls.cannibalisation.compare-crawls.content-optimization.crawl-diff.site-crawl.ctr-underperformers.decaying-pages.setup-check.explain-crawl-issue.crawl-report.index-coverage.index-coverage-plan.index-monitor.index-watch.internal-links.keyword-metrics.link-evidence.link-recovery.crawl-history.crawler-rules.measure-change.page-opportunities.performance-audit.query-clusters.quick-wins.ranked-keywords.redirect-trace.second-page.segment-impact.serp-results.serp-competitors.striking-distance.top-fixes.traffic-anomaly.update-correlation.search-performance-overview.refresh-priorities.technical-watch.update-postmortem`.split(`.`),Br=[{days:1,event:`active_d1`},{days:7,event:`active_d7`},{days:30,event:`active_d30`}],Vr=[`GITHUB_ACTIONS`,`GITLAB_CI`,`CIRCLECI`,`TRAVIS`,`BUILDKITE`,`JENKINS_URL`,`TEAMCITY_VERSION`,`TF_BUILD`,`BITBUCKET_BUILD_NUMBER`,`CODEBUILD_BUILD_ID`];function Hr(e){return e.env??process.env}function Ur(e){return e.now??new Date}function Wr(e){return e.stateFile??fr().telemetryStateFile}function Gr(e){return e===`1`||e?.toLowerCase()===`true`}function Kr(e=process.env){return e.NODE_ENV===`test`||!!e.NODE_TEST_CONTEXT||Gr(e.CI)||Vr.some(t=>!!e[t])}function qr(e){if(Kr(e))return`ci`;if(Gr(e.DO_NOT_TRACK))return`do_not_track`;if(Gr(e.SEOSKILL_TELEMETRY_DISABLED)||Gr(e.SEO_TELEMETRY_DISABLED))return`environment`}function Jr(e){return typeof e==`string`&&[`first_run`,`setup_complete`,`first_audit_complete`,`active_d1`,`active_d7`,`active_d30`].includes(e)}function Yr(e){return typeof e==`string`&&zr.includes(e)}function Xr(e){return typeof e==`string`&&/^\d{4}-W(?:0[1-9]|[1-4]\d|5[0-3])$/.test(e)}function Zr(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.telemetryEnabled==`boolean`&&typeof t.firstRunAt==`string`&&Number.isFinite(Date.parse(t.firstRunAt))&&Xr(t.cohort)&&Array.isArray(t.sentMilestones)&&t.sentMilestones.every(Jr)}function Qr(e){if(!S(e))return{kind:`missing`};let t=gr(e);return Zr(t)?{kind:`valid`,state:t}:{kind:`invalid`}}function $r(e,t){_r(e,t,384)}function ei(e,t=!0){let n=Ur(e);return{telemetryEnabled:t,firstRunAt:n.toISOString(),cohort:Ir(n),sentMilestones:[]}}function ti(e={}){let t=e.env??process.env;return Lr(e.clientName)||(t.CLAUDECODE||t.CLAUDE_CODE?`claude-code`:t.CURSOR_AGENT||t.CURSOR_TRACE_ID||t.CURSOR_SESSION_ID?`cursor`:t.CODEX_HOME||t.CODEX_THREAD_ID||t.CODEX_SANDBOX?`codex`:`cli`)}function ni(e){return e.agent??ti({clientName:e.clientName,env:Hr(e)})}function ri(e){return e.replace(/^v/,``).split(`.`)[0]||`unknown`}function ii(e,t,n={},r={}){return{event:e,version:r.version??Rr,agent:ni(r),os:r.processPlatform??u(),arch:r.processArch??s(),node:ri(r.nodeVersion??process.version),cohort:t.cohort,schema:2,...n.errorCategory?{errorCategory:n.errorCategory}:{},...n.failureReason?{failureReason:n.failureReason}:{},...n.failureContext?{failureContext:n.failureContext}:{},...n.operation?{operation:n.operation}:{},...n.report?{report:n.report}:{}}}function ai(e,t){let n=t.fetch??globalThis.fetch;try{n(t.endpoint??`https://seoskill.dev/api/t`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e),signal:AbortSignal.timeout(2e3)}).catch(()=>void 0)}catch{}}function oi(e){let t=Wr(e),n=qr(Hr(e)),r=Qr(t);return n?{enabled:!1,reason:n,stateFile:t,...r.kind===`valid`?{state:r.state}:{}}:r.kind===`invalid`?{enabled:!1,reason:`invalid_state`,stateFile:t}:r.kind===`valid`&&!r.state.telemetryEnabled?{enabled:!1,reason:`local_setting`,stateFile:t,state:r.state}:{enabled:!0,stateFile:t,...r.kind===`valid`?{state:r.state}:{}}}function si(e={}){return oi(e)}function ci(e,t={}){let n=Wr(t),r=Qr(n),i=r.kind===`valid`?r.state:ei(t,e);return i.telemetryEnabled=e,$r(n,i),oi(t)}function li(e){let t=oi(e);return t.enabled?t.state:void 0}function ui(e={}){let t=oi(e);if(!t.enabled)return t;let n=t.stateFile,r=t.state??ei(e),i=[];if(!r.sentMilestones.includes(`first_run`)){try{(e.notice??(e=>process.stderr.write(e)))(`SEO Skill collects anonymous usage data to improve the tool (event name,
13
+ `));if(r)return r;let i=Mr(n);if(i)return i;if(t.some(e=>e.name===`AbortError`||e.name===`TimeoutError`))return{errorCategory:`crawl_timeout`,failureReason:`crawl_timeout`};for(let e of n){let t=wr[e];if(t)return t}return t.some(e=>e.name===`CLIError`)?{errorCategory:`config`,failureReason:`invalid_input`}:{errorCategory:`unknown`,failureReason:`unknown`}}function Pr(e){try{return Nr(e)}catch{return{errorCategory:`unknown`,failureReason:`unknown`}}}function Fr(e){return typeof e==`string`&&Cr.includes(e)}function Ir(e){let t=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),n=t.getUTCDay()||7;t.setUTCDate(t.getUTCDate()+4-n);let r=new Date(Date.UTC(t.getUTCFullYear(),0,1)),i=Math.ceil(((t.getTime()-r.getTime())/864e5+1)/7);return`${t.getUTCFullYear()}-W${String(i).padStart(2,`0`)}`}function Lr(e){let t=e?.toLowerCase()??``;return t?t.includes(`claude`)?`claude-code`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)||t.includes(`openai`)?`codex`:`unknown`:null}const Rr=`0.8.3`,zr=`affected-urls.ai-referrals.audit-page.audit-urls.cannibalisation.compare-crawls.content-optimization.crawl-diff.site-crawl.ctr-underperformers.decaying-pages.setup-check.explain-crawl-issue.crawl-report.index-coverage.index-coverage-plan.index-monitor.index-watch.internal-links.keyword-metrics.link-evidence.link-recovery.crawl-history.crawler-rules.measure-change.page-opportunities.performance-audit.query-clusters.quick-wins.ranked-keywords.redirect-trace.second-page.segment-impact.serp-results.serp-competitors.striking-distance.top-fixes.traffic-anomaly.update-correlation.search-performance-overview.refresh-priorities.technical-watch.update-postmortem`.split(`.`),Br=[{days:1,event:`active_d1`},{days:7,event:`active_d7`},{days:30,event:`active_d30`}],Vr=[`GITHUB_ACTIONS`,`GITLAB_CI`,`CIRCLECI`,`TRAVIS`,`BUILDKITE`,`JENKINS_URL`,`TEAMCITY_VERSION`,`TF_BUILD`,`BITBUCKET_BUILD_NUMBER`,`CODEBUILD_BUILD_ID`];function Hr(e){return e.env??process.env}function Ur(e){return e.now??new Date}function Wr(e){return e.stateFile??fr().telemetryStateFile}function Gr(e){return e===`1`||e?.toLowerCase()===`true`}function Kr(e=process.env){return e.NODE_ENV===`test`||!!e.NODE_TEST_CONTEXT||Gr(e.CI)||Vr.some(t=>!!e[t])}function qr(e){if(Kr(e))return`ci`;if(Gr(e.DO_NOT_TRACK))return`do_not_track`;if(Gr(e.SEOSKILL_TELEMETRY_DISABLED)||Gr(e.SEO_TELEMETRY_DISABLED))return`environment`}function Jr(e){return typeof e==`string`&&[`first_run`,`setup_complete`,`first_audit_complete`,`active_d1`,`active_d7`,`active_d30`].includes(e)}function Yr(e){return typeof e==`string`&&zr.includes(e)}function Xr(e){return typeof e==`string`&&/^\d{4}-W(?:0[1-9]|[1-4]\d|5[0-3])$/.test(e)}function Zr(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;return typeof t.telemetryEnabled==`boolean`&&typeof t.firstRunAt==`string`&&Number.isFinite(Date.parse(t.firstRunAt))&&Xr(t.cohort)&&Array.isArray(t.sentMilestones)&&t.sentMilestones.every(Jr)}function Qr(e){if(!S(e))return{kind:`missing`};let t=gr(e);return Zr(t)?{kind:`valid`,state:t}:{kind:`invalid`}}function $r(e,t){_r(e,t,384)}function ei(e,t=!0){let n=Ur(e);return{telemetryEnabled:t,firstRunAt:n.toISOString(),cohort:Ir(n),sentMilestones:[]}}function ti(e={}){let t=e.env??process.env;return Lr(e.clientName)||(t.CLAUDECODE||t.CLAUDE_CODE?`claude-code`:t.CURSOR_AGENT||t.CURSOR_TRACE_ID||t.CURSOR_SESSION_ID?`cursor`:t.CODEX_HOME||t.CODEX_THREAD_ID||t.CODEX_SANDBOX?`codex`:`cli`)}function ni(e){return e.agent??ti({clientName:e.clientName,env:Hr(e)})}function ri(e){return e.replace(/^v/,``).split(`.`)[0]||`unknown`}function ii(e,t,n={},r={}){return{event:e,version:r.version??Rr,agent:ni(r),os:r.processPlatform??u(),arch:r.processArch??s(),node:ri(r.nodeVersion??process.version),cohort:t.cohort,schema:2,...n.errorCategory?{errorCategory:n.errorCategory}:{},...n.failureReason?{failureReason:n.failureReason}:{},...n.failureContext?{failureContext:n.failureContext}:{},...n.operation?{operation:n.operation}:{},...n.report?{report:n.report}:{}}}function ai(e,t){let n=t.fetch??globalThis.fetch;try{n(t.endpoint??`https://seoskill.dev/api/t`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e),signal:AbortSignal.timeout(2e3)}).catch(()=>void 0)}catch{}}function oi(e){let t=Wr(e),n=qr(Hr(e)),r=Qr(t);return n?{enabled:!1,reason:n,stateFile:t,...r.kind===`valid`?{state:r.state}:{}}:r.kind===`invalid`?{enabled:!1,reason:`invalid_state`,stateFile:t}:r.kind===`valid`&&!r.state.telemetryEnabled?{enabled:!1,reason:`local_setting`,stateFile:t,state:r.state}:{enabled:!0,stateFile:t,...r.kind===`valid`?{state:r.state}:{}}}function si(e={}){return oi(e)}function ci(e,t={}){let n=Wr(t),r=Qr(n),i=r.kind===`valid`?r.state:ei(t,e);return i.telemetryEnabled=e,$r(n,i),oi(t)}function li(e){let t=oi(e);return t.enabled?t.state:void 0}function ui(e={}){let t=oi(e);if(!t.enabled)return t;let n=t.stateFile,r=t.state??ei(e),i=[];if(!r.sentMilestones.includes(`first_run`)){try{(e.notice??(e=>process.stderr.write(e)))(`SEO Skill collects anonymous usage data to improve the tool (event name,
14
14
  fixed report or command name, fixed failure classification, version, agent,
15
15
  OS, architecture, Node major, and install week; never URLs, report data, error
16
16
  messages, command arguments, or identifiers of any kind).
@@ -300,49 +300,56 @@ CREATE INDEX IF NOT EXISTS idx_performance_reports_expires ON performance_report
300
300
  `,` `).replaceAll(`|`,`\\|`)}function xz(e,t=120){let n=bz(e).trim();return n.length<=t?n:`${n.slice(0,t-1)}...`}function Sz(e){return e.flatMap(e=>{let t=e.columns.map(e=>bz(e.label)),n=e.columns.map(e=>e.type===`number`?`---:`:`---`);return[`## ${e.title}`,``,`| ${t.join(` | `)} |`,`| ${n.join(` | `)} |`,...e.rows.map(t=>[``,...e.columns.map(e=>xz(t[e.key])),``].join(` | `)),``]})}function Cz(e){return typeof e==`object`&&!!e}function wz(e){if(!Cz(e))return[];let t=e.queue;return Array.isArray(t)?t.filter(e=>Cz(e)):[]}function Tz(e){if(e.steps.length)return{id:`steps`,title:`Steps`,columns:[{key:`tool`,label:`Tool`},{key:`status`,label:`Status`},{key:`summary`,label:`Summary`}],rows:e.steps.map(e=>({tool:e.tool,status:e.status,summary:e.summary}))}}function Ez(e){if(e.actions.length)return{id:`recommended_actions`,title:`Recommended Actions`,columns:[{key:`priority`,label:`Priority`,type:`number`},{key:`title`,label:`Title`},{key:`confidence`,label:`Confidence`},{key:`action`,label:`Action`}],rows:e.actions.map((e,t)=>({priority:t+1,title:e.title,confidence:e.confidence,action:e.action}))}}function Dz(e,t){if(e.length)return{id:`priority_queue`,title:`Priority Queue`,columns:[{key:`rank`,label:`Rank`,type:`number`},{key:`source`,label:`Source`},{key:`category`,label:`Category`},{key:`score`,label:`Score`,type:`number`},{key:`confidence`,label:`Confidence`},{key:`target`,label:`Target`,type:`url`},{key:`action`,label:`Action`}],rows:e.slice(0,t).map((e,t)=>({rank:t+1,source:e.source,category:e.category,score:Number(e.score.toFixed(1)),confidence:e.confidence,target:e.target,action:e.action}))}}function Oz(e,t={}){let n=wz(e.output);return{tables:[Tz(e),Ez(e),Dz(n,t.queueLimit??10)].filter(e=>!!e),charts:n.length?[{id:`priority_scores`,title:`Priority Scores`,type:`bar`,tableId:`priority_queue`,xKey:`rank`,yKey:`score`}]:[]}}function kz(e,t={}){let n=Oz(e,t);return[`# ${e.workflow}`,``,`Property: ${e.site}`,`Generated: ${e.generatedAt}`,``,e.summary,``,...Sz(n.tables)].join(`
301
301
  `).trim()}const Az=new Set([`quick-win`,`striking-distance`]);function jz(e){return e?e.id.endsWith(`-salary`)?`salary-page`:e.id:`no-template`}function Mz(e){if(!Az.has(e.source)||e.grouped)return;let t=jz(e.template);return[e.source,e.category,t,$S(e.title)].join(`|`)}function Nz(e){if(!Az.has(e.source)||e.grouped)return;let t=jz(e.template);return[e.source,e.category,t,$S(e.target)].join(`|`)}function Pz(e){let t=e[0];if(!t)return``;let n=new Set(e.map(e=>e.target)).size;return n<=1&&e.length<=1?t.action:n<=1?`${e.length} findings point at this URL. Start with the highest-impact issue first: ${t.action}`:`${n} URLs have the same issue. Apply this action across the affected pages: ${t.action}`}function Fz(e){let t=e.reduce((e,t)=>e+t.impact,0),n=new Set(e.map(e=>e.action)).size,r=e.slice(0,3).map(e=>e.target).join(`, `),i=n>1?` ${n} action variants are preserved in grouped findings.`:``;return`Grouped ${e.length} matching findings; total impact ${t.toFixed(2)}.${i} Top targets: ${r}.`}function Iz(e){let t=[...e].sort((e,t)=>t.score-e.score),n=t[0];if(!n)throw Error(`Cannot group an empty priority list.`);let r=t.reduce((e,t)=>e+t.impact,0),i=t.reduce((e,t)=>e+t.score,0),a=Number(Math.min(n.score*(1+Math.log1p(t.length-1)/8),300).toFixed(2));return{...n,score:a,impact:Number(r.toFixed(2)),action:Pz(t),evidence:Fz(t),grouped:{count:t.length,totalImpact:Number(r.toFixed(2)),totalScore:Number(i.toFixed(2)),findings:t.map(e=>({source:e.source,title:e.title,target:e.target,category:e.category,score:e.score,impact:e.impact,impactKind:e.impactKind,confidence:e.confidence,template:e.template,analytics:e.analytics,action:e.action,evidence:e.evidence}))}}}function Lz(e,t){let n=new Map,r=[];for(let i of e){let e=t(i);if(!e){r.push(i);continue}let a=n.get(e)??[];a.push(i),n.set(e,a)}return[...r,...[...n.values()].flatMap(e=>e.length>1?[Iz(e)]:e)]}function Rz(e){return Lz(Lz(e,Nz),Mz).sort((e,t)=>t.score-e.score)}function zz(e){let t=e.templates?.find(t=>t.id===e.id);return t?.urlCount??t?.count}function Bz(e,t){let n=cz({source:e.source,impact:e.impact,confidence:e.confidence,effort:e.effort,verification:e.verification,templateCount:e.template?.count,analyticsSessions:t?e.analytics?.sessions:void 0});return{...e,category:sz(e.source,e.verification),score:n.final,scoreBreakdown:n}}function Vz(e){return e.groups.filter(e=>e.count>=3||e.totalClickLoss>=10).map(t=>({source:`decay`,title:`${t.label} cluster`,target:t.sampleUrls[0]??e.site,impact:t.totalClickLoss,impactKind:`observed_retained_query_clicks`,confidence:`medium`,effort:t.diagnosis===`lost_ctr`?`S`:`M`,template:{id:t.template.id,label:t.template.label,count:t.count},action:t.recommendation,evidence:`${t.count} matching query/page rows retained in both windows had ${t.totalClickLoss.toFixed(0)} fewer clicks. Examples: ${t.sampleQueries.slice(0,3).join(`; `)}.`}))}async function Hz(e){let t=await yF({...e,verifyContent:e.verifyContent??!0,verifyLimit:e.verifyContent===!1?void 0:e.verifyLimit??Math.min(e.limit??5,5)}),n=rC(e.days??28),r=await OA({connection:e.analyticsConnection,propertyId:e.googleAnalyticsPropertyId,startDate:n.startDate,endDate:n.endDate,refresh:e.refresh}),i=DA({connection:e.analyticsConnection,propertyId:e.googleAnalyticsPropertyId,source:r.source,warning:r.warning}),a=i.warnings,o=[],s=Math.max(e.limit??25,25);for(let e of t.strikingDistance.items){let n=zz({templates:t.strikingDistance.templates,id:e.template.id}),i=TA(r.values,e.url);o.push({source:`striking-distance`,title:e.query,target:e.url,impact:e.priority.score,impactKind:`heuristic_priority_score`,confidence:e.recommendation.confidence,verification:e.contentVerification?.classification,template:{id:e.template.id,label:e.template.label,count:n??1},analytics:i,action:e.recommendation.action,evidence:e.recommendation.evidence})}for(let e of t.quickWins.items.slice(0,s)){let n=zz({templates:t.quickWins.templates,id:e.template.id}),i=TA(r.values,e.url);o.push({source:`quick-win`,title:e.query,target:e.url,impact:Number(e.estimatedCtrClickShortfall.toFixed(2)),impactKind:`heuristic_ctr_click_shortfall`,confidence:e.recommendation.confidence,effort:e.recommendation.effort,verification:e.contentVerification?.classification,template:{id:e.template.id,label:e.template.label,count:n??1},analytics:i,action:e.recommendation.action,evidence:e.recommendation.evidenceRef})}for(let e of t.decay.items){let n=zz({templates:t.decay.templates,id:e.template.id}),i=TA(r.values,e.url);o.push({source:`decay`,title:e.query,target:e.url,impact:e.clickLoss,impactKind:`observed_retained_query_clicks`,confidence:e.recommendation.confidence,effort:e.recommendation.effort,template:{id:e.template.id,label:e.template.label,count:n??1},analytics:i,action:e.recommendation.action,evidence:e.recommendation.evidenceRef})}o.push(...Vz({groups:t.decay.groups,site:e.site}));for(let e of t.cannibalization.items)o.push({source:`cannibalization`,title:e.query,target:e.suggestedOwnerUrl,impact:e.priority.score,impactKind:`heuristic_multi_url_exposure`,confidence:e.recommendation.confidence,effort:e.recommendation.effort,template:e.template?{id:e.template.id,label:e.template.label,count:e.pages.length}:void 0,action:e.recommendation.action,evidence:e.recommendation.evidenceRef});for(let n of t.priorities)o.push({source:`diagnosis`,title:n.label,target:e.site,impact:n.confidence===`high`?150:n.confidence===`medium`?75:25,impactKind:`ordinal`,confidence:n.confidence,action:n.action,evidence:n.reason});for(let e of t.quickWins.templateRecommendations)o.push({source:`template`,title:`${e.templateLabel} opportunity template`,target:`${e.templateLabel} template (${e.urlCount} URLs)`,impact:e.totalEstimatedCtrClickShortfall,impactKind:`heuristic_ctr_click_shortfall`,confidence:`medium`,effort:`M`,template:{id:e.templateId,label:e.templateLabel,count:e.urlCount},action:e.action,evidence:e.evidence});let c=Rz(o.map(e=>Bz(e,i.canRank)).filter(e=>e.score>0).sort((e,t)=>t.score-e.score)).slice(0,e.limit??25);return lz({workflow:`refresh-priorities`,site:e.site,summary:`${c.length} ranked SEO priorities refreshed.`,steps:[{tool:`seo_diagnose_property`,status:`completed`,summary:`Combined diagnosis, decay, striking-distance, quick-win, and cannibalisation signals.`}],actions:c.slice(0,5).map(e=>({title:e.title,action:e.action,confidence:e.confidence})),output:{queue:c,warnings:a,diagnosis:t,analyticsSource:r.source,analyticsRankingEligible:i.canRank,analyticsRankingApplied:c.some(e=>e.scoreBreakdown.analytics>1)}})}function Uz(e,t){return e<t?-1:+(e>t)}function Wz(e){let t=e.items.filter(e=>e.clickDelta>0).sort((e,t)=>t.clickDelta-e.clickDelta||Uz(e.key,t.key)),n=e.items.filter(e=>e.clickDelta<0).sort((e,t)=>e.clickDelta-t.clickDelta||Uz(e.key,t.key)),r=t.length+n.length;return{dataStatus:e.dataStatus,coverage:{evidenceScope:`matched-retained-segments`,eligibleRows:e.selection.matchedRows,returnedRows:e.selection.returnedRows,limitedRows:e.selection.limitedRows,resultLimit:e.filters.limit,sourceRowLimit:e.filters.maxRows,movedRows:r,unchangedRows:Math.max(0,e.selection.returnedRows-r),sourcePossiblyTruncated:e.source.before.possiblyTruncated||e.source.after.possiblyTruncated},summary:e.summary,unmatchedSegments:e.unmatchedSegments,warnings:e.warnings,winners:t,losers:n}}function Gz(e){return Math.abs(e).toLocaleString(`en-GB`)}function Kz(e){return`${Math.round(e*100)}%`}function qz(e,t){return e<t?-1:+(e>t)}function Jz(e){return`${e.returnedRows} of ${e.eligibleRows} eligible matched retained rows returned under result limit ${e.resultLimit}${e.sourcePossiblyTruncated?`; at least one source window reached the ${e.sourceRowLimit}-row source limit`:``}`}function Yz(e){return e.clickDelta>0?`gained`:e.clickDelta<0?`lost`:`held flat`}function Xz(e,t){return e===`page`?t.key.replace(/^https?:\/\//,``):t.key}function Zz(e,t){if(t.dataStatus===`unavailable`||t.dataStatus===`empty`)return{dimension:e,dataStatus:t.dataStatus,coverage:t.coverage,unmatchedRows:t.summary.unmatchedRows,summary:`${e}: no matched retained segment movement was available. ${t.summary.verdict} Scope: ${Jz(t.coverage)}.`};let n=t.dataStatus===`partial`?` Evidence is partial; ${t.summary.unmatchedRows} one-window rows were not treated as zero.`:``,r=` Scope: ${Jz(t.coverage)}.`,i=t.winners[0],a=t.losers[0];return i&&a?{dimension:e,dataStatus:t.dataStatus,coverage:t.coverage,unmatchedRows:t.summary.unmatchedRows,winner:i,loser:a,summary:`${e}: top winner ${Xz(e,i)} ${Yz(i)} ${Gz(i.clickDelta)} clicks; top loser ${Xz(e,a)} ${Yz(a)} ${Gz(a.clickDelta)} clicks.${n}${r}`}:i?{dimension:e,dataStatus:t.dataStatus,coverage:t.coverage,unmatchedRows:t.summary.unmatchedRows,winner:i,summary:`${e}: top winner ${Xz(e,i)} ${Yz(i)} ${Gz(i.clickDelta)} clicks; no material loser appeared in the returned segment rows.${n}${r}`}:a?{dimension:e,dataStatus:t.dataStatus,coverage:t.coverage,unmatchedRows:t.summary.unmatchedRows,loser:a,summary:`${e}: top loser ${Xz(e,a)} ${Yz(a)} ${Gz(a.clickDelta)} clicks; no material winner appeared in the returned segment rows.${n}${r}`}:{dimension:e,dataStatus:t.dataStatus,coverage:t.coverage,unmatchedRows:t.summary.unmatchedRows,summary:`${e}: no material winner or loser appeared in the returned matched retained segment rows.${n}${r}`}}function Qz(e){let t=e.insights.find(e=>e.dimension===`page`),n=e.insights.find(e=>e.dimension===`query`);return`Cause not established; ${t?.dataStatus===`empty`||t?.dataStatus===`unavailable`?`page segment evidence unavailable`:t?.winner?`top returned page gained ${Gz(t.winner.clickDelta)} clicks`:t?.loser?`top returned page lost ${Gz(t.loser.clickDelta)} clicks`:`no material page movement found in returned rows`}; ${n?.dataStatus===`empty`||n?.dataStatus===`unavailable`?`query segment evidence unavailable`:n?.winner?`top returned query gained ${Gz(n.winner.clickDelta)} clicks`:n?.loser?`top returned query lost ${Gz(n.loser.clickDelta)} clicks`:`no material query movement found in returned rows`}.`}function $z(e){let t=[],n=e.segments.page.winners.length,r=e.segments.page.losers.length,i=e.segments.query.winners.length,a=e.segments.query.losers.length,o=e.templateMovement[0];return o&&t.push({title:`${o.direction===`winner`?`Protect`:`Fix`} ${o.signature}`,action:o.direction===`winner`?`${o.signature} is a repeated winning URL pattern across ${o.urlCount} URLs in the returned matched-retained page subset. Preserve the shared title/H1/content/internal-link pattern before making broad edits.`:`${o.signature} is a repeated losing URL pattern across ${o.urlCount} URLs in the returned matched-retained page subset. Check indexability, canonical/robots state, internal links, and whether the shared template still matches search intent.`,confidence:o.confidence}),e.update.confounders.length>0?t.push({title:`Test overlapping site changes first`,action:`Start with the known overlapping changes, then compare changed sections against unchanged sections. Keep the Google update window as timing context, not a cause.`,confidence:`medium`}):e.update.classification===`significant-movement-with-update-overlap`?t.push({title:`Map movement by template`,action:`Group the top page and query movers into templates or content types. Preserve winning patterns and investigate losing templates, but do not treat timing overlap as proof of an update effect.`,confidence:`medium`}):t.push({title:`Treat this as exploratory`,action:`Use the segment splits as a triage view, but do not over-attribute the movement to a Google update yet.`,confidence:`low`}),n>0&&r===0&&t.push({title:`Protect the winning pages`,action:`The returned page split contains positive movers and no negative movers. Check those pages for common query intent, title/H1 pattern, internal links, and template shape before making broad edits.`,confidence:`medium`}),(r>0||a>0)&&t.push({title:`Triage the largest losers first`,action:`For losing pages and queries, check whether impressions dropped, average position worsened, or CTR fell. That separates ranking/index loss from snippet or SERP layout issues.`,confidence:`medium`}),i>0&&a===0&&t.push({title:`Expand winning query angles`,action:`The returned query split contains positive movers and no negative movers. Use that query wording to improve internal anchors and supporting copy on related pages.`,confidence:`medium`}),t}function eB(e,t){return e.filter(e=>t===`winner`?e.clickDelta>0:e.clickDelta<0)}function tB(e){let t=new Map;for(let n of e.items){let r=II(n.key,e.clusters);if(r===`/`)continue;let i=e.clusters.find(e=>e.signature===r),a=t.get(r)??{cluster:i,signature:r,items:[],clickDelta:0,impressionDelta:0};a.items.push(n),a.clickDelta+=n.clickDelta,a.impressionDelta+=n.impressionDelta,t.set(r,a)}return[...t.values()]}function nB(e){return e?[...new Set(e.shape.variableSegments.flatMap(e=>e.tokenExamples))].slice(0,6):[]}function rB(e){return tB({items:eB(e.items,e.direction),clusters:e.clusters}).map(t=>{let n=Math.abs(t.clickDelta),r=e.totalMovement?n/e.totalMovement:0;if(t.items.length<3||r<.2)return;let i=t.items.length>=10&&r>=.35&&e.segmentCoverage.limitedRows===0&&!e.segmentCoverage.sourcePossiblyTruncated?`high`:`medium`,a=e.direction===`winner`?`gained`:`lost`,o=nB(t.cluster),s=o.length?` Common URL terms: ${o.join(`, `)}.`:``;return{signature:t.signature,direction:e.direction,confidence:i,urlCount:t.items.length,clickDelta:Number(t.clickDelta.toFixed(3)),impressionDelta:Number(t.impressionDelta.toFixed(3)),movementShare:Number(r.toFixed(3)),movementShareScope:`returned-directional-page-click-movement`,confidenceScope:`pattern-within-returned-matched-retained-page-segments`,segmentCoverage:e.segmentCoverage,commonTerms:o,sampleUrls:t.items.slice(0,5).map(e=>e.key),summary:`${t.signature} ${a} ${Gz(t.clickDelta)} clicks across ${t.items.length} moved URLs (${Kz(r)} of returned ${e.direction} page click movement). Coverage: ${e.segmentCoverage.returnedRows} of ${e.segmentCoverage.eligibleRows} eligible matched retained page rows returned under result limit ${e.segmentCoverage.resultLimit}.${s}`}}).filter(e=>!!e).sort((e,t)=>Math.abs(t.clickDelta)-Math.abs(e.clickDelta)||t.urlCount-e.urlCount||qz(e.signature,t.signature))}function iB(e){let t=[...e.winners,...e.losers].filter(e=>e.key.startsWith(`http`)).filter(e=>Math.abs(e.clickDelta)>0).sort((e,t)=>Math.abs(t.clickDelta)-Math.abs(e.clickDelta)||qz(e.key,t.key));if(t.length<6)return[];let n=RI(t.map(e=>e.key),{minUrls:3,minShare:.15,limit:20}).filter(e=>e.signature!==`/`&&e.urlCount>=3);if(!n.length)return[];let r=e.winners.reduce((e,t)=>e+Math.max(0,t.clickDelta),0),i=Math.abs(e.losers.reduce((e,t)=>e+Math.min(0,t.clickDelta),0));return[...rB({direction:`winner`,items:t,clusters:n,totalMovement:r,segmentCoverage:e.coverage}),...rB({direction:`loser`,items:t,clusters:n,totalMovement:i,segmentCoverage:e.coverage})].slice(0,6)}async function aB(e,t={}){let n=e.limit??20,r=t.updateCorrelation??sF,i=t.segmentImpact??Hj,[a,o,s,c,l]=await Promise.all([r(e),i({...e,dimension:`page`,limit:n}),i({...e,dimension:`query`,limit:n}),i({...e,dimension:`device`,limit:n}),i({...e,dimension:`country`,limit:n})]),u={page:Wz(o),query:Wz(s),device:Wz(c),country:Wz(l)},d=[Zz(`page`,u.page),Zz(`query`,u.query),Zz(`device`,u.device),Zz(`country`,u.country)],f=iB(u.page),p=[u.page,u.query,u.device,u.country].every(e=>e.dataStatus===`empty`||e.dataStatus===`unavailable`)?`skipped`:`completed`;return lz({workflow:`update-postmortem`,site:e.site,summary:Qz({update:a,insights:d}),steps:[{tool:`seo_update_correlate`,status:`completed`,summary:`Cause not established. ${a.summary}`},{tool:`seo_segment_impact`,status:p,summary:d.map(e=>e.summary).join(` `)}],actions:$z({update:a,segments:u,templateMovement:f}),output:{update:a,insights:d,templateMovement:f,segments:u}})}var oB=class extends Error{code;constructor(e,t){super(t),this.code=e}};function sB(e){return/^\d{1,30}$/u.test(e.trim())}function cB(e){return/^[A-Za-z0-9]{12,64}$/u.test(e.trim())}async function lB(e,t,n={}){let r=new URL(`https://api.clicky.com/api/stats/4`);r.searchParams.set(`site_id`,e.siteId),r.searchParams.set(`sitekey`,e.sitekey),r.searchParams.set(`type`,t.join(`,`)),r.searchParams.set(`output`,`json`),r.searchParams.set(`limit`,String(n.limit??1e3)),r.searchParams.set(`app`,`seo`),n.date&&r.searchParams.set(`date`,n.date);let i=await fetch(r).catch(()=>{throw new oB(`remote`,`Could not reach Clicky. Try again.`)});if(!i.ok)throw new oB(`remote`,`Clicky returned ${i.status}.`);let a=await kt(i,`Clicky`,{maxBytes:5e6});if(!Array.isArray(a))throw new oB(`remote`,`Clicky returned invalid data.`);let o=a.find(e=>typeof e?.error==`string`);if(o?.error)throw/sitekey|site id|authenticat|permission/iu.test(o.error)?new oB(`auth`,`Clicky rejected site ID ${e.siteId} or its sitekey.`):new oB(`remote`,`Clicky: ${o.error.slice(0,200)}`);let s={};for(let e of t)s[e]=[];for(let e of a)if(!(!e?.type||!(e.type in s)))for(let t of e.dates??[])for(let n of t.items??[])n&&typeof n==`object`&&s[e.type]?.push(n);return s}async function uB(e){let{pages:t}=await lB(e,[`pages`],{date:`last-30-days`,limit:1}),n=t?.find(e=>e.url)?.url;if(!n)return null;try{return new URL(n).hostname.replace(/^www\./u,``)}catch{return null}}function dB(e){let t=e.rows.length;if(e.detail===`full`)return`${e.title}\n\n${JSON.stringify(e.rows.slice(e.offset,e.offset+e.limit))}`;let n=e.detail===`summary`?Math.min(e.limit,25):e.limit,r=e.rows.slice(e.offset,e.offset+n),i=[...new Set(r.flatMap(e=>Object.keys(e)))],a=e.offset+r.length;return[e.title,...e.notes??[],t===0?`No rows.`:`Rows ${e.offset+1} to ${a} of ${t}:\n${Un(r,i,e.origin??null)}`,a<t?`More: ${e.more?e.more(a):`detail "rows", offset ${a}`}.`:``].filter(Boolean).join(`
302
302
 
303
- `)}const fB=[`query`,`page`,`date`,`country`,`device`,`searchAppearance`],pB=25e3;async function mB(e,t){let n=e.dimensions?.length?e.dimensions:[`query`],r=e.filters??[],i=Cn(e,28),a=wn(i),o={dimensions:n,type:`web`,maxRows:pB,...r.length?{dimensionFilterGroups:[{groupType:`and`,filters:r}]}:{}},[s,c]=await Promise.all([t.searchAnalytics(e.site,{...o,...i}),t.searchAnalytics(e.site,{...o,...a})]),l=n.indexOf(`page`),u=e=>l<0?e:tj(e,{pageKeyIndex:l}).rows,d=u(s.rows),f=u(c.rows),p=e=>e.join(`\0`),m=n.indexOf(`date`),h=(e,t)=>p(e.map((e,n)=>n===m?String(Math.round((Date.parse(e)-Date.parse(t))/864e5)):e)),g=new Map(f.map(e=>[h(e.keys,a.startDate),e])),_=new Set,v=d.map(e=>{let t=h(e.keys,i.startDate);_.add(t);let r=g.get(t);return{...Object.fromEntries(n.map((t,n)=>[t,e.keys[n]])),clicks:e.clicks,impressions:e.impressions,ctr:e.ctr,position:e.position,...m>=0?{previous_date:r?.keys[m]??null}:{},previous_clicks:r?.clicks??0,clicks_change:e.clicks-(r?.clicks??0),previous_position:r?.position??null}});if(m<0)for(let e of f)_.has(h(e.keys,a.startDate))||v.push({...Object.fromEntries(n.map((t,n)=>[t,e.keys[n]])),clicks:0,impressions:0,ctr:0,position:null,previous_clicks:e.clicks,clicks_change:-e.clicks,previous_position:e.position});v.sort((e,t)=>m>=0?String(e.date).localeCompare(String(t.date)):Number(t.clicks??0)-Number(e.clicks??0));let y=[];if(!n.includes(`query`)&&!n.includes(`page`)){let e=e=>v.reduce((t,n)=>t+Number(n[e]??0),0);y.push(`Totals: clicks ${e(`clicks`)}, impressions ${e(`impressions`)}; previous period clicks ${e(`previous_clicks`)}.`)}y.push(`Compared with ${a.startDate} to ${a.endDate}${c.rowsFetched>=pB?` (earlier period hit the row limit)`:``}. 0 clicks with no position means the row had no impressions in the current period.`),l>=0&&y.push(`Page URLs with #fragments are merged into their page.`),s.rowsFetched>=pB&&y.push(`Search Console has more than ${pB} rows; add a filter to narrow it.`),y.push(`Search Console hides some rare queries for privacy, so query rows do not add up to the site totals.`);let b=e.detail??`summary`;return{text:`${dB({title:`Search Console ${e.site}, ${i.startDate} to ${i.endDate}, web, by ${n.join(` and `)}.`,rows:v,offset:e.offset??0,limit:50,detail:b,notes:y,origin:Tn(e.site),more:r=>t.call(`data`,{site:e.site,dimensions:n.join(`,`),detail:`rows`,offset:r})})}\n\n${bn}`,data:{range:i,comparisonRange:a,total:v.length,offset:e.offset??0,rows:v.slice(e.offset??0,(e.offset??0)+50)}}}async function hB(e,t,n){let r=e.length===1?e[0]:void 0;if(r)return r.google;let i=(await Promise.all(e.map(async e=>(await Bt(e.google,{signIn:n}).catch(()=>[])).some(e=>e.propertySummaries.some(e=>e.property===`properties/${t}`))?e:null))).find(Boolean);if(i)return i.google;throw new yn(`NO_ACCESS`,`No connected Google account can read Google Analytics property ${t}. Call seo_sites to list the properties.`)}async function gB(e,t,n){let r=Cn(e,28),i=e.offset??0,a=Math.min(1e3,i+50),o=await Ht(t,e.property,{dateRanges:[r],dimensions:[{name:`landingPage`}],metrics:[{name:`sessions`},{name:`totalUsers`},{name:`engagedSessions`},{name:`keyEvents`}],dimensionFilter:{filter:{fieldName:`sessionDefaultChannelGroup`,stringFilter:{value:`Organic Search`}}},orderBys:[{metric:{metricName:`sessions`},desc:!0}],limit:a},n),s=[`Sessions in the Organic Search default channel group.`];o.metadata?.subjectToThresholding&&s.push(`Google Analytics applied thresholding; small rows can be hidden.`),o.metadata?.dataLossFromOtherRow&&s.push(`Some rows were grouped into (other) by Google Analytics.`),(o.rowCount??0)>a&&s.push(`${o.rowCount} landing pages in total; ${a} read.`);let c=(o.rows??[]).map(e=>({page:e.dimensionValues[0]?.value??``,sessions:Number(e.metricValues[0]?.value??0),users:Number(e.metricValues[1]?.value??0),engaged_sessions:Number(e.metricValues[2]?.value??0),key_events:Number(e.metricValues[3]?.value??0)}));return{text:dB({title:`Google Analytics property ${e.property}: search landing pages, ${r.startDate} to ${r.endDate}.`,rows:c,offset:i,limit:50,detail:e.detail??`summary`,notes:s,more:n.call}),data:{range:r,total:c.length,offset:i,rows:c.slice(i,i+50)}}}function _B(e){try{let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`?void 0:t.hostname.toLowerCase().replace(/\.$/,``)||void 0}catch{return}}function vB(e){if(!e.startsWith(`sc-domain:`))return;let t=e.slice(10).trim().toLowerCase();if(!(!t||/[/:]/.test(t)))return t.replace(/\.$/,``)||void 0}function yB(e,t){let n=vB(e);return n?t===n||t.endsWith(`.${n}`)?`domain`:void 0:_B(e)===t?`hostname`:void 0}function bB(e,t){return t.flatMap(t=>{let n=t.stream.webStreamData?.defaultUri;if(!n)return[];let r=_B(n);if(!r)return[];let i=yB(e,r);return i?[{...t,defaultUri:n,hostname:r,match:i}]:[]})}const xB=e=>{let t=e.replace(/^sc-domain:/,``);try{return new URL(t.includes(`://`)?t:`https://${t}`).hostname}catch{return t}},SB=e=>e.toLowerCase().replace(/[^a-z0-9]/g,``);function CB(e,t){let n=xB(e).replace(/^www\./,``),r=[SB(n),SB(n.split(`.`)[0]??``)].filter(e=>e.length>=3),i=e=>+!r.some(t=>SB(e.propertyName).includes(t));return[...t].sort((e,t)=>i(e)-i(t)||e.property.localeCompare(t.property,`en`,{numeric:!0}))}function wB(e,t){let n=xB(e).replace(/^www\./,``),r=e=>e.hostname===n||e.hostname===`www.${n}`?0:1;return[...t].sort((e,t)=>r(e)-r(t)||e.hostname.length-t.hostname.length||e.property.localeCompare(t.property,`en`,{numeric:!0}))}async function TB(e,t){let n=await e.accounts(),r=await Promise.all(n.map(t=>Bt(t.google,{signIn:e.signIn}).then(e=>({account:t,summaries:e}),e=>e instanceof Error?e:Error(String(e))))),i=new Set,a=[];for(let e of r)if(!(e instanceof Error))for(let t of e.summaries)for(let n of t.propertySummaries){let r=n.property.replace(/^properties\//,``);i.has(r)||!/^\d+$/.test(r)||(i.add(r),a.push({account:t.account,property:r,propertyName:n.displayName??r,google:e.account.google}))}if(!a.length){let e=r.find(e=>e instanceof Error);return e?`could not be read. ${e.message}`:`the connected Google accounts cannot read any property.`}let o=CB(t,a).slice(0,30),s=0;for(let n=0;n<o.length;n+=5){let r=o.slice(n,n+5),i=await Promise.all(r.map(t=>Vt(t.google,t.property,{signIn:e.signIn}).catch(()=>(s+=1,[])))),a=wB(t,r.flatMap((e,n)=>bB(t,(i[n]??[]).map(t=>({...e,stream:t}))))),c=new Map;for(let e of a){let t=r.find(t=>t.property===e.property);!t||c.has(e.property)||c.set(e.property,{property:e.property,name:e.propertyName,stream:e.defaultUri,google:t.google})}if(c.size)return[...c.values()].slice(0,3)}return`no web stream matches ${t} in ${o.length<a.length?`the first ${o.length} of ${a.length} properties, named like the site first`:`${a.length} ${a.length===1?`property`:`properties`}`}${s?` (${s} could not be read)`:``}.`}const EB=[`chatgpt.com`,`chatgpt`,`chat.openai.com`,`perplexity.ai`,`perplexity`,`claude.ai`,`gemini.google.com`,`copilot.microsoft.com`,`copilot.com`,`chat.deepseek.com`,`meta.ai`,`grok.com`,`chat.mistral.ai`,`you.com`,`phind.com`,`poe.com`],DB=`(www\\.)?(${EB.map(e=>e.replaceAll(`.`,`\\.`)).join(`|`)})`,OB=(e,t,n=`EXACT`)=>({filter:{fieldName:e,stringFilter:{matchType:n,value:t}}});async function kB(e,t,n,r,i){let a=(i,a)=>Ht(e.google,e.property,{dateRanges:[{...n,name:`now`},{...r,name:`before`}],dimensions:i.map(e=>({name:e})),metrics:[{name:`sessions`},{name:`keyEvents`}],...a.length?{dimensionFilter:{andGroup:{expressions:a}}}:{},limit:100},{signIn:t.signIn}),o=i?[OB(`landingPage`,i,`CONTAINS`)]:[],s=[...o,OB(`sessionSource`,DB,`FULL_REGEXP`)],[c,l,u,d]=await Promise.all([a([`sessionDefaultChannelGroup`],o),a([],[...o,OB(`sessionDefaultChannelGroup`,`Organic Search`),OB(`sessionSource`,`google`)]),a([`sessionSource`],s),a([`landingPage`],s)]),f=()=>({google:{sessions:0,keyEvents:0},organic:{sessions:0,keyEvents:0},all:{sessions:0,keyEvents:0}}),p={now:f(),before:f()},m=(e,t)=>{let n=(e.dimensionHeaders?.map(e=>e.name)??[]).indexOf(`dateRange`);for(let r of e.rows??[]){let e=r.dimensionValues??[];t((n>=0?e[n]:e.at(-1))?.value===`before`?p.before:p.now,e[0]?.value??``,{sessions:Number(r.metricValues?.[0]?.value??0),keyEvents:Number(r.metricValues?.[1]?.value??0)})}},h=(e,t)=>{e.sessions+=t.sessions,e.keyEvents+=t.keyEvents};m(c,(e,t,n)=>{h(e.all,n),t===`Organic Search`&&h(e.organic,n)}),m(l,(e,t,n)=>h(e.google,n));let g=(e,t)=>{let n=new Map,r=(e.dimensionHeaders?.map(e=>e.name)??[]).indexOf(`dateRange`);for(let t of e.rows??[]){let e=t.dimensionValues??[],i=e[0]?.value??``,a=(r>=0?e[r]:e.at(-1))?.value===`before`,o=n.get(i)??{now:0,before:0,keyEvents:0},s=Number(t.metricValues?.[0]?.value??0);a?o.before+=s:(o.now+=s,o.keyEvents+=Number(t.metricValues?.[1]?.value??0)),n.set(i,o)}return[...n].map(([e,n])=>({[t]:e,sessions:n.now,previousSessions:n.before,keyEvents:n.keyEvents})).sort((e,n)=>n.sessions-e.sessions||n.previousSessions-e.previousSessions||String(e[t]).localeCompare(String(n[t])))},_=g(u,`source`),v=_.reduce((e,t)=>e+t.sessions,0),y=_.reduce((e,t)=>e+t.previousSessions,0),b={metadata:{timeZone:c.metadata?.timeZone,subjectToThresholding:[c,l,u,d].some(e=>e.metadata?.subjectToThresholding),dataLossFromOtherRow:[c,l,u,d].some(e=>e.metadata?.dataLossFromOtherRow)}},x=[];return b.metadata?.timeZone&&b.metadata.timeZone!==`America/Los_Angeles`&&x.push(`Google Analytics days use the property's time zone, ${b.metadata.timeZone}; Search Console days use Pacific time.`),b.metadata?.subjectToThresholding&&x.push(`Google Analytics applied thresholding; small rows can be hidden.`),b.metadata?.dataLossFromOtherRow&&x.push(`Google Analytics grouped some rows into (other).`),{property:e.property,propertyName:e.name,webStream:e.stream,...i?{landingPageContains:i}:{},organicSearchFromGoogle:{sessions:p.now.google.sessions,previousSessions:p.before.google.sessions,sessionsChangePct:En(p.now.google.sessions,p.before.google.sessions)},organicSearch:{sessions:p.now.organic.sessions,previousSessions:p.before.organic.sessions,sessionsChangePct:En(p.now.organic.sessions,p.before.organic.sessions),keyEvents:p.now.organic.keyEvents,previousKeyEvents:p.before.organic.keyEvents},allChannels:{sessions:p.now.all.sessions,previousSessions:p.before.all.sessions,sessionsChangePct:En(p.now.all.sessions,p.before.all.sessions)},aiAssistants:{sessions:v,previousSessions:y,sessionsChangePct:En(v,y),bySource:_,topLandingPages:g(d,`page`).slice(0,20),sources:EB},notes:x}}const AB=e=>e===null?`n/a`:`${e>0?`+`:``}${e}%`;function jB(e){let t=(e,t)=>e.slice(0,5).map(e=>`${e[t]} ${e.sessions} (was ${e.previousSessions})`).join(`, `);return!e.sessions&&!e.previousSessions?`Visits from AI assistants (ChatGPT, Perplexity, Claude, Gemini, Copilot and others): none in either period.`:[`Visits from AI assistants (ChatGPT, Perplexity, Claude, Gemini, Copilot and others): ${e.sessions} sessions (was ${e.previousSessions}, ${AB(e.sessionsChangePct)}). By source: ${t(e.bySource,`source`)}.`,e.topLandingPages.length?`Top landing pages from AI assistants: ${t(e.topLandingPages,`page`)}.`:``,`Only visits that pass a referrer or utm_source count; AI apps that send none show as Direct.`].filter(Boolean).join(` `)}async function MB(e,t,n,r,i){if(!e)return null;try{let a=await TB(e,t);if(typeof a==`string`)return{text:`Google Analytics: ${a}`,data:{error:a}};let o=await Promise.all(a.map(t=>kB(t,e,n,r,i).catch(e=>e instanceof Error?e:Error(String(e))))),s=[...o.filter(e=>!(e instanceof Error))].sort((e,t)=>t.allChannels.sessions-e.allChannels.sessions)[0];if(!s)throw o[0];let c=a.filter(e=>e.property!==s.property).map(e=>`${e.name} (${e.property})`),l=s.organicSearchFromGoogle,u=s.organicSearch,d=s.allChannels,f=u.keyEvents||u.previousKeyEvents?`, Organic Search key events ${u.keyEvents} (was ${u.previousKeyEvents})`:``;return{text:[`Google Analytics, property ${s.propertyName} (${s.property}), matched by its web stream ${s.webStream}${i?`, landing pages whose path contains "${i}"`:``}: Organic Search sessions from Google ${l.sessions} (was ${l.previousSessions}, ${AB(l.sessionsChangePct)}), from every search engine ${u.sessions} (was ${u.previousSessions}, ${AB(u.sessionsChangePct)})${f}, sessions from all channels ${d.sessions} (was ${d.previousSessions}, ${AB(d.sessionsChangePct)}).`,`Sessions are Google Analytics’ own count, not Search Console clicks.`,...s.notes,...c.length?[`Other properties with a matching web stream, with fewer sessions: ${c.join(`, `)}.`]:[]].join(` `).concat(`
303
+ `)}const fB=[`query`,`page`,`date`,`country`,`device`,`searchAppearance`],pB=25e3;async function mB(e,t){let n=e.dimensions?.length?e.dimensions:[`query`],r=e.filters??[],i=Cn(e,28),a=wn(i),o={dimensions:n,type:`web`,maxRows:pB,...r.length?{dimensionFilterGroups:[{groupType:`and`,filters:r}]}:{}},[s,c]=await Promise.all([t.searchAnalytics(e.site,{...o,...i}),t.searchAnalytics(e.site,{...o,...a})]),l=n.indexOf(`page`),u=e=>l<0?e:tj(e,{pageKeyIndex:l}).rows,d=u(s.rows),f=u(c.rows),p=e=>e.join(`\0`),m=n.indexOf(`date`),h=(e,t)=>p(e.map((e,n)=>n===m?String(Math.round((Date.parse(e)-Date.parse(t))/864e5)):e)),g=new Map(f.map(e=>[h(e.keys,a.startDate),e])),_=new Set,v=d.map(e=>{let t=h(e.keys,i.startDate);_.add(t);let r=g.get(t);return{...Object.fromEntries(n.map((t,n)=>[t,e.keys[n]])),clicks:e.clicks,impressions:e.impressions,ctr:e.ctr,position:e.position,...m>=0?{previous_date:r?.keys[m]??null}:{},previous_clicks:r?.clicks??0,clicks_change:e.clicks-(r?.clicks??0),previous_position:r?.position??null}});if(m<0)for(let e of f)_.has(h(e.keys,a.startDate))||v.push({...Object.fromEntries(n.map((t,n)=>[t,e.keys[n]])),clicks:0,impressions:0,ctr:0,position:null,previous_clicks:e.clicks,clicks_change:-e.clicks,previous_position:e.position});v.sort((e,t)=>m>=0?String(e.date).localeCompare(String(t.date)):Number(t.clicks??0)-Number(e.clicks??0));let y=[];if(!n.includes(`query`)&&!n.includes(`page`)){let e=e=>v.reduce((t,n)=>t+Number(n[e]??0),0);y.push(`Totals: clicks ${e(`clicks`)}, impressions ${e(`impressions`)}; previous period clicks ${e(`previous_clicks`)}.`)}y.push(`Compared with ${a.startDate} to ${a.endDate}${c.rowsFetched>=pB?` (earlier period hit the row limit)`:``}. 0 clicks with no position means the row had no impressions in the current period.`),l>=0&&y.push(`Page URLs with #fragments are merged into their page.`),s.rowsFetched>=pB&&y.push(`Search Console has more than ${pB} rows; add a filter to narrow it.`),y.push(`Search Console hides some rare queries for privacy, so query rows do not add up to the site totals.`);let b=e.detail??`summary`;return{text:`${dB({title:`Search Console ${e.site}, ${i.startDate} to ${i.endDate}, web, by ${n.join(` and `)}.`,rows:v,offset:e.offset??0,limit:50,detail:b,notes:y,origin:Tn(e.site),more:r=>t.call(`data`,{site:e.site,dimensions:n.join(`,`),detail:`rows`,offset:r})})}\n\n${bn}`,data:{range:i,comparisonRange:a,total:v.length,offset:e.offset??0,rows:v.slice(e.offset??0,(e.offset??0)+50)}}}async function hB(e,t,n){let r=e.length===1?e[0]:void 0;if(r)return r.google;let i=(await Promise.all(e.map(async e=>(await Bt(e.google,{signIn:n}).catch(()=>[])).some(e=>e.propertySummaries.some(e=>e.property===`properties/${t}`))?e:null))).find(Boolean);if(i)return i.google;throw new yn(`NO_ACCESS`,`No connected Google account can read Google Analytics property ${t}. Call seo_sites to list the properties.`)}async function gB(e,t,n){let r=Cn(e,28),i=e.offset??0,a=Math.min(1e3,i+50),o=await Ht(t,e.property,{dateRanges:[r],dimensions:[{name:`landingPage`}],metrics:[{name:`sessions`},{name:`totalUsers`},{name:`engagedSessions`},{name:`keyEvents`}],dimensionFilter:{filter:{fieldName:`sessionDefaultChannelGroup`,stringFilter:{value:`Organic Search`}}},orderBys:[{metric:{metricName:`sessions`},desc:!0}],limit:a},n),s=[`Sessions in the Organic Search default channel group.`];o.metadata?.subjectToThresholding&&s.push(`Google Analytics applied thresholding; small rows can be hidden.`),o.metadata?.dataLossFromOtherRow&&s.push(`Some rows were grouped into (other) by Google Analytics.`),(o.rowCount??0)>a&&s.push(`${o.rowCount} landing pages in total; ${a} read.`);let c=(o.rows??[]).map(e=>({page:e.dimensionValues[0]?.value??``,sessions:Number(e.metricValues[0]?.value??0),users:Number(e.metricValues[1]?.value??0),engaged_sessions:Number(e.metricValues[2]?.value??0),key_events:Number(e.metricValues[3]?.value??0)}));return{text:dB({title:`Google Analytics property ${e.property}: search landing pages, ${r.startDate} to ${r.endDate}.`,rows:c,offset:i,limit:50,detail:e.detail??`summary`,notes:s,more:n.call}),data:{range:r,total:c.length,offset:i,rows:c.slice(i,i+50)}}}function _B(e){try{let t=new URL(e);return t.protocol!==`http:`&&t.protocol!==`https:`?void 0:t.hostname.toLowerCase().replace(/\.$/,``)||void 0}catch{return}}function vB(e){if(!e.startsWith(`sc-domain:`))return;let t=e.slice(10).trim().toLowerCase();if(!(!t||/[/:]/.test(t)))return t.replace(/\.$/,``)||void 0}function yB(e,t){let n=vB(e);return n?t===n||t.endsWith(`.${n}`)?`domain`:void 0:_B(e)===t?`hostname`:void 0}function bB(e,t){return t.flatMap(t=>{let n=t.stream.webStreamData?.defaultUri;if(!n)return[];let r=_B(n);if(!r)return[];let i=yB(e,r);return i?[{...t,defaultUri:n,hostname:r,match:i}]:[]})}const xB=e=>{let t=e.replace(/^sc-domain:/,``);try{return new URL(t.includes(`://`)?t:`https://${t}`).hostname}catch{return t}},SB=e=>e.toLowerCase().replace(/[^a-z0-9]/g,``);function CB(e,t){let n=xB(e).replace(/^www\./,``),r=[SB(n),SB(n.split(`.`)[0]??``)].filter(e=>e.length>=3),i=e=>+!r.some(t=>SB(e.propertyName).includes(t));return[...t].sort((e,t)=>i(e)-i(t)||e.property.localeCompare(t.property,`en`,{numeric:!0}))}function wB(e,t){let n=xB(e).replace(/^www\./,``),r=e=>e.hostname===n||e.hostname===`www.${n}`?0:1;return[...t].sort((e,t)=>r(e)-r(t)||e.hostname.length-t.hostname.length||e.property.localeCompare(t.property,`en`,{numeric:!0}))}async function TB(e,t){let n=await e.accounts(),r=await Promise.all(n.map(t=>Bt(t.google,{signIn:e.signIn}).then(e=>({account:t,summaries:e}),e=>e instanceof Error?e:Error(String(e))))),i=new Set,a=[];for(let e of r)if(!(e instanceof Error))for(let t of e.summaries)for(let n of t.propertySummaries){let r=n.property.replace(/^properties\//,``);i.has(r)||!/^\d+$/.test(r)||(i.add(r),a.push({account:t.account,property:r,propertyName:n.displayName??r,google:e.account.google}))}if(!a.length){let e=r.find(e=>e instanceof Error);return e?`could not be read. ${e.message}`:`the connected Google accounts cannot read any property.`}let o=CB(t,a).slice(0,30),s=0;for(let n=0;n<o.length;n+=5){let r=o.slice(n,n+5),i=await Promise.all(r.map(t=>Vt(t.google,t.property,{signIn:e.signIn}).catch(()=>(s+=1,[])))),a=wB(t,r.flatMap((e,n)=>bB(t,(i[n]??[]).map(t=>({...e,stream:t}))))),c=new Map;for(let e of a){let t=r.find(t=>t.property===e.property);!t||c.has(e.property)||c.set(e.property,{property:e.property,name:e.propertyName,stream:e.defaultUri,google:t.google})}if(c.size)return[...c.values()].slice(0,3)}return`no web stream matches ${t} in ${o.length<a.length?`the first ${o.length} of ${a.length} properties, named like the site first`:`${a.length} ${a.length===1?`property`:`properties`}`}${s?` (${s} could not be read)`:``}.`}const EB=[`chatgpt.com`,`chatgpt`,`chat.openai.com`,`perplexity.ai`,`perplexity`,`claude.ai`,`gemini.google.com`,`copilot.microsoft.com`,`copilot.com`,`chat.deepseek.com`,`meta.ai`,`grok.com`,`chat.mistral.ai`,`you.com`,`phind.com`,`poe.com`],DB=`(www\\.)?(${EB.map(e=>e.replaceAll(`.`,`\\.`)).join(`|`)})`,OB=(e,t,n=`EXACT`)=>({filter:{fieldName:e,stringFilter:{matchType:n,value:t}}});async function kB(e,t,n,r,i){let a=(i,a)=>Ht(e.google,e.property,{dateRanges:[{...n,name:`now`},{...r,name:`before`}],dimensions:i.map(e=>({name:e})),metrics:[{name:`sessions`},{name:`keyEvents`}],...a.length?{dimensionFilter:{andGroup:{expressions:a}}}:{},limit:100},{signIn:t.signIn}),o=i?[OB(`landingPage`,i,`CONTAINS`)]:[],s=[...o,OB(`sessionSource`,DB,`FULL_REGEXP`)],[c,l,u,d,f]=await Promise.all([a([`sessionDefaultChannelGroup`],o),a([],[...o,OB(`sessionDefaultChannelGroup`,`Organic Search`),OB(`sessionSource`,`google`)]),a([`sessionSource`],s),a([`landingPage`],s),a([`sessionSource`],[...o,OB(`sessionDefaultChannelGroup`,`Organic Search`)])]),p=()=>({google:{sessions:0,keyEvents:0},organic:{sessions:0,keyEvents:0},all:{sessions:0,keyEvents:0}}),m={now:p(),before:p()},h=(e,t)=>{let n=(e.dimensionHeaders?.map(e=>e.name)??[]).indexOf(`dateRange`);for(let r of e.rows??[]){let e=r.dimensionValues??[];t((n>=0?e[n]:e.at(-1))?.value===`before`?m.before:m.now,e[0]?.value??``,{sessions:Number(r.metricValues?.[0]?.value??0),keyEvents:Number(r.metricValues?.[1]?.value??0)})}},g=(e,t)=>{e.sessions+=t.sessions,e.keyEvents+=t.keyEvents};h(c,(e,t,n)=>{g(e.all,n),t===`Organic Search`&&g(e.organic,n)}),h(l,(e,t,n)=>g(e.google,n));let _=(e,t)=>{let n=new Map,r=(e.dimensionHeaders?.map(e=>e.name)??[]).indexOf(`dateRange`);for(let t of e.rows??[]){let e=t.dimensionValues??[],i=e[0]?.value??``,a=(r>=0?e[r]:e.at(-1))?.value===`before`,o=n.get(i)??{now:0,before:0,keyEvents:0},s=Number(t.metricValues?.[0]?.value??0);a?o.before+=s:(o.now+=s,o.keyEvents+=Number(t.metricValues?.[1]?.value??0)),n.set(i,o)}return[...n].map(([e,n])=>({[t]:e,sessions:n.now,previousSessions:n.before,keyEvents:n.keyEvents})).sort((e,n)=>n.sessions-e.sessions||n.previousSessions-e.previousSessions||String(e[t]).localeCompare(String(n[t])))},v=_(u,`source`),y=_(f,`source`),b=v.reduce((e,t)=>e+t.sessions,0),x=v.reduce((e,t)=>e+t.previousSessions,0),S={metadata:{timeZone:c.metadata?.timeZone,subjectToThresholding:[c,l,u,d,f].some(e=>e.metadata?.subjectToThresholding),dataLossFromOtherRow:[c,l,u,d,f].some(e=>e.metadata?.dataLossFromOtherRow)}},C=[];return S.metadata?.timeZone&&S.metadata.timeZone!==`America/Los_Angeles`&&C.push(`Google Analytics days use the property's time zone, ${S.metadata.timeZone}; Search Console days use Pacific time.`),S.metadata?.subjectToThresholding&&C.push(`Google Analytics applied thresholding; small rows can be hidden.`),S.metadata?.dataLossFromOtherRow&&C.push(`Google Analytics grouped some rows into (other).`),{property:e.property,propertyName:e.name,webStream:e.stream,...i?{landingPageContains:i}:{},organicSearchFromGoogle:{sessions:m.now.google.sessions,previousSessions:m.before.google.sessions,sessionsChangePct:En(m.now.google.sessions,m.before.google.sessions)},organicSearch:{sessions:m.now.organic.sessions,previousSessions:m.before.organic.sessions,sessionsChangePct:En(m.now.organic.sessions,m.before.organic.sessions),keyEvents:m.now.organic.keyEvents,previousKeyEvents:m.before.organic.keyEvents},allChannels:{sessions:m.now.all.sessions,previousSessions:m.before.all.sessions,sessionsChangePct:En(m.now.all.sessions,m.before.all.sessions)},organicSearchByEngine:y.slice(0,10),aiAssistants:{sessions:b,previousSessions:x,sessionsChangePct:En(b,x),bySource:v,topLandingPages:_(d,`page`).slice(0,20),sources:EB},notes:C}}const AB=e=>e===null?`n/a`:`${e>0?`+`:``}${e}%`;function jB(e){let t=e.filter(e=>e.sessions||e.previousSessions);return t.length<2?``:`Organic Search sessions by search engine: ${t.slice(0,5).map(e=>`${e.source} ${e.sessions} (was ${e.previousSessions})`).join(`, `)}.`}function MB(e){let t=(e,t)=>e.slice(0,5).map(e=>`${e[t]} ${e.sessions} (was ${e.previousSessions})`).join(`, `);return!e.sessions&&!e.previousSessions?`Visits from AI assistants (ChatGPT, Perplexity, Claude, Gemini, Copilot and others): none in either period.`:[`Visits from AI assistants (ChatGPT, Perplexity, Claude, Gemini, Copilot and others): ${e.sessions} sessions (was ${e.previousSessions}, ${AB(e.sessionsChangePct)}). By source: ${t(e.bySource,`source`)}.`,e.topLandingPages.length?`Top landing pages from AI assistants: ${t(e.topLandingPages,`page`)}.`:``,`Only visits that pass a referrer or utm_source count; AI apps that send none show as Direct.`].filter(Boolean).join(` `)}async function NB(e,t,n,r,i){if(!e)return null;try{let a=await TB(e,t);if(typeof a==`string`)return{text:`Google Analytics: ${a}`,data:{error:a}};let o=await Promise.all(a.map(t=>kB(t,e,n,r,i).catch(e=>e instanceof Error?e:Error(String(e))))),s=[...o.filter(e=>!(e instanceof Error))].sort((e,t)=>t.allChannels.sessions-e.allChannels.sessions)[0];if(!s)throw o[0];let c=a.filter(e=>e.property!==s.property).map(e=>`${e.name} (${e.property})`),l=s.organicSearchFromGoogle,u=s.organicSearch,d=s.allChannels,f=u.keyEvents||u.previousKeyEvents?`, Organic Search key events ${u.keyEvents} (was ${u.previousKeyEvents})`:``;return{text:[`Google Analytics, property ${s.propertyName} (${s.property}), matched by its web stream ${s.webStream}${i?`, landing pages whose path contains "${i}"`:``}: Organic Search sessions from Google ${l.sessions} (was ${l.previousSessions}, ${AB(l.sessionsChangePct)}), from every search engine ${u.sessions} (was ${u.previousSessions}, ${AB(u.sessionsChangePct)})${f}, sessions from all channels ${d.sessions} (was ${d.previousSessions}, ${AB(d.sessionsChangePct)}).`,jB(s.organicSearchByEngine),`Sessions are Google Analytics’ own count, not Search Console clicks.`,...s.notes,...c.length?[`Other properties with a matching web stream, with fewer sessions: ${c.join(`, `)}.`]:[]].filter(Boolean).join(` `).concat(`
304
304
 
305
- `,jB(s.aiAssistants)),data:{...s,...c.length?{otherMatches:c}:{}}}}catch(e){let t=e instanceof Error?e.message:String(e);return{text:`Google Analytics: could not be read. ${t}`,data:{error:t}}}}const NB=[`Bing and Google count clicks, impressions and positions their own way. Their numbers sit side by side here and are never added together.`,`Bing lists only its top queries and pages, grouped by week. A query or page missing from Bing’s list is unknown, not zero.`],PB="If you have a shell, link the CLI to the same account once: run `npx -y seo login`, show the person the link it prints, and after they approve it run `npx -y seo login` again. `npx -y seo` commands then use the same Google accounts, Bing and keys.",FB=`Bing blocks the hosted server, so Bing data comes from the CLI on a machine. ${PB} Connect Bing on the account page if it is not connected, then run \`npx -y seo report --site <site> --section bing --json\`.`,IB="Bing: not included here, so these totals show Google only. Some sites get most of their search visits from Bing; the CLI reads them with the same account: `npx -y seo login` once, then `npx -y seo report --site <site> --section bing --json`.",LB=`https://www.bing.com/webmasters`,RB=e=>`Bing has no data for ${e} yet. Newly added or newly verified sites take a few days to show data in Bing Webmaster Tools.`,zB=new WeakMap;async function BB(e,t){if(!e.bing)return{call:null,site:null,missing:FB};let n=await e.bing();if(!n)return{call:null,site:null,missing:`Bing is not connected. ${e.bingConnect??``}`.trim()};let r=zB.get(n);r||(r=qt(n),zB.set(n,r));let i=Qt(await r,t);return i?.verified?{call:n,site:i.url}:{call:null,site:null,missing:i?`${i.url} is in the connected Bing account but is not verified, so Bing gives no data for it. Verify it at ${LB}.`:`The connected Bing account does not have ${t.replace(/^sc-domain:/,``)}. Add and verify it at ${LB} (it can import sites from Search Console). New sites take a few days to show data.`}}function VB(e){return Math.round((Date.parse(e.endDate)-Date.parse(e.startDate))/864e5)+1}async function HB(e,t,n){if(!e.call)return{missing:e.missing};let r=await Jt(e.call,e.site);if(!r.rows.length&&!r.invalidRows)return{missing:RB(e.site)};let i=e=>{let t=r.rows.filter(t=>t.date>=e.startDate&&t.date<=e.endDate);return{clicks:t.reduce((e,t)=>e+t.clicks,0),impressions:t.reduce((e,t)=>e+t.impressions,0),days:new Set(t.map(e=>e.date)).size,expectedDays:VB(e)}};return{site:e.site,current:i(t),previous:i(n),invalidRows:r.invalidRows}}const UB=(e,t)=>{let n=En(e,t);return n===null?`n/a`:`${n>0?`+`:``}${n}%`};function WB(e,t){if(`missing`in t)return`Bing: ${t.missing}`;let{current:n,previous:r}=t,i=[`Search engines, same dates. Google (Search Console): clicks ${e.clicks} (was ${e.previousClicks}, ${UB(e.clicks,e.previousClicks)}), impressions ${e.impressions}. Bing (${t.site}): clicks ${n.clicks} (was ${r.clicks}, ${UB(n.clicks,r.clicks)}), impressions ${n.impressions} (was ${r.impressions}).`],a=e.clicks+n.clicks;return a>0&&i.push(`Share of these clicks: Google ${Math.round(e.clicks/a*100)}%, Bing ${Math.round(n.clicks/a*100)}%.`),(n.days<n.expectedDays||r.days<r.expectedDays)&&i.push(`Bing has data for ${n.days} of ${n.expectedDays} days (earlier period ${r.days} of ${r.expectedDays}), so its totals are partial.`),i.join(` `)}function GB(e,t){let n=e.filter(e=>e.date>=t.startDate&&e.date<=t.endDate),r=new Map;for(let e of n){let t=r.get(e.key)??{key:e.key,clicks:0,impressions:0,position:null,weighted:0,seen:0};t.clicks+=e.clicks,t.impressions+=e.impressions,e.position!==null&&e.impressions>0&&(t.weighted+=e.position*e.impressions,t.seen+=e.impressions),r.set(e.key,t)}return{rows:[...r.values()].map(({weighted:e,seen:t,...n})=>({...n,position:t>0?Math.round(e/t*10)/10:null})).sort((e,t)=>t.clicks-e.clicks||t.impressions-e.impressions||(e.key<t.key?-1:+(e.key>t.key))),weeks:[...new Set(n.map(e=>e.date))].sort()}}async function KB(e,t,n,r){if(!e.call)throw new yn(`NOT_CONNECTED`,e.missing);let i=e=>t(n,{...r,dimensions:[e],type:`web`,dataState:`final`,maxRows:25e3}),[a,o,s]=await Promise.all([Xt(e.call,e.site),Zt(e.call,e.site),Promise.all([i(`query`),i(`page`)]).catch(e=>e instanceof Error?e:Error(String(e)))]),c=s instanceof Error?s:null,[l,u]=s instanceof Error?[]:s,d=(e,t,n)=>{let r=e=>n===`query`?e.toLowerCase().trim():e.replace(/#.*$/,``),i=new Map(t?.map(e=>[r(e.keys[0]??``),e]));return e.map(e=>{let a=i.get(r(e.key)),o=t?0:null;return{[n]:e.key,bingClicks:e.clicks,bingImpressions:e.impressions,bingPosition:e.position,googleClicks:a?.clicks??o,googleImpressions:a?.impressions??o,googlePosition:a?Math.round(a.position*10)/10:null}})},f=GB(a.rows,r),p=GB(o.rows,r),m=a.invalidRows+o.invalidRows,h=!a.rows.length&&!o.rows.length&&!m;return{range:r,bingSite:e.site,summary:{bingQueries:f.rows.length,bingPages:p.rows.length,weeks:f.weeks.length},items:d(f.rows,l?.rows,`query`),topPages:d(p.rows,u?.rows,`page`),caveats:[...h?[RB(e.site)]:[],...c?[`Search Console was not available, so the Google columns are empty (unknown, not zero): ${c.message}`]:[],`Bing weeks counted: ${f.weeks.join(`, `)||`none`} (each date names a week). Google numbers cover ${r.startDate} to ${r.endDate} exactly.`,`Google numbers are for the same query text or page URL. 0 means Google showed no row for it in these dates.`,...NB,...m?[`${m} Bing rows were not valid and were left out.`]:[]]}}async function qB(e,t){let n=await BB(t,e.site);if(!n.call)throw new yn(`NOT_CONNECTED`,n.missing);let r=Cn(e,28),i=wn(r),a=await(e.dimension===`page`?Zt:Xt)(n.call,n.site),o=GB(a.rows,r),s=GB(a.rows,i),c=new Map(s.rows.map(e=>[e.key,e])),l=new Set(o.rows.map(e=>e.key)),u=o.rows.map(t=>({[e.dimension]:t.key,clicks:t.clicks,impressions:t.impressions,position:t.position,previous_clicks:c.get(t.key)?.clicks??0,clicks_change:t.clicks-(c.get(t.key)?.clicks??0)}));for(let t of s.rows)l.has(t.key)||u.push({[e.dimension]:t.key,clicks:0,impressions:0,position:null,previous_clicks:t.clicks,clicks_change:-t.clicks});let d=[...a.rows.length||a.invalidRows?[]:[RB(n.site)],`Bing weeks counted: ${o.weeks.join(`, `)||`none`}; earlier period ${s.weeks.join(`, `)||`none`}. Each date names a week.`,...NB.slice(1),...a.invalidRows?[`${a.invalidRows} Bing rows were not valid and were left out.`]:[]];return{text:`${dB({title:`Bing Webmaster ${n.site}, ${r.startDate} to ${r.endDate}, by ${e.dimension}.`,rows:u,offset:e.offset??0,limit:50,detail:e.detail??`summary`,notes:d,origin:Tn(n.site),more:n=>t.call(`data`,{site:e.site,source:`bing`,dimensions:e.dimension,detail:`rows`,offset:n})})}\n\n${bn.replace(`Search Console`,`Bing Webmaster Tools`)}`,data:{bingSite:n.site,range:r,comparisonRange:i,weeks:o.weeks,total:u.length,offset:e.offset??0,rows:u.slice(e.offset??0,(e.offset??0)+50)}}}const JB=`x-clicky-`;function YB(e){let t=[];for(let[n,r]of e){if(!n.startsWith(`x-clicky-`))continue;let e=n.slice(9);if(!sB(e))continue;let i=r.trim(),a=null,o=!1;if(i.startsWith(`{`))try{let e=JSON.parse(i);i=typeof e.sitekey==`string`?e.sitekey:``,a=typeof e.domain==`string`?e.domain:null,o=e.account===!0}catch{continue}cB(i)&&t.push({siteId:e,sitekey:i,domain:a,account:o})}return t.sort((e,t)=>e.siteId<t.siteId?-1:+(e.siteId>t.siteId))}const XB=e=>e.domain?`${e.siteId} (${e.domain})`:e.siteId;function ZB(e){let t=e.trim().toLowerCase().replace(/^sc-domain:/u,``);try{return new URL(t.includes(`://`)?t:`https://${t}`).hostname.replace(/^www\./u,``)}catch{return t}}async function QB(e,t,n,r){let i=ZB(t),a=e=>e.siteId===t.trim()||e.domain===i,o=e;if(!o.some(a)&&r&&(o=await r()??o),!o.length)throw new yn(`NO_KEY`,`No Clicky site is saved. Add your Clicky account, or one site's ID and sitekey (Clicky, Preferences, Info): ${n}`);let s=o.find(a);if(s)return s;if(!sB(t)){for(let e of o.filter(e=>!e.domain).slice(0,10))e.domain=await uB(e).catch(()=>null);let e=o.find(a);if(e)return e}throw new yn(`NO_ACCESS`,`No saved Clicky site matches ${t}. Saved Clicky sites: ${o.map(XB).join(`, `)}. Pass one of these site IDs, or add the site: ${n}`)}const $B=864e5,eV=e=>new Date(e).toISOString().slice(0,10);function tV(e){if(!e.startDate&&!e.endDate){let e=Date.now()-$B;return{startDate:eV(e-27*$B),endDate:eV(e)}}let t=Date.parse(`${e.startDate}T00:00:00Z`),n=Date.parse(`${e.endDate}T00:00:00Z`);if(!e.startDate||!e.endDate||!(t<=n))throw new yn(`INVALID_INPUT`,`Send a start date and an end date together, in order.`);if((n-t)/$B+1>31)throw new yn(`INVALID_INPUT`,`Clicky reads at most 31 days at a time. Send a shorter range.`);return{startDate:e.startDate,endDate:e.endDate}}const nV=e=>{let t=Number(e.value);return Number.isSafeInteger(t)&&t>=0?t:null},rV=e=>e.map(e=>({name:e.title??``,visits:nV(e)})).filter(e=>!!e.name&&e.visits!==null),iV=e=>{let t=e.slice(0,10).map(e=>`${e.name} ${e.visits}`),n=e.slice(10);return n.length&&t.push(`${n.length} others ${n.reduce((e,t)=>e+t.visits,0)}`),t.join(`; `)},aV=1e3;async function oV(e,t,n){let r=n.refresh,i=await QB(YB(t),e.site,n.connect,r&&(async()=>{let e=await r().catch(()=>null);return e&&YB(e)})),a=tV(e),o=e.offset??0,s=await lB(i,[`pages-entrance`,`traffic-sources`,`searches-engines`],{date:`${a.startDate},${a.endDate}`,limit:aV}).catch(e=>{throw e instanceof oB?new yn(e.code===`auth`?`NO_ACCESS`:`PROVIDER_ERROR`,e.code===`auth`?`${e.message} Save it again: ${n.connect}`:e.message):e}),c=s[`pages-entrance`]??[],l=new Map;for(let e of c){let t=nV(e);if(t===null||!e.url)continue;let n;try{n=new URL(e.url).pathname}catch{continue}l.set(n,(l.get(n)??0)+t)}let u=[...l].map(([e,t])=>({page:e,visits:t})).sort((e,t)=>t.visits-e.visits||(e.page<t.page?-1:+(e.page>t.page))),d=rV(s[`traffic-sources`]??[]),f=rV(s[`searches-engines`]??[]),p=[`Visits by landing page from every source, as Clicky counts them, in the Clicky site’s time zone. Clicky does not split landing pages by source.`,d.length?`Traffic sources (visits): ${iV(d)}.`:`Traffic sources: none in this range.`,f.length?`Search engines (visits): ${iV(f)}.`:`Search engines: none in this range.`];return c.length>=aV&&p.push(`Clicky returned its ${aV}-row limit; pages past it are missing, not zero.`),{text:dB({title:`Clicky site ${XB(i)}: landing pages, ${a.startDate} to ${a.endDate}.`,rows:u,offset:o,limit:50,detail:e.detail??`summary`,notes:p,more:n.call}),data:{siteId:i.siteId,domain:i.domain,range:a,metric:`visits`,sources:d,searchEngines:f,capped:c.length>=aV,total:u.length,offset:o,rows:u.slice(o,o+50)}}}const sV=`domain_rating: Domain Rating by Ahrefs (https://ahrefs.com/).`,cV=[`domain`,`competitor_domain`,`Dn`];function lV(e){return e.replace(/^sc-domain:/,``).replace(/^https?:\/\//,``).replace(/\/.*$/,``).replace(/^www\./,``).toLowerCase()}async function uV(e,t){let n=`https://api.ahrefs.com/v3/public/domain-rating-free?target=${encodeURIComponent(e)}`,r=globalThis.caches?.default,i=new Request(n),a=await r?.match(i),o=a??await fetch(n,{headers:{authorization:`Bearer ${t}`,accept:`application/json`},signal:AbortSignal.timeout(5e3)});if(!o.ok)return null;let s=await kt(o.clone(),`Ahrefs Domain Rating`);if(r&&!a){let e=new Response(o.body,o);e.headers.set(`cache-control`,`max-age=86400`),await r.put(i,e)}return s.domain_rating?.domain_rating??null}async function dV(e,t){let n=new Map;if(!t)return n;let r=[...new Set(e.map(lV).filter(Boolean))].slice(0,25),i=await Promise.all(r.map(e=>uV(e,t).catch(()=>null)));return r.forEach((e,t)=>{n.set(e,i[t]??null)}),n}async function fV(e,t){let n=cV.find(t=>e.some(e=>typeof e[t]==`string`));if(!t||!n||e.some(e=>`domain_rating`in e))return{rows:e,added:!1};let r=await dV(e.map(e=>String(e[n]??``)),t);return{rows:e.map(e=>{let t={};for(let[i,a]of Object.entries(e))t[i]=a,i===n&&(t.domain_rating=r.get(lV(String(a??``)))??null);return t}),added:!0}}const pV=e=>e?.trim().replace(/\s+/g,` `)||null;async function mV(e){if(!e.body)return``;let t=e.body.getReader(),n=new TextDecoder,r=``,i=0;for(;i<1e6;){let{done:e,value:a}=await t.read();if(e)return r+n.decode();i+=a.byteLength,r+=n.decode(a,{stream:!0})}return await t.cancel(),r}function hV(e,t){let n=``,r=``,i=!1,a=!1,o=!1,s=!1,c=null,l=null,u=[],d=new ce({onopentag(e,n){if(e===`title`&&!o&&(i=!0),e===`h1`&&!s&&(a=!0),e===`meta`){let e=n.name?.toLowerCase();e===`description`&&c===null&&(c=n.content??null),e===`robots`&&n.content&&u.push(n.content)}if(e===`link`&&l===null&&n.rel?.toLowerCase().split(/\s+/).includes(`canonical`)&&n.href)try{l=new URL(n.href,t).toString()}catch{l=n.href}},ontext(e){i&&(n+=e),a&&(r+=e)},onclosetag(e){e===`title`&&i&&(i=!1,o=!0),e===`h1`&&a&&(a=!1,s=!0)}},{decodeEntities:!0,lowerCaseTags:!0});return d.write(e),d.end(),{title:pV(n),description:pV(c),h1:pV(r),canonical:l,robots:u.length?u.join(`, `):null}}async function gV(e){let t={url:e,status:null,redirects_to:null,title:null,description:null,h1:null,canonical:null,robots:null};try{let n=await fetch(e,{redirect:`manual`,headers:{"user-agent":fb,accept:`text/html`},signal:AbortSignal.timeout(6e3)});t.status=n.status;let r=n.headers.get(`location`);r&&(t.redirects_to=new URL(r,e).toString());let i=n.headers.get(`x-robots-tag`);if(n.status!==200||!n.headers.get(`content-type`)?.includes(`html`))return t.robots=i,await n.body?.cancel(),t;let a=hV(await mV(n),e);Object.assign(t,a),t.robots=[i,a.robots].filter(Boolean).join(`, `)||null}catch(e){t.error=e instanceof Error?e.message:`fetch failed`}return t}function _V(e){return Promise.all(e.slice(0,20).map(gV))}function vV(e){let t=e.filter(e=>(e.status===302||e.status===307)&&e.redirects_to!==null&&new URL(e.redirects_to).host===new URL(e.url).host);return t.length?`Note: 302 and 307 are temporary redirects; a permanent move usually uses 301 or 308. Temporary redirects here: ${t.map(e=>`${e.url} (${e.status} to ${e.redirects_to})`).join(`; `)}.`:null}const yV=[[`agent_prompt`,`^(search the web for|browse the web|find sources)|do not invent|return the [0-9]+ most relevant|include source urls|context: location|do not include location|question: `],[`tracker`,`\\. ?my location is |^evaluate the .+ on `],[`reply`,`^(yes|yeah|yep|ok|okay|sure|yes please|go on|continue|keep going|tell me more|why not|how so|really|exactly|show me|and then|thanks|thank you|got it|what else|anything else)[?!.,]*$`],[`follow_up`,`^(what|how) about .{1,40}$|^(and|so|ok so|okay so|but) (what|which|how|why) `],[`operator`,`(^|\\s)-?(site|before|after|intitle|inurl|intext|filetype):|"[^"]*" or "`],[`chat`,`\\b(please|can you|could you|give me|show me|tell me|i want|i need|i have|i am|should i|do i need|is it worth|help me|walk me through)\\b|^(what|how|why|is|does|can|will|would) (it|that|this|they)\\b`],[`long`,`^(\\S+\\s+){9,}\\S+$`]],bV={agent_prompt:`text from an agent prompt, such as "search the web for"`,tracker:`a visibility-tool probe, such as "my location is"`,reply:`a bare reply, such as "yes" or "tell me more"`,follow_up:`a follow-up, such as "what about …"`,operator:`search operators, such as site:, before: or "a" or "b"`,chat:`chat phrasing, such as "can you" or "should i"`,long:`ten or more words with no other sign`},xV=yV.map(([e,t])=>[e,new RegExp(t)]),SV=yV.map(([,e])=>`(?:${e})`).join(`|`);function CV(e){let t=e.trim().toLowerCase();return xV.find(([,e])=>e.test(t))?.[0]??null}const wV=new Set(`the and for with that this what which who how why when where are is was can does do did you your our from about into than then them they their there have has had will would should could not but its it’s me my i am of to in on at by or an as be if so`.split(` `));function TV(e){return new Set(e.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(e=>e.length>=3&&!wV.has(e)).map(e=>e.length>4&&e.endsWith(`s`)?e.slice(0,-1):e))}const EV=25e3,DV=(e,t,n)=>{let r=0,i=0;for(let a of e)i+=n(a),t.has(a)&&(r+=n(a));for(let r of t)e.has(r)||(i+=n(r));return i?r/i:0},OV=(e,t)=>Math.round(e*10**t)/10**t;async function kV(e,t){let n={startDate:e.startDate,endDate:e.endDate},[r,i]=await Promise.all([t(e.site,{...n,dimensions:[`query`,`page`],type:`web`,dataState:`final`,maxRows:EV,dimensionFilterGroups:[{filters:[{dimension:`query`,operator:`includingRegex`,expression:SV}]}]}),t(e.site,{...n,dimensions:[],type:`web`,dataState:`final`})]),a=[...r.rows].sort((e,t)=>t.impressions-e.impressions||String(e.keys[0]).localeCompare(String(t.keys[0]))||String(e.keys[1]).localeCompare(String(t.keys[1]))),o=new Map,s=new Set(a.map(e=>String(e.keys[0]??``)));for(let e of s)for(let t of TV(e))o.set(t,(o.get(t)??0)+1);let c=e=>Math.log((s.size+1)/(o.get(e)??1)),l=[],u=new Map,d=new Map,f=new Map;for(let e of a){let t=String(e.keys[0]??``),n=String(e.keys[1]??``),r=CV(t);if(!r)continue;let i=t.trim().toLowerCase(),a=TV(t),o=d.get(i);if(!o){let e=0;for(let t of a){for(let n of u.get(t)??[]){if(++e>200)break;if(DV(a,n.words,c)>=.6){o=n;break}}if(o||e>200)break}}if(!o){o={words:a,queries:new Map,pages:new Map,kinds:new Map,clicks:0,impressions:0,positionWeight:0},l.push(o);for(let e of a){let t=u.get(e)??[];t.push(o),u.set(e,t)}}d.set(i,o),f.has(i)||(f.set(i,r),o.kinds.set(r,(o.kinds.get(r)??0)+1)),o.queries.set(t,(o.queries.get(t)??0)+e.impressions),o.pages.set(n,(o.pages.get(n)??0)+e.impressions),o.clicks+=e.clicks,o.impressions+=e.impressions,o.positionWeight+=e.position*e.impressions}let p=new Map;for(let e of f.values()){let t=p.get(e)??{queries:0,impressions:0};t.queries+=1,p.set(e,t)}for(let e of a){let t=f.get(String(e.keys[0]??``).trim().toLowerCase()),n=t&&p.get(t);n&&(n.impressions+=e.impressions)}let m=f.size,h=l.reduce((e,t)=>e+t.impressions,0),g=l.reduce((e,t)=>e+t.clicks,0),_=i.rows[0]??{clicks:0,impressions:0},v=l.map(e=>{let t=e=>[...e].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).map(([e])=>e),[n,...r]=t(e.queries),i=[...e.kinds].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0]))[0]?.[0];return{query:n??``,page:t(e.pages)[0]??``,pages:e.pages.size,kind:i,wordings:e.queries.size,impressions:e.impressions,clicks:e.clicks,ctr:e.impressions?OV(e.clicks/e.impressions,4):0,position:e.impressions?OV(e.positionWeight/e.impressions,1):0,otherWordings:r.slice(0,3)}}).sort((e,t)=>t.impressions-e.impressions||t.wordings-e.wordings||e.query.localeCompare(t.query)||e.page.localeCompare(t.page)),y=(e,t)=>t?OV(e/t*100,1):null,b=[...p].sort((e,t)=>t[1].impressions-e[1].impressions||e[0].localeCompare(t[0])).map(([e,t])=>`${e} ${t.queries}`).join(`, `),x=r.rowsFetched>=EV;return{range:n,verdict:m?`${m} queries in ${l.length} questions have the shape of AI conversations or agent searches.`:`No queries with the shape of AI conversations or agent searches.`,summary:{queries:m,questions:l.length,impressions:h,clicks:g,shareOfImpressionsPct:y(h,_.impressions),ctr:h?OV(g/h,4):0,siteCtr:_.impressions?OV(_.clicks/_.impressions,4):0,byKind:b||`none`},kinds:bV,items:v,caveats:[`A heuristic: these queries match the patterns of AI conversations and agent searches. Search Console does not mark AI Mode or AI Overviews, and people type some of these too.`,`A minimum: Search Console leaves out rare queries, and these are rare by nature.`,`Rewordings of one question are grouped by their shared words; page is the page with the most impressions for it.`,`Search Console’s Generative AI report is not in its API, so it is not here.`,...x?[`Capped at the first ${EV} matching query and page rows.`]:[]]}}const AV={overview:`Site totals (clicks, impressions, CTR, position) against the previous period, by device, with the top pages and queries and their change, and Google Analytics sessions for the same dates from the property whose web stream matches the site.`,"quick-wins":`Query and page pairs at average positions 4 to 10 with a click-through rate below the site’s own curve for that position.`,"low-ctr":`Query and page pairs at average positions 1 to 4 with a click-through rate below the site’s own curve: titles and snippets to review with the person.`,"striking-distance":`Queries just outside the top positions, with impressions, for pages that already rank.`,"second-page":`Pages with an average position of 11 to 20 and their queries.`,"content-decay":`Query and page pairs that lost clicks against the previous period.`,cannibalization:`Queries where more than one page of the site gets impressions, with each page’s share.`,"traffic-drop":`Daily clicks and impressions checked for a sudden change that lasted, with the date it started (else the last 7 days against the days before), and Google updates within 3 days of that date. Overlap is timing only, not cause.`,"ai-queries":`Queries with the shape of AI conversations and agent searches (replies such as "yes go on", follow-ups, agent prompts, search operators, chat phrasing, ten or more words), with rewordings grouped into one question and its top page, impressions, clicks and position. A heuristic: Search Console does not mark AI Mode.`,bing:`Bing’s top queries from Bing Webmaster Tools with Google’s clicks, impressions and position for the same query beside them, and the same for pages.`},jV=Object.keys(AV),MV=new Set([`quick-wins`,`low-ctr`,`striking-distance`,`second-page`,`content-decay`,`cannibalization`]),NV={overview:28,"quick-wins":28,"low-ctr":28,"striking-distance":28,"second-page":28,"content-decay":28,cannibalization:28,"traffic-drop":90,"ai-queries":90,bing:28};function PV(e,t){let n=e=>`section "${e}"`;return{overview:`Next: ${t(`compare`)} with a change date, or ${t(`page`)} for one page that moved.`,"quick-wins":`Next: ${t(`page`)} for one page’s queries and live facts; ${n(`low-ctr`)} for the top positions.`,"low-ctr":`Next: ${t(`page`)} for one page; ${t(`research`)} serp to see who else ranks.`,"striking-distance":`Next: ${n(`second-page`)} to see the same pages by page; ${t(`research`)} keyword_metrics for search volume.`,"second-page":`Next: ${t(`page`)} for one page’s queries and live facts.`,"content-decay":`Next: ${t(`index`)} for pages that lost most of their clicks; ${t(`page`)} to see which queries moved.`,cannibalization:`Next: ${t(`page`)} on each competing URL to see Google’s chosen canonical.`,"traffic-drop":`Next: ${t(`compare`)} with the date the drop started, for the pages and queries that moved; ${t(`index`)} for pages that lost almost all their clicks and their index status.`,"ai-queries":`Next: ${t(`page`)} for a page that gets many of these questions, to see whether it answers them.`,bing:`Next: ${t(`data`,{source:`bing`})} for every Bing row; ${t(`page`)} for one page.`}[e]}async function FV(e,t,n,r,i){let a=(n,r,a=1e3)=>e(t,{...r,dimensions:n,type:`web`,dataState:`final`,maxRows:a,...i?{dimensionFilterGroups:[{groupType:`and`,filters:[{dimension:`page`,operator:`contains`,expression:i}]}]}:{}}),[o,s,c,l,u,d,f,p]=await Promise.all([a([],n),a([],r),a([`device`],n),a([`device`],r),a([`page`],n,5e3),a([`page`],r,5e3),a([`query`],n,5e3),a([`query`],r,5e3)]),m=e=>e??{clicks:0,impressions:0,ctr:0,position:0},h=m(o.rows[0]),g=m(s.rows[0]),_=(e,t,n,r)=>{let i=new Map(t.map(e=>[e.keys[0],e])),a=new Set(e.map(e=>e.keys[0])),o=e.map(e=>{let t=i.get(e.keys[0]);return{[n]:e.keys[0],clicks:e.clicks,previousClicks:t?.clicks??0,clicksChange:e.clicks-(t?.clicks??0),impressions:e.impressions,previousImpressions:t?.impressions??0,impressionsChange:e.impressions-(t?.impressions??0),position:e.position}});for(let e of t)a.has(e.keys[0])||o.push({[n]:e.keys[0],clicks:0,previousClicks:e.clicks,clicksChange:-e.clicks,impressions:0,previousImpressions:e.impressions,impressionsChange:-e.impressions,position:0});let s=(e,t)=>[...o].sort((n,r)=>t*(Number(r[e])-Number(n[e]))).filter(n=>t*Number(n[e])>0).slice(0,r);return{top:o.slice(0,r),biggestLosses:s(`clicksChange`,-1),biggestGains:s(`clicksChange`,1),biggestImpressionLosses:s(`impressionsChange`,-1)}},v=new Map(l.rows.map(e=>[e.keys[0],e]));return{range:n,comparisonRange:r,...i?{pageContains:i}:{},summary:{clicks:h.clicks,previousClicks:g.clicks,clicksChangePct:En(h.clicks,g.clicks),impressions:h.impressions,previousImpressions:g.impressions,impressionsChangePct:En(h.impressions,g.impressions),ctr:Math.round(h.ctr*1e4)/1e4,previousCtr:Math.round(g.ctr*1e4)/1e4,position:Math.round(h.position*10)/10,previousPosition:Math.round(g.position*10)/10},devices:c.rows.map(e=>({device:e.keys[0],clicks:e.clicks,previousClicks:v.get(e.keys[0])?.clicks??0,impressions:e.impressions,position:e.position})),pages:_(u.rows,d.rows,`page`,15),queries:_(f.rows,p.rows,`query`,15),caveats:[`Totals come from Search Console with no dimension, so they include queries that Search Console hides for privacy.`,`Page and query lists cover the top 5,000 rows in each period.`]}}function IV(e,t,n,r){let i=e.range,a=e.comparisonRange,o=e.summary,s=e=>e==null?`n/a`:`${e>0?`+`:``}${e}%`,c=(t,i)=>{let a=e[i===`page`?`pages`:`queries`]??{},o=[i,`clicks`,`previousClicks`,`clicksChange`,`impressions`,`impressionsChange`,`position`],s=(e,t)=>t.length?`${e}:\n${Un(t.slice(0,r),o,n)}`:``;return[r>=10?s(`Top ${t} by clicks`,a.top??[]):``,s(`Biggest ${t} click losses`,a.biggestLosses??[])||`No ${t} lost clicks.`,s(`Biggest ${t} impression losses`,a.biggestImpressionLosses??[]),s(`Biggest ${t} click gains`,a.biggestGains??[])].filter(Boolean).join(`
305
+ `,MB(s.aiAssistants)),data:{...s,...c.length?{otherMatches:c}:{}}}}catch(e){let t=e instanceof Error?e.message:String(e);return{text:`Google Analytics: could not be read. ${t}`,data:{error:t}}}}const PB=[`Bing and Google count clicks, impressions and positions their own way. Their numbers sit side by side here and are never added together.`,`Bing lists only its top queries and pages, grouped by week. A query or page missing from Bing’s list is unknown, not zero.`],FB="If you have a shell, link the CLI to the same account once: run `npx -y seo login`, show the person the link it prints, and after they approve it run `npx -y seo login` again. `npx -y seo` commands then use the same Google accounts, Bing and keys.",IB=`Bing blocks the hosted server, so Bing data comes from the CLI on a machine. ${FB} Connect Bing on the account page if it is not connected, then run \`npx -y seo report --site <site> --section bing --json\`.`,LB="Bing: not included here, so these totals show Google only. Some sites get most of their search visits from Bing; the CLI reads them with the same account: `npx -y seo login` once, then `npx -y seo report --site <site> --section bing --json`.",RB=`https://www.bing.com/webmasters`,zB=e=>`Bing has no data for ${e} yet. Newly added or newly verified sites take a few days to show data in Bing Webmaster Tools.`,BB=new WeakMap;async function VB(e,t){if(!e.bing)return{call:null,site:null,missing:IB};let n=await e.bing();if(!n)return{call:null,site:null,missing:`Bing is not connected. ${e.bingConnect??``}`.trim()};let r=BB.get(n);r||(r=qt(n),BB.set(n,r));let i=Qt(await r,t);return i?.verified?{call:n,site:i.url}:{call:null,site:null,missing:i?`${i.url} is in the connected Bing account but is not verified, so Bing gives no data for it. Verify it at ${RB}.`:`The connected Bing account does not have ${t.replace(/^sc-domain:/,``)}. Add and verify it at ${RB} (it can import sites from Search Console). New sites take a few days to show data.`}}function HB(e){return Math.round((Date.parse(e.endDate)-Date.parse(e.startDate))/864e5)+1}async function UB(e,t,n){if(!e.call)return{missing:e.missing};let r=await Jt(e.call,e.site);if(!r.rows.length&&!r.invalidRows)return{missing:zB(e.site)};let i=e=>{let t=r.rows.filter(t=>t.date>=e.startDate&&t.date<=e.endDate);return{clicks:t.reduce((e,t)=>e+t.clicks,0),impressions:t.reduce((e,t)=>e+t.impressions,0),days:new Set(t.map(e=>e.date)).size,expectedDays:HB(e)}};return{site:e.site,current:i(t),previous:i(n),invalidRows:r.invalidRows}}const WB=(e,t)=>{let n=En(e,t);return n===null?`n/a`:`${n>0?`+`:``}${n}%`};function GB(e,t){if(`missing`in t)return`Bing: ${t.missing}`;let{current:n,previous:r}=t,i=[`Search engines, same dates. Google (Search Console): clicks ${e.clicks} (was ${e.previousClicks}, ${WB(e.clicks,e.previousClicks)}), impressions ${e.impressions}. Bing (${t.site}): clicks ${n.clicks} (was ${r.clicks}, ${WB(n.clicks,r.clicks)}), impressions ${n.impressions} (was ${r.impressions}).`],a=e.clicks+n.clicks;return a>0&&i.push(`Share of these clicks: Google ${Math.round(e.clicks/a*100)}%, Bing ${Math.round(n.clicks/a*100)}%.`),(n.days<n.expectedDays||r.days<r.expectedDays)&&i.push(`Bing has data for ${n.days} of ${n.expectedDays} days (earlier period ${r.days} of ${r.expectedDays}), so its totals are partial.`),i.join(` `)}function KB(e,t){let n=e.filter(e=>e.date>=t.startDate&&e.date<=t.endDate),r=new Map;for(let e of n){let t=r.get(e.key)??{key:e.key,clicks:0,impressions:0,position:null,weighted:0,seen:0};t.clicks+=e.clicks,t.impressions+=e.impressions,e.position!==null&&e.impressions>0&&(t.weighted+=e.position*e.impressions,t.seen+=e.impressions),r.set(e.key,t)}return{rows:[...r.values()].map(({weighted:e,seen:t,...n})=>({...n,position:t>0?Math.round(e/t*10)/10:null})).sort((e,t)=>t.clicks-e.clicks||t.impressions-e.impressions||(e.key<t.key?-1:+(e.key>t.key))),weeks:[...new Set(n.map(e=>e.date))].sort()}}async function qB(e,t,n,r){if(!e.call)throw new yn(`NOT_CONNECTED`,e.missing);let i=e=>t(n,{...r,dimensions:[e],type:`web`,dataState:`final`,maxRows:25e3}),[a,o,s]=await Promise.all([Xt(e.call,e.site),Zt(e.call,e.site),Promise.all([i(`query`),i(`page`)]).catch(e=>e instanceof Error?e:Error(String(e)))]),c=s instanceof Error?s:null,[l,u]=s instanceof Error?[]:s,d=(e,t,n)=>{let r=e=>n===`query`?e.toLowerCase().trim():e.replace(/#.*$/,``),i=new Map(t?.map(e=>[r(e.keys[0]??``),e]));return e.map(e=>{let a=i.get(r(e.key)),o=t?0:null;return{[n]:e.key,bingClicks:e.clicks,bingImpressions:e.impressions,bingPosition:e.position,googleClicks:a?.clicks??o,googleImpressions:a?.impressions??o,googlePosition:a?Math.round(a.position*10)/10:null}})},f=KB(a.rows,r),p=KB(o.rows,r),m=a.invalidRows+o.invalidRows,h=!a.rows.length&&!o.rows.length&&!m;return{range:r,bingSite:e.site,summary:{bingQueries:f.rows.length,bingPages:p.rows.length,weeks:f.weeks.length},items:d(f.rows,l?.rows,`query`),topPages:d(p.rows,u?.rows,`page`),caveats:[...h?[zB(e.site)]:[],...c?[`Search Console was not available, so the Google columns are empty (unknown, not zero): ${c.message}`]:[],`Bing weeks counted: ${f.weeks.join(`, `)||`none`} (each date names a week). Google numbers cover ${r.startDate} to ${r.endDate} exactly.`,`Google numbers are for the same query text or page URL. 0 means Google showed no row for it in these dates.`,...PB,...m?[`${m} Bing rows were not valid and were left out.`]:[]]}}async function JB(e,t){let n=await VB(t,e.site);if(!n.call)throw new yn(`NOT_CONNECTED`,n.missing);let r=Cn(e,28),i=wn(r),a=await(e.dimension===`page`?Zt:Xt)(n.call,n.site),o=KB(a.rows,r),s=KB(a.rows,i),c=new Map(s.rows.map(e=>[e.key,e])),l=new Set(o.rows.map(e=>e.key)),u=o.rows.map(t=>({[e.dimension]:t.key,clicks:t.clicks,impressions:t.impressions,position:t.position,previous_clicks:c.get(t.key)?.clicks??0,clicks_change:t.clicks-(c.get(t.key)?.clicks??0)}));for(let t of s.rows)l.has(t.key)||u.push({[e.dimension]:t.key,clicks:0,impressions:0,position:null,previous_clicks:t.clicks,clicks_change:-t.clicks});let d=[...a.rows.length||a.invalidRows?[]:[zB(n.site)],`Bing weeks counted: ${o.weeks.join(`, `)||`none`}; earlier period ${s.weeks.join(`, `)||`none`}. Each date names a week.`,...PB.slice(1),...a.invalidRows?[`${a.invalidRows} Bing rows were not valid and were left out.`]:[]];return{text:`${dB({title:`Bing Webmaster ${n.site}, ${r.startDate} to ${r.endDate}, by ${e.dimension}.`,rows:u,offset:e.offset??0,limit:50,detail:e.detail??`summary`,notes:d,origin:Tn(n.site),more:n=>t.call(`data`,{site:e.site,source:`bing`,dimensions:e.dimension,detail:`rows`,offset:n})})}\n\n${bn.replace(`Search Console`,`Bing Webmaster Tools`)}`,data:{bingSite:n.site,range:r,comparisonRange:i,weeks:o.weeks,total:u.length,offset:e.offset??0,rows:u.slice(e.offset??0,(e.offset??0)+50)}}}function YB(e,t,n,r,i){let a=KB(e,t),o=KB(e,n),s=new Map(o.rows.map(e=>[e.key,e])),c=new Set(a.rows.map(e=>e.key)),l=a.rows.map(e=>{let t=s.get(e.key);return{[r]:e.key,clicks:e.clicks,previousClicks:t?t.clicks:null,clicksChange:t?e.clicks-t.clicks:null,impressions:e.impressions,position:e.position}}),u=e=>l.filter(t=>t.clicksChange!==null&&e*t.clicksChange>0).sort((t,n)=>e*(n.clicksChange-t.clicksChange)||String(t[r]).localeCompare(String(n[r]))).slice(0,i);return{top:l.slice(0,i),biggestLosses:u(-1),biggestGains:u(1),leftTopList:o.rows.filter(e=>!c.has(e.key)).slice(0,i).map(e=>({[r]:e.key,previousClicks:e.clicks})),weeks:a.weeks,previousWeeks:o.weeks}}async function XB(e,t,n){if(!e.call)throw new yn(`NOT_CONNECTED`,e.missing);let[r,i,a]=await Promise.all([UB(e,t,n),Xt(e.call,e.site),Zt(e.call,e.site)]);if(`missing`in r)throw new yn(`NOT_CONNECTED`,r.missing);let{current:o,previous:s}=r,c=YB(i.rows,t,n,`query`,15),l=YB(a.rows,t,n,`page`,15);return{bingSite:e.site,range:t,comparisonRange:n,summary:{clicks:o.clicks,previousClicks:s.clicks,clicksChangePct:En(o.clicks,s.clicks),impressions:o.impressions,previousImpressions:s.impressions,impressionsChangePct:En(o.impressions,s.impressions),days:o.days,previousDays:s.days},pages:l,queries:c,caveats:[...o.days<o.expectedDays||s.days<s.expectedDays?[`Bing has data for ${o.days} of ${o.expectedDays} days (earlier period ${s.days} of ${s.expectedDays}), so its totals are partial.`]:[],`Totals are Bing's daily site totals. Page and query rows are Bing's weekly top rows: weeks ${c.weeks.join(`, `)||`none`} against ${c.previousWeeks.join(`, `)||`none`}.`,...PB.slice(1)]}}function ZB(e,t,n,r){let i=e.range,a=e.comparisonRange,o=e.summary,s=e=>[e,`clicks`,`previousClicks`,`clicksChange`,`impressions`,`position`],c=(e,t,i)=>{let a=t??[];return a.length?`${e}:\n${Un(a.slice(0,r),s(i),n)}`:``},l=(t,n)=>{let i=e[t];return[c(`Biggest Bing ${t===`pages`?`page`:`query`} click losses`,i.biggestLosses,n),c(`Biggest Bing ${t===`pages`?`page`:`query`} click gains`,i.biggestGains,n),i.leftTopList?.length?`Left Bing's top ${t} list (now unknown, not zero): ${i.leftTopList.slice(0,r).map(e=>`${e[n]} (had ${e.previousClicks} clicks)`).join(`, `)}.`:``,r>=10?c(`Top Bing ${t}`,i.top,n):``].filter(Boolean).join(`
306
+
307
+ `)};return[`${t}, ${i.startDate} to ${i.endDate} against ${a.startDate} to ${a.endDate}.`,o.days||o.previousDays?`Bing totals: clicks ${o.clicks} (was ${o.previousClicks}, ${WB(o.clicks,o.previousClicks)}), impressions ${o.impressions} (was ${o.previousImpressions}, ${WB(o.impressions,o.previousImpressions)}).`:`Bing totals: unknown. Bing has no daily data for these dates.`,l(`pages`,`page`),l(`queries`,`query`),`Limits:\n${e.caveats.map(e=>`- ${e}`).join(`
308
+ `)}`].filter(Boolean).join(`
309
+
310
+ `)}const QB=`x-clicky-`;function $B(e){let t=[];for(let[n,r]of e){if(!n.startsWith(`x-clicky-`))continue;let e=n.slice(9);if(!sB(e))continue;let i=r.trim(),a=null,o=!1;if(i.startsWith(`{`))try{let e=JSON.parse(i);i=typeof e.sitekey==`string`?e.sitekey:``,a=typeof e.domain==`string`?e.domain:null,o=e.account===!0}catch{continue}cB(i)&&t.push({siteId:e,sitekey:i,domain:a,account:o})}return t.sort((e,t)=>e.siteId<t.siteId?-1:+(e.siteId>t.siteId))}const eV=e=>e.domain?`${e.siteId} (${e.domain})`:e.siteId;function tV(e){let t=e.trim().toLowerCase().replace(/^sc-domain:/u,``);try{return new URL(t.includes(`://`)?t:`https://${t}`).hostname.replace(/^www\./u,``)}catch{return t}}async function nV(e,t,n,r){let i=tV(t),a=e=>e.siteId===t.trim()||e.domain===i,o=e;if(!o.some(a)&&r&&(o=await r()??o),!o.length)throw new yn(`NO_KEY`,`No Clicky site is saved. Add your Clicky account, or one site's ID and sitekey (Clicky, Preferences, Info): ${n}`);let s=o.find(a);if(s)return s;if(!sB(t)){for(let e of o.filter(e=>!e.domain).slice(0,10))e.domain=await uB(e).catch(()=>null);let e=o.find(a);if(e)return e}throw new yn(`NO_ACCESS`,`No saved Clicky site matches ${t}. Saved Clicky sites: ${o.map(eV).join(`, `)}. Pass one of these site IDs, or add the site: ${n}`)}const rV=864e5,iV=e=>new Date(e).toISOString().slice(0,10);function aV(e){if(!e.startDate&&!e.endDate){let e=Date.now()-rV;return{startDate:iV(e-27*rV),endDate:iV(e)}}let t=Date.parse(`${e.startDate}T00:00:00Z`),n=Date.parse(`${e.endDate}T00:00:00Z`);if(!e.startDate||!e.endDate||!(t<=n))throw new yn(`INVALID_INPUT`,`Send a start date and an end date together, in order.`);if((n-t)/rV+1>31)throw new yn(`INVALID_INPUT`,`Clicky reads at most 31 days at a time. Send a shorter range.`);return{startDate:e.startDate,endDate:e.endDate}}const oV=e=>{let t=Number(e.value);return Number.isSafeInteger(t)&&t>=0?t:null},sV=e=>e.map(e=>({name:e.title??``,visits:oV(e)})).filter(e=>!!e.name&&e.visits!==null),cV=e=>{let t=e.slice(0,10).map(e=>`${e.name} ${e.visits}`),n=e.slice(10);return n.length&&t.push(`${n.length} others ${n.reduce((e,t)=>e+t.visits,0)}`),t.join(`; `)},lV=1e3;async function uV(e,t,n){let r=n.refresh,i=await nV($B(t),e.site,n.connect,r&&(async()=>{let e=await r().catch(()=>null);return e&&$B(e)})),a=aV(e),o=e.offset??0,s=await lB(i,[`pages-entrance`,`traffic-sources`,`searches-engines`],{date:`${a.startDate},${a.endDate}`,limit:lV}).catch(e=>{throw e instanceof oB?new yn(e.code===`auth`?`NO_ACCESS`:`PROVIDER_ERROR`,e.code===`auth`?`${e.message} Save it again: ${n.connect}`:e.message):e}),c=s[`pages-entrance`]??[],l=new Map;for(let e of c){let t=oV(e);if(t===null||!e.url)continue;let n;try{n=new URL(e.url).pathname}catch{continue}l.set(n,(l.get(n)??0)+t)}let u=[...l].map(([e,t])=>({page:e,visits:t})).sort((e,t)=>t.visits-e.visits||(e.page<t.page?-1:+(e.page>t.page))),d=sV(s[`traffic-sources`]??[]),f=sV(s[`searches-engines`]??[]),p=[`Visits by landing page from every source, as Clicky counts them, in the Clicky site’s time zone. Clicky does not split landing pages by source.`,d.length?`Traffic sources (visits): ${cV(d)}.`:`Traffic sources: none in this range.`,f.length?`Search engines (visits): ${cV(f)}.`:`Search engines: none in this range.`];return c.length>=lV&&p.push(`Clicky returned its ${lV}-row limit; pages past it are missing, not zero.`),{text:dB({title:`Clicky site ${eV(i)}: landing pages, ${a.startDate} to ${a.endDate}.`,rows:u,offset:o,limit:50,detail:e.detail??`summary`,notes:p,more:n.call}),data:{siteId:i.siteId,domain:i.domain,range:a,metric:`visits`,sources:d,searchEngines:f,capped:c.length>=lV,total:u.length,offset:o,rows:u.slice(o,o+50)}}}const dV=`domain_rating: Domain Rating by Ahrefs (https://ahrefs.com/).`,fV=[`domain`,`competitor_domain`,`Dn`];function pV(e){return e.replace(/^sc-domain:/,``).replace(/^https?:\/\//,``).replace(/\/.*$/,``).replace(/^www\./,``).toLowerCase()}async function mV(e,t){let n=`https://api.ahrefs.com/v3/public/domain-rating-free?target=${encodeURIComponent(e)}`,r=globalThis.caches?.default,i=new Request(n),a=await r?.match(i),o=a??await fetch(n,{headers:{authorization:`Bearer ${t}`,accept:`application/json`},signal:AbortSignal.timeout(5e3)});if(!o.ok)return null;let s=await kt(o.clone(),`Ahrefs Domain Rating`);if(r&&!a){let e=new Response(o.body,o);e.headers.set(`cache-control`,`max-age=86400`),await r.put(i,e)}return s.domain_rating?.domain_rating??null}async function hV(e,t){let n=new Map;if(!t)return n;let r=[...new Set(e.map(pV).filter(Boolean))].slice(0,25),i=await Promise.all(r.map(e=>mV(e,t).catch(()=>null)));return r.forEach((e,t)=>{n.set(e,i[t]??null)}),n}async function gV(e,t){let n=fV.find(t=>e.some(e=>typeof e[t]==`string`));if(!t||!n||e.some(e=>`domain_rating`in e))return{rows:e,added:!1};let r=await hV(e.map(e=>String(e[n]??``)),t);return{rows:e.map(e=>{let t={};for(let[i,a]of Object.entries(e))t[i]=a,i===n&&(t.domain_rating=r.get(pV(String(a??``)))??null);return t}),added:!0}}const _V=e=>e?.trim().replace(/\s+/g,` `)||null;async function vV(e){if(!e.body)return``;let t=e.body.getReader(),n=new TextDecoder,r=``,i=0;for(;i<1e6;){let{done:e,value:a}=await t.read();if(e)return r+n.decode();i+=a.byteLength,r+=n.decode(a,{stream:!0})}return await t.cancel(),r}function yV(e,t){let n=``,r=``,i=!1,a=!1,o=!1,s=!1,c=null,l=null,u=[],d=new ce({onopentag(e,n){if(e===`title`&&!o&&(i=!0),e===`h1`&&!s&&(a=!0),e===`meta`){let e=n.name?.toLowerCase();e===`description`&&c===null&&(c=n.content??null),e===`robots`&&n.content&&u.push(n.content)}if(e===`link`&&l===null&&n.rel?.toLowerCase().split(/\s+/).includes(`canonical`)&&n.href)try{l=new URL(n.href,t).toString()}catch{l=n.href}},ontext(e){i&&(n+=e),a&&(r+=e)},onclosetag(e){e===`title`&&i&&(i=!1,o=!0),e===`h1`&&a&&(a=!1,s=!0)}},{decodeEntities:!0,lowerCaseTags:!0});return d.write(e),d.end(),{title:_V(n),description:_V(c),h1:_V(r),canonical:l,robots:u.length?u.join(`, `):null}}async function bV(e){let t={url:e,status:null,redirects_to:null,title:null,description:null,h1:null,canonical:null,robots:null};try{let n=await fetch(e,{redirect:`manual`,headers:{"user-agent":fb,accept:`text/html`},signal:AbortSignal.timeout(6e3)});t.status=n.status;let r=n.headers.get(`location`);r&&(t.redirects_to=new URL(r,e).toString());let i=n.headers.get(`x-robots-tag`);if(n.status!==200||!n.headers.get(`content-type`)?.includes(`html`))return t.robots=i,await n.body?.cancel(),t;let a=yV(await vV(n),e);Object.assign(t,a),t.robots=[i,a.robots].filter(Boolean).join(`, `)||null}catch(e){t.error=e instanceof Error?e.message:`fetch failed`}return t}function xV(e){return Promise.all(e.slice(0,20).map(bV))}function SV(e){let t=e.filter(e=>(e.status===302||e.status===307)&&e.redirects_to!==null&&new URL(e.redirects_to).host===new URL(e.url).host);return t.length?`Note: 302 and 307 are temporary redirects; a permanent move usually uses 301 or 308. Temporary redirects here: ${t.map(e=>`${e.url} (${e.status} to ${e.redirects_to})`).join(`; `)}.`:null}const CV=[[`agent_prompt`,`^(search the web for|browse the web|find sources)|do not invent|return the [0-9]+ most relevant|include source urls|context: location|do not include location|question: `],[`tracker`,`\\. ?my location is |^evaluate the .+ on `],[`reply`,`^(yes|yeah|yep|ok|okay|sure|yes please|go on|continue|keep going|tell me more|why not|how so|really|exactly|show me|and then|thanks|thank you|got it|what else|anything else)[?!.,]*$`],[`follow_up`,`^(what|how) about .{1,40}$|^(and|so|ok so|okay so|but) (what|which|how|why) `],[`operator`,`(^|\\s)-?(site|before|after|intitle|inurl|intext|filetype):|"[^"]*" or "`],[`chat`,`\\b(please|can you|could you|give me|show me|tell me|i want|i need|i have|i am|should i|do i need|is it worth|help me|walk me through)\\b|^(what|how|why|is|does|can|will|would) (it|that|this|they)\\b`],[`long`,`^(\\S+\\s+){9,}\\S+$`]],wV={agent_prompt:`text from an agent prompt, such as "search the web for"`,tracker:`a visibility-tool probe, such as "my location is"`,reply:`a bare reply, such as "yes" or "tell me more"`,follow_up:`a follow-up, such as "what about …"`,operator:`search operators, such as site:, before: or "a" or "b"`,chat:`chat phrasing, such as "can you" or "should i"`,long:`ten or more words with no other sign`},TV=CV.map(([e,t])=>[e,new RegExp(t)]),EV=CV.map(([,e])=>`(?:${e})`).join(`|`);function DV(e){let t=e.trim().toLowerCase();return TV.find(([,e])=>e.test(t))?.[0]??null}const OV=new Set(`the and for with that this what which who how why when where are is was can does do did you your our from about into than then them they their there have has had will would should could not but its it’s me my i am of to in on at by or an as be if so`.split(` `));function kV(e){return new Set(e.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(e=>e.length>=3&&!OV.has(e)).map(e=>e.length>4&&e.endsWith(`s`)?e.slice(0,-1):e))}const AV=25e3,jV=(e,t,n)=>{let r=0,i=0;for(let a of e)i+=n(a),t.has(a)&&(r+=n(a));for(let r of t)e.has(r)||(i+=n(r));return i?r/i:0},MV=(e,t)=>Math.round(e*10**t)/10**t;async function NV(e,t){let n={startDate:e.startDate,endDate:e.endDate},[r,i]=await Promise.all([t(e.site,{...n,dimensions:[`query`,`page`],type:`web`,dataState:`final`,maxRows:AV,dimensionFilterGroups:[{filters:[{dimension:`query`,operator:`includingRegex`,expression:EV}]}]}),t(e.site,{...n,dimensions:[],type:`web`,dataState:`final`})]),a=[...r.rows].sort((e,t)=>t.impressions-e.impressions||String(e.keys[0]).localeCompare(String(t.keys[0]))||String(e.keys[1]).localeCompare(String(t.keys[1]))),o=new Map,s=new Set(a.map(e=>String(e.keys[0]??``)));for(let e of s)for(let t of kV(e))o.set(t,(o.get(t)??0)+1);let c=e=>Math.log((s.size+1)/(o.get(e)??1)),l=[],u=new Map,d=new Map,f=new Map;for(let e of a){let t=String(e.keys[0]??``),n=String(e.keys[1]??``),r=DV(t);if(!r)continue;let i=t.trim().toLowerCase(),a=kV(t),o=d.get(i);if(!o){let e=0;for(let t of a){for(let n of u.get(t)??[]){if(++e>200)break;if(jV(a,n.words,c)>=.6){o=n;break}}if(o||e>200)break}}if(!o){o={words:a,queries:new Map,pages:new Map,kinds:new Map,clicks:0,impressions:0,positionWeight:0},l.push(o);for(let e of a){let t=u.get(e)??[];t.push(o),u.set(e,t)}}d.set(i,o),f.has(i)||(f.set(i,r),o.kinds.set(r,(o.kinds.get(r)??0)+1)),o.queries.set(t,(o.queries.get(t)??0)+e.impressions),o.pages.set(n,(o.pages.get(n)??0)+e.impressions),o.clicks+=e.clicks,o.impressions+=e.impressions,o.positionWeight+=e.position*e.impressions}let p=new Map;for(let e of f.values()){let t=p.get(e)??{queries:0,impressions:0};t.queries+=1,p.set(e,t)}for(let e of a){let t=f.get(String(e.keys[0]??``).trim().toLowerCase()),n=t&&p.get(t);n&&(n.impressions+=e.impressions)}let m=f.size,h=l.reduce((e,t)=>e+t.impressions,0),g=l.reduce((e,t)=>e+t.clicks,0),_=i.rows[0]??{clicks:0,impressions:0},v=l.map(e=>{let t=e=>[...e].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).map(([e])=>e),[n,...r]=t(e.queries),i=[...e.kinds].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0]))[0]?.[0];return{query:n??``,page:t(e.pages)[0]??``,pages:e.pages.size,kind:i,wordings:e.queries.size,impressions:e.impressions,clicks:e.clicks,ctr:e.impressions?MV(e.clicks/e.impressions,4):0,position:e.impressions?MV(e.positionWeight/e.impressions,1):0,otherWordings:r.slice(0,3)}}).sort((e,t)=>t.impressions-e.impressions||t.wordings-e.wordings||e.query.localeCompare(t.query)||e.page.localeCompare(t.page)),y=(e,t)=>t?MV(e/t*100,1):null,b=[...p].sort((e,t)=>t[1].impressions-e[1].impressions||e[0].localeCompare(t[0])).map(([e,t])=>`${e} ${t.queries}`).join(`, `),x=r.rowsFetched>=AV;return{range:n,verdict:m?`${m} queries in ${l.length} questions have the shape of AI conversations or agent searches.`:`No queries with the shape of AI conversations or agent searches.`,summary:{queries:m,questions:l.length,impressions:h,clicks:g,shareOfImpressionsPct:y(h,_.impressions),ctr:h?MV(g/h,4):0,siteCtr:_.impressions?MV(_.clicks/_.impressions,4):0,byKind:b||`none`},kinds:wV,items:v,caveats:[`A heuristic: these queries match the patterns of AI conversations and agent searches. Search Console does not mark AI Mode or AI Overviews, and people type some of these too.`,`A minimum: Search Console leaves out rare queries, and these are rare by nature.`,`Rewordings of one question are grouped by their shared words; page is the page with the most impressions for it.`,`Search Console’s Generative AI report is not in its API, so it is not here.`,...x?[`Capped at the first ${AV} matching query and page rows.`]:[]]}}const PV={overview:`Site totals (clicks, impressions, CTR, position) against the previous period, by device, with the top pages and queries and their change, and Google Analytics sessions for the same dates from the property whose web stream matches the site.`,"quick-wins":`Query and page pairs at average positions 4 to 10 with a click-through rate below the site’s own curve for that position.`,"low-ctr":`Query and page pairs at average positions 1 to 4 with a click-through rate below the site’s own curve: titles and snippets to review with the person.`,"striking-distance":`Queries just outside the top positions, with impressions, for pages that already rank.`,"second-page":`Pages with an average position of 11 to 20 and their queries.`,"content-decay":`Query and page pairs that lost clicks against the previous period.`,cannibalization:`Queries where more than one page of the site gets impressions, with each page’s share.`,"traffic-drop":`Daily clicks and impressions checked for a sudden change that lasted, with the date it started (else the last 7 days against the days before), and Google updates within 3 days of that date. Overlap is timing only, not cause.`,"ai-queries":`Queries with the shape of AI conversations and agent searches (replies such as "yes go on", follow-ups, agent prompts, search operators, chat phrasing, ten or more words), with rewordings grouped into one question and its top page, impressions, clicks and position. A heuristic: Search Console does not mark AI Mode.`,bing:`Bing’s top queries from Bing Webmaster Tools with Google’s clicks, impressions and position for the same query beside them, and the same for pages.`},FV=Object.keys(PV),IV=new Set([`quick-wins`,`low-ctr`,`striking-distance`,`second-page`,`content-decay`,`cannibalization`]),LV={overview:28,"quick-wins":28,"low-ctr":28,"striking-distance":28,"second-page":28,"content-decay":28,cannibalization:28,"traffic-drop":90,"ai-queries":90,bing:28};function RV(e,t){let n=e=>`section "${e}"`;return{overview:`Next: ${t(`compare`)} with a change date, or ${t(`page`)} for one page that moved.`,"quick-wins":`Next: ${t(`page`)} for one page’s queries and live facts; ${n(`low-ctr`)} for the top positions.`,"low-ctr":`Next: ${t(`page`)} for one page; ${t(`research`)} serp to see who else ranks.`,"striking-distance":`Next: ${n(`second-page`)} to see the same pages by page; ${t(`research`)} keyword_metrics for search volume.`,"second-page":`Next: ${t(`page`)} for one page’s queries and live facts.`,"content-decay":`Next: ${t(`index`)} for pages that lost most of their clicks; ${t(`page`)} to see which queries moved.`,cannibalization:`Next: ${t(`page`)} on each competing URL to see Google’s chosen canonical.`,"traffic-drop":`Next: ${t(`compare`)} with the date the drop started, for the pages and queries that moved; ${t(`index`)} for pages that lost almost all their clicks and their index status.`,"ai-queries":`Next: ${t(`page`)} for a page that gets many of these questions, to see whether it answers them.`,bing:`Next: ${t(`data`,{source:`bing`})} for every Bing row; ${t(`page`)} for one page.`}[e]}async function zV(e,t,n,r,i){let a=(n,r,a=1e3)=>e(t,{...r,dimensions:n,type:`web`,dataState:`final`,maxRows:a,...i?{dimensionFilterGroups:[{groupType:`and`,filters:[{dimension:`page`,operator:`contains`,expression:i}]}]}:{}}),[o,s,c,l,u,d,f,p]=await Promise.all([a([],n),a([],r),a([`device`],n),a([`device`],r),a([`page`],n,5e3),a([`page`],r,5e3),a([`query`],n,5e3),a([`query`],r,5e3)]),m=e=>e??{clicks:0,impressions:0,ctr:0,position:0},h=m(o.rows[0]),g=m(s.rows[0]),_=(e,t,n,r)=>{let i=new Map(t.map(e=>[e.keys[0],e])),a=new Set(e.map(e=>e.keys[0])),o=e.map(e=>{let t=i.get(e.keys[0]);return{[n]:e.keys[0],clicks:e.clicks,previousClicks:t?.clicks??0,clicksChange:e.clicks-(t?.clicks??0),impressions:e.impressions,previousImpressions:t?.impressions??0,impressionsChange:e.impressions-(t?.impressions??0),position:e.position}});for(let e of t)a.has(e.keys[0])||o.push({[n]:e.keys[0],clicks:0,previousClicks:e.clicks,clicksChange:-e.clicks,impressions:0,previousImpressions:e.impressions,impressionsChange:-e.impressions,position:0});let s=(e,t)=>[...o].sort((n,r)=>t*(Number(r[e])-Number(n[e]))).filter(n=>t*Number(n[e])>0).slice(0,r);return{top:o.slice(0,r),biggestLosses:s(`clicksChange`,-1),biggestGains:s(`clicksChange`,1),biggestImpressionLosses:s(`impressionsChange`,-1)}},v=new Map(l.rows.map(e=>[e.keys[0],e]));return{range:n,comparisonRange:r,...i?{pageContains:i}:{},summary:{clicks:h.clicks,previousClicks:g.clicks,clicksChangePct:En(h.clicks,g.clicks),impressions:h.impressions,previousImpressions:g.impressions,impressionsChangePct:En(h.impressions,g.impressions),ctr:Math.round(h.ctr*1e4)/1e4,previousCtr:Math.round(g.ctr*1e4)/1e4,position:Math.round(h.position*10)/10,previousPosition:Math.round(g.position*10)/10},devices:c.rows.map(e=>({device:e.keys[0],clicks:e.clicks,previousClicks:v.get(e.keys[0])?.clicks??0,impressions:e.impressions,position:e.position})),pages:_(u.rows,d.rows,`page`,15),queries:_(f.rows,p.rows,`query`,15),caveats:[`Totals come from Search Console with no dimension, so they include queries that Search Console hides for privacy.`,`Page and query lists cover the top 5,000 rows in each period.`]}}function BV(e,t,n,r){let i=e.range,a=e.comparisonRange,o=e.summary,s=e=>e==null?`n/a`:`${e>0?`+`:``}${e}%`,c=(t,i)=>{let a=e[i===`page`?`pages`:`queries`]??{},o=[i,`clicks`,`previousClicks`,`clicksChange`,`impressions`,`impressionsChange`,`position`],s=(e,t)=>t.length?`${e}:\n${Un(t.slice(0,r),o,n)}`:``;return[r>=10?s(`Top ${t} by clicks`,a.top??[]):``,s(`Biggest ${t} click losses`,a.biggestLosses??[])||`No ${t} lost clicks.`,s(`Biggest ${t} impression losses`,a.biggestImpressionLosses??[]),s(`Biggest ${t} click gains`,a.biggestGains??[])].filter(Boolean).join(`
306
311
 
307
312
  `)};return[`${t}, ${i.startDate} to ${i.endDate} against ${a.startDate} to ${a.endDate}${e.pageContains?`, pages whose URL contains "${e.pageContains}"`:``}.`,`Totals: clicks ${o.clicks} (was ${o.previousClicks}, ${s(o.clicksChangePct)}), impressions ${o.impressions} (was ${o.previousImpressions}, ${s(o.impressionsChangePct)}), CTR ${o.ctr} (was ${o.previousCtr}), average position ${o.position} (was ${o.previousPosition}).`,`Devices:\n${Un(e.devices,[`device`,`clicks`,`previousClicks`,`impressions`,`position`],null)}`,c(`pages`,`page`),c(`queries`,`query`),`Limits:\n${e.caveats.map(e=>`- ${e}`).join(`
308
313
  `)}`].join(`
309
314
 
310
- `)}function LV(e){let t;return()=>(t??=e(),t)}async function RV(e,t){let n=e.summary;try{return WB(n,await HB(await t(),e.range,e.comparisonRange))}catch(e){return`Bing: could not be read. ${e instanceof Error?e.message:String(e)}`}}async function zV(e,t,n,r,i,a){let o={searchAnalytics:e,now:i},s={site:t,limit:100,includeBrand:!1,...r},c={overview:()=>FV(e,t,r,wn(r)),"quick-wins":()=>lP({...s,verifyContent:!1},o),"low-ctr":()=>_j(s,o),"striking-distance":()=>AP({...s,verifyContent:!1},o),"second-page":()=>ZR({...s,verifyContent:!1},o),"content-decay":()=>BN({...s,comparison:`previous-period`},o),cannibalization:async()=>{let e=await CN(s,o),t=e.items??[];return{...e,items:t.map(e=>{let t=e.pages??[];return{...e,urls:t.map(e=>`${e.url} (${Math.round(e.impressionShare*100)}%)`).join(` ; `),topPage:e.suggestedOwnerUrl}})}},"traffic-drop":async()=>{let e=await iF({site:t,...r,recentDays:7},o),n=IP(e.anomalies);return{...e,updateWindow:n&&{...n,paddingDays:3},googleUpdates:await kn(n)}},"ai-queries":()=>kV({site:t,...r},e),bing:async()=>KB(await a(),e,t,r)}[n];return Sn(await c())}function BV(e){let t=e.brand;return t?.terms?`Brand terms left out: ${t.terms.join(`, `)||`none`}${t.excluded?.length?`. Not treated as brand: ${t.excluded.map(e=>e.term).join(`, `)}`:``}.`:null}function VV(e,t){let n=[],r=(e,i=``)=>{if(!(n.length>=20)){if(typeof e==`string`){if(/^(url|page|finalUrl|targetUrl)$/i.test(i)){let r=e.startsWith(`/`)?`${t}${e}`:e;/^https?:\/\//.test(r)&&!n.includes(r)&&n.push(r)}return}if(Array.isArray(e))for(let t of e)r(t,i);else if(e&&typeof e==`object`)for(let[t,n]of Object.entries(e))r(n,t)}};for(let t of e)r(t);return n}function HV(e,t){let n=Un(e,[`url`,`status`,`redirects_to`,`title`,`description`,`h1`,`canonical`,`robots`,...e.some(e=>e.error)?[`error`]:[]],t,320),r=vV(e);return r?`${n}\n${r}`:n}async function UV(e,t){let n=t.now??(()=>new Date),r=On(t.searchAnalytics),i=Tn(e.site),a=LV(()=>BB(t,e.site)),o=jV.filter(e=>e!==`bing`||t.bing),s=Cn(e,NV.overview),c=MB(t.analytics,e.site,s,wn(s)),[l,...u]=await Promise.all(o.map(t=>zV(r,e.site,t,Cn(e,NV[t]),n,a).catch(e=>e instanceof Error?e:Error(String(e)))));if(!l||l instanceof Error)throw l??Error(`The overview did not run.`);let d=[IV(l,`Report on ${e.site}`,i,5)];d.push(t.bing?await RV(l,a):IB);let f=await c;f&&d.push(f.text);let p=u.find(e=>!(e instanceof Error)&&BV(e)!==null);p&&d.push(BV(p));let m={};return o.slice(1).forEach((e,t)=>{let n=u[t];if(!n||n instanceof Error){let t=n?.message??`did not run`;d.push(`## ${e}\nNot available: ${t}`),m[e]={error:t};return}let r=Zn(n,i,3);m[e]={total:r.total},d.push([`## ${e}: ${r.total} ${r.total===1?`row`:`rows`}`,AV[e],r.text,e===`traffic-drop`?jn(n.googleUpdates,n.updateWindow):null].filter(Boolean).join(`
315
+ `)}function VV(e){let t;return()=>(t??=e(),t)}async function HV(e,t){let n=e.summary;try{return GB(n,await UB(await t(),e.range,e.comparisonRange))}catch(e){return`Bing: could not be read. ${e instanceof Error?e.message:String(e)}`}}async function UV(e,t,n,r){let i=e.range,a=e.comparisonRange,o=e.summary.clicks;try{let e=await t();if(!e.call)return null;let s=await UB(e,i,a);if(`missing`in s||s.current.clicks<=o)return null;let c=await XB(e,i,a);return{text:`## Bing\n${ZB(c,`Bing sends more clicks than Google here, so here is Bing's overview of ${s.site}`,n,r)}`,data:c}}catch{return null}}async function WV(e,t,n,r,i,a){let o={searchAnalytics:e,now:i},s={site:t,limit:100,includeBrand:!1,...r},c={overview:()=>zV(e,t,r,wn(r)),"quick-wins":()=>lP({...s,verifyContent:!1},o),"low-ctr":()=>_j(s,o),"striking-distance":()=>AP({...s,verifyContent:!1},o),"second-page":()=>ZR({...s,verifyContent:!1},o),"content-decay":()=>BN({...s,comparison:`previous-period`},o),cannibalization:async()=>{let e=await CN(s,o),t=e.items??[];return{...e,items:t.map(e=>{let t=e.pages??[];return{...e,urls:t.map(e=>`${e.url} (${Math.round(e.impressionShare*100)}%)`).join(` ; `),topPage:e.suggestedOwnerUrl}})}},"traffic-drop":async()=>{let e=await iF({site:t,...r,recentDays:7},o),n=IP(e.anomalies);return{...e,updateWindow:n&&{...n,paddingDays:3},googleUpdates:await kn(n)}},"ai-queries":()=>NV({site:t,...r},e),bing:async()=>qB(await a(),e,t,r)}[n];return Sn(await c())}function GV(e){let t=e.brand;return t?.terms?`Brand terms left out: ${t.terms.join(`, `)||`none`}${t.excluded?.length?`. Not treated as brand: ${t.excluded.map(e=>e.term).join(`, `)}`:``}.`:null}function KV(e,t){let n=[],r=(e,i=``)=>{if(!(n.length>=20)){if(typeof e==`string`){if(/^(url|page|finalUrl|targetUrl)$/i.test(i)){let r=e.startsWith(`/`)?`${t}${e}`:e;/^https?:\/\//.test(r)&&!n.includes(r)&&n.push(r)}return}if(Array.isArray(e))for(let t of e)r(t,i);else if(e&&typeof e==`object`)for(let[t,n]of Object.entries(e))r(n,t)}};for(let t of e)r(t);return n}function qV(e,t){let n=Un(e,[`url`,`status`,`redirects_to`,`title`,`description`,`h1`,`canonical`,`robots`,...e.some(e=>e.error)?[`error`]:[]],t,320),r=SV(e);return r?`${n}\n${r}`:n}async function JV(e,t){let n=t.now??(()=>new Date),r=On(t.searchAnalytics),i=Tn(e.site),a=VV(()=>VB(t,e.site)),o=FV.filter(e=>e!==`bing`||t.bing),s=Cn(e,LV.overview),c=NB(t.analytics,e.site,s,wn(s)),[l,...u]=await Promise.all(o.map(t=>WV(r,e.site,t,Cn(e,LV[t]),n,a).catch(e=>e instanceof Error?e:Error(String(e)))));if(!l||l instanceof Error)throw l??Error(`The overview did not run.`);let d=[BV(l,`Report on ${e.site}`,i,5)];d.push(t.bing?await HV(l,a):LB);let f=t.bing?await UV(l,a,i,5):null;f&&d.push(f.text);let p=await c;p&&d.push(p.text);let m=u.find(e=>!(e instanceof Error)&&GV(e)!==null);m&&d.push(GV(m));let h={};return o.slice(1).forEach((e,t)=>{let n=u[t];if(!n||n instanceof Error){let t=n?.message??`did not run`;d.push(`## ${e}\nNot available: ${t}`),h[e]={error:t};return}let r=Zn(n,i,3);h[e]={total:r.total},d.push([`## ${e}: ${r.total} ${r.total===1?`row`:`rows`}`,PV[e],r.text,e===`traffic-drop`?jn(n.googleUpdates,n.updateWindow):null].filter(Boolean).join(`
311
316
  `))}),d.push(`More: ${t.call(`report`,{site:e.site,section:`<section>`})} for its rows (${o.join(`, `)}). Page sections also check their top 20 URLs live and merge same-site redirects.`),{text:`${d.join(`
312
317
 
313
- `)}\n\n${bn}`,data:{site:e.site,overview:l,...f?{analytics:f.data}:{},sections:m}}}async function WV(e,t){let n=t.now??(()=>new Date),{site:r,section:i}=e,a=e.detail??`summary`,o=Cn(e,NV[i]),s=Tn(r),c=LV(()=>BB(t,r)),l=await zV(On(t.searchAnalytics),r,i,o,n,c),u=PV(i,t.call);if(i===`overview`){let e=await MB(t.analytics,r,o,wn(o));if(e&&(l.analytics=e.data),a!==`full`)return{text:[IV(l,`overview of ${r}`,s,10),t.bing?await RV(l,c):IB,e?.text,`More: ${t.call(`report`,{site:r,section:i,detail:`full`})} for every row.`,u,bn].filter(Boolean).join(`
318
+ `)}\n\n${bn}`,data:{site:e.site,overview:l,...p?{analytics:p.data}:{},...f?{bingOverview:f.data}:{},sections:h}}}async function YV(e,t){let n=t.now??(()=>new Date),{site:r,section:i}=e,a=e.detail??`summary`,o=Cn(e,LV[i]),s=Tn(r),c=VV(()=>VB(t,r)),l=await WV(On(t.searchAnalytics),r,i,o,n,c),u=RV(i,t.call);if(i===`overview`){let e=await NB(t.analytics,r,o,wn(o));e&&(l.analytics=e.data);let n=t.bing?await UV(l,c,s,10):null;if(n&&(l.bingOverview=n.data),a!==`full`)return{text:[BV(l,`overview of ${r}`,s,10),t.bing?await HV(l,c):LB,n?.text,e?.text,`More: ${t.call(`report`,{site:r,section:i,detail:`full`})} for every row.`,u,bn].filter(Boolean).join(`
319
+
320
+ `),data:l}}let d=[],f=[];if(IV.has(i)){let e=Object.values(l).find(e=>Array.isArray(e)&&e.length>0);d=await t.checkPages(KV(l.items??e??[],s));let a=new Map;for(let e of d)e.redirects_to&&new URL(e.redirects_to).host===new URL(e.url).host&&(a.set(e.url,e.redirects_to.replace(/#.*$/,``)),f.push(`${e.url} → ${e.redirects_to}`));a.size&&(l=await WV(On(t.searchAnalytics,a),r,i,o,n,c)),l.pageChecks=d}let p=[],m=GV(l);m&&p.push(m);let h=jn(l.googleUpdates,l.updateWindow);h&&p.push(h),d.length&&p.push(`Live page checks (${d.length} URLs, fetched now, no redirects followed):\n${qV(d,s)}`),f.length&&p.push(`Redirect sources merged into their targets, so each pair counts as one page here: ${f.join(`; `)}.`);let g=wn(o),_=Xn({report:l,headline:[`${i} on ${r}.`,typeof l.verdict==`string`?l.verdict:``].filter(Boolean).join(` `),label:i,range:i===`content-decay`?`${o.startDate} to ${o.endDate} against ${g.startDate} to ${g.endDate}`:`${o.startDate} to ${o.endDate}`,notes:p,origin:s,detail:a,offset:e.offset??0,limit:50,more:(e,n)=>t.call(`report`,{site:r,section:i,detail:e,offset:n})}),v=i===`bing`?bn.replace(`Search Console`,`Search Console and Bing`):bn;return{text:`${_.text}\n\n${u}\n\n${v}`,data:a===`full`?l:_.data}}function XV(e,t){return e.section?YV({...e,section:e.section},t):JV(e,t)}async function ZV(e,t){let n=Cn(e,LV.overview),r=wn(n),i=await VB(t,e.site);if(!i.call)throw new yn(`NOT_CONNECTED`,i.missing);let[a,o]=await Promise.all([XB(i,n,r),NB(t.analytics,i.site,n,r)]);return o&&(a.analytics=o.data),{text:[ZB(a,`Bing report on ${i.site}. No Search Console property covers this site, so this report uses Bing`,Tn(i.site),10),o?.text,`More: ${t.call(`data`,{source:`bing`,site:e.site,dimensions:`page`})} for every Bing page, or the same with query.`,bn.replace(`Search Console`,`Bing Webmaster Tools`)].filter(Boolean).join(`
314
321
 
315
- `),data:l}}let d=[],f=[];if(MV.has(i)){let e=Object.values(l).find(e=>Array.isArray(e)&&e.length>0);d=await t.checkPages(VV(l.items??e??[],s));let a=new Map;for(let e of d)e.redirects_to&&new URL(e.redirects_to).host===new URL(e.url).host&&(a.set(e.url,e.redirects_to.replace(/#.*$/,``)),f.push(`${e.url} → ${e.redirects_to}`));a.size&&(l=await zV(On(t.searchAnalytics,a),r,i,o,n,c)),l.pageChecks=d}let p=[],m=BV(l);m&&p.push(m);let h=jn(l.googleUpdates,l.updateWindow);h&&p.push(h),d.length&&p.push(`Live page checks (${d.length} URLs, fetched now, no redirects followed):\n${HV(d,s)}`),f.length&&p.push(`Redirect sources merged into their targets, so each pair counts as one page here: ${f.join(`; `)}.`);let g=wn(o),_=Xn({report:l,headline:[`${i} on ${r}.`,typeof l.verdict==`string`?l.verdict:``].filter(Boolean).join(` `),label:i,range:i===`content-decay`?`${o.startDate} to ${o.endDate} against ${g.startDate} to ${g.endDate}`:`${o.startDate} to ${o.endDate}`,notes:p,origin:s,detail:a,offset:e.offset??0,limit:50,more:(e,n)=>t.call(`report`,{site:r,section:i,detail:e,offset:n})}),v=i===`bing`?bn.replace(`Search Console`,`Search Console and Bing`):bn;return{text:`${_.text}\n\n${u}\n\n${v}`,data:a===`full`?l:_.data}}function GV(e,t){return e.section?WV({...e,section:e.section},t):UV(e,t)}function KV(e,t){let n=t===`dataforseo`?[e.get(`x-dataforseo-login`),e.get(`x-dataforseo-password`)]:[e.get(`x-ahrefs-key`)];if(n.some(e=>!e))throw new yn(`NO_KEY`,`No ${t} key. Hosted MCP: save it at https://seoskill.dev/account#keys. CLI and local MCP: run \`seo login\` to use the account's keys, or \`seo providers ${t} connect\`.`);return n}async function qV(e,t){let n=await fetch(t);if(n.ok)return n;let r=(await n.text()).slice(0,300);throw new yn(n.status===401||n.status===403?`NO_KEY`:`PROVIDER_ERROR`,`${e} answered ${n.status}. ${r}`)}function JV(e){let t=e.action===`keyword_metrics`||e.action===`serp`;if(t&&e.keywords.length===0)throw new yn(`INVALID_INPUT`,`${e.action} needs keywords.`);if(!t&&!e.target)throw new yn(`INVALID_INPUT`,`${e.action} needs a target domain or URL.`)}async function YV(e,t,n){JV(n);let r=KV(t,e);return e===`dataforseo`?eH(r,n):rH(r[0]??``,n)}function XV(e){return new Intl.DisplayNames(`en`,{type:`region`}).of(e.toUpperCase())??`United States`}function ZV(e){try{return new Intl.Locale(`und-${e.toUpperCase()}`).maximize().language}catch{return`en`}}const QV=new Map(`ae:ar al:sq am:hy ao:pt ar:es at:de au:en az:az ba:bs bd:bn be:nl bf:fr
322
+ `),data:a}}function QV(e,t){let n=t===`dataforseo`?[e.get(`x-dataforseo-login`),e.get(`x-dataforseo-password`)]:[e.get(`x-ahrefs-key`)];if(n.some(e=>!e))throw new yn(`NO_KEY`,`No ${t} key. Hosted MCP: save it at https://seoskill.dev/account#keys. CLI and local MCP: run \`seo login\` to use the account's keys, or \`seo providers ${t} connect\`.`);return n}async function $V(e,t){let n=await fetch(t);if(n.ok)return n;let r=(await n.text()).slice(0,300);throw new yn(n.status===401||n.status===403?`NO_KEY`:`PROVIDER_ERROR`,`${e} answered ${n.status}. ${r}`)}function eH(e){let t=e.action===`keyword_metrics`||e.action===`serp`;if(t&&e.keywords.length===0)throw new yn(`INVALID_INPUT`,`${e.action} needs keywords.`);if(!t&&!e.target)throw new yn(`INVALID_INPUT`,`${e.action} needs a target domain or URL.`)}async function tH(e,t,n){eH(n);let r=QV(t,e);return e===`dataforseo`?oH(r,n):lH(r[0]??``,n)}function nH(e){return new Intl.DisplayNames(`en`,{type:`region`}).of(e.toUpperCase())??`United States`}function rH(e){try{return new Intl.Locale(`und-${e.toUpperCase()}`).maximize().language}catch{return`en`}}const iH=new Map(`ae:ar al:sq am:hy ao:pt ar:es at:de au:en az:az ba:bs bd:bn be:nl bf:fr
316
323
  bg:bg bh:ar bo:es br:pt ca:en ch:de ci:fr cl:es cm:fr co:es cr:es cy:el
317
324
  cz:cs de:de dk:da dz:ar ec:es ee:et eg:ar es:es fi:fi fr:fr gb:en gh:en
318
325
  gr:el gt:es hk:en hr:hr hu:hu id:id ie:en il:he in:en it:it jo:ar jp:ja
319
326
  ke:en kh:en kr:ko kz:ru lk:en lt:lt lv:lv ma:ar mc:fr md:ro mk:mk mm:en
320
327
  mt:en mx:es my:en ng:en ni:es nl:nl no:nb nz:en pa:es pe:es ph:en pk:en
321
328
  pl:pl pt:pt py:es ro:ro rs:sr sa:ar se:sv sg:en si:sl sk:sk sn:fr sv:es
322
- th:th tn:ar tr:tr tw:zh-TW ua:uk us:en uy:es ve:es vn:vi za:en`.split(/\s+/).map(e=>e.split(`:`)));function $V(e){return QV.get(e.toLowerCase())??null}async function eH([e,t],n){let r=$V(n.country);if(!r&&n.action!==`serp`&&n.action!==`backlinks`)throw new yn(`INVALID_INPUT`,`DataForSEO has no ${n.action} data for country "${n.country}".`);let i={location_name:XV(n.country),language_code:r??ZV(n.country)},a=async(n,r)=>{let a=(await kt(await qV(`dataforseo`,new Request(`https://api.dataforseo.com/${n}`,{method:`POST`,headers:{authorization:`Basic ${btoa(`${e}:${t}`)}`,"content-type":`application/json`},body:JSON.stringify([{...i,...r}])})),`DataForSEO`)).tasks?.[0];if(!a||a.status_code>=4e4)throw new yn(`PROVIDER_ERROR`,`dataforseo: ${a?.status_message??`no task result`}`);return a.result?.[0]?.items??[]},o=(e,t)=>t.split(`.`).reduce((e,t)=>e&&typeof e==`object`?e[t]:void 0,e),s=(e,t)=>Object.fromEntries(Object.entries(t).map(([t,n])=>[t,o(e,n)??null]));if(n.action===`keyword_metrics`)return(await a(`v3/dataforseo_labs/google/keyword_overview/live`,{keywords:n.keywords.slice(0,700)})).map(e=>s(e,{keyword:`keyword`,search_volume:`keyword_info.search_volume`,keyword_difficulty:`keyword_properties.keyword_difficulty`,cpc:`keyword_info.cpc`,competition:`keyword_info.competition`,main_intent:`search_intent_info.main_intent`}));if(n.action===`ranked_keywords`)return(await a(`v3/dataforseo_labs/google/ranked_keywords/live`,{target:nH(n.target),limit:n.limit,order_by:[`ranked_serp_element.serp_item.etv,desc`]})).map(e=>s(e,{keyword:`keyword_data.keyword`,position:`ranked_serp_element.serp_item.rank_absolute`,url:`ranked_serp_element.serp_item.url`,search_volume:`keyword_data.keyword_info.search_volume`,etv:`ranked_serp_element.serp_item.etv`,keyword_difficulty:`keyword_data.keyword_properties.keyword_difficulty`,main_intent:`keyword_data.search_intent_info.main_intent`}));if(n.action===`serp`){let e=[];for(let t of n.keywords.slice(0,5)){let r=await a(`v3/serp/google/organic/live/advanced`,{keyword:t,depth:Math.min(n.limit,100)});for(let n of r)n.type===`organic`&&e.push({keyword:t,...s(n,{position:`rank_absolute`,url:`url`,domain:`domain`,title:`title`})})}return e}return n.action===`backlinks`?(await a(`v3/backlinks/referring_domains/live`,{target:nH(n.target),limit:n.limit,order_by:[`rank,desc`]})).map(e=>s(e,{domain:`domain`,rank:`rank`,backlinks:`backlinks`,referring_pages:`referring_pages`,first_seen:`first_seen`})):(await a(`v3/dataforseo_labs/google/competitors_domain/live`,{target:nH(n.target),limit:n.limit})).map(e=>s(e,{domain:`domain`,shared_keywords:`intersections`,avg_position:`avg_position`,organic_keywords:`full_domain_metrics.organic.count`,organic_etv:`full_domain_metrics.organic.etv`}))}function tH(e){return/\/./.test(nH(e))}function nH(e){return e.replace(/^https?:\/\//,``).replace(/\/$/,``)}async function rH(e,t){let n=async(t,n)=>{let r=new URL(`https://api.ahrefs.com/v3/${t}`);for(let[e,t]of Object.entries(n))r.searchParams.set(e,t);return kt(await qV(`ahrefs`,new Request(r,{headers:{authorization:`Bearer ${e}`,accept:`application/json`}})),`Ahrefs`)},r=new Date().toISOString().slice(0,10);if(t.action===`keyword_metrics`)return((await n(`keywords-explorer/overview`,{select:`keyword,volume,difficulty,cpc,traffic_potential,intents`,country:t.country,keywords:t.keywords.slice(0,100).join(`,`)})).keywords??[]).map(iH);if(t.action===`ranked_keywords`)return(await n(`site-explorer/organic-keywords`,{select:`keyword,best_position,best_position_url,volume,sum_traffic,keyword_difficulty,cpc`,target:t.target,country:t.country,date:r,mode:tH(t.target)?`exact`:`subdomains`,limit:String(t.limit),order_by:`sum_traffic:desc`})).keywords??[];if(t.action===`serp`){let e=[];for(let r of t.keywords.slice(0,5)){let i=await n(`serp-overview/serp-overview`,{select:`position,type,url,title,domain_rating,traffic,keywords`,keyword:r,country:t.country,top_positions:String(Math.min(t.limit,100))});for(let t of i.positions??[])e.push({keyword:r,...t})}return e}return t.action===`backlinks`?(await n(`site-explorer/refdomains`,{select:`domain,domain_rating,links_to_target,dofollow_links,first_seen,last_seen`,target:t.target,mode:tH(t.target)?`exact`:`subdomains`,history:`live`,limit:String(t.limit),order_by:`domain_rating:desc`})).refdomains??[]:(await n(`site-explorer/organic-competitors`,{select:`competitor_domain,keywords_common,keywords_competitor,keywords_target,share,traffic,domain_rating`,target:t.target,country:t.country,date:r,mode:`subdomains`,limit:String(t.limit),order_by:`keywords_common:desc`})).competitors??[]}function iH(e){let t=e.intents;if(!t||typeof t!=`object`)return e;let n=Object.entries(t).filter(([,e])=>e===!0).map(([e])=>e.replace(/^is_/,``));return{...e,intents:n.join(` `)||null}}const aH=[`keyword_metrics`,`ranked_keywords`,`serp`,`competitors`,`backlinks`],oH=[`dataforseo`,`ahrefs`],sH=[`youtube.com`,`facebook.com`,`wikipedia.org`,`reddit.com`,`quora.com`,`instagram.com`,`linkedin.com`,`x.com`,`twitter.com`,`pinterest.com`,`tiktok.com`,`amazon.com`],cH=(e,t)=>e===t||e.endsWith(`.${t}`);function lH(e,t){let n=lV(t),r=e=>lV(String(e.domain??e.competitor_domain??``)),i=e=>n!==``&&cH(e,n),a=e=>sH.some(t=>cH(e,t)),o=e.map(r),s=o.filter(i),c=o.filter(e=>!i(e)&&a(e)),l=s.length+c.length;if(!l)return{rows:e,note:null};let u=[s.length?`the target itself (${s.join(`, `)})`:``,c.length?`generic platforms that share keywords with most sites (${c.join(`, `)})`:``].filter(Boolean);return{rows:e.filter(e=>{let t=r(e);return!i(t)&&!a(t)}),note:`Left out ${l} ${l===1?`row`:`rows`}: ${u.join(` and `)}. The fixed platform list is ${sH.join(`, `)}.`}}async function uH(e,t,n){let r=e.country??`us`,i=e.target??``,a=e.offset??0,o=e.provider===`dataforseo`?$V(r):null,s=await YV(e.provider,t,{action:e.action,keywords:e.keywords??[],target:i,country:r,limit:Math.min(1e3,Math.max(100,a+50))}),{rows:c,note:l}=e.action===`competitors`?lH(s,i):{rows:s,note:null},u=t.get(`x-ahrefs-key`)??n.drKey,d=await fV(c,u),f=i?(await dV([i],u)).get(lV(i)):void 0,p=f!=null;return{text:dB({title:`${e.provider} ${e.action}${i?` for ${i}`:``}, ${r}${o?`, language ${o}`:``}.`,rows:d.rows,offset:a,limit:50,detail:e.detail??`summary`,notes:[`${e.provider} estimates, in the provider’s own units.`,...l?[l]:[],...p?[`${lV(i)} domain_rating: ${f}.`]:[],...d.added||p?[sV]:[]],more:n.call}),data:{provider:e.provider,action:e.action,target:i||null,country:r,language:o,targetDomainRating:p?f:null,attribution:d.added||p?sV:null,leftOut:l,total:d.rows.length,offset:a,rows:d.rows.slice(a,a+50)}}}function dH(e){let t=e?.inspectionResult?.indexStatusResult??e?.indexStatusResult??{},n=e=>typeof e==`string`?e:null;return{verdict:n(t.verdict),coverage:n(t.coverageState),indexing:n(t.indexingState),last_crawl:n(t.lastCrawlTime),google_canonical:n(t.googleCanonical),user_canonical:n(t.userCanonical)}}async function fH(e,t){let n=Cn(e,28),r=wn(n),i=n=>t.searchAnalytics(e.site,{...n,dimensions:[`query`],type:`web`,maxRows:5e3,dimensionFilterGroups:[{groupType:`and`,filters:[{dimension:`page`,operator:`equals`,expression:e.url}]}]}),a=e.detail===`full`,[[o],s,c,l,u]=await Promise.all([t.checkPages([e.url]),t.inspect(e.site,e.url),i(n),i(r),a&&t.pageMarkdown?t.pageMarkdown(e.url).catch(e=>({error:e instanceof Error?e.message:String(e)})):null]),d=new Map(l.rows.map(e=>[e.keys[0],e])),f=new Set,p=c.rows.map(e=>{f.add(e.keys[0]??``);let t=d.get(e.keys[0]);return{query:e.keys[0],clicks:e.clicks,previous_clicks:t?.clicks??0,clicks_change:e.clicks-(t?.clicks??0),impressions:e.impressions,ctr:e.ctr,position:e.position,previous_position:t?.position??null}});for(let e of l.rows)f.has(e.keys[0]??``)||p.push({query:e.keys[0],clicks:0,previous_clicks:e.clicks,clicks_change:-e.clicks,impressions:0,ctr:0,position:null,previous_position:e.position});p.sort((e,t)=>Number(t.clicks)-Number(e.clicks)||Number(t.impressions)-Number(e.impressions));let m=(e,t)=>e.reduce((e,n)=>e+n[t],0),h=e.offset??0;return{text:[dB({title:`${e.url} in ${e.site}, ${n.startDate} to ${n.endDate} against ${r.startDate} to ${r.endDate}.`,notes:[`Live page (fetched now, no redirects followed):\n${o?HV([o],null):`Not fetched.`}`,s?`Google index status:\n${Un([s],Object.keys(s),null)}`:`Google index status: not available for this URL.`,`Query totals: clicks ${m(c.rows,`clicks`)} (was ${m(l.rows,`clicks`)}), impressions ${m(c.rows,`impressions`)} (was ${m(l.rows,`impressions`)}). Search Console hides rare queries, so these can be lower than the page total.`,t.pageMarkdown?`Main content as Markdown: ${t.call(`page`,{url:e.url,detail:`full`})}.`:`Main content as Markdown: only in the CLI and the local MCP server, with \`npx -y seo page --url ${e.url} --detail full\`.`],rows:p,offset:h,limit:50,detail:e.detail??`summary`,more:n=>t.call(`page`,{url:e.url,detail:`rows`,offset:n})}),...a?[pH(u,e.url)]:[],`Next: ${t.call(`research`)} serp with the top query to see who else ranks.`,bn].join(`
329
+ th:th tn:ar tr:tr tw:zh-TW ua:uk us:en uy:es ve:es vn:vi za:en`.split(/\s+/).map(e=>e.split(`:`)));function aH(e){return iH.get(e.toLowerCase())??null}async function oH([e,t],n){let r=aH(n.country);if(!r&&n.action!==`serp`&&n.action!==`backlinks`)throw new yn(`INVALID_INPUT`,`DataForSEO has no ${n.action} data for country "${n.country}".`);let i={location_name:nH(n.country),language_code:r??rH(n.country)},a=async(n,r)=>{let a=(await kt(await $V(`dataforseo`,new Request(`https://api.dataforseo.com/${n}`,{method:`POST`,headers:{authorization:`Basic ${btoa(`${e}:${t}`)}`,"content-type":`application/json`},body:JSON.stringify([{...i,...r}])})),`DataForSEO`)).tasks?.[0];if(!a||a.status_code>=4e4)throw new yn(`PROVIDER_ERROR`,`dataforseo: ${a?.status_message??`no task result`}`);return a.result?.[0]?.items??[]},o=(e,t)=>t.split(`.`).reduce((e,t)=>e&&typeof e==`object`?e[t]:void 0,e),s=(e,t)=>Object.fromEntries(Object.entries(t).map(([t,n])=>[t,o(e,n)??null]));if(n.action===`keyword_metrics`)return(await a(`v3/dataforseo_labs/google/keyword_overview/live`,{keywords:n.keywords.slice(0,700)})).map(e=>s(e,{keyword:`keyword`,search_volume:`keyword_info.search_volume`,keyword_difficulty:`keyword_properties.keyword_difficulty`,cpc:`keyword_info.cpc`,competition:`keyword_info.competition`,main_intent:`search_intent_info.main_intent`}));if(n.action===`ranked_keywords`)return(await a(`v3/dataforseo_labs/google/ranked_keywords/live`,{target:cH(n.target),limit:n.limit,order_by:[`ranked_serp_element.serp_item.etv,desc`]})).map(e=>s(e,{keyword:`keyword_data.keyword`,position:`ranked_serp_element.serp_item.rank_absolute`,url:`ranked_serp_element.serp_item.url`,search_volume:`keyword_data.keyword_info.search_volume`,etv:`ranked_serp_element.serp_item.etv`,keyword_difficulty:`keyword_data.keyword_properties.keyword_difficulty`,main_intent:`keyword_data.search_intent_info.main_intent`}));if(n.action===`serp`){let e=[];for(let t of n.keywords.slice(0,5)){let r=await a(`v3/serp/google/organic/live/advanced`,{keyword:t,depth:Math.min(n.limit,100)});for(let n of r)n.type===`organic`&&e.push({keyword:t,...s(n,{position:`rank_absolute`,url:`url`,domain:`domain`,title:`title`})})}return e}return n.action===`backlinks`?(await a(`v3/backlinks/referring_domains/live`,{target:cH(n.target),limit:n.limit,order_by:[`rank,desc`]})).map(e=>s(e,{domain:`domain`,rank:`rank`,backlinks:`backlinks`,referring_pages:`referring_pages`,first_seen:`first_seen`})):(await a(`v3/dataforseo_labs/google/competitors_domain/live`,{target:cH(n.target),limit:n.limit})).map(e=>s(e,{domain:`domain`,shared_keywords:`intersections`,avg_position:`avg_position`,organic_keywords:`full_domain_metrics.organic.count`,organic_etv:`full_domain_metrics.organic.etv`}))}function sH(e){return/\/./.test(cH(e))}function cH(e){return e.replace(/^https?:\/\//,``).replace(/\/$/,``)}async function lH(e,t){let n=async(t,n)=>{let r=new URL(`https://api.ahrefs.com/v3/${t}`);for(let[e,t]of Object.entries(n))r.searchParams.set(e,t);return kt(await $V(`ahrefs`,new Request(r,{headers:{authorization:`Bearer ${e}`,accept:`application/json`}})),`Ahrefs`)},r=new Date().toISOString().slice(0,10);if(t.action===`keyword_metrics`)return((await n(`keywords-explorer/overview`,{select:`keyword,volume,difficulty,cpc,traffic_potential,intents`,country:t.country,keywords:t.keywords.slice(0,100).join(`,`)})).keywords??[]).map(uH);if(t.action===`ranked_keywords`)return(await n(`site-explorer/organic-keywords`,{select:`keyword,best_position,best_position_url,volume,sum_traffic,keyword_difficulty,cpc`,target:t.target,country:t.country,date:r,mode:sH(t.target)?`exact`:`subdomains`,limit:String(t.limit),order_by:`sum_traffic:desc`})).keywords??[];if(t.action===`serp`){let e=[];for(let r of t.keywords.slice(0,5)){let i=await n(`serp-overview/serp-overview`,{select:`position,type,url,title,domain_rating,traffic,keywords`,keyword:r,country:t.country,top_positions:String(Math.min(t.limit,100))});for(let t of i.positions??[])e.push({keyword:r,...t})}return e}return t.action===`backlinks`?(await n(`site-explorer/refdomains`,{select:`domain,domain_rating,links_to_target,dofollow_links,first_seen,last_seen`,target:t.target,mode:sH(t.target)?`exact`:`subdomains`,history:`live`,limit:String(t.limit),order_by:`domain_rating:desc`})).refdomains??[]:(await n(`site-explorer/organic-competitors`,{select:`competitor_domain,keywords_common,keywords_competitor,keywords_target,share,traffic,domain_rating`,target:t.target,country:t.country,date:r,mode:`subdomains`,limit:String(t.limit),order_by:`keywords_common:desc`})).competitors??[]}function uH(e){let t=e.intents;if(!t||typeof t!=`object`)return e;let n=Object.entries(t).filter(([,e])=>e===!0).map(([e])=>e.replace(/^is_/,``));return{...e,intents:n.join(` `)||null}}const dH=[`keyword_metrics`,`ranked_keywords`,`serp`,`competitors`,`backlinks`],fH=[`dataforseo`,`ahrefs`],pH=[`youtube.com`,`facebook.com`,`wikipedia.org`,`reddit.com`,`quora.com`,`instagram.com`,`linkedin.com`,`x.com`,`twitter.com`,`pinterest.com`,`tiktok.com`,`amazon.com`],mH=(e,t)=>e===t||e.endsWith(`.${t}`);function hH(e,t){let n=pV(t),r=e=>pV(String(e.domain??e.competitor_domain??``)),i=e=>n!==``&&mH(e,n),a=e=>pH.some(t=>mH(e,t)),o=e.map(r),s=o.filter(i),c=o.filter(e=>!i(e)&&a(e)),l=s.length+c.length;if(!l)return{rows:e,note:null};let u=[s.length?`the target itself (${s.join(`, `)})`:``,c.length?`generic platforms that share keywords with most sites (${c.join(`, `)})`:``].filter(Boolean);return{rows:e.filter(e=>{let t=r(e);return!i(t)&&!a(t)}),note:`Left out ${l} ${l===1?`row`:`rows`}: ${u.join(` and `)}. The fixed platform list is ${pH.join(`, `)}.`}}async function gH(e,t,n){let r=e.country??`us`,i=e.target??``,a=e.offset??0,o=e.provider===`dataforseo`?aH(r):null,s=await tH(e.provider,t,{action:e.action,keywords:e.keywords??[],target:i,country:r,limit:Math.min(1e3,Math.max(100,a+50))}),{rows:c,note:l}=e.action===`competitors`?hH(s,i):{rows:s,note:null},u=t.get(`x-ahrefs-key`)??n.drKey,d=await gV(c,u),f=i?(await hV([i],u)).get(pV(i)):void 0,p=f!=null;return{text:dB({title:`${e.provider} ${e.action}${i?` for ${i}`:``}, ${r}${o?`, language ${o}`:``}.`,rows:d.rows,offset:a,limit:50,detail:e.detail??`summary`,notes:[`${e.provider} estimates, in the provider’s own units.`,...l?[l]:[],...p?[`${pV(i)} domain_rating: ${f}.`]:[],...d.added||p?[dV]:[]],more:n.call}),data:{provider:e.provider,action:e.action,target:i||null,country:r,language:o,targetDomainRating:p?f:null,attribution:d.added||p?dV:null,leftOut:l,total:d.rows.length,offset:a,rows:d.rows.slice(a,a+50)}}}function _H(e){let t=e?.inspectionResult?.indexStatusResult??e?.indexStatusResult??{},n=e=>typeof e==`string`?e:null;return{verdict:n(t.verdict),coverage:n(t.coverageState),indexing:n(t.indexingState),last_crawl:n(t.lastCrawlTime),google_canonical:n(t.googleCanonical),user_canonical:n(t.userCanonical)}}async function vH(e,t){let n=Cn(e,28),r=wn(n),i=n=>t.searchAnalytics(e.site,{...n,dimensions:[`query`],type:`web`,maxRows:5e3,dimensionFilterGroups:[{groupType:`and`,filters:[{dimension:`page`,operator:`equals`,expression:e.url}]}]}),a=e.detail===`full`,[[o],s,c,l,u]=await Promise.all([t.checkPages([e.url]),t.inspect(e.site,e.url),i(n),i(r),a&&t.pageMarkdown?t.pageMarkdown(e.url).catch(e=>({error:e instanceof Error?e.message:String(e)})):null]),d=new Map(l.rows.map(e=>[e.keys[0],e])),f=new Set,p=c.rows.map(e=>{f.add(e.keys[0]??``);let t=d.get(e.keys[0]);return{query:e.keys[0],clicks:e.clicks,previous_clicks:t?.clicks??0,clicks_change:e.clicks-(t?.clicks??0),impressions:e.impressions,ctr:e.ctr,position:e.position,previous_position:t?.position??null}});for(let e of l.rows)f.has(e.keys[0]??``)||p.push({query:e.keys[0],clicks:0,previous_clicks:e.clicks,clicks_change:-e.clicks,impressions:0,ctr:0,position:null,previous_position:e.position});p.sort((e,t)=>Number(t.clicks)-Number(e.clicks)||Number(t.impressions)-Number(e.impressions));let m=(e,t)=>e.reduce((e,n)=>e+n[t],0),h=e.offset??0;return{text:[dB({title:`${e.url} in ${e.site}, ${n.startDate} to ${n.endDate} against ${r.startDate} to ${r.endDate}.`,notes:[`Live page (fetched now, no redirects followed):\n${o?qV([o],null):`Not fetched.`}`,s?`Google index status:\n${Un([s],Object.keys(s),null)}`:`Google index status: not available for this URL.`,`Query totals: clicks ${m(c.rows,`clicks`)} (was ${m(l.rows,`clicks`)}), impressions ${m(c.rows,`impressions`)} (was ${m(l.rows,`impressions`)}). Search Console hides rare queries, so these can be lower than the page total.`,t.pageMarkdown?`Main content as Markdown: ${t.call(`page`,{url:e.url,detail:`full`})}.`:`Main content as Markdown: only in the CLI and the local MCP server, with \`npx -y seo page --url ${e.url} --detail full\`.`],rows:p,offset:h,limit:50,detail:e.detail??`summary`,more:n=>t.call(`page`,{url:e.url,detail:`rows`,offset:n})}),...a?[yH(u,e.url)]:[],`Next: ${t.call(`research`)} serp with the top query to see who else ranks.`,bn].join(`
323
330
 
324
- `),data:{url:e.url,range:n,comparisonRange:r,page:o??null,index:s,totalQueries:p.length,queries:p.slice(h,h+50),...a?{markdown:u}:{}}}}function pH(e,t){return e?`error`in e?`Main content as Markdown: the page could not be read (${e.error}).`:e.markdown?`Main content as Markdown (live page${e.truncated?`, cut to ${e.markdown.length.toLocaleString(`en-US`)} of ${e.characters.toLocaleString(`en-US`)} characters`:``}):\n\n${e.markdown}`:`Main content as Markdown: the page has no main content to read.`:`Main content as Markdown: not on this server; it runs in the CLI and the local MCP server. ${PB} Then run \`npx -y seo page --url ${t} --detail full\`.`}async function mH(e,t){if(!/^\d{4}-\d{2}-\d{2}$/.test(e.date))throw new yn(`INVALID_INPUT`,`The date must be YYYY-MM-DD.`);let n=tn(t.now?.()??new Date),r=Math.round((Date.parse(n)-Date.parse(e.date))/864e5)+1;if(r<3)throw new yn(`INVALID_INPUT`,`Search Console has final data to ${n}. Use a date at least 3 days before that.`);let i=Math.min(28,r),a={startDate:e.date,endDate:en(e.date,i-1)},o={startDate:en(e.date,-i),endDate:en(e.date,-1)},[s,c,l]=await Promise.all([FV(On(t.searchAnalytics),e.site,a,o,e.pages),kn({start:o.startDate,end:a.endDate}),MB(t.analytics,e.site,a,o,e.pages)]);return{text:[IV(s,`Compare on ${e.site}: ${i} days after ${e.date}`,Tn(e.site),10),l?.text,jn(c),`Next: ${t.call(`page`)} for a page that moved.`,bn].filter(Boolean).join(`
331
+ `),data:{url:e.url,range:n,comparisonRange:r,page:o??null,index:s,totalQueries:p.length,queries:p.slice(h,h+50),...a?{markdown:u}:{}}}}function yH(e,t){return e?`error`in e?`Main content as Markdown: the page could not be read (${e.error}).`:e.markdown?`Main content as Markdown (live page${e.truncated?`, cut to ${e.markdown.length.toLocaleString(`en-US`)} of ${e.characters.toLocaleString(`en-US`)} characters`:``}):\n\n${e.markdown}`:`Main content as Markdown: the page has no main content to read.`:`Main content as Markdown: not on this server; it runs in the CLI and the local MCP server. ${FB} Then run \`npx -y seo page --url ${t} --detail full\`.`}async function bH(e,t){if(!/^\d{4}-\d{2}-\d{2}$/.test(e.date))throw new yn(`INVALID_INPUT`,`The date must be YYYY-MM-DD.`);let n=tn(t.now?.()??new Date),r=Math.round((Date.parse(n)-Date.parse(e.date))/864e5)+1;if(r<3)throw new yn(`INVALID_INPUT`,`Search Console has final data to ${n}. Use a date at least 3 days before that.`);let i=Math.min(28,r),a={startDate:e.date,endDate:en(e.date,i-1)},o={startDate:en(e.date,-i),endDate:en(e.date,-1)},[s,c,l]=await Promise.all([zV(On(t.searchAnalytics),e.site,a,o,e.pages),kn({start:o.startDate,end:a.endDate}),NB(t.analytics,e.site,a,o,e.pages)]);return{text:[BV(s,`Compare on ${e.site}: ${i} days after ${e.date}`,Tn(e.site),10),l?.text,jn(c),`Next: ${t.call(`page`)} for a page that moved.`,bn].filter(Boolean).join(`
325
332
 
326
- `),data:{...s,...l?{analytics:l.data}:{},googleUpdates:c}}}const hH=.2;function gH(e,t){let n=e.filter(e=>e?.verdict!=null),r=n.filter(e=>e.verdict===`PASS`).length,i=new Map;for(let e of n){if(e.verdict===`PASS`)continue;let t=e.coverage??e.verdict??`unknown`;i.set(t,(i.get(t)??0)+1)}let a=n.length-r,o=t?.status?.verdict?t.status.verdict===`PASS`:null,s=a>=5&&a*2>n.length&&o,c=[...i].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).map(([e,t])=>({state:e,count:t}));return{text:(n.length?[`Index status of the ${n.length} inspected pages: ${r} indexed, ${a} not indexed${c.length?` (${c.map(e=>`${e.count} ${e.state}`).join(`; `)})`:``}.${t&&o!==null?` Home page ${t.url}: ${o?`indexed`:`not indexed (${t.status?.coverage??t.status?.verdict})`}.`:``}`,s?`Site-wide pattern: ${a} of ${n.length} inspected pages are not in Google's index, but the home page is. This points to the whole site, not single pages. It does not show the cause.`:null]:[]).filter(Boolean).join(`
327
- `),data:{inspected:n.length,indexed:r,notIndexed:a,byCoverage:c,homePage:t&&o!==null?{url:t.url,indexed:o}:null,siteWide:!!s}}}const _H=`Pages that had at least 3 clicks in the previous 28 days and kept ${hH*100}% or less of them in the last 28 days, with a live check of the top 20 and Google’s index status for the top 10 and the home page.`;async function vH(e,t){let n=Cn(e,28),r=wn(n),i=n=>t.searchAnalytics(e.site,{...n,dimensions:[`page`],type:`web`,maxRows:25e3}),[a,o]=await Promise.all([i(n),i(r)]),s=new Map(a.rows.map(e=>[e.keys[0],e.clicks])),c=o.rows.filter(e=>e.clicks>=3&&!e.keys[0]?.includes(`#`)).map(e=>({url:e.keys[0]??``,previous_clicks:e.clicks,clicks:s.get(e.keys[0])??0})).filter(e=>e.clicks<=e.previous_clicks*hH).sort((e,t)=>t.previous_clicks-t.clicks-(e.previous_clicks-e.clicks)||e.url.localeCompare(t.url)),l=c.slice(0,20),u=l[0]?`${new URL(l[0].url).origin}/`:null,[d,f,p]=await Promise.all([t.checkPages(l.map(e=>e.url)),Promise.all(l.slice(0,10).map(n=>t.inspect(e.site,n.url))),u&&!l.slice(0,10).some(e=>e.url===u)?t.inspect(e.site,u).catch(()=>null):null]),m=l.slice(0,10).findIndex(e=>e.url===u),h=gH(m>=0?f.filter((e,t)=>t!==m):f,u?{url:u,status:m>=0?f[m]??null:p}:null),g=l.map((e,t)=>({...e,status:d[t]?.status??null,redirects_to:d[t]?.redirects_to??null,robots:d[t]?.robots??null,canonical:d[t]?.canonical??null,verdict:f[t]?.verdict??null,coverage:f[t]?.coverage??null,google_canonical:f[t]?.google_canonical??null}));return{text:[`Pages that lost their clicks on ${e.site}: ${n.startDate} to ${n.endDate} against ${r.startDate} to ${r.endDate}.`,`${c.length} pages kept ${hH*100}% or less of at least 3 clicks${c.length>20?`; the top 20 by clicks lost are shown`:``}.`,g.length?Un(g,Object.keys(g[0]??{}),Tn(e.site)):`No pages lost their clicks.`,h.text,`Live checks are fetched now with no redirects followed. Index status is from URL Inspection; Google allows about 2,000 inspections a day per property.`,vV(g),`Next: ${t.call(`page`)} for one URL; ${t.call(`report`,{site:e.site,section:`content-decay`})} for pages that lost part of their clicks.`,bn].filter(Boolean).join(`
333
+ `),data:{...s,...l?{analytics:l.data}:{},googleUpdates:c}}}const xH=.2;function SH(e,t){let n=e.filter(e=>e?.verdict!=null),r=n.filter(e=>e.verdict===`PASS`).length,i=new Map;for(let e of n){if(e.verdict===`PASS`)continue;let t=e.coverage??e.verdict??`unknown`;i.set(t,(i.get(t)??0)+1)}let a=n.length-r,o=t?.status?.verdict?t.status.verdict===`PASS`:null,s=a>=5&&a*2>n.length&&o,c=[...i].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).map(([e,t])=>({state:e,count:t}));return{text:(n.length?[`Index status of the ${n.length} inspected pages: ${r} indexed, ${a} not indexed${c.length?` (${c.map(e=>`${e.count} ${e.state}`).join(`; `)})`:``}.${t&&o!==null?` Home page ${t.url}: ${o?`indexed`:`not indexed (${t.status?.coverage??t.status?.verdict})`}.`:``}`,s?`Site-wide pattern: ${a} of ${n.length} inspected pages are not in Google's index, but the home page is. This points to the whole site, not single pages. It does not show the cause.`:null]:[]).filter(Boolean).join(`
334
+ `),data:{inspected:n.length,indexed:r,notIndexed:a,byCoverage:c,homePage:t&&o!==null?{url:t.url,indexed:o}:null,siteWide:!!s}}}const CH=`Pages that had at least 3 clicks in the previous 28 days and kept ${xH*100}% or less of them in the last 28 days, with a live check of the top 20 and Google’s index status for the top 10 and the home page.`;async function wH(e,t){let n=Cn(e,28),r=wn(n),i=n=>t.searchAnalytics(e.site,{...n,dimensions:[`page`],type:`web`,maxRows:25e3}),[a,o]=await Promise.all([i(n),i(r)]),s=new Map(a.rows.map(e=>[e.keys[0],e.clicks])),c=o.rows.filter(e=>e.clicks>=3&&!e.keys[0]?.includes(`#`)).map(e=>({url:e.keys[0]??``,previous_clicks:e.clicks,clicks:s.get(e.keys[0])??0})).filter(e=>e.clicks<=e.previous_clicks*xH).sort((e,t)=>t.previous_clicks-t.clicks-(e.previous_clicks-e.clicks)||e.url.localeCompare(t.url)),l=c.slice(0,20),u=l[0]?`${new URL(l[0].url).origin}/`:null,[d,f,p]=await Promise.all([t.checkPages(l.map(e=>e.url)),Promise.all(l.slice(0,10).map(n=>t.inspect(e.site,n.url))),u&&!l.slice(0,10).some(e=>e.url===u)?t.inspect(e.site,u).catch(()=>null):null]),m=l.slice(0,10).findIndex(e=>e.url===u),h=SH(m>=0?f.filter((e,t)=>t!==m):f,u?{url:u,status:m>=0?f[m]??null:p}:null),g=l.map((e,t)=>({...e,status:d[t]?.status??null,redirects_to:d[t]?.redirects_to??null,robots:d[t]?.robots??null,canonical:d[t]?.canonical??null,verdict:f[t]?.verdict??null,coverage:f[t]?.coverage??null,google_canonical:f[t]?.google_canonical??null}));return{text:[`Pages that lost their clicks on ${e.site}: ${n.startDate} to ${n.endDate} against ${r.startDate} to ${r.endDate}.`,`${c.length} pages kept ${xH*100}% or less of at least 3 clicks${c.length>20?`; the top 20 by clicks lost are shown`:``}.`,g.length?Un(g,Object.keys(g[0]??{}),Tn(e.site)):`No pages lost their clicks.`,h.text,`Live checks are fetched now with no redirects followed. Index status is from URL Inspection; Google allows about 2,000 inspections a day per property.`,SV(g),`Next: ${t.call(`page`)} for one URL; ${t.call(`report`,{site:e.site,section:`content-decay`})} for pages that lost part of their clicks.`,bn].filter(Boolean).join(`
328
335
 
329
- `),data:{range:n,comparisonRange:r,rule:_H,lostPages:c.length,index:h.data,pages:g}}}const yH={overview:`search-performance-overview`,"quick-wins":`quick-wins`,"low-ctr":`ctr-underperformers`,"striking-distance":`striking-distance`,"second-page":`second-page`,"content-decay":`decaying-pages`,cannibalization:`cannibalisation`,"traffic-drop":`traffic-anomaly`},bH={keyword_metrics:`keyword-metrics`,ranked_keywords:`ranked-keywords`,serp:`serp-results`,competitors:`serp-competitors`,backlinks:`link-evidence`};function xH(e,t={}){return e===`report`?yH[t.section||`overview`]??null:e===`research`?bH[t.action??``]??null:{page:`page-opportunities`,compare:`measure-change`,index:`link-recovery`,crawl:`site-crawl`,"internal-links":`internal-links`}[e]??null}const SH=o.string().min(1).describe(`Search Console property or site, such as sc-domain:example.com, https://example.com/ or example.com.`),CH={start_date:o.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe(`YYYY-MM-DD. Optional; send with end_date.`),end_date:o.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe(`YYYY-MM-DD. Optional; send with start_date.`)},wH={detail:o.enum([`summary`,`rows`,`full`]).default(`summary`).describe(`summary first. rows: the next page of rows. full: every field as JSON.`),offset:o.number().int().min(0).default(0).describe(`rows only: the first row to return.`)},TH=[`search_console`,`google_analytics`,`bing`,`clicky`];function EH(e){return e}const DH=[EH({name:`seo_sites`,command:`data`,title:`List sites`,description:`Lists the Search Console and Google Analytics properties the connected Google accounts can read, the Bing Webmaster site for each, and which research keys are set. Call it first.`,input:o.object({}),run:async e=>er({accounts:await e.accounts(),keys:await e.keys(),clicky:YB(await e.keys()).map(XB),signIn:e.signIn,bing:e.deps.bing?await e.deps.bing():void 0,connect:e.connect})}),EH({name:`seo_report`,command:`report`,title:`Search Console report`,description:`The main report for a Search Console property. Without a section it returns the overview plus each section's row count and top rows. With a section it returns that section's rows; page sections also check their top 20 URLs live. Sections:\n${Object.entries(AV).map(([e,t])=>`- ${e}: ${t}`).join(`
330
- `)}`,input:o.object({site:SH,section:o.enum(jV).optional().describe(`Optional. Leave it out first; then ask for one section.`),...CH,...wH}),run:async(e,t)=>GV({site:t.section===`bing`?await e.resolveSite(t.site).catch(()=>t.site):await e.resolveSite(t.site),section:t.section,startDate:t.start_date,endDate:t.end_date,detail:t.detail,offset:t.offset},e.deps)}),EH({name:`seo_page`,command:`page`,title:`One page`,description:`Everything for one URL: live page facts (status, redirect, title, description, H1, canonical, robots), Google’s index status from URL Inspection, and the page’s Search Console queries against the previous period.`,input:o.object({url:o.url(),...CH,...wH}),run:async(e,t)=>fH({site:await e.resolveSite(t.url),url:t.url,startDate:t.start_date,endDate:t.end_date,detail:t.detail,offset:t.offset},e.deps)}),EH({name:`seo_compare`,command:`compare`,title:`Before and after a date`,description:`Compares equal periods before and after a date, such as a site change or a Google update: totals, devices, and the pages and queries that moved, Google Analytics sessions from the property whose web stream matches the site, and Google updates in the window. Optional pages narrows it to URLs that contain that text, such as /blog/.`,input:o.object({site:SH,date:o.string().regex(/^\d{4}-\d{2}-\d{2}$/).describe(`YYYY-MM-DD: the first day after the change.`),pages:o.string().min(1).optional().describe(`Optional URL text, such as /blog/.`)}),run:async(e,t)=>mH({site:await e.resolveSite(t.site),date:t.date,pages:t.pages},e.deps)}),EH({name:`seo_index`,command:`index`,title:`Pages that lost their clicks`,description:`${_H} It shows pages that broke, redirect, block indexing or dropped out of Google.`,input:o.object({site:SH,...CH}),run:async(e,t)=>vH({site:await e.resolveSite(t.site),startDate:t.start_date,endDate:t.end_date},e.deps)}),EH({name:`seo_research`,command:`research`,title:`Keyword, competitor and backlink data`,description:`Data from the person’s own DataForSEO or Ahrefs account, which costs them credits. It uses the key the person saved on their seoskill.dev account (or on this machine for the CLI). Actions: keyword_metrics (keywords: volume, difficulty, CPC), ranked_keywords (target: keywords a domain or URL ranks for), serp (keywords, up to 5: the ranking pages), competitors (target: domains that share keywords), backlinks (target: referring domains). Rows with a domain, and the target, get a free Ahrefs domain_rating column. Numbers are provider estimates, not Search Console data.`,input:o.object({provider:o.enum(oH),action:o.enum(aH),keywords:o.array(o.string().min(1)).max(100).default([]),target:o.string().default(``).describe(`Domain or URL.`),country:o.string().regex(/^[a-z]{2}$/).default(`us`).describe(`Two-letter country code.`),...wH}),run:async(e,t)=>uH(t,await e.keys(),{drKey:e.drKey,call:e=>`seo_research with the same input, detail "rows", offset ${e}`})}),EH({name:`seo_data`,command:`data`,title:`Raw rows`,description:`Raw rows for questions the report does not answer. search_console (default): rows for any dimensions, each with the previous period and the change; page and query narrow to rows whose URL or query contains that text. google_analytics: landing pages for visits from search, with Google Analytics’ own metric names. bing: Bing Webmaster query or page rows (first dimension) for the same site, by week. clicky: landing-page visits, traffic sources and search engines from a Clicky site the person saved (site is its domain or Clicky site ID; at most 31 days).`,input:o.object({source:o.enum(TH).default(`search_console`),site:o.string().min(1).describe(`search_console and bing: the property or site. google_analytics: numeric property id from seo_sites. clicky: the site or its Clicky site ID.`),dimensions:o.array(o.enum(fB)).max(4).default([`query`]).describe(`search_console; bing uses the first, query or page.`),page:o.string().min(1).optional().describe(`search_console only: URL text, such as /blog/.`),query:o.string().min(1).optional().describe(`search_console only: query text.`),...CH,...wH}),run:async(e,t)=>t.source===`clicky`?oV({site:t.site,startDate:t.start_date,endDate:t.end_date,detail:t.detail,offset:t.offset},await e.keys(),{connect:e.connect,call:e=>`seo_data with source "clicky", site "${t.site}", detail "rows", offset ${e}`,refresh:e.refreshClicky}):t.source===`bing`?qB({site:t.site,dimension:t.dimensions[0]===`page`?`page`:`query`,startDate:t.start_date,endDate:t.end_date,detail:t.detail,offset:t.offset},e.deps):t.source===`google_analytics`?gB({property:t.site,startDate:t.start_date,endDate:t.end_date,detail:t.detail,offset:t.offset},await hB(await e.accounts(),t.site,e.signIn),{signIn:e.signIn,call:e=>`seo_data with source "google_analytics", site "${t.site}", detail "rows", offset ${e}`}):mB({site:await e.resolveSite(t.site),dimensions:t.dimensions,filters:[...t.page?[{dimension:`page`,operator:`contains`,expression:t.page}]:[],...t.query?[{dimension:`query`,operator:`contains`,expression:t.query}]:[]],startDate:t.start_date,endDate:t.end_date,detail:t.detail,offset:t.offset},e.deps)})];async function OH(e,t,n){let r=e.input.safeParse(n??{});if(!r.success)throw new yn(`INVALID_INPUT`,r.error.issues.map(e=>`${e.path.join(`.`)||`input`}: ${e.message}`).join(`; `));return e.run(t,r.data)}const kH=(e,t)=>{let n=`seo_${e.replace(`-`,`_`)}`,r=Object.entries(t??{}).filter(([,e])=>e!==void 0);return r.length?`${n} with ${r.map(([e,t])=>`${e} ${typeof t==`number`?t:`"${t}"`}`).join(`, `)}`:n},AH={name:`seo-skill`,uri:`skill://seo/SKILL.md`,title:`SEO Skill`,description:`How to use these tools: what each command returns and how to reach it.`,mimeType:`text/markdown`};function jH(e){let t=t=>{let n=t.trim();if(!n||n.length>4096)throw new BO({provider:e.provider,operation:`credentials`,code:`configuration`,message:e.invalidMessage});return n};return{async write(n){return ik(e.secretName,t(n))},async read(n={}){let r=await rk({name:e.secretName,envVar:e.environmentVariable,env:n.env});return r?{apiKey:t(r.value),source:r.source}:void 0},async remove(){await ak(e.secretName)}}}const MH=`SEO_AHREFS_API_KEY`,NH=JO.ahrefsApiKey,PH=jH({provider:`ahrefs`,environmentVariable:MH,secretName:NH,invalidMessage:`Ahrefs needs a valid API v3 key.`});async function FH(e){return PH.write(e)}async function IH(e={}){return PH.read(e)}async function LH(){await PH.remove()}const RH=`SEO_BING_API_KEY`,zH=JO.bingApiKey,BH=jH({provider:`bing`,environmentVariable:RH,secretName:zH,invalidMessage:`Bing Webmaster needs a valid API key.`});async function VH(e){return BH.write(e)}async function HH(e={}){return BH.read(e)}async function UH(){await BH.remove()}const WH=`SEO_DATAFORSEO_LOGIN`,GH=`SEO_DATAFORSEO_PASSWORD`,KH=JO.dataForSeoCredentials,qH=o.object({version:o.literal(1),login:o.string().trim().min(1).max(320),password:o.string().min(1).max(2048)}).strict();function JH(e){return new BO({provider:`dataforseo`,operation:`credentials`,code:`configuration`,message:e})}function YH(e){let t=qH.safeParse({version:1,login:e.login,password:e.password});if(!t.success)throw JH(`DataForSEO credentials need both an API login and API password.`);return{login:t.data.login,password:t.data.password}}function XH(){let e=ra();return!e.providers.dataForSeoLogin&&!e.providers.dataForSeoPassword?!1:(ia({...e,providers:{...e.providers,dataForSeoLogin:void 0,dataForSeoPassword:void 0}}),!0)}function ZH(e){let t=e[WH]?.trim(),n=e[GH];if(!(!t&&!n)){if(!t||!n)throw JH(`Set both ${WH} and ${GH}.`);return YH({login:t,password:n})}}function QH(e){let t;try{t=JSON.parse(e)}catch{throw JH("Saved DataForSEO credentials are invalid. Run `seo providers dataforseo disconnect`, then connect again.")}let n=qH.safeParse(t);if(!n.success)throw JH("Saved DataForSEO credentials are invalid. Run `seo providers dataforseo disconnect`, then connect again.");return{login:n.data.login,password:n.data.password}}async function $H(e){let t=YH(e),n=await ik(KH,JSON.stringify({version:1,...t}));return XH(),n}async function eU(){let e=ra(),t=e.providers.dataForSeoLogin,n=e.providers.dataForSeoPassword;if(!t&&!n)return;if(!t||!n)throw JH("Legacy DataForSEO config contains only part of the credential pair. Run `seo providers dataforseo disconnect`, then connect again.");let r=YH({login:t,password:n}),i=await $H(r);return{...r,source:i,migrated:!0}}async function tU(e={}){let t=ZH(e.env??process.env);if(t)return{...t,source:`environment`,migrated:!1};let n=await rk({name:KH});if(n){let e=QH(n.value),t=XH();return{...e,source:n.source,migrated:t}}return eU()}async function nU(){await ak(KH),XH()}function rU(e){return{searchAnalytics:(t,n)=>qx(t,n,{refresh:e.refresh,accountEmail:e.account}),checkPages:_V,inspect:async(t,n)=>{try{return dH(await Wx({siteUrl:t,inspectionUrl:n,accountEmail:e.account}))}catch{return null}},pageMarkdown:async t=>Kv(await kx(t,{refresh:e.refresh})),call:e.call,bing:oU,bingConnect:iU,analytics:{accounts:sU,signIn:To.signIn}}}const iU="Connect Bing on your seoskill.dev account and run `seo login`, or run `seo providers bing connect` with an API key from Bing Webmaster Tools (Settings, API access).";let aU;function oU(){return aU??=HH().catch(()=>void 0).then(e=>e?Ut({apiKey:e.apiKey},{signIn:iU}):Ci()?Fi():null),aU}async function sU(){return Ci()?(await Mi()).map(e=>({email:e,google:Mt(()=>ji(e))})):[{email:null,google:await pU()}]}async function cU(){let[e,t,n,r]=await Promise.all([tU().catch(()=>void 0),IH().catch(()=>void 0),hk().catch(()=>({})),Ci()?Ii().catch(()=>({})):{}]),i=new Headers(r);for(let[e,t]of Object.entries(n)){let n=`${JB}${e}`;i.has(n)||i.set(n,t)}return e&&(i.set(`x-dataforseo-login`,e.login),i.set(`x-dataforseo-password`,e.password)),t?.apiKey&&i.set(`x-ahrefs-key`,t.apiKey),i}async function lU(){return Ci()?(await Oi({refreshClicky:!0}),cU()):null}async function uU(e,t={}){let n=Mn((await eS(t.refresh,t.account)).map(e=>e.siteUrl),e);if(!n)throw new yn(`NO_ACCESS`,`This Google login has no Search Console property for ${e}. Run \`seo sites\` to list the properties it can read.`);return n}const dU={INVALID_INPUT:`INVALID_INPUT`,NOT_CONNECTED:`AUTH_REQUIRED`,NO_ACCESS:`PROPERTY_NOT_FOUND`,NO_KEY:`AUTH_CONFIG_REQUIRED`,RATE_LIMITED:`RATE_LIMITED`,GOOGLE_ERROR:`PROVIDER_UNAVAILABLE`,PROVIDER_ERROR:`PROVIDER_UNAVAILABLE`};function fU(e){return e instanceof yn?new N(dU[e.code],e.message):e}async function pU(e){let{client:t}=await Co(e);return wo(t)}const mU=[`https://www.googleapis.com/auth/webmasters.readonly`,`https://www.googleapis.com/auth/analytics.readonly`];async function hU(e={}){let t=fr(),n=Aa(),r=Ga(),i=await va(),a=Ta(),o=i?!!Ma(i.client_source):void 0,s=[];try{let t=(e.checkDatabase??Yo)();s.push({id:`local-database`,label:`Local database`,status:`pass`,detail:t.dbPath})}catch(e){s.push({id:`local-database`,label:`Local database`,status:`fail`,detail:e instanceof Error?e.message:`The local database could not be opened.`,fix:"Upgrade or reinstall `seo`. If this still fails, report it at https://github.com/iannuttall/seo/issues."})}s.push({id:`config-dir`,label:`Config directory`,status:S(t.configDir)?`pass`:`warn`,detail:t.configDir,fix:S(t.configDir)?void 0:"Run `seo start` or `seo auth setup-client`."}),s.push({id:`oauth-client`,label:`Google credentials`,status:r.configured?`pass`:o===!1||r.error?`fail`:n.sharedConfigured||n.byoConfigured?`pass`:`fail`,detail:r.configured?`Service account configured for ${r.identity}.`:o===!1?`Stored Google login uses the ${i?.client_source===`shared`?`shared seo app`:`BYO client`}, but that client is not configured.`:r.error?r.error:n.sharedConfigured?`Shared client configured.`:n.byoConfigured?`BYO client configured at ${t.oauthClientFile}.`:`No shared or BYO Google OAuth client configured.`,fix:r.configured?void 0:o===!1?i?.client_source===`shared`?"Reinstall `seo`. If the shared client is still missing, report it at https://github.com/iannuttall/seo/issues.":"Restore the same client with `seo auth setup-client`, or run `seo auth logout` before signing in with a different client.":r.error?"Set one valid service account credential source, then run `seo doctor` again.":n.sharedConfigured||n.byoConfigured?void 0:"Run `seo auth setup-client` or set SEO_GOOGLE_CLIENT_ID and SEO_GOOGLE_CLIENT_SECRET."}),s.push({id:`oauth-client-file`,label:`BYO OAuth file`,status:a?`pass`:`warn`,detail:a?t.oauthClientFile:`No BYO OAuth client file. This is fine if using a shared client.`}),s.push({id:`google-login`,label:`Google login`,status:r.configured||i?`pass`:`fail`,detail:r.configured?`Using service account ${r.identity}.`:i?`Signed in as ${i.account_email}.`:`No Google token found.`,fix:r.configured||i?void 0:"Run `seo auth login`, or configure a service account for CI."});let c=new Set(i?.scope.split(/\s+/).filter(Boolean)??[]);for(let e of mU)s.push({id:`scope:${e}`,label:e.endsWith(`webmasters.readonly`)?`Search Console scope`:`Google Analytics scope`,status:r.configured||i&&c.has(e)?`pass`:i?`fail`:`warn`,detail:r.configured?`${e} requested by the service account.`:i?c.has(e)?e:`Missing ${e}.`:`Cannot inspect scopes until login is complete.`,fix:!r.configured&&i&&!c.has(e)?"Run `seo auth logout` then `seo auth login`.":void 0});return{ok:s.every(e=>e.status!==`fail`),generatedAt:new Date().toISOString(),checks:s}}function gU(e){return S(e)?T(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.log`)).map(t=>{let n=g(e,t.name),r=O(n);return{path:n,size:r.size,modifiedAt:r.mtimeMs}}):[]}function _U(e,t){let n=p(e),r=f(e,`.log`),i=0;for(;;){let e=g(n,`${r}.${t}${i?`-${i}`:``}.log`);if(!S(e))return e;i+=1}}function vU(e={}){let t=e.directory??fr().logDir,n=e.now??Date.now(),r=e.maxFileBytes??8388608,i=e.maxTotalBytes??67108864,a=e.maxAgeMs??12096e5;C(t,{recursive:!0,mode:448});let o=0,s=0;for(let e of gU(t))e.size<=r||(E(e.path,_U(e.path,n)),o+=1);for(let e of gU(t))e.modifiedAt>=n-a||(D(e.path,{force:!0}),s+=1);let c=gU(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;D(e.path,{force:!0}),l-=e.size,s+=1}return{rotated:o,removed:s,sizeBytes:l}}function yU(e){let t=Object.entries(e);if(t.length>100)throw Error(`Provider action input is too large.`);for(let[e]of t)if(!/^[A-Za-z][A-Za-z0-9-]{0,63}$/u.test(e))throw Error(`Provider action parameter names are invalid.`);let n=bU(Object.fromEntries(t));return xU(n,{maxBytes:65536,maxDepth:16,maxValues:5e3,message:`Provider action input is too large.`}),n}function bU(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`?e:Array.isArray(e)?e.map(bU):Object.fromEntries(Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,bU(t)]))}function xU(e,t){let n=0,r=new WeakSet,i=(e,a)=>{if(n+=1,n>t.maxValues||a>t.maxDepth)throw Error(t.message);if(e!==null&&typeof e!=`string`&&typeof e!=`boolean`&&!(typeof e==`number`&&Number.isFinite(e))){if(typeof e!=`object`)throw Error(`Provider action result must contain JSON values only.`);if(r.has(e))throw Error(`Provider action result must not contain cycles.`);if(r.add(e),Array.isArray(e))for(let t of e)i(t,a+1);else for(let[t,n]of Object.entries(e)){if(t.length>256)throw Error(`Provider action result contains a key that is too long.`);i(n,a+1)}r.delete(e)}};i(e,0);let a=JSON.stringify(e);if(Buffer.byteLength(a)>t.maxBytes)throw Error(t.message);return JSON.parse(a)}function SU(e,t,n){let r;try{r=o.fromJSONSchema(e)}catch{throw Error(`Provider action ${n} schema is invalid.`)}let i=r.safeParse(t);if(!i.success)throw Error(`Provider action ${n} does not match its JSON schema.`);return i.data}async function CU(e){let t={...e.supplied};return Object.keys(t).length===0&&(t=await Uk({providerId:e.providerId,account:e.account,fields:e.fields})),t}async function wU(e){let t=await fA(),n=t.registry.get(e.providerId),r=t.registry.action(e.providerId,e.actionId);if(!n)throw Error(`Provider ${e.providerId} is not installed.`);if(!r)throw Error(`Provider ${e.providerId} does not support action ${e.actionId}.`);let i=dA(n,e.account),a=bU(SU(r.inputSchema,yU(e.params??{}),`input`)),s={provider:e.providerId,credentialScope:UO(e.providerId,JSON.stringify(i)),operation:`action:${r.id}`,request:{account:i,params:a}};if(!e.refresh&&r.cacheTtlMs){let t=KO(s,o.unknown());if(t)return{provider:e.providerId,action:r.id,cache:`hit`,data:bU(SU(r.outputSchema,t.data,`output`))}}let c=await CU({providerId:e.providerId,account:i,fields:n.connection.fields,supplied:e.credentials}),l;try{l=await r.run({account:i,credentials:c,params:a},mA(e.providerId,e.runtime??{}))}catch(t){throw pA(e.providerId,t,c)}let u=bU(SU(r.outputSchema,xU(l,{maxBytes:10485760,maxDepth:20,maxValues:1e5,message:`Provider action result is too large.`}),`output`));if(r.cacheTtlMs){let e=u&&typeof u==`object`&&!Array.isArray(u)&&Array.isArray(u.rows)?u.rows.length:null;qO(s,{data:u,ttlMs:r.cacheTtlMs,rowCount:e,sourceCostMicros:null,taskIds:[]})}return{provider:e.providerId,action:r.id,cache:r.cacheTtlMs?e.refresh?`bypass`:`miss`:`disabled`,data:u}}function TU(e){let t=Tk.parse(e);return{...ra().providers.connections?.[t]??{}}}function EU(e,t){let n=Tk.parse(e),r=ra(),i=Object.fromEntries(Object.entries(t).map(([e,t])=>[e,t.trim()]).filter(([,e])=>e));return ia({...r,providers:{...r.providers,connections:{...r.providers.connections,[n]:i}}}),i}function DU(e){let t=Tk.parse(e),n=ra(),r={...n.providers.connections};delete r[t],ia({...n,providers:{...n.providers,connections:r}})}async function OU(){let e=eA().packages,t=await uA({installed:e}),n=new Map(t.failures.map(e=>[e.id,e]));return{schemaVersion:1,installed:e.map(e=>({...e,loadStatus:n.has(e.id)?`failed`:`ready`,error:n.get(e.id)?.message}))}}async function kU(e){let t=await uA(),n=t.registry.get(e);if(!n){let n=t.failures.find(t=>t.id===e);throw Error(n?`Provider ${e} could not load: ${n.message}`:`Provider ${e} is not installed.`)}return{schemaVersion:1,id:n.id,displayName:n.displayName,description:n.description,package:n.package,version:n.version,kinds:n.kinds,connection:n.connection.fields.map(e=>({id:e.id,label:e.label,description:e.description,kind:e.kind,required:e.required!==!1,envVar:e.envVar})),capabilities:n.capabilities.map(e=>JSON.parse(JSON.stringify(e))),actions:(n.actions??[]).map(e=>({id:e.id,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema,cacheTtlMs:e.cacheTtlMs??0}))}}const AU=Ee(De),jU=5*1024*1024,MU=o.object({name:Ek,version:Dk,dependencies:o.record(o.string(),o.string()).optional(),optionalDependencies:o.record(o.string(),o.string()).optional(),bundledDependencies:o.array(o.string()).optional(),dist:o.object({integrity:Ok,unpackedSize:o.number().int().nonnegative()}).passthrough(),seo:Ik,description:o.string().trim().max(500).nullish(),repository:o.union([o.string().trim().max(2048),o.object({url:o.string().trim().max(2048)}).passthrough()]).nullish(),author:o.union([o.string().trim().max(500),o.object({name:o.string().trim().max(200)}).passthrough()]).nullish(),maintainers:o.array(o.union([o.string().trim().max(200),o.object({name:o.string().trim().max(200)}).passthrough()])).max(100).nullish(),_npmUser:o.union([o.string().trim().max(200),o.object({name:o.string().trim().max(200)}).passthrough()]).nullish()}).passthrough(),NU=o.object({package:Ek,version:Dk,integrity:Ok,unpackedSize:o.number().int().nonnegative(),apiVersion:o.literal(1),entryPoints:o.number().int().min(1).max(16),description:o.string().trim().max(500).optional(),repository:o.string().trim().max(2048).optional(),publisher:o.string().trim().max(200).optional()}).strict(),PU=o.object({packages:o.record(o.string(),o.object({version:Dk.optional(),integrity:Ok.optional()}).passthrough())}).passthrough();async function FU(e,t,n){let r=await AU(e,[...t],{cwd:n.cwd,env:{...process.env,NPM_CONFIG_UPDATE_NOTIFIER:`false`},maxBuffer:1048576});return{stdout:r.stdout,stderr:r.stderr}}function IU(e){pr(),C(e,{recursive:!0,mode:448});let t=g(e,`package.json`);S(t)||_r(t,{name:`seo-local-provider-packages`,private:!0,type:`module`,dependencies:{}},420)}function LU(e){let t=Object.keys(e.dependencies??{}),n=Object.keys(e.optionalDependencies??{}),r=e.bundledDependencies??[];if(t.length>0||n.length>0||r.length>0)throw Error(`Provider packages must bundle their runtime code and declare no runtime, optional, or bundled dependencies.`);if(e.dist.unpackedSize>jU)throw Error(`Provider package exceeds the ${jU} byte unpacked-size limit.`)}function RU(e,t){let n=PU.parse(JSON.parse(w(g(e,`package-lock.json`),`utf8`))).packages[`node_modules/${t.package}`];if(n?.version!==t.version||n.integrity!==t.integrity)throw Error(`${t.package} does not match the approved package release.`)}function zU(e){let t=e.trim(),n=t,r;if(t.startsWith(`@`)){let e=t.indexOf(`/`),i=t.lastIndexOf(`@`);e>1&&i>e&&(n=t.slice(0,i),r=t.slice(i+1))}else{let e=t.lastIndexOf(`@`);e>0&&(n=t.slice(0,e),r=t.slice(e+1))}if(!Ek.safeParse(n).success||r!==void 0&&!Dk.safeParse(r).success)throw Error(`Provider package must be an npm package name with an optional exact version, such as @scope/provider or @scope/provider@1.2.3.`);return{package:n,...r?{version:r}:{}}}function BU(e){return(typeof e==`string`?e:e?.url)?.replace(/^git\+/u,``).replace(/\.git$/u,``)}function VU(e){if(typeof e._npmUser==`string`)return e._npmUser;if(e._npmUser?.name)return e._npmUser.name;if(typeof e.author==`string`)return e.author;if(e.author?.name)return e.author.name;let t=e.maintainers?.[0];return typeof t==`string`?t:t?.name}async function HU(e,t,n){let r=await n.run(process.platform===`win32`?`npm.cmd`:`npm`,[`view`,t?`${e}@${t}`:e,`--json`],{cwd:n.packagesDir}),i=MU.parse(JSON.parse(r.stdout));if(i.name!==e)throw Error(`npm returned metadata for ${i.name}, not ${e}.`);if(t&&i.version!==t)throw Error(`npm returned ${i.name}@${i.version}, not ${e}@${t}.`);return LU(i),i}async function UU(e,t={}){let n=t.packagesDir??fr().providerPackagesDir,r=t.run??FU,i=zU(e);IU(n);let a=await HU(i.package,i.version,{packagesDir:n,run:r});return NU.parse({package:a.name,version:a.version,integrity:a.dist.integrity,unpackedSize:a.dist.unpackedSize,apiVersion:a.seo.apiVersion,entryPoints:a.seo.providers.length,...a.description?{description:a.description}:{},...BU(a.repository)?{repository:BU(a.repository)}:{},...VU(a)?{publisher:VU(a)}:{}})}async function WU(e,t={}){let n=NU.parse(e),r=t.packagesDir??fr().providerPackagesDir,i=t.run??FU,a=eA();if(a.packages.some(e=>e.package===n.package))throw Error(`${n.package} is already installed. Remove it before installing another version.`);IU(r);let o=await HU(n.package,n.version,{packagesDir:r,run:i});if(o.version!==n.version||o.dist.integrity!==n.integrity||o.seo.apiVersion!==n.apiVersion||o.seo.providers.length!==n.entryPoints)throw Error(`${n.package} npm metadata changed after approval. Run the install command again to review it.`);await i(process.platform===`win32`?`npm.cmd`:`npm`,[`install`,`--ignore-scripts`,`--no-audit`,`--no-fund`,`--legacy-peer-deps`,`--omit=optional`,`--save-exact`,`${n.package}@${n.version}`],{cwd:r});try{RU(r,n);let e=await lA({package:n.package,version:n.version},{packagesDir:r});if(e.length!==1)throw Error(`${n.package} must register exactly one provider; received ${e.length}.`);let i=e[0];if(!i)throw Error(`${n.package} did not register a provider.`);if(a.packages.some(e=>e.id===i.id))throw Error(`Provider ${i.id} is already installed.`);let o={id:i.id,package:n.package,version:n.version,integrity:n.integrity,enabled:!0,installedAt:(t.now??(()=>new Date))().toISOString()};return nA(o),o}catch(e){throw await i(process.platform===`win32`?`npm.cmd`:`npm`,[`uninstall`,`--ignore-scripts`,`--no-audit`,`--no-fund`,n.package],{cwd:r}).catch(()=>void 0),e}}async function GU(e,t={}){let n=t.packagesDir??fr().providerPackagesDir,r=t.run??FU,i=eA().packages.find(t=>t.id===e);if(i)return await r(process.platform===`win32`?`npm.cmd`:`npm`,[`uninstall`,`--ignore-scripts`,`--no-audit`,`--no-fund`,i.package],{cwd:n}),rA(e)}const KU=o.object({limits_and_usage:o.object({api_key_expiration_date:o.string().trim().min(1).max(100),subscription:o.string().trim().min(1).max(200),units_limit_api_key:o.number().int().nonnegative().nullable(),units_limit_workspace:o.number().int().nonnegative().nullable(),units_usage_api_key:o.number().int().nonnegative(),units_usage_workspace:o.number().int().nonnegative().nullable(),usage_reset_date:o.string().trim().min(1).max(100)}).strict()}).strict();function qU(e,t){return e===null||t===null?null:Math.max(0,e-t)}var JU=class{apiKey;credentials;fetch;baseUrl;timeoutMs;now;constructor(e={}){this.apiKey=e.apiKey?.trim(),this.credentials=e.credentials,this.fetch=e.fetch??ae,this.baseUrl=e.baseUrl??`https://api.ahrefs.com/v3/`,this.timeoutMs=e.timeoutMs??1e4,this.now=e.now??(()=>new Date)}async getApiKey(e){let t=this.apiKey??await this.credentials?.()??(await IH())?.apiKey;if(!t?.trim()||t.trim().length>4096)throw new BO({provider:`ahrefs`,operation:e,code:`configuration`,message:"Ahrefs is not connected. Run `seo providers ahrefs connect`, or set SEO_AHREFS_API_KEY for this process."});return t.trim()}async limitsAndUsageForKey(e){let t=`limits-and-usage`,n=(await Zk({provider:`ahrefs`,operation:t,url:new URL(`subscription-info/limits-and-usage`,this.baseUrl),fetch:this.fetch,maxResponseBytes:65536,timeoutMs:this.timeoutMs,retry:`safe`,schema:KU,init:{method:`GET`,headers:{accept:`application/json`,authorization:`Bearer ${e}`}}}).catch(e=>{throw e instanceof BO&&e.code===`authentication`?new BO({provider:`ahrefs`,operation:t,code:`authentication`,status:e.status??void 0,message:`Ahrefs rejected the API v3 key. Create or copy a key from Ahrefs Account settings, then connect again.`,cause:e}):e})).limits_and_usage;return{provider:`ahrefs`,apiVersion:3,subscription:n.subscription,apiKeyExpiresAt:n.api_key_expiration_date,usageResetsAt:n.usage_reset_date,apiKeyUnits:{limit:n.units_limit_api_key,used:n.units_usage_api_key,remaining:qU(n.units_limit_api_key,n.units_usage_api_key)},workspaceUnits:{limit:n.units_limit_workspace,used:n.units_usage_workspace,remaining:qU(n.units_limit_workspace,n.units_usage_workspace)},observedAt:this.now().toISOString(),requestCostUnits:0}}async limitsAndUsage(){return this.limitsAndUsageForKey(await this.getApiKey(`limits-and-usage`))}};const YU=o.object({total:o.number().finite().nonnegative().optional(),balance:o.number().finite().optional()}).passthrough(),XU=o.object({login:o.string().min(1).max(320),timezone:o.string().min(1).max(100).optional(),money:YU.optional()}).passthrough(),ZU=o.object({id:o.string().min(1).max(100).optional(),status_code:o.number().int(),status_message:o.string().max(1e3),cost:o.number().finite().nonnegative().optional(),result_count:o.number().int().nonnegative().optional(),result:o.array(XU).max(10).nullable()}).passthrough(),QU=o.object({version:o.string().min(1).max(100).optional(),status_code:o.number().int(),status_message:o.string().max(1e3),cost:o.number().finite().nonnegative().optional(),tasks_count:o.number().int().nonnegative(),tasks_error:o.number().int().nonnegative(),tasks:o.array(ZU).max(10)}).passthrough();function $U(e){return e===void 0?null:Math.round(e*1e6)}function eW(e){return e>=40100&&e<40200?`authentication`:e===40202?`rate-limit`:`remote-error`}var tW=class{fetch;credentials;baseUrl;timeoutMs;maxResponseBytes;now;constructor(e={}){this.fetch=e.fetch??ae,this.credentials=e.credentials??tU,this.baseUrl=e.baseUrl??`https://api.dataforseo.com/`,this.timeoutMs=e.timeoutMs??15e3,this.maxResponseBytes=e.maxResponseBytes??5242880,this.now=e.now??(()=>new Date)}async getCredentials(e){let t=await this.credentials();if(!t)throw new BO({provider:`dataforseo`,operation:e,code:`configuration`,message:"DataForSEO is not connected. Run `seo providers dataforseo connect`, or set SEO_DATAFORSEO_LOGIN and SEO_DATAFORSEO_PASSWORD."});return t}authorization(e){return`Basic ${Buffer.from(`${e.login}:${e.password}`).toString(`base64`)}`}async userDataForCredentials(e){let t;try{t=await Zk({provider:`dataforseo`,operation:`account-status`,url:new URL(`v3/appendix/user_data`,this.baseUrl),fetch:this.fetch,maxResponseBytes:this.maxResponseBytes,timeoutMs:this.timeoutMs,retry:`safe`,schema:QU,init:{method:`GET`,headers:{authorization:this.authorization(e)}}})}catch(e){throw e instanceof BO&&e.code===`authentication`?new BO({provider:`dataforseo`,operation:`account-status`,code:`authentication`,status:e.status??void 0,message:"DataForSEO rejected the API login or API password. Run `seo providers dataforseo connect` again, or check SEO_DATAFORSEO_LOGIN and SEO_DATAFORSEO_PASSWORD.",cause:e}):e}let n=t.tasks.find(e=>e.status_code!==2e4);if(t.status_code!==2e4||t.tasks_error>0||n){let e=n?.status_code??t.status_code;throw new BO({provider:`dataforseo`,operation:`account-status`,code:eW(e),message:`DataForSEO could not return account status (${e}).`,retryable:e===40202})}let r=t.tasks[0]?.result?.[0];if(!r)throw new BO({provider:`dataforseo`,operation:`account-status`,code:`invalid-response`,message:`DataForSEO returned account status without an account row.`});return{provider:`dataforseo`,login:r.login,timezone:r.timezone??null,balanceMicros:$U(r.money?.balance),depositedMicros:$U(r.money?.total),apiVersion:t.version??null,requestCostMicros:$U(t.cost)??0,taskIds:t.tasks.flatMap(e=>e.id?[e.id]:[]),observedAt:this.now().toISOString()}}async userData(){return this.userDataForCredentials(await this.getCredentials(`account-status`))}};new class{getGoogleOAuthClient(){let e=Ta();if(e)return{clientId:e.clientId,clientSecret:e.clientSecret,source:`byo`};let t=ra(),n=process.env.SEO_GOOGLE_CLIENT_ID??process.env.GSC_CLIENT_ID??ka.clientId??t.auth.sharedClientId,r=process.env.SEO_GOOGLE_CLIENT_SECRET??process.env.GSC_CLIENT_SECRET??ka.clientSecret??t.auth.sharedClientSecret;if(!(!n||!r))return{clientId:n,clientSecret:r,source:`shared`}}readGoogleTokens(){return va()}writeGoogleTokens(e){return xa(e)}deleteGoogleTokens(){return Sa()}};async function nW(){let e=(await Promise.allSettled([Sa(),ok()])).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(e.length>0)throw Error("Reset stopped before deleting local files because saved credentials could not be removed. Unlock the system keychain and run `seo reset --yes` again.",{cause:AggregateError(e)});let t=fr();D(t.configDir,{recursive:!0,force:!0}),D(t.cacheDir,{recursive:!0,force:!0}),D(t.logDir,{recursive:!0,force:!0})}function rW(e){return!!e._zod}function iW(e){let t=Object.values(e);if(t.length===0)return ke.object({});let n=t.every(rW),r=t.every(e=>!rW(e));if(n)return ke.object(e);if(r)return Oe.object(e);throw Error(`Mixed Zod versions detected in object shape.`)}function aW(e,t){return rW(e)?ke.safeParse(e,t):e.safeParse(t)}async function oW(e,t){return rW(e)?await ke.safeParseAsync(e,t):await e.safeParseAsync(t)}function sW(e){if(!e)return;let t;if(t=rW(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function cW(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return iW(e)}}if(rW(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function lW(e){return e.length===0?`object root`:e.reduce((e,t,n)=>n===0?String(t):typeof t==`number`?`${e}[${t}]`:`${e}.${t}`,``)}function uW(e){if(e&&typeof e==`object`){if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0)return e.issues.map(e=>e.path?.length?`${e.message} at ${lW(e.path)}`:e.message).join(`
331
- `);if(`message`in e&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function dW(e){return e.description}function fW(e){if(rW(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function pW(e){if(rW(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}const mW=`2025-11-25`,hW=[mW,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],gW=`io.modelcontextprotocol/related-task`,_W=A.custom(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),vW=A.union([A.string(),A.number().int()]),yW=A.string();A.looseObject({ttl:A.number().optional(),pollInterval:A.number().optional()});const bW=A.object({ttl:A.number().optional()}),xW=A.object({taskId:A.string()}),SW=A.looseObject({progressToken:vW.optional(),[gW]:xW.optional()}),CW=A.object({_meta:SW.optional()}),wW=CW.extend({task:bW.optional()}),TW=e=>wW.safeParse(e).success,EW=A.object({method:A.string(),params:CW.loose().optional()}),DW=A.object({_meta:SW.optional()}),OW=A.object({method:A.string(),params:DW.loose().optional()}),kW=A.looseObject({_meta:SW.optional()}),AW=A.union([A.string(),A.number().int()]),jW=A.object({jsonrpc:A.literal(`2.0`),id:AW,...EW.shape}).strict(),MW=e=>jW.safeParse(e).success,NW=A.object({jsonrpc:A.literal(`2.0`),...OW.shape}).strict(),PW=e=>NW.safeParse(e).success,FW=A.object({jsonrpc:A.literal(`2.0`),id:AW,result:kW}).strict(),IW=e=>FW.safeParse(e).success;var J;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(J||={});const LW=A.object({jsonrpc:A.literal(`2.0`),id:AW.optional(),error:A.object({code:A.number().int(),message:A.string(),data:A.unknown().optional()})}).strict(),RW=e=>LW.safeParse(e).success,zW=A.union([jW,NW,FW,LW]);A.union([FW,LW]);const BW=kW.strict(),VW=DW.extend({requestId:AW.optional(),reason:A.string().optional()}),HW=OW.extend({method:A.literal(`notifications/cancelled`),params:VW}),UW=A.object({src:A.string(),mimeType:A.string().optional(),sizes:A.array(A.string()).optional(),theme:A.enum([`light`,`dark`]).optional()}),WW=A.object({icons:A.array(UW).optional()}),GW=A.object({name:A.string(),title:A.string().optional()}),KW=GW.extend({...GW.shape,...WW.shape,version:A.string(),websiteUrl:A.string().optional(),description:A.string().optional()}),qW=A.intersection(A.object({applyDefaults:A.boolean().optional()}),A.record(A.string(),A.unknown())),JW=A.preprocess(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,A.intersection(A.object({form:qW.optional(),url:_W.optional()}),A.record(A.string(),A.unknown()).optional())),YW=A.looseObject({list:_W.optional(),cancel:_W.optional(),requests:A.looseObject({sampling:A.looseObject({createMessage:_W.optional()}).optional(),elicitation:A.looseObject({create:_W.optional()}).optional()}).optional()}),XW=A.looseObject({list:_W.optional(),cancel:_W.optional(),requests:A.looseObject({tools:A.looseObject({call:_W.optional()}).optional()}).optional()}),ZW=A.object({experimental:A.record(A.string(),_W).optional(),sampling:A.object({context:_W.optional(),tools:_W.optional()}).optional(),elicitation:JW.optional(),roots:A.object({listChanged:A.boolean().optional()}).optional(),tasks:YW.optional(),extensions:A.record(A.string(),_W).optional()}),QW=CW.extend({protocolVersion:A.string(),capabilities:ZW,clientInfo:KW}),$W=EW.extend({method:A.literal(`initialize`),params:QW}),eG=A.object({experimental:A.record(A.string(),_W).optional(),logging:_W.optional(),completions:_W.optional(),prompts:A.object({listChanged:A.boolean().optional()}).optional(),resources:A.object({subscribe:A.boolean().optional(),listChanged:A.boolean().optional()}).optional(),tools:A.object({listChanged:A.boolean().optional()}).optional(),tasks:XW.optional(),extensions:A.record(A.string(),_W).optional()}),tG=kW.extend({protocolVersion:A.string(),capabilities:eG,serverInfo:KW,instructions:A.string().optional()}),nG=OW.extend({method:A.literal(`notifications/initialized`),params:DW.optional()}),rG=EW.extend({method:A.literal(`ping`),params:CW.optional()}),iG=A.object({progress:A.number(),total:A.optional(A.number()),message:A.optional(A.string())}),aG=A.object({...DW.shape,...iG.shape,progressToken:vW}),oG=OW.extend({method:A.literal(`notifications/progress`),params:aG}),sG=CW.extend({cursor:yW.optional()}),cG=EW.extend({params:sG.optional()}),lG=kW.extend({nextCursor:yW.optional()}),uG=A.enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),dG=A.object({taskId:A.string(),status:uG,ttl:A.union([A.number(),A.null()]),createdAt:A.string(),lastUpdatedAt:A.string(),pollInterval:A.optional(A.number()),statusMessage:A.optional(A.string())}),fG=kW.extend({task:dG}),pG=DW.merge(dG),mG=OW.extend({method:A.literal(`notifications/tasks/status`),params:pG}),hG=EW.extend({method:A.literal(`tasks/get`),params:CW.extend({taskId:A.string()})}),gG=kW.merge(dG),_G=EW.extend({method:A.literal(`tasks/result`),params:CW.extend({taskId:A.string()})});kW.loose();const vG=cG.extend({method:A.literal(`tasks/list`)}),yG=lG.extend({tasks:A.array(dG)}),bG=EW.extend({method:A.literal(`tasks/cancel`),params:CW.extend({taskId:A.string()})}),xG=kW.merge(dG),SG=A.object({uri:A.string(),mimeType:A.optional(A.string()),_meta:A.record(A.string(),A.unknown()).optional()}),CG=SG.extend({text:A.string()}),wG=A.string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),TG=SG.extend({blob:wG}),EG=A.enum([`user`,`assistant`]),DG=A.object({audience:A.array(EG).optional(),priority:A.number().min(0).max(1).optional(),lastModified:A.iso.datetime({offset:!0}).optional()}),OG=A.object({...GW.shape,...WW.shape,uri:A.string(),description:A.optional(A.string()),mimeType:A.optional(A.string()),size:A.optional(A.number()),annotations:DG.optional(),_meta:A.optional(A.looseObject({}))}),kG=A.object({...GW.shape,...WW.shape,uriTemplate:A.string(),description:A.optional(A.string()),mimeType:A.optional(A.string()),annotations:DG.optional(),_meta:A.optional(A.looseObject({}))}),AG=cG.extend({method:A.literal(`resources/list`)}),jG=lG.extend({resources:A.array(OG)}),MG=cG.extend({method:A.literal(`resources/templates/list`)}),NG=lG.extend({resourceTemplates:A.array(kG)}),PG=CW.extend({uri:A.string()}),FG=PG,IG=EW.extend({method:A.literal(`resources/read`),params:FG}),LG=kW.extend({contents:A.array(A.union([CG,TG]))}),RG=OW.extend({method:A.literal(`notifications/resources/list_changed`),params:DW.optional()}),zG=PG,BG=EW.extend({method:A.literal(`resources/subscribe`),params:zG}),VG=PG,HG=EW.extend({method:A.literal(`resources/unsubscribe`),params:VG}),UG=DW.extend({uri:A.string()}),WG=OW.extend({method:A.literal(`notifications/resources/updated`),params:UG}),GG=A.object({name:A.string(),description:A.optional(A.string()),required:A.optional(A.boolean())}),KG=A.object({...GW.shape,...WW.shape,description:A.optional(A.string()),arguments:A.optional(A.array(GG)),_meta:A.optional(A.looseObject({}))}),qG=cG.extend({method:A.literal(`prompts/list`)}),JG=lG.extend({prompts:A.array(KG)}),YG=CW.extend({name:A.string(),arguments:A.record(A.string(),A.string()).optional()}),XG=EW.extend({method:A.literal(`prompts/get`),params:YG}),ZG=A.object({type:A.literal(`text`),text:A.string(),annotations:DG.optional(),_meta:A.record(A.string(),A.unknown()).optional()}),QG=A.object({type:A.literal(`image`),data:wG,mimeType:A.string(),annotations:DG.optional(),_meta:A.record(A.string(),A.unknown()).optional()}),$G=A.object({type:A.literal(`audio`),data:wG,mimeType:A.string(),annotations:DG.optional(),_meta:A.record(A.string(),A.unknown()).optional()}),eK=A.object({type:A.literal(`tool_use`),name:A.string(),id:A.string(),input:A.record(A.string(),A.unknown()),_meta:A.record(A.string(),A.unknown()).optional()}),tK=A.object({type:A.literal(`resource`),resource:A.union([CG,TG]),annotations:DG.optional(),_meta:A.record(A.string(),A.unknown()).optional()}),nK=OG.extend({type:A.literal(`resource_link`)}),rK=A.union([ZG,QG,$G,nK,tK]),iK=A.object({role:EG,content:rK}),aK=kW.extend({description:A.string().optional(),messages:A.array(iK)}),oK=OW.extend({method:A.literal(`notifications/prompts/list_changed`),params:DW.optional()}),sK=A.object({title:A.string().optional(),readOnlyHint:A.boolean().optional(),destructiveHint:A.boolean().optional(),idempotentHint:A.boolean().optional(),openWorldHint:A.boolean().optional()}),cK=A.object({taskSupport:A.enum([`required`,`optional`,`forbidden`]).optional()}),lK=A.object({...GW.shape,...WW.shape,description:A.string().optional(),inputSchema:A.object({type:A.literal(`object`),properties:A.record(A.string(),_W).optional(),required:A.array(A.string()).optional()}).catchall(A.unknown()),outputSchema:A.object({type:A.literal(`object`),properties:A.record(A.string(),_W).optional(),required:A.array(A.string()).optional()}).catchall(A.unknown()).optional(),annotations:sK.optional(),execution:cK.optional(),_meta:A.record(A.string(),A.unknown()).optional()}),uK=cG.extend({method:A.literal(`tools/list`)}),dK=lG.extend({tools:A.array(lK)}),fK=kW.extend({content:A.array(rK).default([]),structuredContent:A.record(A.string(),A.unknown()).optional(),isError:A.boolean().optional()});fK.or(kW.extend({toolResult:A.unknown()}));const pK=wW.extend({name:A.string(),arguments:A.record(A.string(),A.unknown()).optional()}),mK=EW.extend({method:A.literal(`tools/call`),params:pK}),hK=OW.extend({method:A.literal(`notifications/tools/list_changed`),params:DW.optional()});A.object({autoRefresh:A.boolean().default(!0),debounceMs:A.number().int().nonnegative().default(300)});const gK=A.enum([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),_K=CW.extend({level:gK}),vK=EW.extend({method:A.literal(`logging/setLevel`),params:_K}),yK=DW.extend({level:gK,logger:A.string().optional(),data:A.unknown()}),bK=OW.extend({method:A.literal(`notifications/message`),params:yK}),xK=A.object({name:A.string().optional()}),SK=A.object({hints:A.array(xK).optional(),costPriority:A.number().min(0).max(1).optional(),speedPriority:A.number().min(0).max(1).optional(),intelligencePriority:A.number().min(0).max(1).optional()}),CK=A.object({mode:A.enum([`auto`,`required`,`none`]).optional()}),wK=A.object({type:A.literal(`tool_result`),toolUseId:A.string().describe(`The unique identifier for the corresponding tool call.`),content:A.array(rK).default([]),structuredContent:A.object({}).loose().optional(),isError:A.boolean().optional(),_meta:A.record(A.string(),A.unknown()).optional()}),TK=A.discriminatedUnion(`type`,[ZG,QG,$G]),EK=A.discriminatedUnion(`type`,[ZG,QG,$G,eK,wK]),DK=A.object({role:EG,content:A.union([EK,A.array(EK)]),_meta:A.record(A.string(),A.unknown()).optional()}),OK=wW.extend({messages:A.array(DK),modelPreferences:SK.optional(),systemPrompt:A.string().optional(),includeContext:A.enum([`none`,`thisServer`,`allServers`]).optional(),temperature:A.number().optional(),maxTokens:A.number().int(),stopSequences:A.array(A.string()).optional(),metadata:_W.optional(),tools:A.array(lK).optional(),toolChoice:CK.optional()}),kK=EW.extend({method:A.literal(`sampling/createMessage`),params:OK}),AK=kW.extend({model:A.string(),stopReason:A.optional(A.enum([`endTurn`,`stopSequence`,`maxTokens`]).or(A.string())),role:EG,content:TK}),jK=kW.extend({model:A.string(),stopReason:A.optional(A.enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A.string())),role:EG,content:A.union([EK,A.array(EK)])}),MK=A.object({type:A.literal(`boolean`),title:A.string().optional(),description:A.string().optional(),default:A.boolean().optional()}),NK=A.object({type:A.literal(`string`),title:A.string().optional(),description:A.string().optional(),minLength:A.number().optional(),maxLength:A.number().optional(),format:A.enum([`email`,`uri`,`date`,`date-time`]).optional(),default:A.string().optional()}),PK=A.object({type:A.enum([`number`,`integer`]),title:A.string().optional(),description:A.string().optional(),minimum:A.number().optional(),maximum:A.number().optional(),default:A.number().optional()}),FK=A.object({type:A.literal(`string`),title:A.string().optional(),description:A.string().optional(),enum:A.array(A.string()),default:A.string().optional()}),IK=A.object({type:A.literal(`string`),title:A.string().optional(),description:A.string().optional(),oneOf:A.array(A.object({const:A.string(),title:A.string()})),default:A.string().optional()}),LK=A.object({type:A.literal(`string`),title:A.string().optional(),description:A.string().optional(),enum:A.array(A.string()),enumNames:A.array(A.string()).optional(),default:A.string().optional()}),RK=A.union([FK,IK]),zK=A.object({type:A.literal(`array`),title:A.string().optional(),description:A.string().optional(),minItems:A.number().optional(),maxItems:A.number().optional(),items:A.object({type:A.literal(`string`),enum:A.array(A.string())}),default:A.array(A.string()).optional()}),BK=A.object({type:A.literal(`array`),title:A.string().optional(),description:A.string().optional(),minItems:A.number().optional(),maxItems:A.number().optional(),items:A.object({anyOf:A.array(A.object({const:A.string(),title:A.string()}))}),default:A.array(A.string()).optional()}),VK=A.union([zK,BK]),HK=A.union([LK,RK,VK]),UK=A.union([HK,MK,NK,PK]),WK=wW.extend({mode:A.literal(`form`).optional(),message:A.string(),requestedSchema:A.object({type:A.literal(`object`),properties:A.record(A.string(),UK),required:A.array(A.string()).optional()})}),GK=wW.extend({mode:A.literal(`url`),message:A.string(),elicitationId:A.string(),url:A.string().url()}),KK=A.union([WK,GK]),qK=EW.extend({method:A.literal(`elicitation/create`),params:KK}),JK=DW.extend({elicitationId:A.string()}),YK=OW.extend({method:A.literal(`notifications/elicitation/complete`),params:JK}),XK=kW.extend({action:A.enum([`accept`,`decline`,`cancel`]),content:A.preprocess(e=>e===null?void 0:e,A.record(A.string(),A.union([A.string(),A.number(),A.boolean(),A.array(A.string())])).optional())}),ZK=A.object({type:A.literal(`ref/resource`),uri:A.string()}),QK=A.object({type:A.literal(`ref/prompt`),name:A.string()}),$K=CW.extend({ref:A.union([QK,ZK]),argument:A.object({name:A.string(),value:A.string()}),context:A.object({arguments:A.record(A.string(),A.string()).optional()}).optional()}),eq=EW.extend({method:A.literal(`completion/complete`),params:$K});function tq(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function nq(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const rq=kW.extend({completion:A.looseObject({values:A.array(A.string()).max(100),total:A.optional(A.number().int()),hasMore:A.optional(A.boolean())})}),iq=A.object({uri:A.string().startsWith(`file://`),name:A.string().optional(),_meta:A.record(A.string(),A.unknown()).optional()}),aq=EW.extend({method:A.literal(`roots/list`),params:CW.optional()}),oq=kW.extend({roots:A.array(iq)}),sq=OW.extend({method:A.literal(`notifications/roots/list_changed`),params:DW.optional()});A.union([rG,$W,eq,vK,XG,qG,AG,MG,IG,BG,HG,mK,uK,hG,_G,vG,bG]),A.union([HW,oG,nG,sq,mG]),A.union([BW,AK,jK,XK,oq,gG,yG,fG]),A.union([rG,kK,qK,aq,hG,_G,vG,bG]),A.union([HW,oG,bK,WG,RG,hK,oK,mG,YK]),A.union([BW,tG,rq,aK,JG,jG,NG,LG,fK,dK,gG,yG,fG]);var Y=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===J.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new cq(e.elicitations,n)}return new e(t,n,r)}},cq=class extends Y{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(J.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function lq(e){return e===`completed`||e===`failed`||e===`cancelled`}const uq=Symbol(`Let zodToJsonSchema decide on which parser to use`),dq={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},fq=e=>typeof e==`string`?{...dq,name:e}:{...dq,...e},pq=e=>{let t=fq(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function mq(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function hq(e,t,n,r,i){e[t]=n,mq(e,t,r,i)}const gq=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function _q(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?gq(t,e.currentPath):t.join(`/`)}}function vq(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==k.ZodAny&&(n.items=X(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&hq(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&hq(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(hq(n,`minItems`,e.exactLength.value,e.exactLength.message,t),hq(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function yq(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?hq(n,`minimum`,r.value,r.message,t):hq(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),hq(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?hq(n,`maximum`,r.value,r.message,t):hq(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),hq(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:hq(n,`multipleOf`,r.value,r.message,t);break}return n}function bq(){return{type:`boolean`}}function xq(e,t){return X(e.type._def,t)}const Sq=(e,t)=>X(e.innerType._def,t);function Cq(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>Cq(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return wq(e,t)}}const wq=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:hq(n,`minimum`,r.value,r.message,t);break;case`max`:hq(n,`maximum`,r.value,r.message,t);break}return n};function Tq(e,t){return{...X(e.innerType._def,t),default:e.defaultValue()}}function Eq(e,t){return t.effectStrategy===`input`?X(e.schema._def,t):_q(t)}function Dq(e){return{type:`string`,enum:Array.from(e.values)}}const Oq=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function kq(e,t){let n=[X(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),X(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(Oq(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function Aq(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}let jq;const Mq={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(jq===void 0&&(jq=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),jq),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Nq(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:hq(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:hq(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:Lq(n,`email`,r.message,t);break;case`format:idn-email`:Lq(n,`idn-email`,r.message,t);break;case`pattern:zod`:Rq(n,Mq.email,r.message,t);break}break;case`url`:Lq(n,`uri`,r.message,t);break;case`uuid`:Lq(n,`uuid`,r.message,t);break;case`regex`:Rq(n,r.regex,r.message,t);break;case`cuid`:Rq(n,Mq.cuid,r.message,t);break;case`cuid2`:Rq(n,Mq.cuid2,r.message,t);break;case`startsWith`:Rq(n,RegExp(`^${Pq(r.value,t)}`),r.message,t);break;case`endsWith`:Rq(n,RegExp(`${Pq(r.value,t)}$`),r.message,t);break;case`datetime`:Lq(n,`date-time`,r.message,t);break;case`date`:Lq(n,`date`,r.message,t);break;case`time`:Lq(n,`time`,r.message,t);break;case`duration`:Lq(n,`duration`,r.message,t);break;case`length`:hq(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),hq(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:Rq(n,RegExp(Pq(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&Lq(n,`ipv4`,r.message,t),r.version!==`v4`&&Lq(n,`ipv6`,r.message,t);break;case`base64url`:Rq(n,Mq.base64url,r.message,t);break;case`jwt`:Rq(n,Mq.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&Rq(n,Mq.ipv4Cidr,r.message,t),r.version!==`v4`&&Rq(n,Mq.ipv6Cidr,r.message,t);break;case`emoji`:Rq(n,Mq.emoji(),r.message,t);break;case`ulid`:Rq(n,Mq.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:Lq(n,`binary`,r.message,t);break;case`contentEncoding:base64`:hq(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:Rq(n,Mq.base64,r.message,t);break}break;case`nanoid`:Rq(n,Mq.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:}return n}function Pq(e,t){return t.patternStrategy===`escape`?Iq(e):e}const Fq=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Iq(e){let t=``;for(let n=0;n<e.length;n++)Fq.has(e[n])||(t+=`\\`),t+=e[n];return t}function Lq(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):hq(e,`format`,t,n,r)}function Rq(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:zq(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):hq(e,`pattern`,zq(t,r),n,r)}function zq(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
336
+ `),data:{range:n,comparisonRange:r,rule:CH,lostPages:c.length,index:h.data,pages:g}}}const TH={overview:`search-performance-overview`,"quick-wins":`quick-wins`,"low-ctr":`ctr-underperformers`,"striking-distance":`striking-distance`,"second-page":`second-page`,"content-decay":`decaying-pages`,cannibalization:`cannibalisation`,"traffic-drop":`traffic-anomaly`},EH={keyword_metrics:`keyword-metrics`,ranked_keywords:`ranked-keywords`,serp:`serp-results`,competitors:`serp-competitors`,backlinks:`link-evidence`};function DH(e,t={}){return e===`report`?TH[t.section||`overview`]??null:e===`research`?EH[t.action??``]??null:{page:`page-opportunities`,compare:`measure-change`,index:`link-recovery`,crawl:`site-crawl`,"internal-links":`internal-links`}[e]??null}const OH=o.string().min(1).describe(`Search Console property or site, such as sc-domain:example.com, https://example.com/ or example.com.`),kH={start_date:o.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe(`YYYY-MM-DD. Optional; send with end_date.`),end_date:o.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe(`YYYY-MM-DD. Optional; send with start_date.`)},AH={detail:o.enum([`summary`,`rows`,`full`]).default(`summary`).describe(`summary first. rows: the next page of rows. full: every field as JSON.`),offset:o.number().int().min(0).default(0).describe(`rows only: the first row to return.`)},jH=[`search_console`,`google_analytics`,`bing`,`clicky`];function MH(e){return e}const NH=[MH({name:`seo_sites`,command:`data`,title:`List sites`,description:`Lists the Search Console and Google Analytics properties the connected Google accounts can read, the Bing Webmaster site for each, and which research keys are set. Call it first.`,input:o.object({}),run:async e=>er({accounts:await e.accounts(),keys:await e.keys(),clicky:$B(await e.keys()).map(eV),signIn:e.signIn,bing:e.deps.bing?await e.deps.bing():void 0,connect:e.connect})}),MH({name:`seo_report`,command:`report`,title:`Search Console report`,description:`The main report for a Search Console property. Without a section it returns the overview plus each section's row count and top rows. With a section it returns that section's rows; page sections also check their top 20 URLs live. Sections:\n${Object.entries(PV).map(([e,t])=>`- ${e}: ${t}`).join(`
337
+ `)}`,input:o.object({site:OH,section:o.enum(FV).optional().describe(`Optional. Leave it out first; then ask for one section.`),...kH,...AH}),run:async(e,t)=>{let n=await e.resolveSite(t.site).catch(e=>e instanceof Error?e:Error(String(e)));if(n instanceof Error&&!t.section&&e.deps.bing)return ZV({site:t.site,startDate:t.start_date,endDate:t.end_date},e.deps).catch(()=>{throw n});if(n instanceof Error&&t.section!==`bing`)throw n;return XV({site:n instanceof Error?t.site:n,section:t.section,startDate:t.start_date,endDate:t.end_date,detail:t.detail,offset:t.offset},e.deps)}}),MH({name:`seo_page`,command:`page`,title:`One page`,description:`Everything for one URL: live page facts (status, redirect, title, description, H1, canonical, robots), Google’s index status from URL Inspection, and the page’s Search Console queries against the previous period.`,input:o.object({url:o.url(),...kH,...AH}),run:async(e,t)=>vH({site:await e.resolveSite(t.url),url:t.url,startDate:t.start_date,endDate:t.end_date,detail:t.detail,offset:t.offset},e.deps)}),MH({name:`seo_compare`,command:`compare`,title:`Before and after a date`,description:`Compares equal periods before and after a date, such as a site change or a Google update: totals, devices, and the pages and queries that moved, Google Analytics sessions from the property whose web stream matches the site, and Google updates in the window. Optional pages narrows it to URLs that contain that text, such as /blog/.`,input:o.object({site:OH,date:o.string().regex(/^\d{4}-\d{2}-\d{2}$/).describe(`YYYY-MM-DD: the first day after the change.`),pages:o.string().min(1).optional().describe(`Optional URL text, such as /blog/.`)}),run:async(e,t)=>bH({site:await e.resolveSite(t.site),date:t.date,pages:t.pages},e.deps)}),MH({name:`seo_index`,command:`index`,title:`Pages that lost their clicks`,description:`${CH} It shows pages that broke, redirect, block indexing or dropped out of Google.`,input:o.object({site:OH,...kH}),run:async(e,t)=>wH({site:await e.resolveSite(t.site),startDate:t.start_date,endDate:t.end_date},e.deps)}),MH({name:`seo_research`,command:`research`,title:`Keyword, competitor and backlink data`,description:`Data from the person’s own DataForSEO or Ahrefs account, which costs them credits. It uses the key the person saved on their seoskill.dev account (or on this machine for the CLI). Actions: keyword_metrics (keywords: volume, difficulty, CPC), ranked_keywords (target: keywords a domain or URL ranks for), serp (keywords, up to 5: the ranking pages), competitors (target: domains that share keywords), backlinks (target: referring domains). Rows with a domain, and the target, get a free Ahrefs domain_rating column. Numbers are provider estimates, not Search Console data.`,input:o.object({provider:o.enum(fH),action:o.enum(dH),keywords:o.array(o.string().min(1)).max(100).default([]),target:o.string().default(``).describe(`Domain or URL.`),country:o.string().regex(/^[a-z]{2}$/).default(`us`).describe(`Two-letter country code.`),...AH}),run:async(e,t)=>gH(t,await e.keys(),{drKey:e.drKey,call:e=>`seo_research with the same input, detail "rows", offset ${e}`})}),MH({name:`seo_data`,command:`data`,title:`Raw rows`,description:`Raw rows for questions the report does not answer. search_console (default): rows for any dimensions, each with the previous period and the change; page and query narrow to rows whose URL or query contains that text. google_analytics: landing pages for visits from search, with Google Analytics’ own metric names. bing: Bing Webmaster query or page rows (first dimension) for the same site, by week. clicky: landing-page visits, traffic sources and search engines from a Clicky site the person saved (site is its domain or Clicky site ID; at most 31 days).`,input:o.object({source:o.enum(jH).default(`search_console`),site:o.string().min(1).describe(`search_console and bing: the property or site. google_analytics: numeric property id from seo_sites. clicky: the site or its Clicky site ID.`),dimensions:o.array(o.enum(fB)).max(4).default([`query`]).describe(`search_console; bing uses the first, query or page.`),page:o.string().min(1).optional().describe(`search_console only: URL text, such as /blog/.`),query:o.string().min(1).optional().describe(`search_console only: query text.`),...kH,...AH}),run:async(e,t)=>t.source===`clicky`?uV({site:t.site,startDate:t.start_date,endDate:t.end_date,detail:t.detail,offset:t.offset},await e.keys(),{connect:e.connect,call:e=>`seo_data with source "clicky", site "${t.site}", detail "rows", offset ${e}`,refresh:e.refreshClicky}):t.source===`bing`?JB({site:t.site,dimension:t.dimensions[0]===`page`?`page`:`query`,startDate:t.start_date,endDate:t.end_date,detail:t.detail,offset:t.offset},e.deps):t.source===`google_analytics`?gB({property:t.site,startDate:t.start_date,endDate:t.end_date,detail:t.detail,offset:t.offset},await hB(await e.accounts(),t.site,e.signIn),{signIn:e.signIn,call:e=>`seo_data with source "google_analytics", site "${t.site}", detail "rows", offset ${e}`}):mB({site:await e.resolveSite(t.site),dimensions:t.dimensions,filters:[...t.page?[{dimension:`page`,operator:`contains`,expression:t.page}]:[],...t.query?[{dimension:`query`,operator:`contains`,expression:t.query}]:[]],startDate:t.start_date,endDate:t.end_date,detail:t.detail,offset:t.offset},e.deps)})];async function PH(e,t,n){let r=e.input.safeParse(n??{});if(!r.success)throw new yn(`INVALID_INPUT`,r.error.issues.map(e=>`${e.path.join(`.`)||`input`}: ${e.message}`).join(`; `));return e.run(t,r.data)}const FH=(e,t)=>{let n=`seo_${e.replace(`-`,`_`)}`,r=Object.entries(t??{}).filter(([,e])=>e!==void 0);return r.length?`${n} with ${r.map(([e,t])=>`${e} ${typeof t==`number`?t:`"${t}"`}`).join(`, `)}`:n},IH={name:`seo-skill`,uri:`skill://seo/SKILL.md`,title:`SEO Skill`,description:`How to use these tools: what each command returns and how to reach it.`,mimeType:`text/markdown`};function LH(e){let t=t=>{let n=t.trim();if(!n||n.length>4096)throw new BO({provider:e.provider,operation:`credentials`,code:`configuration`,message:e.invalidMessage});return n};return{async write(n){return ik(e.secretName,t(n))},async read(n={}){let r=await rk({name:e.secretName,envVar:e.environmentVariable,env:n.env});return r?{apiKey:t(r.value),source:r.source}:void 0},async remove(){await ak(e.secretName)}}}const RH=`SEO_AHREFS_API_KEY`,zH=JO.ahrefsApiKey,BH=LH({provider:`ahrefs`,environmentVariable:RH,secretName:zH,invalidMessage:`Ahrefs needs a valid API v3 key.`});async function VH(e){return BH.write(e)}async function HH(e={}){return BH.read(e)}async function UH(){await BH.remove()}const WH=`SEO_BING_API_KEY`,GH=JO.bingApiKey,KH=LH({provider:`bing`,environmentVariable:WH,secretName:GH,invalidMessage:`Bing Webmaster needs a valid API key.`});async function qH(e){return KH.write(e)}async function JH(e={}){return KH.read(e)}async function YH(){await KH.remove()}const XH=`SEO_DATAFORSEO_LOGIN`,ZH=`SEO_DATAFORSEO_PASSWORD`,QH=JO.dataForSeoCredentials,$H=o.object({version:o.literal(1),login:o.string().trim().min(1).max(320),password:o.string().min(1).max(2048)}).strict();function eU(e){return new BO({provider:`dataforseo`,operation:`credentials`,code:`configuration`,message:e})}function tU(e){let t=$H.safeParse({version:1,login:e.login,password:e.password});if(!t.success)throw eU(`DataForSEO credentials need both an API login and API password.`);return{login:t.data.login,password:t.data.password}}function nU(){let e=ra();return!e.providers.dataForSeoLogin&&!e.providers.dataForSeoPassword?!1:(ia({...e,providers:{...e.providers,dataForSeoLogin:void 0,dataForSeoPassword:void 0}}),!0)}function rU(e){let t=e[XH]?.trim(),n=e[ZH];if(!(!t&&!n)){if(!t||!n)throw eU(`Set both ${XH} and ${ZH}.`);return tU({login:t,password:n})}}function iU(e){let t;try{t=JSON.parse(e)}catch{throw eU("Saved DataForSEO credentials are invalid. Run `seo providers dataforseo disconnect`, then connect again.")}let n=$H.safeParse(t);if(!n.success)throw eU("Saved DataForSEO credentials are invalid. Run `seo providers dataforseo disconnect`, then connect again.");return{login:n.data.login,password:n.data.password}}async function aU(e){let t=tU(e),n=await ik(QH,JSON.stringify({version:1,...t}));return nU(),n}async function oU(){let e=ra(),t=e.providers.dataForSeoLogin,n=e.providers.dataForSeoPassword;if(!t&&!n)return;if(!t||!n)throw eU("Legacy DataForSEO config contains only part of the credential pair. Run `seo providers dataforseo disconnect`, then connect again.");let r=tU({login:t,password:n}),i=await aU(r);return{...r,source:i,migrated:!0}}async function sU(e={}){let t=rU(e.env??process.env);if(t)return{...t,source:`environment`,migrated:!1};let n=await rk({name:QH});if(n){let e=iU(n.value),t=nU();return{...e,source:n.source,migrated:t}}return oU()}async function cU(){await ak(QH),nU()}function lU(e){return{searchAnalytics:(t,n)=>qx(t,n,{refresh:e.refresh,accountEmail:e.account}),checkPages:xV,inspect:async(t,n)=>{try{return _H(await Wx({siteUrl:t,inspectionUrl:n,accountEmail:e.account}))}catch{return null}},pageMarkdown:async t=>Kv(await kx(t,{refresh:e.refresh})),call:e.call,bing:fU,bingConnect:uU,analytics:{accounts:pU,signIn:To.signIn}}}const uU="Connect Bing on your seoskill.dev account and run `seo login`, or run `seo providers bing connect` with an API key from Bing Webmaster Tools (Settings, API access).";let dU;function fU(){return dU??=JH().catch(()=>void 0).then(e=>e?Ut({apiKey:e.apiKey},{signIn:uU}):Ci()?Fi():null),dU}async function pU(){return Ci()?(await Mi()).map(e=>({email:e,google:Mt(()=>ji(e))})):[{email:null,google:await yU()}]}async function mU(){let[e,t,n,r]=await Promise.all([sU().catch(()=>void 0),HH().catch(()=>void 0),hk().catch(()=>({})),Ci()?Ii().catch(()=>({})):{}]),i=new Headers(r);for(let[e,t]of Object.entries(n)){let n=`${QB}${e}`;i.has(n)||i.set(n,t)}return e&&(i.set(`x-dataforseo-login`,e.login),i.set(`x-dataforseo-password`,e.password)),t?.apiKey&&i.set(`x-ahrefs-key`,t.apiKey),i}async function hU(){return Ci()?(await Oi({refreshClicky:!0}),mU()):null}async function gU(e,t={}){let n=Mn((await eS(t.refresh,t.account)).map(e=>e.siteUrl),e);if(!n)throw new yn(`NO_ACCESS`,`This Google login has no Search Console property for ${e}. Run \`seo sites\` to list the properties it can read.`);return n}const _U={INVALID_INPUT:`INVALID_INPUT`,NOT_CONNECTED:`AUTH_REQUIRED`,NO_ACCESS:`PROPERTY_NOT_FOUND`,NO_KEY:`AUTH_CONFIG_REQUIRED`,RATE_LIMITED:`RATE_LIMITED`,GOOGLE_ERROR:`PROVIDER_UNAVAILABLE`,PROVIDER_ERROR:`PROVIDER_UNAVAILABLE`};function vU(e){return e instanceof yn?new N(_U[e.code],e.message):e}async function yU(e){let{client:t}=await Co(e);return wo(t)}const bU=[`https://www.googleapis.com/auth/webmasters.readonly`,`https://www.googleapis.com/auth/analytics.readonly`];async function xU(e={}){let t=fr(),n=Aa(),r=Ga(),i=await va(),a=Ta(),o=i?!!Ma(i.client_source):void 0,s=[];try{let t=(e.checkDatabase??Yo)();s.push({id:`local-database`,label:`Local database`,status:`pass`,detail:t.dbPath})}catch(e){s.push({id:`local-database`,label:`Local database`,status:`fail`,detail:e instanceof Error?e.message:`The local database could not be opened.`,fix:"Upgrade or reinstall `seo`. If this still fails, report it at https://github.com/iannuttall/seo/issues."})}s.push({id:`config-dir`,label:`Config directory`,status:S(t.configDir)?`pass`:`warn`,detail:t.configDir,fix:S(t.configDir)?void 0:"Run `seo start` or `seo auth setup-client`."}),s.push({id:`oauth-client`,label:`Google credentials`,status:r.configured?`pass`:o===!1||r.error?`fail`:n.sharedConfigured||n.byoConfigured?`pass`:`fail`,detail:r.configured?`Service account configured for ${r.identity}.`:o===!1?`Stored Google login uses the ${i?.client_source===`shared`?`shared seo app`:`BYO client`}, but that client is not configured.`:r.error?r.error:n.sharedConfigured?`Shared client configured.`:n.byoConfigured?`BYO client configured at ${t.oauthClientFile}.`:`No shared or BYO Google OAuth client configured.`,fix:r.configured?void 0:o===!1?i?.client_source===`shared`?"Reinstall `seo`. If the shared client is still missing, report it at https://github.com/iannuttall/seo/issues.":"Restore the same client with `seo auth setup-client`, or run `seo auth logout` before signing in with a different client.":r.error?"Set one valid service account credential source, then run `seo doctor` again.":n.sharedConfigured||n.byoConfigured?void 0:"Run `seo auth setup-client` or set SEO_GOOGLE_CLIENT_ID and SEO_GOOGLE_CLIENT_SECRET."}),s.push({id:`oauth-client-file`,label:`BYO OAuth file`,status:a?`pass`:`warn`,detail:a?t.oauthClientFile:`No BYO OAuth client file. This is fine if using a shared client.`}),s.push({id:`google-login`,label:`Google login`,status:r.configured||i?`pass`:`fail`,detail:r.configured?`Using service account ${r.identity}.`:i?`Signed in as ${i.account_email}.`:`No Google token found.`,fix:r.configured||i?void 0:"Run `seo auth login`, or configure a service account for CI."});let c=new Set(i?.scope.split(/\s+/).filter(Boolean)??[]);for(let e of bU)s.push({id:`scope:${e}`,label:e.endsWith(`webmasters.readonly`)?`Search Console scope`:`Google Analytics scope`,status:r.configured||i&&c.has(e)?`pass`:i?`fail`:`warn`,detail:r.configured?`${e} requested by the service account.`:i?c.has(e)?e:`Missing ${e}.`:`Cannot inspect scopes until login is complete.`,fix:!r.configured&&i&&!c.has(e)?"Run `seo auth logout` then `seo auth login`.":void 0});return{ok:s.every(e=>e.status!==`fail`),generatedAt:new Date().toISOString(),checks:s}}function SU(e){return S(e)?T(e,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.endsWith(`.log`)).map(t=>{let n=g(e,t.name),r=O(n);return{path:n,size:r.size,modifiedAt:r.mtimeMs}}):[]}function CU(e,t){let n=p(e),r=f(e,`.log`),i=0;for(;;){let e=g(n,`${r}.${t}${i?`-${i}`:``}.log`);if(!S(e))return e;i+=1}}function wU(e={}){let t=e.directory??fr().logDir,n=e.now??Date.now(),r=e.maxFileBytes??8388608,i=e.maxTotalBytes??67108864,a=e.maxAgeMs??12096e5;C(t,{recursive:!0,mode:448});let o=0,s=0;for(let e of SU(t))e.size<=r||(E(e.path,CU(e.path,n)),o+=1);for(let e of SU(t))e.modifiedAt>=n-a||(D(e.path,{force:!0}),s+=1);let c=SU(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;D(e.path,{force:!0}),l-=e.size,s+=1}return{rotated:o,removed:s,sizeBytes:l}}function TU(e){let t=Object.entries(e);if(t.length>100)throw Error(`Provider action input is too large.`);for(let[e]of t)if(!/^[A-Za-z][A-Za-z0-9-]{0,63}$/u.test(e))throw Error(`Provider action parameter names are invalid.`);let n=EU(Object.fromEntries(t));return DU(n,{maxBytes:65536,maxDepth:16,maxValues:5e3,message:`Provider action input is too large.`}),n}function EU(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`?e:Array.isArray(e)?e.map(EU):Object.fromEntries(Object.entries(e).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,EU(t)]))}function DU(e,t){let n=0,r=new WeakSet,i=(e,a)=>{if(n+=1,n>t.maxValues||a>t.maxDepth)throw Error(t.message);if(e!==null&&typeof e!=`string`&&typeof e!=`boolean`&&!(typeof e==`number`&&Number.isFinite(e))){if(typeof e!=`object`)throw Error(`Provider action result must contain JSON values only.`);if(r.has(e))throw Error(`Provider action result must not contain cycles.`);if(r.add(e),Array.isArray(e))for(let t of e)i(t,a+1);else for(let[t,n]of Object.entries(e)){if(t.length>256)throw Error(`Provider action result contains a key that is too long.`);i(n,a+1)}r.delete(e)}};i(e,0);let a=JSON.stringify(e);if(Buffer.byteLength(a)>t.maxBytes)throw Error(t.message);return JSON.parse(a)}function OU(e,t,n){let r;try{r=o.fromJSONSchema(e)}catch{throw Error(`Provider action ${n} schema is invalid.`)}let i=r.safeParse(t);if(!i.success)throw Error(`Provider action ${n} does not match its JSON schema.`);return i.data}async function kU(e){let t={...e.supplied};return Object.keys(t).length===0&&(t=await Uk({providerId:e.providerId,account:e.account,fields:e.fields})),t}async function AU(e){let t=await fA(),n=t.registry.get(e.providerId),r=t.registry.action(e.providerId,e.actionId);if(!n)throw Error(`Provider ${e.providerId} is not installed.`);if(!r)throw Error(`Provider ${e.providerId} does not support action ${e.actionId}.`);let i=dA(n,e.account),a=EU(OU(r.inputSchema,TU(e.params??{}),`input`)),s={provider:e.providerId,credentialScope:UO(e.providerId,JSON.stringify(i)),operation:`action:${r.id}`,request:{account:i,params:a}};if(!e.refresh&&r.cacheTtlMs){let t=KO(s,o.unknown());if(t)return{provider:e.providerId,action:r.id,cache:`hit`,data:EU(OU(r.outputSchema,t.data,`output`))}}let c=await kU({providerId:e.providerId,account:i,fields:n.connection.fields,supplied:e.credentials}),l;try{l=await r.run({account:i,credentials:c,params:a},mA(e.providerId,e.runtime??{}))}catch(t){throw pA(e.providerId,t,c)}let u=EU(OU(r.outputSchema,DU(l,{maxBytes:10485760,maxDepth:20,maxValues:1e5,message:`Provider action result is too large.`}),`output`));if(r.cacheTtlMs){let e=u&&typeof u==`object`&&!Array.isArray(u)&&Array.isArray(u.rows)?u.rows.length:null;qO(s,{data:u,ttlMs:r.cacheTtlMs,rowCount:e,sourceCostMicros:null,taskIds:[]})}return{provider:e.providerId,action:r.id,cache:r.cacheTtlMs?e.refresh?`bypass`:`miss`:`disabled`,data:u}}function jU(e){let t=Tk.parse(e);return{...ra().providers.connections?.[t]??{}}}function MU(e,t){let n=Tk.parse(e),r=ra(),i=Object.fromEntries(Object.entries(t).map(([e,t])=>[e,t.trim()]).filter(([,e])=>e));return ia({...r,providers:{...r.providers,connections:{...r.providers.connections,[n]:i}}}),i}function NU(e){let t=Tk.parse(e),n=ra(),r={...n.providers.connections};delete r[t],ia({...n,providers:{...n.providers,connections:r}})}async function PU(){let e=eA().packages,t=await uA({installed:e}),n=new Map(t.failures.map(e=>[e.id,e]));return{schemaVersion:1,installed:e.map(e=>({...e,loadStatus:n.has(e.id)?`failed`:`ready`,error:n.get(e.id)?.message}))}}async function FU(e){let t=await uA(),n=t.registry.get(e);if(!n){let n=t.failures.find(t=>t.id===e);throw Error(n?`Provider ${e} could not load: ${n.message}`:`Provider ${e} is not installed.`)}return{schemaVersion:1,id:n.id,displayName:n.displayName,description:n.description,package:n.package,version:n.version,kinds:n.kinds,connection:n.connection.fields.map(e=>({id:e.id,label:e.label,description:e.description,kind:e.kind,required:e.required!==!1,envVar:e.envVar})),capabilities:n.capabilities.map(e=>JSON.parse(JSON.stringify(e))),actions:(n.actions??[]).map(e=>({id:e.id,description:e.description,inputSchema:e.inputSchema,outputSchema:e.outputSchema,cacheTtlMs:e.cacheTtlMs??0}))}}const IU=Ee(De),LU=5*1024*1024,RU=o.object({name:Ek,version:Dk,dependencies:o.record(o.string(),o.string()).optional(),optionalDependencies:o.record(o.string(),o.string()).optional(),bundledDependencies:o.array(o.string()).optional(),dist:o.object({integrity:Ok,unpackedSize:o.number().int().nonnegative()}).passthrough(),seo:Ik,description:o.string().trim().max(500).nullish(),repository:o.union([o.string().trim().max(2048),o.object({url:o.string().trim().max(2048)}).passthrough()]).nullish(),author:o.union([o.string().trim().max(500),o.object({name:o.string().trim().max(200)}).passthrough()]).nullish(),maintainers:o.array(o.union([o.string().trim().max(200),o.object({name:o.string().trim().max(200)}).passthrough()])).max(100).nullish(),_npmUser:o.union([o.string().trim().max(200),o.object({name:o.string().trim().max(200)}).passthrough()]).nullish()}).passthrough(),zU=o.object({package:Ek,version:Dk,integrity:Ok,unpackedSize:o.number().int().nonnegative(),apiVersion:o.literal(1),entryPoints:o.number().int().min(1).max(16),description:o.string().trim().max(500).optional(),repository:o.string().trim().max(2048).optional(),publisher:o.string().trim().max(200).optional()}).strict(),BU=o.object({packages:o.record(o.string(),o.object({version:Dk.optional(),integrity:Ok.optional()}).passthrough())}).passthrough();async function VU(e,t,n){let r=await IU(e,[...t],{cwd:n.cwd,env:{...process.env,NPM_CONFIG_UPDATE_NOTIFIER:`false`},maxBuffer:1048576});return{stdout:r.stdout,stderr:r.stderr}}function HU(e){pr(),C(e,{recursive:!0,mode:448});let t=g(e,`package.json`);S(t)||_r(t,{name:`seo-local-provider-packages`,private:!0,type:`module`,dependencies:{}},420)}function UU(e){let t=Object.keys(e.dependencies??{}),n=Object.keys(e.optionalDependencies??{}),r=e.bundledDependencies??[];if(t.length>0||n.length>0||r.length>0)throw Error(`Provider packages must bundle their runtime code and declare no runtime, optional, or bundled dependencies.`);if(e.dist.unpackedSize>LU)throw Error(`Provider package exceeds the ${LU} byte unpacked-size limit.`)}function WU(e,t){let n=BU.parse(JSON.parse(w(g(e,`package-lock.json`),`utf8`))).packages[`node_modules/${t.package}`];if(n?.version!==t.version||n.integrity!==t.integrity)throw Error(`${t.package} does not match the approved package release.`)}function GU(e){let t=e.trim(),n=t,r;if(t.startsWith(`@`)){let e=t.indexOf(`/`),i=t.lastIndexOf(`@`);e>1&&i>e&&(n=t.slice(0,i),r=t.slice(i+1))}else{let e=t.lastIndexOf(`@`);e>0&&(n=t.slice(0,e),r=t.slice(e+1))}if(!Ek.safeParse(n).success||r!==void 0&&!Dk.safeParse(r).success)throw Error(`Provider package must be an npm package name with an optional exact version, such as @scope/provider or @scope/provider@1.2.3.`);return{package:n,...r?{version:r}:{}}}function KU(e){return(typeof e==`string`?e:e?.url)?.replace(/^git\+/u,``).replace(/\.git$/u,``)}function qU(e){if(typeof e._npmUser==`string`)return e._npmUser;if(e._npmUser?.name)return e._npmUser.name;if(typeof e.author==`string`)return e.author;if(e.author?.name)return e.author.name;let t=e.maintainers?.[0];return typeof t==`string`?t:t?.name}async function JU(e,t,n){let r=await n.run(process.platform===`win32`?`npm.cmd`:`npm`,[`view`,t?`${e}@${t}`:e,`--json`],{cwd:n.packagesDir}),i=RU.parse(JSON.parse(r.stdout));if(i.name!==e)throw Error(`npm returned metadata for ${i.name}, not ${e}.`);if(t&&i.version!==t)throw Error(`npm returned ${i.name}@${i.version}, not ${e}@${t}.`);return UU(i),i}async function YU(e,t={}){let n=t.packagesDir??fr().providerPackagesDir,r=t.run??VU,i=GU(e);HU(n);let a=await JU(i.package,i.version,{packagesDir:n,run:r});return zU.parse({package:a.name,version:a.version,integrity:a.dist.integrity,unpackedSize:a.dist.unpackedSize,apiVersion:a.seo.apiVersion,entryPoints:a.seo.providers.length,...a.description?{description:a.description}:{},...KU(a.repository)?{repository:KU(a.repository)}:{},...qU(a)?{publisher:qU(a)}:{}})}async function XU(e,t={}){let n=zU.parse(e),r=t.packagesDir??fr().providerPackagesDir,i=t.run??VU,a=eA();if(a.packages.some(e=>e.package===n.package))throw Error(`${n.package} is already installed. Remove it before installing another version.`);HU(r);let o=await JU(n.package,n.version,{packagesDir:r,run:i});if(o.version!==n.version||o.dist.integrity!==n.integrity||o.seo.apiVersion!==n.apiVersion||o.seo.providers.length!==n.entryPoints)throw Error(`${n.package} npm metadata changed after approval. Run the install command again to review it.`);await i(process.platform===`win32`?`npm.cmd`:`npm`,[`install`,`--ignore-scripts`,`--no-audit`,`--no-fund`,`--legacy-peer-deps`,`--omit=optional`,`--save-exact`,`${n.package}@${n.version}`],{cwd:r});try{WU(r,n);let e=await lA({package:n.package,version:n.version},{packagesDir:r});if(e.length!==1)throw Error(`${n.package} must register exactly one provider; received ${e.length}.`);let i=e[0];if(!i)throw Error(`${n.package} did not register a provider.`);if(a.packages.some(e=>e.id===i.id))throw Error(`Provider ${i.id} is already installed.`);let o={id:i.id,package:n.package,version:n.version,integrity:n.integrity,enabled:!0,installedAt:(t.now??(()=>new Date))().toISOString()};return nA(o),o}catch(e){throw await i(process.platform===`win32`?`npm.cmd`:`npm`,[`uninstall`,`--ignore-scripts`,`--no-audit`,`--no-fund`,n.package],{cwd:r}).catch(()=>void 0),e}}async function ZU(e,t={}){let n=t.packagesDir??fr().providerPackagesDir,r=t.run??VU,i=eA().packages.find(t=>t.id===e);if(i)return await r(process.platform===`win32`?`npm.cmd`:`npm`,[`uninstall`,`--ignore-scripts`,`--no-audit`,`--no-fund`,i.package],{cwd:n}),rA(e)}const QU=o.object({limits_and_usage:o.object({api_key_expiration_date:o.string().trim().min(1).max(100),subscription:o.string().trim().min(1).max(200),units_limit_api_key:o.number().int().nonnegative().nullable(),units_limit_workspace:o.number().int().nonnegative().nullable(),units_usage_api_key:o.number().int().nonnegative(),units_usage_workspace:o.number().int().nonnegative().nullable(),usage_reset_date:o.string().trim().min(1).max(100)}).strict()}).strict();function $U(e,t){return e===null||t===null?null:Math.max(0,e-t)}var eW=class{apiKey;credentials;fetch;baseUrl;timeoutMs;now;constructor(e={}){this.apiKey=e.apiKey?.trim(),this.credentials=e.credentials,this.fetch=e.fetch??ae,this.baseUrl=e.baseUrl??`https://api.ahrefs.com/v3/`,this.timeoutMs=e.timeoutMs??1e4,this.now=e.now??(()=>new Date)}async getApiKey(e){let t=this.apiKey??await this.credentials?.()??(await HH())?.apiKey;if(!t?.trim()||t.trim().length>4096)throw new BO({provider:`ahrefs`,operation:e,code:`configuration`,message:"Ahrefs is not connected. Run `seo providers ahrefs connect`, or set SEO_AHREFS_API_KEY for this process."});return t.trim()}async limitsAndUsageForKey(e){let t=`limits-and-usage`,n=(await Zk({provider:`ahrefs`,operation:t,url:new URL(`subscription-info/limits-and-usage`,this.baseUrl),fetch:this.fetch,maxResponseBytes:65536,timeoutMs:this.timeoutMs,retry:`safe`,schema:QU,init:{method:`GET`,headers:{accept:`application/json`,authorization:`Bearer ${e}`}}}).catch(e=>{throw e instanceof BO&&e.code===`authentication`?new BO({provider:`ahrefs`,operation:t,code:`authentication`,status:e.status??void 0,message:`Ahrefs rejected the API v3 key. Create or copy a key from Ahrefs Account settings, then connect again.`,cause:e}):e})).limits_and_usage;return{provider:`ahrefs`,apiVersion:3,subscription:n.subscription,apiKeyExpiresAt:n.api_key_expiration_date,usageResetsAt:n.usage_reset_date,apiKeyUnits:{limit:n.units_limit_api_key,used:n.units_usage_api_key,remaining:$U(n.units_limit_api_key,n.units_usage_api_key)},workspaceUnits:{limit:n.units_limit_workspace,used:n.units_usage_workspace,remaining:$U(n.units_limit_workspace,n.units_usage_workspace)},observedAt:this.now().toISOString(),requestCostUnits:0}}async limitsAndUsage(){return this.limitsAndUsageForKey(await this.getApiKey(`limits-and-usage`))}};const tW=o.object({total:o.number().finite().nonnegative().optional(),balance:o.number().finite().optional()}).passthrough(),nW=o.object({login:o.string().min(1).max(320),timezone:o.string().min(1).max(100).optional(),money:tW.optional()}).passthrough(),rW=o.object({id:o.string().min(1).max(100).optional(),status_code:o.number().int(),status_message:o.string().max(1e3),cost:o.number().finite().nonnegative().optional(),result_count:o.number().int().nonnegative().optional(),result:o.array(nW).max(10).nullable()}).passthrough(),iW=o.object({version:o.string().min(1).max(100).optional(),status_code:o.number().int(),status_message:o.string().max(1e3),cost:o.number().finite().nonnegative().optional(),tasks_count:o.number().int().nonnegative(),tasks_error:o.number().int().nonnegative(),tasks:o.array(rW).max(10)}).passthrough();function aW(e){return e===void 0?null:Math.round(e*1e6)}function oW(e){return e>=40100&&e<40200?`authentication`:e===40202?`rate-limit`:`remote-error`}var sW=class{fetch;credentials;baseUrl;timeoutMs;maxResponseBytes;now;constructor(e={}){this.fetch=e.fetch??ae,this.credentials=e.credentials??sU,this.baseUrl=e.baseUrl??`https://api.dataforseo.com/`,this.timeoutMs=e.timeoutMs??15e3,this.maxResponseBytes=e.maxResponseBytes??5242880,this.now=e.now??(()=>new Date)}async getCredentials(e){let t=await this.credentials();if(!t)throw new BO({provider:`dataforseo`,operation:e,code:`configuration`,message:"DataForSEO is not connected. Run `seo providers dataforseo connect`, or set SEO_DATAFORSEO_LOGIN and SEO_DATAFORSEO_PASSWORD."});return t}authorization(e){return`Basic ${Buffer.from(`${e.login}:${e.password}`).toString(`base64`)}`}async userDataForCredentials(e){let t;try{t=await Zk({provider:`dataforseo`,operation:`account-status`,url:new URL(`v3/appendix/user_data`,this.baseUrl),fetch:this.fetch,maxResponseBytes:this.maxResponseBytes,timeoutMs:this.timeoutMs,retry:`safe`,schema:iW,init:{method:`GET`,headers:{authorization:this.authorization(e)}}})}catch(e){throw e instanceof BO&&e.code===`authentication`?new BO({provider:`dataforseo`,operation:`account-status`,code:`authentication`,status:e.status??void 0,message:"DataForSEO rejected the API login or API password. Run `seo providers dataforseo connect` again, or check SEO_DATAFORSEO_LOGIN and SEO_DATAFORSEO_PASSWORD.",cause:e}):e}let n=t.tasks.find(e=>e.status_code!==2e4);if(t.status_code!==2e4||t.tasks_error>0||n){let e=n?.status_code??t.status_code;throw new BO({provider:`dataforseo`,operation:`account-status`,code:oW(e),message:`DataForSEO could not return account status (${e}).`,retryable:e===40202})}let r=t.tasks[0]?.result?.[0];if(!r)throw new BO({provider:`dataforseo`,operation:`account-status`,code:`invalid-response`,message:`DataForSEO returned account status without an account row.`});return{provider:`dataforseo`,login:r.login,timezone:r.timezone??null,balanceMicros:aW(r.money?.balance),depositedMicros:aW(r.money?.total),apiVersion:t.version??null,requestCostMicros:aW(t.cost)??0,taskIds:t.tasks.flatMap(e=>e.id?[e.id]:[]),observedAt:this.now().toISOString()}}async userData(){return this.userDataForCredentials(await this.getCredentials(`account-status`))}};new class{getGoogleOAuthClient(){let e=Ta();if(e)return{clientId:e.clientId,clientSecret:e.clientSecret,source:`byo`};let t=ra(),n=process.env.SEO_GOOGLE_CLIENT_ID??process.env.GSC_CLIENT_ID??ka.clientId??t.auth.sharedClientId,r=process.env.SEO_GOOGLE_CLIENT_SECRET??process.env.GSC_CLIENT_SECRET??ka.clientSecret??t.auth.sharedClientSecret;if(!(!n||!r))return{clientId:n,clientSecret:r,source:`shared`}}readGoogleTokens(){return va()}writeGoogleTokens(e){return xa(e)}deleteGoogleTokens(){return Sa()}};async function cW(){let e=(await Promise.allSettled([Sa(),ok()])).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(e.length>0)throw Error("Reset stopped before deleting local files because saved credentials could not be removed. Unlock the system keychain and run `seo reset --yes` again.",{cause:AggregateError(e)});let t=fr();D(t.configDir,{recursive:!0,force:!0}),D(t.cacheDir,{recursive:!0,force:!0}),D(t.logDir,{recursive:!0,force:!0})}function lW(e){return!!e._zod}function uW(e){let t=Object.values(e);if(t.length===0)return ke.object({});let n=t.every(lW),r=t.every(e=>!lW(e));if(n)return ke.object(e);if(r)return Oe.object(e);throw Error(`Mixed Zod versions detected in object shape.`)}function dW(e,t){return lW(e)?ke.safeParse(e,t):e.safeParse(t)}async function fW(e,t){return lW(e)?await ke.safeParseAsync(e,t):await e.safeParseAsync(t)}function pW(e){if(!e)return;let t;if(t=lW(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function mW(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return uW(e)}}if(lW(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function hW(e){return e.length===0?`object root`:e.reduce((e,t,n)=>n===0?String(t):typeof t==`number`?`${e}[${t}]`:`${e}.${t}`,``)}function gW(e){if(e&&typeof e==`object`){if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0)return e.issues.map(e=>e.path?.length?`${e.message} at ${hW(e.path)}`:e.message).join(`
338
+ `);if(`message`in e&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function _W(e){return e.description}function vW(e){if(lW(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function yW(e){if(lW(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}const bW=`2025-11-25`,xW=[bW,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],SW=`io.modelcontextprotocol/related-task`,CW=A.custom(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),wW=A.union([A.string(),A.number().int()]),TW=A.string();A.looseObject({ttl:A.number().optional(),pollInterval:A.number().optional()});const EW=A.object({ttl:A.number().optional()}),DW=A.object({taskId:A.string()}),OW=A.looseObject({progressToken:wW.optional(),[SW]:DW.optional()}),kW=A.object({_meta:OW.optional()}),AW=kW.extend({task:EW.optional()}),jW=e=>AW.safeParse(e).success,MW=A.object({method:A.string(),params:kW.loose().optional()}),NW=A.object({_meta:OW.optional()}),PW=A.object({method:A.string(),params:NW.loose().optional()}),FW=A.looseObject({_meta:OW.optional()}),IW=A.union([A.string(),A.number().int()]),LW=A.object({jsonrpc:A.literal(`2.0`),id:IW,...MW.shape}).strict(),RW=e=>LW.safeParse(e).success,zW=A.object({jsonrpc:A.literal(`2.0`),...PW.shape}).strict(),BW=e=>zW.safeParse(e).success,VW=A.object({jsonrpc:A.literal(`2.0`),id:IW,result:FW}).strict(),HW=e=>VW.safeParse(e).success;var J;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(J||={});const UW=A.object({jsonrpc:A.literal(`2.0`),id:IW.optional(),error:A.object({code:A.number().int(),message:A.string(),data:A.unknown().optional()})}).strict(),WW=e=>UW.safeParse(e).success,GW=A.union([LW,zW,VW,UW]);A.union([VW,UW]);const KW=FW.strict(),qW=NW.extend({requestId:IW.optional(),reason:A.string().optional()}),JW=PW.extend({method:A.literal(`notifications/cancelled`),params:qW}),YW=A.object({src:A.string(),mimeType:A.string().optional(),sizes:A.array(A.string()).optional(),theme:A.enum([`light`,`dark`]).optional()}),XW=A.object({icons:A.array(YW).optional()}),ZW=A.object({name:A.string(),title:A.string().optional()}),QW=ZW.extend({...ZW.shape,...XW.shape,version:A.string(),websiteUrl:A.string().optional(),description:A.string().optional()}),$W=A.intersection(A.object({applyDefaults:A.boolean().optional()}),A.record(A.string(),A.unknown())),eG=A.preprocess(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,A.intersection(A.object({form:$W.optional(),url:CW.optional()}),A.record(A.string(),A.unknown()).optional())),tG=A.looseObject({list:CW.optional(),cancel:CW.optional(),requests:A.looseObject({sampling:A.looseObject({createMessage:CW.optional()}).optional(),elicitation:A.looseObject({create:CW.optional()}).optional()}).optional()}),nG=A.looseObject({list:CW.optional(),cancel:CW.optional(),requests:A.looseObject({tools:A.looseObject({call:CW.optional()}).optional()}).optional()}),rG=A.object({experimental:A.record(A.string(),CW).optional(),sampling:A.object({context:CW.optional(),tools:CW.optional()}).optional(),elicitation:eG.optional(),roots:A.object({listChanged:A.boolean().optional()}).optional(),tasks:tG.optional(),extensions:A.record(A.string(),CW).optional()}),iG=kW.extend({protocolVersion:A.string(),capabilities:rG,clientInfo:QW}),aG=MW.extend({method:A.literal(`initialize`),params:iG}),oG=A.object({experimental:A.record(A.string(),CW).optional(),logging:CW.optional(),completions:CW.optional(),prompts:A.object({listChanged:A.boolean().optional()}).optional(),resources:A.object({subscribe:A.boolean().optional(),listChanged:A.boolean().optional()}).optional(),tools:A.object({listChanged:A.boolean().optional()}).optional(),tasks:nG.optional(),extensions:A.record(A.string(),CW).optional()}),sG=FW.extend({protocolVersion:A.string(),capabilities:oG,serverInfo:QW,instructions:A.string().optional()}),cG=PW.extend({method:A.literal(`notifications/initialized`),params:NW.optional()}),lG=MW.extend({method:A.literal(`ping`),params:kW.optional()}),uG=A.object({progress:A.number(),total:A.optional(A.number()),message:A.optional(A.string())}),dG=A.object({...NW.shape,...uG.shape,progressToken:wW}),fG=PW.extend({method:A.literal(`notifications/progress`),params:dG}),pG=kW.extend({cursor:TW.optional()}),mG=MW.extend({params:pG.optional()}),hG=FW.extend({nextCursor:TW.optional()}),gG=A.enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),_G=A.object({taskId:A.string(),status:gG,ttl:A.union([A.number(),A.null()]),createdAt:A.string(),lastUpdatedAt:A.string(),pollInterval:A.optional(A.number()),statusMessage:A.optional(A.string())}),vG=FW.extend({task:_G}),yG=NW.merge(_G),bG=PW.extend({method:A.literal(`notifications/tasks/status`),params:yG}),xG=MW.extend({method:A.literal(`tasks/get`),params:kW.extend({taskId:A.string()})}),SG=FW.merge(_G),CG=MW.extend({method:A.literal(`tasks/result`),params:kW.extend({taskId:A.string()})});FW.loose();const wG=mG.extend({method:A.literal(`tasks/list`)}),TG=hG.extend({tasks:A.array(_G)}),EG=MW.extend({method:A.literal(`tasks/cancel`),params:kW.extend({taskId:A.string()})}),DG=FW.merge(_G),OG=A.object({uri:A.string(),mimeType:A.optional(A.string()),_meta:A.record(A.string(),A.unknown()).optional()}),kG=OG.extend({text:A.string()}),AG=A.string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),jG=OG.extend({blob:AG}),MG=A.enum([`user`,`assistant`]),NG=A.object({audience:A.array(MG).optional(),priority:A.number().min(0).max(1).optional(),lastModified:A.iso.datetime({offset:!0}).optional()}),PG=A.object({...ZW.shape,...XW.shape,uri:A.string(),description:A.optional(A.string()),mimeType:A.optional(A.string()),size:A.optional(A.number()),annotations:NG.optional(),_meta:A.optional(A.looseObject({}))}),FG=A.object({...ZW.shape,...XW.shape,uriTemplate:A.string(),description:A.optional(A.string()),mimeType:A.optional(A.string()),annotations:NG.optional(),_meta:A.optional(A.looseObject({}))}),IG=mG.extend({method:A.literal(`resources/list`)}),LG=hG.extend({resources:A.array(PG)}),RG=mG.extend({method:A.literal(`resources/templates/list`)}),zG=hG.extend({resourceTemplates:A.array(FG)}),BG=kW.extend({uri:A.string()}),VG=BG,HG=MW.extend({method:A.literal(`resources/read`),params:VG}),UG=FW.extend({contents:A.array(A.union([kG,jG]))}),WG=PW.extend({method:A.literal(`notifications/resources/list_changed`),params:NW.optional()}),GG=BG,KG=MW.extend({method:A.literal(`resources/subscribe`),params:GG}),qG=BG,JG=MW.extend({method:A.literal(`resources/unsubscribe`),params:qG}),YG=NW.extend({uri:A.string()}),XG=PW.extend({method:A.literal(`notifications/resources/updated`),params:YG}),ZG=A.object({name:A.string(),description:A.optional(A.string()),required:A.optional(A.boolean())}),QG=A.object({...ZW.shape,...XW.shape,description:A.optional(A.string()),arguments:A.optional(A.array(ZG)),_meta:A.optional(A.looseObject({}))}),$G=mG.extend({method:A.literal(`prompts/list`)}),eK=hG.extend({prompts:A.array(QG)}),tK=kW.extend({name:A.string(),arguments:A.record(A.string(),A.string()).optional()}),nK=MW.extend({method:A.literal(`prompts/get`),params:tK}),rK=A.object({type:A.literal(`text`),text:A.string(),annotations:NG.optional(),_meta:A.record(A.string(),A.unknown()).optional()}),iK=A.object({type:A.literal(`image`),data:AG,mimeType:A.string(),annotations:NG.optional(),_meta:A.record(A.string(),A.unknown()).optional()}),aK=A.object({type:A.literal(`audio`),data:AG,mimeType:A.string(),annotations:NG.optional(),_meta:A.record(A.string(),A.unknown()).optional()}),oK=A.object({type:A.literal(`tool_use`),name:A.string(),id:A.string(),input:A.record(A.string(),A.unknown()),_meta:A.record(A.string(),A.unknown()).optional()}),sK=A.object({type:A.literal(`resource`),resource:A.union([kG,jG]),annotations:NG.optional(),_meta:A.record(A.string(),A.unknown()).optional()}),cK=PG.extend({type:A.literal(`resource_link`)}),lK=A.union([rK,iK,aK,cK,sK]),uK=A.object({role:MG,content:lK}),dK=FW.extend({description:A.string().optional(),messages:A.array(uK)}),fK=PW.extend({method:A.literal(`notifications/prompts/list_changed`),params:NW.optional()}),pK=A.object({title:A.string().optional(),readOnlyHint:A.boolean().optional(),destructiveHint:A.boolean().optional(),idempotentHint:A.boolean().optional(),openWorldHint:A.boolean().optional()}),mK=A.object({taskSupport:A.enum([`required`,`optional`,`forbidden`]).optional()}),hK=A.object({...ZW.shape,...XW.shape,description:A.string().optional(),inputSchema:A.object({type:A.literal(`object`),properties:A.record(A.string(),CW).optional(),required:A.array(A.string()).optional()}).catchall(A.unknown()),outputSchema:A.object({type:A.literal(`object`),properties:A.record(A.string(),CW).optional(),required:A.array(A.string()).optional()}).catchall(A.unknown()).optional(),annotations:pK.optional(),execution:mK.optional(),_meta:A.record(A.string(),A.unknown()).optional()}),gK=mG.extend({method:A.literal(`tools/list`)}),_K=hG.extend({tools:A.array(hK)}),vK=FW.extend({content:A.array(lK).default([]),structuredContent:A.record(A.string(),A.unknown()).optional(),isError:A.boolean().optional()});vK.or(FW.extend({toolResult:A.unknown()}));const yK=AW.extend({name:A.string(),arguments:A.record(A.string(),A.unknown()).optional()}),bK=MW.extend({method:A.literal(`tools/call`),params:yK}),xK=PW.extend({method:A.literal(`notifications/tools/list_changed`),params:NW.optional()});A.object({autoRefresh:A.boolean().default(!0),debounceMs:A.number().int().nonnegative().default(300)});const SK=A.enum([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),CK=kW.extend({level:SK}),wK=MW.extend({method:A.literal(`logging/setLevel`),params:CK}),TK=NW.extend({level:SK,logger:A.string().optional(),data:A.unknown()}),EK=PW.extend({method:A.literal(`notifications/message`),params:TK}),DK=A.object({name:A.string().optional()}),OK=A.object({hints:A.array(DK).optional(),costPriority:A.number().min(0).max(1).optional(),speedPriority:A.number().min(0).max(1).optional(),intelligencePriority:A.number().min(0).max(1).optional()}),kK=A.object({mode:A.enum([`auto`,`required`,`none`]).optional()}),AK=A.object({type:A.literal(`tool_result`),toolUseId:A.string().describe(`The unique identifier for the corresponding tool call.`),content:A.array(lK).default([]),structuredContent:A.object({}).loose().optional(),isError:A.boolean().optional(),_meta:A.record(A.string(),A.unknown()).optional()}),jK=A.discriminatedUnion(`type`,[rK,iK,aK]),MK=A.discriminatedUnion(`type`,[rK,iK,aK,oK,AK]),NK=A.object({role:MG,content:A.union([MK,A.array(MK)]),_meta:A.record(A.string(),A.unknown()).optional()}),PK=AW.extend({messages:A.array(NK),modelPreferences:OK.optional(),systemPrompt:A.string().optional(),includeContext:A.enum([`none`,`thisServer`,`allServers`]).optional(),temperature:A.number().optional(),maxTokens:A.number().int(),stopSequences:A.array(A.string()).optional(),metadata:CW.optional(),tools:A.array(hK).optional(),toolChoice:kK.optional()}),FK=MW.extend({method:A.literal(`sampling/createMessage`),params:PK}),IK=FW.extend({model:A.string(),stopReason:A.optional(A.enum([`endTurn`,`stopSequence`,`maxTokens`]).or(A.string())),role:MG,content:jK}),LK=FW.extend({model:A.string(),stopReason:A.optional(A.enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A.string())),role:MG,content:A.union([MK,A.array(MK)])}),RK=A.object({type:A.literal(`boolean`),title:A.string().optional(),description:A.string().optional(),default:A.boolean().optional()}),zK=A.object({type:A.literal(`string`),title:A.string().optional(),description:A.string().optional(),minLength:A.number().optional(),maxLength:A.number().optional(),format:A.enum([`email`,`uri`,`date`,`date-time`]).optional(),default:A.string().optional()}),BK=A.object({type:A.enum([`number`,`integer`]),title:A.string().optional(),description:A.string().optional(),minimum:A.number().optional(),maximum:A.number().optional(),default:A.number().optional()}),VK=A.object({type:A.literal(`string`),title:A.string().optional(),description:A.string().optional(),enum:A.array(A.string()),default:A.string().optional()}),HK=A.object({type:A.literal(`string`),title:A.string().optional(),description:A.string().optional(),oneOf:A.array(A.object({const:A.string(),title:A.string()})),default:A.string().optional()}),UK=A.object({type:A.literal(`string`),title:A.string().optional(),description:A.string().optional(),enum:A.array(A.string()),enumNames:A.array(A.string()).optional(),default:A.string().optional()}),WK=A.union([VK,HK]),GK=A.object({type:A.literal(`array`),title:A.string().optional(),description:A.string().optional(),minItems:A.number().optional(),maxItems:A.number().optional(),items:A.object({type:A.literal(`string`),enum:A.array(A.string())}),default:A.array(A.string()).optional()}),KK=A.object({type:A.literal(`array`),title:A.string().optional(),description:A.string().optional(),minItems:A.number().optional(),maxItems:A.number().optional(),items:A.object({anyOf:A.array(A.object({const:A.string(),title:A.string()}))}),default:A.array(A.string()).optional()}),qK=A.union([GK,KK]),JK=A.union([UK,WK,qK]),YK=A.union([JK,RK,zK,BK]),XK=AW.extend({mode:A.literal(`form`).optional(),message:A.string(),requestedSchema:A.object({type:A.literal(`object`),properties:A.record(A.string(),YK),required:A.array(A.string()).optional()})}),ZK=AW.extend({mode:A.literal(`url`),message:A.string(),elicitationId:A.string(),url:A.string().url()}),QK=A.union([XK,ZK]),$K=MW.extend({method:A.literal(`elicitation/create`),params:QK}),eq=NW.extend({elicitationId:A.string()}),tq=PW.extend({method:A.literal(`notifications/elicitation/complete`),params:eq}),nq=FW.extend({action:A.enum([`accept`,`decline`,`cancel`]),content:A.preprocess(e=>e===null?void 0:e,A.record(A.string(),A.union([A.string(),A.number(),A.boolean(),A.array(A.string())])).optional())}),rq=A.object({type:A.literal(`ref/resource`),uri:A.string()}),iq=A.object({type:A.literal(`ref/prompt`),name:A.string()}),aq=kW.extend({ref:A.union([iq,rq]),argument:A.object({name:A.string(),value:A.string()}),context:A.object({arguments:A.record(A.string(),A.string()).optional()}).optional()}),oq=MW.extend({method:A.literal(`completion/complete`),params:aq});function sq(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function cq(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const lq=FW.extend({completion:A.looseObject({values:A.array(A.string()).max(100),total:A.optional(A.number().int()),hasMore:A.optional(A.boolean())})}),uq=A.object({uri:A.string().startsWith(`file://`),name:A.string().optional(),_meta:A.record(A.string(),A.unknown()).optional()}),dq=MW.extend({method:A.literal(`roots/list`),params:kW.optional()}),fq=FW.extend({roots:A.array(uq)}),pq=PW.extend({method:A.literal(`notifications/roots/list_changed`),params:NW.optional()});A.union([lG,aG,oq,wK,nK,$G,IG,RG,HG,KG,JG,bK,gK,xG,CG,wG,EG]),A.union([JW,fG,cG,pq,bG]),A.union([KW,IK,LK,nq,fq,SG,TG,vG]),A.union([lG,FK,$K,dq,xG,CG,wG,EG]),A.union([JW,fG,EK,XG,WG,xK,fK,bG,tq]),A.union([KW,sG,lq,dK,eK,LG,zG,UG,vK,_K,SG,TG,vG]);var Y=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===J.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new mq(e.elicitations,n)}return new e(t,n,r)}},mq=class extends Y{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(J.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function hq(e){return e===`completed`||e===`failed`||e===`cancelled`}const gq=Symbol(`Let zodToJsonSchema decide on which parser to use`),_q={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},vq=e=>typeof e==`string`?{..._q,name:e}:{..._q,...e},yq=e=>{let t=vq(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function bq(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function xq(e,t,n,r,i){e[t]=n,bq(e,t,r,i)}const Sq=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function Cq(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?Sq(t,e.currentPath):t.join(`/`)}}function wq(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==k.ZodAny&&(n.items=X(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&xq(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&xq(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(xq(n,`minItems`,e.exactLength.value,e.exactLength.message,t),xq(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Tq(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?xq(n,`minimum`,r.value,r.message,t):xq(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),xq(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?xq(n,`maximum`,r.value,r.message,t):xq(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),xq(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:xq(n,`multipleOf`,r.value,r.message,t);break}return n}function Eq(){return{type:`boolean`}}function Dq(e,t){return X(e.type._def,t)}const Oq=(e,t)=>X(e.innerType._def,t);function kq(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>kq(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return Aq(e,t)}}const Aq=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:xq(n,`minimum`,r.value,r.message,t);break;case`max`:xq(n,`maximum`,r.value,r.message,t);break}return n};function jq(e,t){return{...X(e.innerType._def,t),default:e.defaultValue()}}function Mq(e,t){return t.effectStrategy===`input`?X(e.schema._def,t):Cq(t)}function Nq(e){return{type:`string`,enum:Array.from(e.values)}}const Pq=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Fq(e,t){let n=[X(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),X(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(Pq(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function Iq(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}let Lq;const Rq={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Lq===void 0&&(Lq=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),Lq),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function zq(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:xq(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:xq(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:Uq(n,`email`,r.message,t);break;case`format:idn-email`:Uq(n,`idn-email`,r.message,t);break;case`pattern:zod`:Wq(n,Rq.email,r.message,t);break}break;case`url`:Uq(n,`uri`,r.message,t);break;case`uuid`:Uq(n,`uuid`,r.message,t);break;case`regex`:Wq(n,r.regex,r.message,t);break;case`cuid`:Wq(n,Rq.cuid,r.message,t);break;case`cuid2`:Wq(n,Rq.cuid2,r.message,t);break;case`startsWith`:Wq(n,RegExp(`^${Bq(r.value,t)}`),r.message,t);break;case`endsWith`:Wq(n,RegExp(`${Bq(r.value,t)}$`),r.message,t);break;case`datetime`:Uq(n,`date-time`,r.message,t);break;case`date`:Uq(n,`date`,r.message,t);break;case`time`:Uq(n,`time`,r.message,t);break;case`duration`:Uq(n,`duration`,r.message,t);break;case`length`:xq(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),xq(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:Wq(n,RegExp(Bq(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&Uq(n,`ipv4`,r.message,t),r.version!==`v4`&&Uq(n,`ipv6`,r.message,t);break;case`base64url`:Wq(n,Rq.base64url,r.message,t);break;case`jwt`:Wq(n,Rq.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&Wq(n,Rq.ipv4Cidr,r.message,t),r.version!==`v4`&&Wq(n,Rq.ipv6Cidr,r.message,t);break;case`emoji`:Wq(n,Rq.emoji(),r.message,t);break;case`ulid`:Wq(n,Rq.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:Uq(n,`binary`,r.message,t);break;case`contentEncoding:base64`:xq(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:Wq(n,Rq.base64,r.message,t);break}break;case`nanoid`:Wq(n,Rq.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:}return n}function Bq(e,t){return t.patternStrategy===`escape`?Hq(e):e}const Vq=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Hq(e){let t=``;for(let n=0;n<e.length;n++)Vq.has(e[n])||(t+=`\\`),t+=e[n];return t}function Uq(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):xq(e,`format`,t,n,r)}function Wq(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Gq(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):xq(e,`pattern`,Gq(t,r),n,r)}function Gq(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
332
339
  ]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
333
- ]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function Bq(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===k.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:X(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??_q(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:X(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===k.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=Nq(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===k.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===k.ZodBranded&&e.keyType._def.type._def.typeName===k.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=xq(e.keyType._def,t);return{...n,propertyNames:i}}return n}function Vq(e,t){return t.mapStrategy===`record`?Bq(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[X(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||_q(t),X(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||_q(t)],minItems:2,maxItems:2}}}function Hq(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function Uq(e){return e.target===`openAi`?void 0:{not:_q({...e,currentPath:[...e.currentPath,`not`]})}}function Wq(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const Gq={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Kq(e,t){if(t.target===`openApi3`)return qq(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in Gq&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=Gq[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return qq(e,t)}const qq=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>X(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function Jq(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:Gq[e.innerType._def.typeName],nullable:!0}:{type:[Gq[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=X(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=X(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Yq(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,mq(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?hq(n,`minimum`,r.value,r.message,t):hq(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),hq(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?hq(n,`maximum`,r.value,r.message,t):hq(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),hq(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:hq(n,`multipleOf`,r.value,r.message,t);break}return n}function Xq(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=Qq(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=X(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=Zq(e,t);return o!==void 0&&(r.additionalProperties=o),r}function Zq(e,t){if(e.catchall._def.typeName!==`ZodNever`)return X(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function Qq(e){try{return e.isOptional()}catch{return!0}}const $q=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return X(e.innerType._def,t);let n=X(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:_q(t)},n]}:_q(t)},eJ=(e,t)=>{if(t.pipeStrategy===`input`)return X(e.in._def,t);if(t.pipeStrategy===`output`)return X(e.out._def,t);let n=X(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,X(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function tJ(e,t){return X(e.type._def,t)}function nJ(e,t){let n={type:`array`,uniqueItems:!0,items:X(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&hq(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&hq(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function rJ(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>X(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:X(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>X(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function iJ(e){return{not:_q(e)}}function aJ(e){return _q(e)}const oJ=(e,t)=>X(e.innerType._def,t),sJ=(e,t,n)=>{switch(t){case k.ZodString:return Nq(e,n);case k.ZodNumber:return Yq(e,n);case k.ZodObject:return Xq(e,n);case k.ZodBigInt:return yq(e,n);case k.ZodBoolean:return bq();case k.ZodDate:return Cq(e,n);case k.ZodUndefined:return iJ(n);case k.ZodNull:return Wq(n);case k.ZodArray:return vq(e,n);case k.ZodUnion:case k.ZodDiscriminatedUnion:return Kq(e,n);case k.ZodIntersection:return kq(e,n);case k.ZodTuple:return rJ(e,n);case k.ZodRecord:return Bq(e,n);case k.ZodLiteral:return Aq(e,n);case k.ZodEnum:return Dq(e);case k.ZodNativeEnum:return Hq(e);case k.ZodNullable:return Jq(e,n);case k.ZodOptional:return $q(e,n);case k.ZodMap:return Vq(e,n);case k.ZodSet:return nJ(e,n);case k.ZodLazy:return()=>e.getter()._def;case k.ZodPromise:return tJ(e,n);case k.ZodNaN:case k.ZodNever:return Uq(n);case k.ZodEffects:return Eq(e,n);case k.ZodAny:return _q(n);case k.ZodUnknown:return aJ(n);case k.ZodDefault:return Tq(e,n);case k.ZodBranded:return xq(e,n);case k.ZodReadonly:return oJ(e,n);case k.ZodCatch:return Sq(e,n);case k.ZodPipeline:return eJ(e,n);case k.ZodFunction:case k.ZodVoid:case k.ZodSymbol:return;default:return(e=>void 0)(t)}};function X(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==uq)return i}if(r&&!n){let e=cJ(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=sJ(e,e.typeName,t),o=typeof a==`function`?X(a(),t):a;if(o&&lJ(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const cJ=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:gq(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),_q(t)):t.$refStrategy===`seen`?_q(t):void 0}},lJ=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),uJ=(e,t)=>{let n=pq(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:X(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??_q(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=X(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??_q(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function dJ(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function fJ(e,t){return rW(e)?ke.toJSONSchema(e,{target:dJ(t?.target),io:t?.pipeStrategy??`input`}):uJ(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function pJ(e){let t=sW(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=pW(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function mJ(e,t){let n=aW(e,t);if(!n.success)throw n.error;return n.data}var hJ=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(HW,e=>{this._oncancel(e)}),this.setNotificationHandler(oG,e=>{this._onprogress(e)}),this.setRequestHandler(rG,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(hG,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Y(J.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(_G,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(!await this._taskStore.getTask(r,t.sessionId))throw new Y(J.InvalidParams,`Task not found: ${r}`);if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r)if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new Y(e.error.code,e.error.message,e.error.data))}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new Y(J.InvalidParams,`Task not found: ${r}`);if(!lq(i.status))return await this._waitForTaskUpdate(r,t.signal,t.sessionId),await n();if(lq(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r,t.sessionId),{...e,_meta:{...e._meta,[gW]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(vG,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new Y(J.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(bG,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Y(J.InvalidParams,`Task not found: ${e.params.taskId}`);if(lq(n.status))throw new Y(J.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId,t.sessionId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new Y(J.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof Y?e:new Y(J.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Y.fromError(J.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),IW(e)||RW(e)?this._onresponse(e):MW(e)?this._onrequest(e,t):PW(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=Y.fromError(J.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[gW]?.taskId,a=r?.sessionId,o=this._taskStore,s=!0,c;if(i&&o&&this._taskMessageQueue&&a!==void 0&&(s=!1,c=(async()=>{if(!await o.getTask(i,a))throw new Y(J.InvalidParams,`Task not found: ${i}`);s=!0})()),n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:J.MethodNotFound,message:`Method not found`}};if(i&&c){let e={type:`error`,message:t,timestamp:Date.now()};c.then(()=>this._enqueueTaskMessage(i,e,a),()=>r?.send(t)).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)))}else i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let u=TW(e.params)?e.params.task:void 0,d=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,f={signal:l.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(l.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(l.signal.aborted)throw new Y(J.ConnectionClosed,`Request was cancelled`);let a={...r,relatedRequestId:e.id};i&&!a.relatedTask&&(a.relatedTask={taskId:i});let o=a.relatedTask?.taskId??i;return o&&d&&await d.updateTaskStatus(o,`input_required`),await this.request(t,n,a)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:d,taskRequestedTtl:u?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};(c??Promise.resolve()).then(()=>{if(c&&l.signal.aborted)throw new Y(J.ConnectionClosed,`Request was cancelled`);u&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,f)).then(async t=>{if(l.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(l.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:J.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue&&s?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===l&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),IW(e)?n(e):n(new Y(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(IW(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),IW(e)?r(e):r(Y.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof Y?e:new Y(J.InternalError,String(e))}}return}let i;try{let r=await this.request(e,fG,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new Y(J.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},lq(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new Y(J.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new Y(J.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof Y?e:new Y(J.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[gW]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof Y?e:new Y(J.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=aW(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(Y.fromError(J.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},gG,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},yG,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},xG,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[gW]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[gW]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[gW]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=pJ(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=mJ(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=pJ(e);this._notificationHandlers.set(n,n=>{let r=mJ(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n??this._transport?.sessionId,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&MW(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new Y(J.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e,n);t?.pollInterval&&(r=t.pollInterval)}catch{}return new Promise((e,n)=>{if(t.aborted){n(new Y(J.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,r);t.addEventListener(`abort`,()=>{clearTimeout(i),n(new Y(J.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new Y(J.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=mG.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),lq(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new Y(J.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(lq(a.status))throw new Y(J.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=mG.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),lq(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function gJ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _J(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];gJ(a)&&gJ(i)?n[r]={...a,...i}:n[r]=i}return n}var vJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),yJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=vJ();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),Z=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=vJ(),n=yJ();var r=vJ();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var i=yJ();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=O(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=O(this.rhs,e,n),this}get names(){return D(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=O(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(te(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>E(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(ne(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=O(this.condition,e,t),this}get names(){let e=super.names;return D(e,this.condition),this.else&&E(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=O(this.iteration,e,t),this}get names(){return E(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return D(D(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=O(this.iterable,e,t),this}get names(){return E(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&E(e,this.catch.names),this.finally&&E(e,this.finally.names),e}},T=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};T.kind=`catch`;var ee=class extends m{render(e){return`finally`+super.render(e)}};ee.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
334
- `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new T(e),t(e)}return n&&(this._currNode=r.finally=new ee,this.code(n)),this._endBlockNode(T,ee)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-->0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function E(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function D(e,n){return n instanceof t._CodeOrName?E(e,n.names):e}function O(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function te(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function ne(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ce(e)}`}e.not=ne;let re=se(e.operators.AND);function ie(...e){return e.reduce(re)}e.and=ie;let ae=se(e.operators.OR);function oe(...e){return e.reduce(ae)}e.or=oe;function se(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ce(n)} ${e} ${ce(r)}`}function ce(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),Q=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=Z(),n=vJ();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0?!0:(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0||{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0||(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0||Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;let _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),bJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),xJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=Z(),n=Q(),r=bJ();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),SJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=xJ(),n=Z(),r=bJ(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),CJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),wJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),TJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=CJ(),n=wJ(),r=xJ(),i=Z(),a=Q();var o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;let u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
340
+ ]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function Kq(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===k.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:X(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??Cq(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:X(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===k.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=zq(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===k.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===k.ZodBranded&&e.keyType._def.type._def.typeName===k.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=Dq(e.keyType._def,t);return{...n,propertyNames:i}}return n}function qq(e,t){return t.mapStrategy===`record`?Kq(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[X(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||Cq(t),X(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||Cq(t)],minItems:2,maxItems:2}}}function Jq(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function Yq(e){return e.target===`openAi`?void 0:{not:Cq({...e,currentPath:[...e.currentPath,`not`]})}}function Xq(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const Zq={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Qq(e,t){if(t.target===`openApi3`)return $q(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in Zq&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=Zq[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return $q(e,t)}const $q=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>X(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function eJ(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:Zq[e.innerType._def.typeName],nullable:!0}:{type:[Zq[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=X(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=X(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function tJ(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,bq(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?xq(n,`minimum`,r.value,r.message,t):xq(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),xq(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?xq(n,`maximum`,r.value,r.message,t):xq(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),xq(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:xq(n,`multipleOf`,r.value,r.message,t);break}return n}function nJ(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=iJ(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=X(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=rJ(e,t);return o!==void 0&&(r.additionalProperties=o),r}function rJ(e,t){if(e.catchall._def.typeName!==`ZodNever`)return X(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function iJ(e){try{return e.isOptional()}catch{return!0}}const aJ=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return X(e.innerType._def,t);let n=X(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:Cq(t)},n]}:Cq(t)},oJ=(e,t)=>{if(t.pipeStrategy===`input`)return X(e.in._def,t);if(t.pipeStrategy===`output`)return X(e.out._def,t);let n=X(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,X(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function sJ(e,t){return X(e.type._def,t)}function cJ(e,t){let n={type:`array`,uniqueItems:!0,items:X(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&xq(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&xq(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function lJ(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>X(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:X(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>X(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function uJ(e){return{not:Cq(e)}}function dJ(e){return Cq(e)}const fJ=(e,t)=>X(e.innerType._def,t),pJ=(e,t,n)=>{switch(t){case k.ZodString:return zq(e,n);case k.ZodNumber:return tJ(e,n);case k.ZodObject:return nJ(e,n);case k.ZodBigInt:return Tq(e,n);case k.ZodBoolean:return Eq();case k.ZodDate:return kq(e,n);case k.ZodUndefined:return uJ(n);case k.ZodNull:return Xq(n);case k.ZodArray:return wq(e,n);case k.ZodUnion:case k.ZodDiscriminatedUnion:return Qq(e,n);case k.ZodIntersection:return Fq(e,n);case k.ZodTuple:return lJ(e,n);case k.ZodRecord:return Kq(e,n);case k.ZodLiteral:return Iq(e,n);case k.ZodEnum:return Nq(e);case k.ZodNativeEnum:return Jq(e);case k.ZodNullable:return eJ(e,n);case k.ZodOptional:return aJ(e,n);case k.ZodMap:return qq(e,n);case k.ZodSet:return cJ(e,n);case k.ZodLazy:return()=>e.getter()._def;case k.ZodPromise:return sJ(e,n);case k.ZodNaN:case k.ZodNever:return Yq(n);case k.ZodEffects:return Mq(e,n);case k.ZodAny:return Cq(n);case k.ZodUnknown:return dJ(n);case k.ZodDefault:return jq(e,n);case k.ZodBranded:return Dq(e,n);case k.ZodReadonly:return fJ(e,n);case k.ZodCatch:return Oq(e,n);case k.ZodPipeline:return oJ(e,n);case k.ZodFunction:case k.ZodVoid:case k.ZodSymbol:return;default:return(e=>void 0)(t)}};function X(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==gq)return i}if(r&&!n){let e=mJ(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=pJ(e,e.typeName,t),o=typeof a==`function`?X(a(),t):a;if(o&&hJ(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const mJ=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:Sq(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),Cq(t)):t.$refStrategy===`seen`?Cq(t):void 0}},hJ=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),gJ=(e,t)=>{let n=yq(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:X(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??Cq(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=X(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??Cq(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function _J(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function vJ(e,t){return lW(e)?ke.toJSONSchema(e,{target:_J(t?.target),io:t?.pipeStrategy??`input`}):gJ(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function yJ(e){let t=pW(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=yW(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function bJ(e,t){let n=dW(e,t);if(!n.success)throw n.error;return n.data}var xJ=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(JW,e=>{this._oncancel(e)}),this.setNotificationHandler(fG,e=>{this._onprogress(e)}),this.setRequestHandler(lG,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(xG,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Y(J.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(CG,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(!await this._taskStore.getTask(r,t.sessionId))throw new Y(J.InvalidParams,`Task not found: ${r}`);if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r)if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new Y(e.error.code,e.error.message,e.error.data))}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new Y(J.InvalidParams,`Task not found: ${r}`);if(!hq(i.status))return await this._waitForTaskUpdate(r,t.signal,t.sessionId),await n();if(hq(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r,t.sessionId),{...e,_meta:{...e._meta,[SW]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(wG,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new Y(J.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(EG,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Y(J.InvalidParams,`Task not found: ${e.params.taskId}`);if(hq(n.status))throw new Y(J.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId,t.sessionId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new Y(J.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof Y?e:new Y(J.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Y.fromError(J.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),HW(e)||WW(e)?this._onresponse(e):RW(e)?this._onrequest(e,t):BW(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=Y.fromError(J.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[SW]?.taskId,a=r?.sessionId,o=this._taskStore,s=!0,c;if(i&&o&&this._taskMessageQueue&&a!==void 0&&(s=!1,c=(async()=>{if(!await o.getTask(i,a))throw new Y(J.InvalidParams,`Task not found: ${i}`);s=!0})()),n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:J.MethodNotFound,message:`Method not found`}};if(i&&c){let e={type:`error`,message:t,timestamp:Date.now()};c.then(()=>this._enqueueTaskMessage(i,e,a),()=>r?.send(t)).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)))}else i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let u=jW(e.params)?e.params.task:void 0,d=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,f={signal:l.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(l.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(l.signal.aborted)throw new Y(J.ConnectionClosed,`Request was cancelled`);let a={...r,relatedRequestId:e.id};i&&!a.relatedTask&&(a.relatedTask={taskId:i});let o=a.relatedTask?.taskId??i;return o&&d&&await d.updateTaskStatus(o,`input_required`),await this.request(t,n,a)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:d,taskRequestedTtl:u?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};(c??Promise.resolve()).then(()=>{if(c&&l.signal.aborted)throw new Y(J.ConnectionClosed,`Request was cancelled`);u&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,f)).then(async t=>{if(l.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(l.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:J.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue&&s?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===l&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),HW(e)?n(e):n(new Y(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(HW(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),HW(e)?r(e):r(Y.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof Y?e:new Y(J.InternalError,String(e))}}return}let i;try{let r=await this.request(e,vG,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new Y(J.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},hq(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new Y(J.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new Y(J.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof Y?e:new Y(J.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[SW]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof Y?e:new Y(J.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=dW(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(Y.fromError(J.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},SG,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},TG,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},DG,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[SW]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[SW]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[SW]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=yJ(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=bJ(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=yJ(e);this._notificationHandlers.set(n,n=>{let r=bJ(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n??this._transport?.sessionId,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&RW(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new Y(J.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e,n);t?.pollInterval&&(r=t.pollInterval)}catch{}return new Promise((e,n)=>{if(t.aborted){n(new Y(J.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,r);t.addEventListener(`abort`,()=>{clearTimeout(i),n(new Y(J.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new Y(J.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=bG.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),hq(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new Y(J.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(hq(a.status))throw new Y(J.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=bG.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),hq(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function SJ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function CJ(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];SJ(a)&&SJ(i)?n[r]={...a,...i}:n[r]=i}return n}var wJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),TJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=wJ();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),Z=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=wJ(),n=TJ();var r=wJ();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var i=TJ();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=O(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=O(this.rhs,e,n),this}get names(){return D(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=O(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(te(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>E(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(ne(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=O(this.condition,e,t),this}get names(){let e=super.names;return D(e,this.condition),this.else&&E(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=O(this.iteration,e,t),this}get names(){return E(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return D(D(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=O(this.iterable,e,t),this}get names(){return E(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&E(e,this.catch.names),this.finally&&E(e,this.finally.names),e}},T=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};T.kind=`catch`;var ee=class extends m{render(e){return`finally`+super.render(e)}};ee.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
341
+ `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new T(e),t(e)}return n&&(this._currNode=r.finally=new ee,this.code(n)),this._endBlockNode(T,ee)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-->0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function E(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function D(e,n){return n instanceof t._CodeOrName?E(e,n.names):e}function O(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function te(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function ne(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ce(e)}`}e.not=ne;let re=se(e.operators.AND);function ie(...e){return e.reduce(re)}e.and=ie;let ae=se(e.operators.OR);function oe(...e){return e.reduce(ae)}e.or=oe;function se(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ce(n)} ${e} ${ce(r)}`}function ce(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),Q=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=Z(),n=wJ();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0?!0:(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0||{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0||(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0||Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;let _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),EJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),DJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=Z(),n=Q(),r=EJ();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),OJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=DJ(),n=Z(),r=EJ(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),kJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),AJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),jJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=kJ(),n=AJ(),r=DJ(),i=Z(),a=Q();var o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;let u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
335
342
  || (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${s} === "boolean" || ${a} === null
336
343
  || (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(c,(0,i._)`+${a}`);return;case`boolean`:r.elseIf((0,i._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(c,!1).elseIf((0,i._)`${a} === "true" || ${a} === 1`).assign(c,!0);return;case`null`:r.elseIf((0,i._)`${a} === "" || ${a} === 0 || ${a} === false`),r.assign(c,null);return;case`array`:r.elseIf((0,i._)`${s} === "string" || ${s} === "number"
337
- || ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;let g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),EJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=Z(),n=Q();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),DJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=Z(),n=Q(),r=bJ(),i=Q();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;let h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),OJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=Z(),n=bJ(),r=DJ(),i=xJ();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),kJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=Z(),n=Q();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),AJ=j(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),jJ=j(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else(p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),MJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=Q(),n=AJ(),r=jJ(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;let o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;let d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;let m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),NJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=SJ(),n=TJ(),r=wJ(),i=TJ(),a=EJ(),o=OJ(),s=kJ(),c=Z(),l=bJ(),u=MJ(),d=Q(),f=xJ();function p(e){if(S(e)&&(w(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&te(e),E(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),T(e),ne(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(w(e),x(e))){C(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function C(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&te(e),D(e),O(e);let a=r.const(`_errs`,l.default.errors);T(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),ee(e)}function T(e,t){if(e.opts.jtd)return ie(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);ie(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function ee(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function E(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function D(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function O(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function te({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function ne(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&re(e),t.return((0,c._)`${l.default.errors} === 0`))}function re({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function ie(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>he(e,`$ref`,h.all.$ref.definition));return}p.jtd||oe(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),ae(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):ae(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function ae(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&he(e,n.keyword,n.definition,t.type)})}function oe(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(se(e,t),e.opts.allowUnionTypes||ce(e,t),le(e,e.dataTypes))}function se(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{de(e.dataTypes,t)||pe(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),fe(e,t)}}function ce(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&pe(e,`use allowUnionTypes to allow union type keyword`)}function le(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>ue(t,e))&&pe(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function ue(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function de(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function fe(e,t){let n=[];for(let r of e.dataTypes)de(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function pe(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var me=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,ve(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=me;function he(e,t,n,r){let i=new me(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}let ge=/^\/(?:[^~]|~0|~1)*$/,_e=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ve(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!ge.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=_e.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=ve})),PJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),FJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=MJ();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),IJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=Z(),n=PJ(),r=bJ(),i=MJ(),a=Q(),o=NJ();var s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;let h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),LJ=j(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),RJ=j(((e,t)=>{let n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),i=RegExp.prototype.test.bind(/^\d*$/u),a=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),o=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),s=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),c=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),l=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),u=Array(256);{let e=`0123456789ABCDEF`;for(let t=0;t<256;t++)u[t]=`%`+e[t>>4]+e[t&15]}function d(e){return e<2048?u[192|e>>6]+u[128|e&63]:e<65536?u[224|e>>12]+u[128|e>>6&63]+u[128|e&63]:u[240|e>>18]+u[128|e>>12&63]+u[128|e>>6&63]+u[128|e&63]}function f(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}let p=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),m=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),h=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),g=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function _(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!h(e[t])){if(e[t]===`%`&&t+2<e.length&&a(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function v(e){let t=-1,n=0,r=-1,i=0;for(let a=0;a<e.length;a++)e[a]===`0`?(r===-1&&(r=a),i++,i>n&&(n=i,t=r)):(r=-1,i=0);if(n<2)return e.join(`:`);let a=e.slice(0,t).join(`:`),o=e.slice(t+n).join(`:`);return a+`::`+o}function y(e){let t=e.indexOf(`::`);if(t!==-1&&e.indexOf(`::`,t+1)!==-1)return;let n=t===-1?e.split(`:`):e.slice(0,t).split(`:`),i=t===-1?[]:e.slice(t+2).split(`:`);t!==-1&&(n.length===1&&n[0]===``&&(n.length=0),i.length===1&&i[0]===``&&(i.length=0));let a=n.concat(i),o=0;for(let e=0;e<a.length;e++){let n=a[e];if(n===``)return;if(n.indexOf(`.`)!==-1){if(e!==a.length-1||t!==-1&&i.length===0||!r(n))return;o+=2;continue}if(!p(n))return;a[e]=parseInt(n,16).toString(16),o++}if(t===-1)return o===8?v(a):void 0;if(o>=8)return;let s=a.slice(0,n.length);for(let e=o;e<8;e++)s.push(`0`);for(let e=n.length;e<a.length;e++)s.push(a[e]);return v(s)}function b(e){let t=e[0]===`[`&&e[e.length-1]===`]`;if((e[0]===`[`||e[e.length-1]===`]`)&&!t)return{host:e,isIPV6:!1,error:!0};let n=t?e.slice(1,-1):e;if(t&&m(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(x(n,`:`)<2)return{host:e,isIPV6:!1,error:t};let r=``,i=n.indexOf(`%`);if(i!==-1){let t=n.slice(i,i+3).toLowerCase()===`%25`?3:1;if(r=n.slice(i+t),!_(r))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,i)}let a=y(n);return a===void 0?{host:e,isIPV6:!1,error:!0}:{host:a+(r?`%`+r:``),escapedHost:a+(r?`%25`+r:``),isIPV6:!0}}function x(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function S(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}else{n.push(t);break}}else if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}else if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}else n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}let C={"@":`%40`,"/":`%2F`,"?":`%3F`,"#":`%23`,":":`%3A`},w=/[@/?#:]/g,T=/[@/?#]/g;function ee(e,t){let n=t?T:w;return n.lastIndex=0,e.replace(n,e=>C[e])}function E(e,t=!1){if(e.indexOf(`%`)===-1)return e;let n=``;for(let r=0;r<e.length;r++){if(e[r]===`%`&&r+2<e.length){let i=e.slice(r+1,r+3);if(a(i)){let e=i.toUpperCase(),a=String.fromCharCode(parseInt(e,16));t&&o(a)?n+=a:n+=`%`+e,r+=2;continue}}n+=e[r]}return n}function D(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));i!==`.`&&o(i)?t+=i:t+=`%`+e,n+=2;continue}}if(s(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=ae(i)?r:u[i];else if(i<55296||i>57343)t+=d(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=d(65536+(i-55296<<10)+(r-56320)),n++):t+=d(65533)}else t+=d(65533)}}return t}function O(e,t=!1){let n=``,r=t&&e[0]!==`/`;for(let t=0;t<e.length;t++){let i=e[t];if(i===`%`&&t+2<e.length){let r=e.slice(t+1,t+3);if(a(r)){n+=`%`+r.toUpperCase(),t+=2;continue}}if(i===`/`&&(r=!1),s(i)&&(i!==`:`||!r))n+=i;else{let r=e.charCodeAt(t);if(r<128)n+=u[r];else if(r<55296||r>57343)n+=d(r);else if(r<=56319&&t+1<e.length){let i=e.charCodeAt(t+1);i>=56320&&i<=57343?(n+=d(65536+(r-55296<<10)+(i-56320)),t++):n+=d(65533)}else n+=d(65533)}}return n}function te(e,t){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(i===`%`&&r+2<e.length){let t=e.slice(r+1,r+3);if(a(t)){n+=`%`+t.toUpperCase(),r+=2;continue}}if(t(i))n+=i;else{let t=e.charCodeAt(r);if(t<128)n+=u[t];else if(t<55296||t>57343)n+=d(t);else if(t<=56319&&r+1<e.length){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(n+=d(65536+(t-55296<<10)+(i-56320)),r++):n+=d(65533)}else n+=d(65533)}}return n}function ne(e){return te(e,l)}function re(e){return te(e,c)}function ie(e){return te(e,c)}function ae(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===42||e===43||e===45||e===46||e===47||e===64||e===95}function oe(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));o(i)?t+=i:t+=`%`+e,n+=2;continue}}if(c(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=ae(i)?r:u[i];else if(i<55296||i>57343)t+=d(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=d(65536+(i-55296<<10)+(r-56320)),n++):t+=d(65533)}else t+=d(65533)}}return t}function se(e){let t=``;for(let n=0;n<e.length;n++){if(e[n]===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){t+=`%`+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function ce(e){let t=[];if(e.userinfo!==void 0&&(t.push(ne(e.userinfo)),t.push(`@`)),e.host!==void 0){let n=e.host;if(!r(n)){let e=b(n);e.isIPV6!==!0&&e.isIPVFuture!==!0&&(n=E(n,!0),e=b(n)),n=e.isIPV6===!0||e.isIPVFuture===!0?`[${e.escapedHost}]`:ee(n,!1)}t.push(n)}if(typeof e.port==`number`||typeof e.port==`string`){let n=String(e.port);if(!i(n))throw TypeError(`URI port is malformed.`);t.push(`:`),t.push(n)}return t.length?t.join(``):void 0}t.exports={nonSimpleDomain:g,recomposeAuthority:ce,reescapeHostDelimiters:ee,normalizePercentEncoding:E,normalizePathEncoding:D,serializePathEncoding:O,normalizeQueryFragmentEncoding:oe,encodeUserinfo:ne,encodeQuery:re,encodeFragment:ie,escapePreservingEscapes:se,removeDotSegments:S,isIPv4:r,isUUID:n,normalizeIPv6:b,stringArrayToHexStripped:f}})),zJ=j(((e,t)=>{let{isUUID:n}=RJ(),r=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let t=e.resourceName.indexOf(`?`),n=t===-1?e.resourceName:e.resourceName.slice(0,t);e.path=n&&n!==`/`?n:void 0,e.query=t===-1?void 0:e.resourceName.slice(t+1),e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n&&n[0]===e.path){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=y(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=y(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={http:h,https:g,ws:_,wss:{scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},urn:{scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},"urn:uuid":{scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0}};Object.setPrototypeOf(v,null);function y(e){return e&&(v[e]||v[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:v,isValidSchemeName:a,getSchemeHandler:y}})),BJ=j(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizePercentEncoding:a,normalizePathEncoding:o,serializePathEncoding:s,normalizeQueryFragmentEncoding:c,encodeQuery:l,encodeFragment:u,reescapeHostDelimiters:d,isIPv4:f,nonSimpleDomain:p}=RJ(),{SCHEMES:m,getSchemeHandler:h}=zJ(),g=/^[A-Za-z][A-Za-z0-9+.-]*$/u,_=`URI scheme is malformed.`;function v(e){let t=unescape(String(e));if(!g.test(t))throw TypeError(_);return t}function y(e,t){return typeof e==`string`?e=ae(e,t):typeof e==`object`&&(e=ie(C(e,t),t)),e}function b(e,t,r){let i=r?Object.assign({scheme:`null`},r):{scheme:`null`},{parsed:a,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:c,malformedHost:l,malformedScheme:u}=re(e,i),{parsed:d,malformedAuthorityOrPort:p,malformedPercentEncoding:m,malformedSchemeSpecific:g,malformedHost:_,malformedScheme:v}=re(t,i);if(o||p||s||m||c||g||l||_||u||v)throw Error(a.error||d.error||`URI is malformed.`);let y=x(a,d,i,!0),b=h(r&&r.scheme||y.scheme),S=y.host,w=S!==void 0&&S!==``&&(f(S)||n(S).isIPV6);ne(y,r||{},b,w);let T=S&&S.indexOf(`%`)!==-1&&!/\P{ASCII}/u.test(S);if(y.error&&!T)throw Error(y.error);return i.skipEscape=!0,C(y,i)}function x(e,t,n,i){let a={};return i||(e=ie(C(e,n),n),t=ie(C(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?a.path=`/`+t.path:e.path?a.path=e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:a.path=t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,t.query===void 0?a.query=e.query:a.query=t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function S(e,t,n){let r=se(e,n),i=se(t,n);return r!==void 0&&i!==void 0&&r===i}function C(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},o=Object.assign({},t),c=[];n.scheme&&=v(n.scheme);let d=h(o.scheme||n.scheme);d&&d.serialize&&d.serialize(n,o);let f=n.userinfo!==void 0||n.host!==void 0||n.port!==void 0,p=!o.skipEscape&&n.scheme===void 0&&!f;n.path!==void 0&&(o.skipEscape?n.path=a(n.path):n.path=s(n.path,p)),o.reference!==`suffix`&&n.scheme&&(n.scheme=v(n.scheme),c.push(n.scheme,`:`));let m=i(n);if(m!==void 0&&(o.reference!==`suffix`&&c.push(`//`),c.push(m),n.path&&n.path[0]!==`/`&&c.push(`/`)),n.path!==void 0){let e=n.path;!o.absolutePath&&(!d||!d.absolutePath)&&(e=r(e)),p&&(e=s(e,!0)),m===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),c.push(e)}return n.query!==void 0&&c.push(`?`,l(n.query)),n.fragment!==void 0&&c.push(`#`,u(n.fragment)),c.join(``)}let w=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,T=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,ee=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function E(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!==`/`)return`URI path must start with "/" when authority is present.`;if(typeof e.port==`number`&&(e.port<0||e.port>65535))return`URI port is malformed.`}function D(e){if(e===void 0)return!1;let t=e.indexOf(`%`);for(;t!==-1;){if(t+2>=e.length||!/^[\da-f]{2}$/iu.test(e.slice(t+1,t+3)))return!0;t=e.indexOf(`%`,t+3)}return!1}function O(e){return e[0]===`[`&&e[e.length-1]===`]`}function te(e){let t=e[4];return D(e[3])||t!==void 0&&!O(t)&&D(t)||D(e[6])||D(e[7])||D(e[8])}function ne(e,t,n,r){if(!t.unicodeSupport&&(!n||!n.unicodeSupport)&&e.host&&!O(e.host)&&(t.domainHost||n&&n.domainHost)&&r===!1&&p(e.host))try{e.host=new URL(`http://`+e.host).hostname}catch(t){return e.error=e.error||`Host's domain name can not be converted to ASCII: `+t,!0}return!1}function re(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},s=!1,l=!1,u=!1,p=!1,v=!1,y=!1,b=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let x=e.match(T);x!==null&&x[1].indexOf(`\\`)!==-1&&(i.error=`URI authority must not contain a literal backslash.`,s=!0);let S=e.match(ee);if(S!==null){let e=S[1],t=e.replace(/[\t\n\r]/g,``);t.length>=2&&(t.slice(0,2)===`//`?e.length!==t.length&&(i.error=i.error||`URI authority introducer must not contain whitespace.`,s=!0):(i.error=i.error||`URI authority must not contain a literal backslash.`,s=!0))}let C=e.match(w);if(C){if(i.scheme=C[1],i.userinfo=C[3],i.host=C[4],i.port=parseInt(C[5],10),i.path=C[6]||``,i.query=C[7],i.fragment=C[8],i.scheme!==void 0){let e=unescape(i.scheme);g.test(e)?i.scheme=e.toLowerCase():(i.error=i.error||_,y=!0)}l=te(C),l&&(i.error=i.error||`URI contains malformed percent-encoding.`),isNaN(i.port)&&(i.port=C[5]);let t=E(i,C);if(t!==void 0&&(i.error=i.error||t,s=!0),i.host)if(f(i.host)===!1){let e=O(i.host),t=i.host.indexOf(`[`)!==-1||i.host.indexOf(`]`)!==-1,r=n(i.host);b=r.isIPV6||r.isIPVFuture===!0,v=t&&(!e||r.error===!0),i.host=b?r.host:r.host.toLowerCase(),v&&(i.error=i.error||`URI host is malformed.`,s=!0)}else b=!0;i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?i.reference=`same-document`:i.scheme===void 0?i.reference=`relative`:i.fragment===void 0?i.reference=`absolute`:i.reference=`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let x=h(r.scheme||i.scheme);if(v||(p=ne(i,r,x,b)),e.indexOf(`%`)!==-1&&i.host!==void 0&&!v){let e=b?i.host:a(i.host,!0);b||(e=a(e.toLowerCase())),i.host=d(e,b)}(!x||x&&!x.skipNormalize)&&(i.path&&=o(i.path),i.query&&=c(i.query),i.fragment&&=c(i.fragment)),x&&x.parse&&(x.parse(i,r),x===m.urn&&i.nid===void 0&&(u=!0))}else i.error=i.error||`URI can not be parsed.`;return{parsed:i,malformedAuthorityOrPort:s,malformedPercentEncoding:l,malformedSchemeSpecific:u,malformedHost:p,malformedScheme:y}}function ie(e,t){return re(e,t).parsed}function ae(e,t){return oe(e,t).normalized}function oe(e,t){let{parsed:n,malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}=re(e,t);return{normalized:r||i||a||o||s?e:C(n,t),malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}}function se(e,t){if(typeof e!=`string`&&typeof e!=`object`)return;let n;try{n=typeof e==`string`?e:C(e,t)}catch{return}let{normalized:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:o,malformedHost:s,malformedScheme:c}=oe(n,t);return i||a||o||s||c?void 0:r}let ce={SCHEMES:m,normalize:y,resolve:b,resolveComponent:x,equal:S,serialize:C,parse:ie};t.exports=ce,t.exports.default=ce,t.exports.fastUri=ce})),VJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=BJ();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),HJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=NJ();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=Z();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});let r=PJ(),i=FJ(),a=CJ(),o=IJ(),s=Z(),c=MJ(),l=TJ(),u=Q(),d=LJ(),f=VJ(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=E(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,`NOT SUPPORTED`),b.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=T.call(this),e.formats&&C.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&w.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=x.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=x.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(O.call(this,n,t),!t)return(0,u.eachItem)(n,e=>te.call(this,e)),this;re.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>te.call(this,e,r):e=>r.type.forEach(t=>te.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=ae(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function b(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function x(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function C(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function w(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function T(){let e={...this.opts};for(let t of m)delete e[t];return e}let ee={log(){},warn(){},error(){}};function E(e){if(e===!1)return ee;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let D=/^[a-z_$][a-z0-9_$:-]*$/i;function O(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!D.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function te(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?ne.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function ne(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function re(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=ae(t)),e.validateSchema=this.compile(t,!0))}let ie={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function ae(e){return{anyOf:[e,ie]}}})),UJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),WJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=FJ(),n=DJ(),r=Z(),i=bJ(),a=IJ(),o=Q(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);if(h instanceof a.SchemaEnv)return _(h);return v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0)if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}if(l.items!==!0)if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}e.callRef=l,e.default=s})),GJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=UJ(),n=WJ();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),KJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),qJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),JJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),YJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z(),n=Q(),r=JJ();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),XJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=DJ(),n=Q(),r=Z();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),ZJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),QJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=DJ(),n=Z(),r=Q();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),$J=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),eY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=AJ();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),tY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=TJ(),n=Z(),r=Q(),i=eY();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),nY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z(),n=Q(),r=eY();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),rY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z(),n=Q(),r=eY();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),iY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=KJ(),n=qJ(),r=YJ(),i=XJ(),a=ZJ(),o=QJ(),s=$J(),c=tY(),l=nY(),u=rY();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),aY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=Z(),n=Q(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),oY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=Z(),n=Q(),r=DJ(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),sY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=oY();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),cY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z(),n=Q(),r=DJ(),i=aY();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),lY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z(),n=Q();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),uY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=Z(),n=Q(),r=DJ();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
344
+ || ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;let g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),MJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=Z(),n=Q();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),NJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=Z(),n=Q(),r=EJ(),i=Q();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;let h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),PJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=Z(),n=EJ(),r=NJ(),i=DJ();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),FJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=Z(),n=Q();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),IJ=j(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),LJ=j(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else(p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),RJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=Q(),n=IJ(),r=LJ(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;let o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;let d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;let m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),zJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=OJ(),n=jJ(),r=AJ(),i=jJ(),a=MJ(),o=PJ(),s=FJ(),c=Z(),l=EJ(),u=RJ(),d=Q(),f=DJ();function p(e){if(S(e)&&(w(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&te(e),E(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),T(e),ne(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(w(e),x(e))){C(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function C(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&te(e),D(e),O(e);let a=r.const(`_errs`,l.default.errors);T(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),ee(e)}function T(e,t){if(e.opts.jtd)return ie(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);ie(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function ee(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function E(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function D(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function O(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function te({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function ne(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&re(e),t.return((0,c._)`${l.default.errors} === 0`))}function re({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function ie(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>he(e,`$ref`,h.all.$ref.definition));return}p.jtd||oe(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),ae(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):ae(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function ae(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&he(e,n.keyword,n.definition,t.type)})}function oe(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(se(e,t),e.opts.allowUnionTypes||ce(e,t),le(e,e.dataTypes))}function se(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{de(e.dataTypes,t)||pe(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),fe(e,t)}}function ce(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&pe(e,`use allowUnionTypes to allow union type keyword`)}function le(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>ue(t,e))&&pe(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function ue(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function de(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function fe(e,t){let n=[];for(let r of e.dataTypes)de(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function pe(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var me=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,ve(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=me;function he(e,t,n,r){let i=new me(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}let ge=/^\/(?:[^~]|~0|~1)*$/,_e=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ve(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!ge.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=_e.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=ve})),BJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),VJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=RJ();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),HJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=Z(),n=BJ(),r=EJ(),i=RJ(),a=Q(),o=zJ();var s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;let h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),UJ=j(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),WJ=j(((e,t)=>{let n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),i=RegExp.prototype.test.bind(/^\d*$/u),a=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),o=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),s=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),c=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),l=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),u=Array(256);{let e=`0123456789ABCDEF`;for(let t=0;t<256;t++)u[t]=`%`+e[t>>4]+e[t&15]}function d(e){return e<2048?u[192|e>>6]+u[128|e&63]:e<65536?u[224|e>>12]+u[128|e>>6&63]+u[128|e&63]:u[240|e>>18]+u[128|e>>12&63]+u[128|e>>6&63]+u[128|e&63]}function f(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}let p=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),m=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),h=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),g=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function _(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!h(e[t])){if(e[t]===`%`&&t+2<e.length&&a(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function v(e){let t=-1,n=0,r=-1,i=0;for(let a=0;a<e.length;a++)e[a]===`0`?(r===-1&&(r=a),i++,i>n&&(n=i,t=r)):(r=-1,i=0);if(n<2)return e.join(`:`);let a=e.slice(0,t).join(`:`),o=e.slice(t+n).join(`:`);return a+`::`+o}function y(e){let t=e.indexOf(`::`);if(t!==-1&&e.indexOf(`::`,t+1)!==-1)return;let n=t===-1?e.split(`:`):e.slice(0,t).split(`:`),i=t===-1?[]:e.slice(t+2).split(`:`);t!==-1&&(n.length===1&&n[0]===``&&(n.length=0),i.length===1&&i[0]===``&&(i.length=0));let a=n.concat(i),o=0;for(let e=0;e<a.length;e++){let n=a[e];if(n===``)return;if(n.indexOf(`.`)!==-1){if(e!==a.length-1||t!==-1&&i.length===0||!r(n))return;o+=2;continue}if(!p(n))return;a[e]=parseInt(n,16).toString(16),o++}if(t===-1)return o===8?v(a):void 0;if(o>=8)return;let s=a.slice(0,n.length);for(let e=o;e<8;e++)s.push(`0`);for(let e=n.length;e<a.length;e++)s.push(a[e]);return v(s)}function b(e){let t=e[0]===`[`&&e[e.length-1]===`]`;if((e[0]===`[`||e[e.length-1]===`]`)&&!t)return{host:e,isIPV6:!1,error:!0};let n=t?e.slice(1,-1):e;if(t&&m(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(x(n,`:`)<2)return{host:e,isIPV6:!1,error:t};let r=``,i=n.indexOf(`%`);if(i!==-1){let t=n.slice(i,i+3).toLowerCase()===`%25`?3:1;if(r=n.slice(i+t),!_(r))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,i)}let a=y(n);return a===void 0?{host:e,isIPV6:!1,error:!0}:{host:a+(r?`%`+r:``),escapedHost:a+(r?`%25`+r:``),isIPV6:!0}}function x(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function S(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}else{n.push(t);break}}else if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}else if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}else n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}let C={"@":`%40`,"/":`%2F`,"?":`%3F`,"#":`%23`,":":`%3A`},w=/[@/?#:]/g,T=/[@/?#]/g;function ee(e,t){let n=t?T:w;return n.lastIndex=0,e.replace(n,e=>C[e])}function E(e,t=!1){if(e.indexOf(`%`)===-1)return e;let n=``;for(let r=0;r<e.length;r++){if(e[r]===`%`&&r+2<e.length){let i=e.slice(r+1,r+3);if(a(i)){let e=i.toUpperCase(),a=String.fromCharCode(parseInt(e,16));t&&o(a)?n+=a:n+=`%`+e,r+=2;continue}}n+=e[r]}return n}function D(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));i!==`.`&&o(i)?t+=i:t+=`%`+e,n+=2;continue}}if(s(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=ae(i)?r:u[i];else if(i<55296||i>57343)t+=d(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=d(65536+(i-55296<<10)+(r-56320)),n++):t+=d(65533)}else t+=d(65533)}}return t}function O(e,t=!1){let n=``,r=t&&e[0]!==`/`;for(let t=0;t<e.length;t++){let i=e[t];if(i===`%`&&t+2<e.length){let r=e.slice(t+1,t+3);if(a(r)){n+=`%`+r.toUpperCase(),t+=2;continue}}if(i===`/`&&(r=!1),s(i)&&(i!==`:`||!r))n+=i;else{let r=e.charCodeAt(t);if(r<128)n+=u[r];else if(r<55296||r>57343)n+=d(r);else if(r<=56319&&t+1<e.length){let i=e.charCodeAt(t+1);i>=56320&&i<=57343?(n+=d(65536+(r-55296<<10)+(i-56320)),t++):n+=d(65533)}else n+=d(65533)}}return n}function te(e,t){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(i===`%`&&r+2<e.length){let t=e.slice(r+1,r+3);if(a(t)){n+=`%`+t.toUpperCase(),r+=2;continue}}if(t(i))n+=i;else{let t=e.charCodeAt(r);if(t<128)n+=u[t];else if(t<55296||t>57343)n+=d(t);else if(t<=56319&&r+1<e.length){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(n+=d(65536+(t-55296<<10)+(i-56320)),r++):n+=d(65533)}else n+=d(65533)}}return n}function ne(e){return te(e,l)}function re(e){return te(e,c)}function ie(e){return te(e,c)}function ae(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===42||e===43||e===45||e===46||e===47||e===64||e===95}function oe(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));o(i)?t+=i:t+=`%`+e,n+=2;continue}}if(c(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=ae(i)?r:u[i];else if(i<55296||i>57343)t+=d(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=d(65536+(i-55296<<10)+(r-56320)),n++):t+=d(65533)}else t+=d(65533)}}return t}function se(e){let t=``;for(let n=0;n<e.length;n++){if(e[n]===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){t+=`%`+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function ce(e){let t=[];if(e.userinfo!==void 0&&(t.push(ne(e.userinfo)),t.push(`@`)),e.host!==void 0){let n=e.host;if(!r(n)){let e=b(n);e.isIPV6!==!0&&e.isIPVFuture!==!0&&(n=E(n,!0),e=b(n)),n=e.isIPV6===!0||e.isIPVFuture===!0?`[${e.escapedHost}]`:ee(n,!1)}t.push(n)}if(typeof e.port==`number`||typeof e.port==`string`){let n=String(e.port);if(!i(n))throw TypeError(`URI port is malformed.`);t.push(`:`),t.push(n)}return t.length?t.join(``):void 0}t.exports={nonSimpleDomain:g,recomposeAuthority:ce,reescapeHostDelimiters:ee,normalizePercentEncoding:E,normalizePathEncoding:D,serializePathEncoding:O,normalizeQueryFragmentEncoding:oe,encodeUserinfo:ne,encodeQuery:re,encodeFragment:ie,escapePreservingEscapes:se,removeDotSegments:S,isIPv4:r,isUUID:n,normalizeIPv6:b,stringArrayToHexStripped:f}})),GJ=j(((e,t)=>{let{isUUID:n}=WJ(),r=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let t=e.resourceName.indexOf(`?`),n=t===-1?e.resourceName:e.resourceName.slice(0,t);e.path=n&&n!==`/`?n:void 0,e.query=t===-1?void 0:e.resourceName.slice(t+1),e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n&&n[0]===e.path){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=y(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=y(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={http:h,https:g,ws:_,wss:{scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},urn:{scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},"urn:uuid":{scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0}};Object.setPrototypeOf(v,null);function y(e){return e&&(v[e]||v[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:v,isValidSchemeName:a,getSchemeHandler:y}})),KJ=j(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizePercentEncoding:a,normalizePathEncoding:o,serializePathEncoding:s,normalizeQueryFragmentEncoding:c,encodeQuery:l,encodeFragment:u,reescapeHostDelimiters:d,isIPv4:f,nonSimpleDomain:p}=WJ(),{SCHEMES:m,getSchemeHandler:h}=GJ(),g=/^[A-Za-z][A-Za-z0-9+.-]*$/u,_=`URI scheme is malformed.`;function v(e){let t=unescape(String(e));if(!g.test(t))throw TypeError(_);return t}function y(e,t){return typeof e==`string`?e=ae(e,t):typeof e==`object`&&(e=ie(C(e,t),t)),e}function b(e,t,r){let i=r?Object.assign({scheme:`null`},r):{scheme:`null`},{parsed:a,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:c,malformedHost:l,malformedScheme:u}=re(e,i),{parsed:d,malformedAuthorityOrPort:p,malformedPercentEncoding:m,malformedSchemeSpecific:g,malformedHost:_,malformedScheme:v}=re(t,i);if(o||p||s||m||c||g||l||_||u||v)throw Error(a.error||d.error||`URI is malformed.`);let y=x(a,d,i,!0),b=h(r&&r.scheme||y.scheme),S=y.host,w=S!==void 0&&S!==``&&(f(S)||n(S).isIPV6);ne(y,r||{},b,w);let T=S&&S.indexOf(`%`)!==-1&&!/\P{ASCII}/u.test(S);if(y.error&&!T)throw Error(y.error);return i.skipEscape=!0,C(y,i)}function x(e,t,n,i){let a={};return i||(e=ie(C(e,n),n),t=ie(C(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?a.path=`/`+t.path:e.path?a.path=e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:a.path=t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,t.query===void 0?a.query=e.query:a.query=t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function S(e,t,n){let r=se(e,n),i=se(t,n);return r!==void 0&&i!==void 0&&r===i}function C(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},o=Object.assign({},t),c=[];n.scheme&&=v(n.scheme);let d=h(o.scheme||n.scheme);d&&d.serialize&&d.serialize(n,o);let f=n.userinfo!==void 0||n.host!==void 0||n.port!==void 0,p=!o.skipEscape&&n.scheme===void 0&&!f;n.path!==void 0&&(o.skipEscape?n.path=a(n.path):n.path=s(n.path,p)),o.reference!==`suffix`&&n.scheme&&(n.scheme=v(n.scheme),c.push(n.scheme,`:`));let m=i(n);if(m!==void 0&&(o.reference!==`suffix`&&c.push(`//`),c.push(m),n.path&&n.path[0]!==`/`&&c.push(`/`)),n.path!==void 0){let e=n.path;!o.absolutePath&&(!d||!d.absolutePath)&&(e=r(e)),p&&(e=s(e,!0)),m===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),c.push(e)}return n.query!==void 0&&c.push(`?`,l(n.query)),n.fragment!==void 0&&c.push(`#`,u(n.fragment)),c.join(``)}let w=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,T=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,ee=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function E(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!==`/`)return`URI path must start with "/" when authority is present.`;if(typeof e.port==`number`&&(e.port<0||e.port>65535))return`URI port is malformed.`}function D(e){if(e===void 0)return!1;let t=e.indexOf(`%`);for(;t!==-1;){if(t+2>=e.length||!/^[\da-f]{2}$/iu.test(e.slice(t+1,t+3)))return!0;t=e.indexOf(`%`,t+3)}return!1}function O(e){return e[0]===`[`&&e[e.length-1]===`]`}function te(e){let t=e[4];return D(e[3])||t!==void 0&&!O(t)&&D(t)||D(e[6])||D(e[7])||D(e[8])}function ne(e,t,n,r){if(!t.unicodeSupport&&(!n||!n.unicodeSupport)&&e.host&&!O(e.host)&&(t.domainHost||n&&n.domainHost)&&r===!1&&p(e.host))try{e.host=new URL(`http://`+e.host).hostname}catch(t){return e.error=e.error||`Host's domain name can not be converted to ASCII: `+t,!0}return!1}function re(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},s=!1,l=!1,u=!1,p=!1,v=!1,y=!1,b=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let x=e.match(T);x!==null&&x[1].indexOf(`\\`)!==-1&&(i.error=`URI authority must not contain a literal backslash.`,s=!0);let S=e.match(ee);if(S!==null){let e=S[1],t=e.replace(/[\t\n\r]/g,``);t.length>=2&&(t.slice(0,2)===`//`?e.length!==t.length&&(i.error=i.error||`URI authority introducer must not contain whitespace.`,s=!0):(i.error=i.error||`URI authority must not contain a literal backslash.`,s=!0))}let C=e.match(w);if(C){if(i.scheme=C[1],i.userinfo=C[3],i.host=C[4],i.port=parseInt(C[5],10),i.path=C[6]||``,i.query=C[7],i.fragment=C[8],i.scheme!==void 0){let e=unescape(i.scheme);g.test(e)?i.scheme=e.toLowerCase():(i.error=i.error||_,y=!0)}l=te(C),l&&(i.error=i.error||`URI contains malformed percent-encoding.`),isNaN(i.port)&&(i.port=C[5]);let t=E(i,C);if(t!==void 0&&(i.error=i.error||t,s=!0),i.host)if(f(i.host)===!1){let e=O(i.host),t=i.host.indexOf(`[`)!==-1||i.host.indexOf(`]`)!==-1,r=n(i.host);b=r.isIPV6||r.isIPVFuture===!0,v=t&&(!e||r.error===!0),i.host=b?r.host:r.host.toLowerCase(),v&&(i.error=i.error||`URI host is malformed.`,s=!0)}else b=!0;i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?i.reference=`same-document`:i.scheme===void 0?i.reference=`relative`:i.fragment===void 0?i.reference=`absolute`:i.reference=`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let x=h(r.scheme||i.scheme);if(v||(p=ne(i,r,x,b)),e.indexOf(`%`)!==-1&&i.host!==void 0&&!v){let e=b?i.host:a(i.host,!0);b||(e=a(e.toLowerCase())),i.host=d(e,b)}(!x||x&&!x.skipNormalize)&&(i.path&&=o(i.path),i.query&&=c(i.query),i.fragment&&=c(i.fragment)),x&&x.parse&&(x.parse(i,r),x===m.urn&&i.nid===void 0&&(u=!0))}else i.error=i.error||`URI can not be parsed.`;return{parsed:i,malformedAuthorityOrPort:s,malformedPercentEncoding:l,malformedSchemeSpecific:u,malformedHost:p,malformedScheme:y}}function ie(e,t){return re(e,t).parsed}function ae(e,t){return oe(e,t).normalized}function oe(e,t){let{parsed:n,malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}=re(e,t);return{normalized:r||i||a||o||s?e:C(n,t),malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}}function se(e,t){if(typeof e!=`string`&&typeof e!=`object`)return;let n;try{n=typeof e==`string`?e:C(e,t)}catch{return}let{normalized:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:o,malformedHost:s,malformedScheme:c}=oe(n,t);return i||a||o||s||c?void 0:r}let ce={SCHEMES:m,normalize:y,resolve:b,resolveComponent:x,equal:S,serialize:C,parse:ie};t.exports=ce,t.exports.default=ce,t.exports.fastUri=ce})),qJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=KJ();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),JJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=zJ();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=Z();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});let r=BJ(),i=VJ(),a=kJ(),o=HJ(),s=Z(),c=RJ(),l=jJ(),u=Q(),d=UJ(),f=qJ(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=E(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,`NOT SUPPORTED`),b.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=T.call(this),e.formats&&C.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&w.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=x.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=x.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(O.call(this,n,t),!t)return(0,u.eachItem)(n,e=>te.call(this,e)),this;re.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>te.call(this,e,r):e=>r.type.forEach(t=>te.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=ae(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function b(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function x(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function C(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function w(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function T(){let e={...this.opts};for(let t of m)delete e[t];return e}let ee={log(){},warn(){},error(){}};function E(e){if(e===!1)return ee;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let D=/^[a-z_$][a-z0-9_$:-]*$/i;function O(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!D.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function te(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?ne.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function ne(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function re(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=ae(t)),e.validateSchema=this.compile(t,!0))}let ie={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function ae(e){return{anyOf:[e,ie]}}})),YJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),XJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=VJ(),n=NJ(),r=Z(),i=EJ(),a=HJ(),o=Q(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);if(h instanceof a.SchemaEnv)return _(h);return v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0)if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}if(l.items!==!0)if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}e.callRef=l,e.default=s})),ZJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=YJ(),n=XJ();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),QJ=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),$J=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),eY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),tY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z(),n=Q(),r=eY();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),nY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=NJ(),n=Q(),r=Z();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),rY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),iY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=NJ(),n=Z(),r=Q();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),aY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),oY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=IJ();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),sY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=jJ(),n=Z(),r=Q(),i=oY();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),cY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z(),n=Q(),r=oY();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),lY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z(),n=Q(),r=oY();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),uY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=QJ(),n=$J(),r=tY(),i=nY(),a=rY(),o=iY(),s=aY(),c=sY(),l=cY(),u=lY();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),dY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=Z(),n=Q(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),fY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=Z(),n=Q(),r=NJ(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),pY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=fY();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),mY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z(),n=Q(),r=NJ(),i=dY();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),hY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z(),n=Q();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),gY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=Z(),n=Q(),r=NJ();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
338
345
  missingProperty: ${i},
339
346
  depsCount: ${n},
340
- deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),dY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z(),n=Q();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),fY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=DJ(),n=Z(),r=bJ(),i=Q();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),pY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=NJ(),n=DJ(),r=Q(),i=fY();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),mY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=DJ(),n=Z(),r=Q(),i=Q();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),hY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),gY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:DJ().validateUnion,error:{message:`must match a schema in anyOf`}}})),_Y=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z(),n=Q();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),vY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),yY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z(),n=Q(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),bY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),xY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=aY(),n=sY(),r=oY(),i=cY(),a=lY(),o=uY(),s=dY(),c=fY(),l=pY(),u=mY(),d=hY(),f=gY(),p=_Y(),m=vY(),h=yY(),g=bY();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),SY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),CY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[SY().default]})),wY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),TY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=GJ(),n=iY(),r=xY(),i=CY(),a=wY();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),EY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),DY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z(),n=EY(),r=IJ(),i=FJ(),a=Q();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),OY=j(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),kY=j(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=HJ(),r=TY(),i=DY(),a=OY(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var l=NJ();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=Z();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var d=PJ();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=FJ();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),AY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:ee,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-+(d<0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}let b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function C(e){return Number.isInteger(e)}function w(){return!0}let T=/[^\\]\\Z/;function ee(e){if(T.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),jY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=kY(),n=Z(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),MY=j(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=AY(),r=jY(),i=Z(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),NY=ze(kY(),1),PY=ze(MY(),1);function FY(){let e=new NY.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,PY.default)(e),e}var IY=class{constructor(e){this._ajv=e??FY()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},LY=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},AK,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`);break}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},XK,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function RY(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`);break;default:break}}function zY(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var BY=class extends hJ{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(gK.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new IY,this.setRequestHandler($W,e=>this._oninitialize(e)),this.setNotificationHandler(nG,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(vK,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=gK.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new LY(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=_J(this._capabilities,e)}setRequestHandler(e,t){let n=sW(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=pW(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=aW(mK,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new Y(J.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=aW(fG,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new Y(J.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=aW(fK,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new Y(J.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){zY(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&RY(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:hW.includes(t)?t:mW,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},BW)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},jK,t):this.request({method:`sampling/createMessage`,params:e},AK,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},XK,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},XK,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new Y(J.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof Y?e:new Y(J.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},oq,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const VY=Symbol.for(`mcp.completable`);function HY(e){return!!e&&typeof e==`object`&&VY in e}function UY(e){return e[VY]?.complete}var WY;(function(e){e.Completable=`McpCompletable`})(WY||={});const GY=/^[A-Za-z0-9._-]{1,128}$/;function KY(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!GY.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function qY(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function JY(e){let t=KY(e);return qY(e,t.warnings),t.isValid}var YY=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}};function XY(e,t){let n=0,r=[e];for(;r.length>0;){let e=r.pop();if(!(typeof e!=`object`||!e))if(Array.isArray(e))for(let i of e){if(++n>t)return n;typeof i==`object`&&i&&r.push(i)}else for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;if(++n>t)return n;let a=e[i];typeof a==`object`&&a&&r.push(a)}}return n}function ZY(e){if(e!==void 0&&e!==1/0){if(typeof e!=`number`||Number.isNaN(e)||e<1)throw RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}}var QY=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new BY(e,t),this._maxToolInputElements=ZY(t?.maxToolInputElements)}get experimental(){return this._experimental||={tasks:new YY(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(aX(uK)),this.server.assertCanSetRequestHandler(aX(mK)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(uK,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=cW(t.inputSchema);return e?fJ(e,{strictUnions:!0,pipeStrategy:`input`}):$Y})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=cW(t.outputSchema);e&&(n.outputSchema=fJ(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(mK,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new Y(J.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Y(J.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new Y(J.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new Y(J.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof Y&&e.code===J.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(this._maxToolInputElements!==void 0&&XY(t,this._maxToolInputElements)>this._maxToolInputElements)throw new Y(J.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let r=await oW(cW(e.inputSchema)??e.inputSchema,t??{});if(!r.success){let e=uW(`error`in r?r.error:`Unknown error`);throw new Y(J.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new Y(J.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await oW(cW(e.outputSchema),t.structuredContent);if(!r.success){let e=uW(`error`in r?r.error:`Unknown error`);throw new Y(J.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}else{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}else{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new Y(J.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(aX(eq)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(eq,async e=>{switch(e.params.ref.type){case`ref/prompt`:return tq(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return nq(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Y(J.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new Y(J.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new Y(J.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return sX;let r=sW(n.argsSchema)?.[e.params.argument.name];if(!HY(r))return sX;let i=UY(r);return i?oX(await i(e.params.argument.value,e.params.context)):sX}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return sX;throw new Y(J.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?oX(await r(e.params.argument.value,e.params.context)):sX}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(aX(AG)),this.server.assertCanSetRequestHandler(aX(MG)),this.server.assertCanSetRequestHandler(aX(IG)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(AG,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(MG,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(IG,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new Y(J.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new Y(J.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(aX(qG)),this.server.assertCanSetRequestHandler(aX(XG)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(qG,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?iX(t.argsSchema):void 0}))})),this.server.setRequestHandler(XG,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Y(J.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Y(J.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await oW(cW(n.argsSchema),e.params.arguments??{});if(!r.success){let t=uW(`error`in r?r.error:`Unknown error`);throw new Y(J.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}else{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let o={title:t,description:n,argsSchema:r===void 0?void 0:iW(r),callback:i,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=o)),t.title!==void 0&&(o.title=t.title),t.description!==void 0&&(o.description=t.description),t.argsSchema!==void 0&&(o.argsSchema=iW(t.argsSchema)),t.callback!==void 0&&(o.callback=t.callback),t.enabled!==void 0&&(o.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=o,r&&Object.values(r).some(e=>HY(e instanceof a?e._def?.innerType:e))&&this.setCompletionRequestHandler(),o}_createRegisteredTool(e,t,n,r,i,a,o,s,c){JY(e);let l={title:t,description:n,inputSchema:rX(r),outputSchema:rX(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&JY(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=iW(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=iW(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i,a;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(nX(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!nX(t[0])&&(a=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=t.shift()}}let o=t[0];return this._createRegisteredTool(e,void 0,n,r,i,a,{taskSupport:`forbidden`},void 0,o)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};const $Y={type:`object`,properties:{}};function eX(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function tX(e){return`_def`in e||`_zod`in e||eX(e)}function nX(e){return typeof e!=`object`||!e||tX(e)?!1:Object.keys(e).length===0||Object.values(e).some(eX)}function rX(e){if(e){if(nX(e))return iW(e);if(!tX(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function iX(e){let t=sW(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:dW(t),required:!fW(t)})):[]}function aX(e){let t=sW(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=pW(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function oX(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const sX={completion:{values:[],hasMore:!1}};var cX=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??10485760}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
341
- `);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),lX(t)}clear(){this._buffer=void 0}};function lX(e){return zW.parse(JSON.parse(e))}function uX(e){return JSON.stringify(e)+`
342
- `}var dX=class{constructor(e=Ae.stdin,t=Ae.stdout,n){this._stdin=e,this._stdout=t,this._started=!1,this._ondata=e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(e){this.onerror?.(e),this.close().catch(()=>{})}},this._onerror=e=>{this.onerror?.(e)},this._readBuffer=new cX({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=uX(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};function fX(e){return Buffer.byteLength(JSON.stringify(e))}function pX(e){let t=fX(e);for(;e.outputBudget.returnedBytes!==t;)e.outputBudget.returnedBytes=t,t=fX(e);return t}function mX(e,t,n,r){if(typeof e==`string`)return e.length<=n.stringLimit?e:(r.push({path:t,kind:`string`,available:e.length,returned:n.stringLimit}),`${e.slice(0,Math.max(1,n.stringLimit-3)).trimEnd()}...`);if(Array.isArray(e))return e.length>n.arrayLimit&&r.push({path:t,kind:`array`,available:e.length,returned:n.arrayLimit}),e.slice(0,n.arrayLimit).map((e,i)=>mX(e,`${t}[${i}]`,n,r));if(!e||typeof e!=`object`)return e;let i={};for(let[a,o]of Object.entries(e)){let e=t?`${t}.${a}`:a;if(!t&&n.preserveAgentContract&&(a===`findings`||a===`inventories`)){i[a]=o;continue}if(a===`markdown`){r.push({path:e,kind:`field`});continue}i[a]=mX(o,e,n,r)}return i}function hX(e,t={}){let n=t.maxBytes??98304,r=e,i=e.findings,a=i?.schemaVersion===1&&i.scope===`returned-report`&&Array.isArray(i.items),o=fX(r),s={...r,outputBudget:{schemaVersion:1,maxBytes:n,originalBytes:o,returnedBytes:0,truncated:!1,omissions:[],omissionsTruncated:!1,detail:`The complete structured report fits within the agent output budget.`}};if(pX(s)<=n)return s;let c=[{arrayLimit:10,stringLimit:4e3,preserveAgentContract:a},{arrayLimit:5,stringLimit:2e3,preserveAgentContract:a},{arrayLimit:3,stringLimit:1e3,preserveAgentContract:a},{arrayLimit:1,stringLimit:500,preserveAgentContract:a}];for(let e of c){let t=[],i={...mX(r,``,e,t),outputBudget:{schemaVersion:1,maxBytes:n,originalBytes:o,returnedBytes:0,truncated:t.length>0,arrayLimit:e.arrayLimit,stringLimit:e.stringLimit,omissions:t.slice(0,100),omissionsTruncated:t.length>100,detail:`Counts, provenance, caveats, and compact evidence are retained. Run the related focused report when more rows are needed.`}};if(pX(i)<=n)return i}let l={...gt(r),outputBudget:{schemaVersion:1,maxBytes:n,originalBytes:o,returnedBytes:0,truncated:!0,fallback:!0,omissionsTruncated:!1,omissions:[{path:`reportBody`,kind:`field`}],detail:`The detailed report exceeded the budget, so the complete findings and retained inventories are returned instead.`}};if(pX(l)<=n)return l;throw Error(`The complete findings and inventories exceed the ${n}-byte agent output budget. Run a focused report with a narrower bounded scope; actionable rows were not truncated.`)}function $(e){let t=xt(e);return{content:[{type:`text`,text:`Error: ${t.error.message}`}],structuredContent:t,isError:!0}}function gX(e,t,n={}){return{content:[{type:`text`,text:n.markdown??e}],structuredContent:t}}function _X(e){e.registerTool(`seo_list_providers`,{description:`List provider packages installed through the seo CLI. Package installation requires human approval in a terminal.`,inputSchema:{},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async()=>{try{let e=await OU();return gX(`${e.installed.length} provider packages are installed.`,e)}catch(e){return $(e)}}),e.registerTool(`seo_describe_provider`,{description:`Describe one installed provider, its shared capabilities, and its agent action schemas`,inputSchema:{id:A.string().trim().min(1).max(64)},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async({id:e})=>{try{let t=await kU(e);return gX(`${t.id}: ${t.description}`,t)}catch(e){return $(e)}}),e.registerTool(`seo_run_provider`,{description:`Run one action from an installed provider after reading its schema with seo_describe_provider`,inputSchema:{id:A.string().trim().min(1).max(64),action:A.string().trim().min(1).max(64),account:A.record(A.string(),A.string()).optional(),params:A.record(A.string(),A.unknown()).optional(),refresh:A.boolean().optional()},annotations:{readOnlyHint:!1,destructiveHint:!1}},async({id:e,action:t,account:n,params:r,refresh:i})=>{try{let a=await wU({providerId:e,actionId:t,account:n??TU(e),params:r??{},refresh:i});return gX(`Provider ${e} completed action ${t}.`,hX(a))}catch(e){return $(e)}})}const vX=A.iso.date(`Use a YYYY-MM-DD date.`);function yX(e,t){return e===void 0?t:e}const bX={site:{mcp:`site`,schema:A.string()},days:{mcp:`days`,schema:A.number().optional()},recentDays:{mcp:`recentDays`,schema:A.number().optional()},range:{mcp:`range`,schema:A.number().optional()},limit:{mcp:`limit`,schema:A.number().optional()},checkLimit:{mcp:`checkLimit`,schema:A.number().optional()},minImpressions:{mcp:`minImpressions`,schema:A.number().optional()},includeBrand:{mcp:`includeBrand`,schema:A.boolean().optional()},verifyContent:{mcp:`verifyContent`,schema:A.boolean().optional()},verifyLimit:{mcp:`verifyLimit`,schema:A.number().optional()},js:{mcp:`js`,schema:A.boolean().optional()},fetchConcurrency:{mcp:`fetchConcurrency`,schema:A.number().optional()},fetchIntervalCap:{mcp:`fetchIntervalCap`,schema:A.number().optional()},fetchIntervalMs:{mcp:`fetchIntervalMs`,schema:A.number().optional()},refresh:{mcp:`refresh`,schema:A.boolean().optional()}};function xX(e){return Object.fromEntries(e.map(e=>{let t=bX[e];return[t.mcp,t.schema]}))}const SX=A.union([vX,A.string().regex(/^(?:today|yesterday|\d+daysAgo)$/)]).describe(`Use YYYY-MM-DD or a Google Analytics relative date.`);function CX(e,t={}){e.registerTool(`seo_ai_referrals`,{description:`Find AI referral traffic detected in Google Analytics. maxRows bounds retained provider rows; resultLimit bounds returned landing pages.`,inputSchema:{property:A.string().trim().min(1),startDate:SX.optional(),endDate:SX.optional(),maxRows:A.number().int().min(1).max(1e5).describe(`Maximum retained Google Analytics rows. If limit is also supplied, both values must match.`).optional(),limit:A.number().int().min(1).max(1e5).describe(`Legacy alias for maxRows. If maxRows is also supplied, both values must match.`).optional(),resultLimit:A.number().int().min(1).max(1e3).describe(`Maximum ranked landing pages returned. Defaults to 25.`).optional(),refresh:A.boolean().optional()}},async({property:e,startDate:n,endDate:r,maxRows:i,limit:a,resultLimit:o,refresh:s})=>{try{if(i!==void 0&&a!==void 0&&i!==a)throw new N(`INVALID_INPUT`,`maxRows and the legacy limit option must match when both are provided.`);let c=await(t.aiReferralsReport??js)({property:e,startDate:n,endDate:r,maxRows:i,limit:a,resultLimit:o,refresh:s});return gX(`${q(c.summary.sessions,`AI referral session`)} detected across ${q(c.summary.sources,`source`)}; evidence is ${c.dataStatus}.`,c)}catch(e){return $(e)}}),e.registerTool(`seo_page_opportunities`,{description:`Find first-party traffic growth opportunities for one URL from GSC and page content`,inputSchema:{...xX([`site`,`days`,`limit`,`minImpressions`,`includeBrand`,`verifyContent`,`refresh`,`js`]),days:A.number().int().min(1).max(548).optional(),limit:A.number().int().min(1).max(100).optional(),minImpressions:A.number().int().positive().optional(),url:A.string().url()}},async({site:e,url:n,days:r,limit:i,minImpressions:a,includeBrand:o,verifyContent:s,refresh:c,js:l})=>{try{let u=await(t.pageOpportunitiesReport??bw)({site:e,url:n,days:r,limit:i,minImpressions:a,includeBrand:o,verifyContent:s,refresh:c,js:yX(l,`auto`)});return gX(u.summary.verdict,u)}catch(e){return $(e)}}),e.registerTool(`seo_content_optimization`,{description:`Build a content optimization brief for one URL from first-party GSC queries and page content checks`,inputSchema:{...xX([`site`,`days`,`limit`,`minImpressions`,`includeBrand`,`verifyContent`,`refresh`,`js`]),days:A.number().int().min(1).max(548).optional(),limit:A.number().int().min(1).max(100).optional(),minImpressions:A.number().int().positive().optional(),url:A.string().url()}},async({site:e,url:n,days:r,limit:i,minImpressions:a,includeBrand:o,verifyContent:s,refresh:c,js:l})=>{try{let u=await(t.contentOptimizationReport??Aw)({site:e,url:n,days:r,limit:i,minImpressions:a,includeBrand:o,verifyContent:s,refresh:c,js:yX(l,`auto`)});return gX(u.summary.verdict,u)}catch(e){return $(e)}}),e.registerTool(`seo_performance_audit`,{description:`Run a local Lighthouse lab audit and optional device-specific CrUX field Core Web Vitals. Configure CrUX with SEO_CRUX_API_KEY.`,inputSchema:{url:A.string().url(),strategy:A.enum([`mobile`,`desktop`]).optional(),refresh:A.boolean().optional()}},async({url:e,strategy:t,refresh:n})=>{try{let r=await UL({url:e,strategy:t,refresh:n});return gX(r.headline,r)}catch(e){return $(e)}})}function wX(e,t={}){let n=e.requestEvidenceStatus===`available`?`Processed ${e.requests.length} URL requests into ${e.summary.totalPages} unique documents.`:e.requestEvidenceStatus===`partial`?`Observed ${e.requests.length} URL requests and retained ${e.summary.totalPages} unique documents; some started requests were still in flight when the crawl stopped.`:`Loaded ${e.summary.totalPages} unique documents; request evidence is unavailable for this legacy report.`,r={id:e.id,definitionId:e.definitionId,headline:`${n} Found ${e.summary.highIssues} high, ${e.summary.mediumIssues} medium, and ${e.summary.lowIssues} low issues.`,status:e.status,requestEvidenceStatus:e.requestEvidenceStatus,configHash:e.configHash,config:e.config,access:e.access,summary:e.summary,dataSources:e.dataSources,ai:e.ai?{robotsTxt:e.ai.robotsTxt,llmsTxt:e.ai.llmsTxt,agentResources:e.ai.agentResources}:void 0,topFixes:FT(e,{limit:1e3}),reviewObservations:IT(e,{limit:1e3}),issueGroupsComplete:!0,warnings:e.warnings,caveats:e.caveats};return t.includeIssues&&(r.issues=e.issues),t.includePages&&(r.requests=e.requests,r.pages=e.pages),r}const TX=A.number().int().min(1).max(qT).optional(),EX=A.number().int().min(0).max(64).optional(),DX=A.number().int().min(1).max(16).optional(),OX=A.string().regex(/^\d{1,30}$/u).optional();function kX(e){if(e.googleAnalyticsPropertyId&&e.clickySiteId)throw new N(`INVALID_INPUT`,`Pass either googleAnalyticsPropertyId or clickySiteId, not both.`);return e.clickySiteId?{provider:`clicky`,siteId:e.clickySiteId}:void 0}function AX(e){if(e.fetchConcurrency!==void 0||e.fetchIntervalCap!==void 0||e.fetchIntervalMs!==void 0)return{concurrency:e.fetchConcurrency,intervalCap:e.fetchIntervalCap,intervalMs:e.fetchIntervalMs}}function jX(e){e.registerTool(`seo_crawl_site`,{description:`Run a site crawl. Start with health=true for a fast uncached sitemap status and redirect pass, especially on large or unknown sites. Run the full crawl second when content-level evidence is needed. The compact result includes crawler identity and access-block guidance.`,inputSchema:{url:A.string().url().optional().describe(`Site start URL. Optional when sitemapUrl supplies the health-pass scope.`),health:A.boolean().optional().describe(`Run the fast sitemap health pass before a full crawl. Downloads no page bodies and writes no page cache entries.`),sitemapUrl:A.string().url().optional().describe(`Explicit sitemap or sitemap index URL for the health pass.`),site:A.string().optional(),googleAnalyticsPropertyId:A.string().optional(),clickySiteId:OX,maxPages:TX,maxDepth:EX,concurrency:DX,fetchIntervalCap:A.number().int().positive().optional(),fetchIntervalMs:A.number().int().positive().optional(),refresh:A.boolean().optional(),include:A.array(A.string()).optional(),exclude:A.array(A.string()).optional(),useSitemap:A.boolean().optional(),respectRobots:A.boolean().optional(),js:A.boolean().optional(),includePages:A.boolean().optional(),includeIssues:A.boolean().optional()}},async({url:e,health:t,sitemapUrl:n,site:r,googleAnalyticsPropertyId:i,clickySiteId:a,maxPages:o,maxDepth:s,concurrency:c,fetchIntervalCap:l,fetchIntervalMs:u,refresh:d,include:f,exclude:p,useSitemap:m,respectRobots:h,js:g,includePages:_,includeIssues:v})=>{try{let y=kX({googleAnalyticsPropertyId:i,clickySiteId:a}),b=e??(n?new URL(`/`,n).toString():void 0);if(!b)throw new N(`INVALID_INPUT`,`Pass url or an explicit sitemapUrl.`);let x=await zA({url:b,mode:t||n?`sitemap`:`site`,strategy:t?`health`:`full`,sitemapUrl:n,site:r,googleAnalyticsPropertyId:i,analyticsConnection:y,maxPages:o,maxDepth:s,concurrency:c,refresh:d,fetchRate:AX({fetchConcurrency:c,fetchIntervalCap:l,fetchIntervalMs:u}),include:f,exclude:p,useSitemap:m,respectRobots:h,js:!!g});return gX(`${t?`Sitemap health pass`:`Crawl`} complete for ${b}. Found ${x.issues.length} issues across ${x.summary.totalPages} pages.`,wX(x,{includePages:_,includeIssues:v}))}catch(e){return $(e)}}),e.registerTool(`seo_audit_urls`,{description:`Audit an explicit list of URLs with technical SEO checks. The compact result separates prioritised fixes from review observations. Set includePages/includeIssues for raw data.`,inputSchema:{urls:A.array(A.string().url()).min(1).max(qT),site:A.string().optional(),googleAnalyticsPropertyId:A.string().optional(),clickySiteId:OX,maxPages:TX,concurrency:DX,fetchIntervalCap:A.number().int().positive().optional(),fetchIntervalMs:A.number().int().positive().optional(),refresh:A.boolean().optional(),includePages:A.boolean().optional(),includeIssues:A.boolean().optional()}},async({urls:e,site:t,googleAnalyticsPropertyId:n,clickySiteId:r,maxPages:i,concurrency:a,fetchIntervalCap:o,fetchIntervalMs:s,refresh:c,includePages:l,includeIssues:u})=>{try{let d=kX({googleAnalyticsPropertyId:n,clickySiteId:r}),f=await zA({url:e[0]??``,urls:e,mode:`list`,site:t,googleAnalyticsPropertyId:n,analyticsConnection:d,maxPages:i??e.length,concurrency:a,refresh:c,fetchRate:AX({fetchConcurrency:a,fetchIntervalCap:o,fetchIntervalMs:s}),useSitemap:!1});return gX(`URL audit complete. Found ${f.issues.length} issues across ${f.summary.totalPages} pages.`,wX(f,{includePages:l,includeIssues:u}))}catch(e){return $(e)}}),e.registerTool(`seo_top_fixes`,{description:`Return top technical SEO fixes for a URL by running a compact crawl.`,inputSchema:{url:A.string().url(),site:A.string().optional(),maxPages:TX,maxDepth:EX,fetchIntervalCap:A.number().int().positive().optional(),fetchIntervalMs:A.number().int().positive().optional(),refresh:A.boolean().optional(),category:A.string().optional(),limit:A.number().int().min(1).max(1e3).optional()}},async({url:e,site:t,maxPages:n,maxDepth:r,fetchIntervalCap:i,fetchIntervalMs:a,refresh:o,category:s,limit:c})=>{try{let l=await zA({url:e,site:t,maxPages:n,maxDepth:r,refresh:o,fetchRate:AX({fetchIntervalCap:i,fetchIntervalMs:a})}),u=FT(l,{category:s,limit:c}),d=l.status===`completed`?``:` Coverage is ${l.status}: ${q(l.summary.crawledUrls,`URL`)} crawled from ${q(l.summary.discoveredUrls,`discovered URL`)}. Review the returned warnings and caveats before treating this as sitewide.`;return gX(`Found ${q(u.length,`top fix group`)} for ${l.config.url}.${d}`,{url:l.config.url,reportId:l.id,summary:l.summary,dataSources:l.dataSources,topFixes:u,warnings:l.warnings,caveats:l.caveats})}catch(e){return $(e)}}),e.registerTool(`seo_explain_issue`,{description:`Explain a crawler rule in plain English: why it matters, how to fix it, and how to verify it.`,inputSchema:{ruleId:A.string()}},async({ruleId:e})=>{let t=Je(e);return t?gX(`Rule guidance for ${e}.`,t):$(`Unknown rule: ${e}`)}),e.registerTool(`seo_list_rules`,{description:`List crawler rule ids and guidance metadata. Use this before the explain-crawl-issue report when you need valid rule ids.`,inputSchema:{category:OE.optional()}},async({category:e})=>{let t=qe().filter(t=>!e||t.category===e);return gX(`Found ${q(t.length,`crawler rule`)}.`,{rules:t})})}function MX(e,t={}){e.registerTool(`seo_doctor`,{description:`Check the local database, auth, scopes, config, and defaults`,inputSchema:{}},async()=>{try{let e=await hU();return gX(e.ok?`Local seo setup is ready.`:`Local seo setup needs attention.`,e)}catch(e){return $(e)}}),e.registerTool(`seo_segment_impact`,{description:`Compare matched retained GSC segments across adjacent equal-length periods without treating missing rows as zero`,inputSchema:{site:A.string().trim().min(1),days:A.number().int().min(1).max(240).optional(),limit:A.number().int().min(1).max(100).optional(),refresh:A.boolean().optional(),dimension:A.enum([`page`,`query`,`country`,`device`]).optional(),compareDays:A.number().int().min(1).max(240).optional(),startDate:vX.optional(),endDate:vX.optional(),maxRows:A.number().int().min(1).max(25e4).optional(),unmatchedLimit:A.number().int().min(0).max(100).optional()}},async({site:e,dimension:n,days:r,compareDays:i,startDate:a,endDate:o,limit:s,maxRows:c,unmatchedLimit:l,refresh:u})=>{try{let d=await(t.segmentImpact??Hj)({site:e,dimension:n,days:r,compareDays:i,startDate:a,endDate:o,limit:s,maxRows:c,unmatchedLimit:l,refresh:u});return gX(d.summary.verdict,d)}catch(e){return $(e)}}),e.registerTool(`seo_striking_distance`,{description:`Find position 11-20 query/page opportunities from GSC`,inputSchema:{...xX([`site`,`days`,`minImpressions`,`limit`,`verifyContent`,`verifyLimit`,`includeBrand`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),days:A.number().int().min(1).max(548).optional(),minImpressions:A.number().int().min(0).max(1e9).optional(),limit:A.number().int().min(1).max(100).optional(),verifyLimit:A.number().int().min(0).max(100).optional(),brandTerms:A.array(A.string().trim().min(1).max(200)).max(20).optional(),fetchConcurrency:A.number().int().min(1).max(16).optional(),fetchIntervalCap:A.number().int().min(1).max(60).optional(),fetchIntervalMs:A.number().int().min(100).max(6e4).optional()}},async({site:e,days:t,minImpressions:n,limit:r,verifyContent:i,verifyLimit:a,includeBrand:o,brandTerms:s,js:c,fetchConcurrency:l,fetchIntervalCap:u,fetchIntervalMs:d,refresh:f})=>{try{let p=await MP({site:e,days:t,minImpressions:n,limit:r,verifyContent:i,verifyLimit:a,includeBrand:o,brandTerms:s,js:yX(c,void 0),rate:AX({fetchConcurrency:l,fetchIntervalCap:u,fetchIntervalMs:d}),refresh:f});return gX(p.summary.verdict,p)}catch(e){return $(e)}}),e.registerTool(`seo_traffic_anomaly`,{description:`Detect statistically significant recent GSC traffic movement`,inputSchema:{...xX([`site`,`days`,`recentDays`,`refresh`])}},async({site:e,days:t,recentDays:n,refresh:r})=>{try{let i=await oF({site:e,days:t,recentDays:n,refresh:r});return gX(`${i.anomalies.filter(e=>e.significant).length} significant anomalies found.`,i)}catch(e){return $(e)}}),e.registerTool(`seo_update_correlate`,{description:`Overlay recent traffic anomalies against official Google ranking update windows`,inputSchema:{...xX([`site`,`days`,`recentDays`,`refresh`]),paddingDays:A.number().optional()}},async({site:e,days:t,recentDays:n,paddingDays:r,refresh:i})=>{try{let a=await sF({site:e,days:t,recentDays:n,paddingDays:r,refresh:i});return gX(`Classification: ${a.classification}.`,a)}catch(e){return $(e)}})}function NX(e){e.registerTool(`seo_index_coverage`,{description:`Crawl the site, compare it and its sitemap with Search Console page results, then choose representative URLs for URL Inspection`,inputSchema:{site:A.string().min(1),url:A.string().url().optional().describe(`Start URL to crawl. Defaults to the home page.`),sitemaps:A.array(A.string().url()).min(1).max(20).optional(),days:A.number().int().min(1).max(548).optional(),rowLimit:A.number().int().min(1).max(25e4).optional(),maxSitemapUrls:A.number().int().min(1).max(25e4).optional(),itemsPerSection:A.number().int().min(1).max(1e3).optional(),templateClusters:A.number().int().min(1).max(200).optional(),templateSamples:A.number().int().min(1).max(25).optional(),refresh:A.boolean().optional()}},async({site:e,url:t,sitemaps:n,days:r,rowLimit:i,maxSitemapUrls:a,itemsPerSection:o,templateClusters:s,templateSamples:c,refresh:l})=>{try{let u=await iL({site:e,url:t,sitemaps:n,days:r,rowLimit:i,maxSitemapUrls:a,itemsPerSection:o,templateClusters:s,templateSamples:c,refresh:l});return gX(`${u.summary.retainedSearchVisibleUrls} URLs appeared in the returned Search Console data. ${u.summary.crawlableCandidatesWithoutRetainedSearchVisibility} crawlable URLs need evidence review before choosing representative URL Inspection checks.`,u)}catch(e){return $(e)}}),e.registerTool(`seo_redirect_trace`,{description:`Trace redirects and report final indexability/canonical issues for a URL`,inputSchema:{url:A.string().url(),maxHops:A.number().optional(),refresh:A.boolean().optional(),js:A.boolean().optional()}},async({url:e,maxHops:t,refresh:n,js:r})=>{try{let i=await sL({url:e,maxHops:t,refresh:n,js:yX(r,`auto`)});return gX(`Traced ${i.summary.hops} hops. Final status ${i.summary.finalStatus}. ${i.summary.issues.length} issues.`,i)}catch(e){return $(e)}}),e.registerTool(`seo_link_recover`,{description:`Find GSC search-value URLs that are now broken, blocked, or poorly redirected`,inputSchema:{...xX([`site`,`days`,`limit`,`minImpressions`,`refresh`,`js`]),minClicks:A.number().optional()}},async({site:e,days:t,limit:n,minClicks:r,minImpressions:i,refresh:a,js:o})=>{try{let s=await fL({site:e,days:t,limit:n,minClicks:r,minImpressions:i,refresh:a,js:yX(o,`auto`)});return gX(`Checked ${s.summary.checked} search-value URLs. ${s.summary.recoverable} recoverable issues.`,s)}catch(e){return $(e)}})}const PX=A.enum([`dataforseo`,`ahrefs`]),FX=e=>A.string().trim().min(1).max(500).describe(e).optional(),IX=A.strictObject({keyword:FX(`Source column containing the search query.`),url:FX(`Source column containing the ranking URL.`),position:FX(`Source column containing grouped position.`),absolutePosition:FX(`Source column containing absolute result position.`),searchVolume:FX(`Source column containing monthly search volume.`),keywordDifficulty:FX(`Source column containing keyword difficulty.`),cpc:FX(`Source column containing cost per click.`),paidCompetition:FX(`Source column containing paid competition.`),intent:FX(`Source column containing search intent.`),resultCount:FX(`Source column containing estimated result count.`),estimatedTraffic:FX(`Source column containing estimated monthly visits.`),resultType:FX(`Source column containing result type.`),searchVolumeUpdatedAt:FX(`Source column containing the search volume update date.`)}).superRefine((e,t)=>{let n=new Map;for(let[r,i]of Object.entries(e)){if(!i)continue;let e=rM(i),a=n.get(e);a?t.addIssue({code:`custom`,message:`Source column "${i}" is already mapped to "${a}".`,path:[r]}):n.set(e,r)}}).describe(`Optional canonical field to source column mapping. Named fields override automatic header matching.`),LX=A.array(A.strictObject({dataset:A.literal(`ranked-keywords`),file:A.string().trim().min(1).max(4096),provider:PX,exportedAt:A.string().trim().min(1).max(100),format:A.enum([`csv`,`json`,`jsonl`]).optional(),rowLimit:A.number().int().min(1).max(1e5).optional(),columns:IX.optional()})).min(1).max(4).describe(`One to four local ranked-keyword exports from the same provider and market.`);function RX(e,t={}){e.registerTool(`seo_cannibal`,{description:`Find multi-URL query exposure candidates for intent and technical review`,inputSchema:{...xX([`site`,`days`,`limit`,`minImpressions`,`includeBrand`,`refresh`]),days:A.number().int().min(1).max(548).optional(),limit:A.number().int().min(1).max(100).optional(),minImpressions:A.number().int().min(0).max(1e9).optional(),brandTerms:A.array(A.string().trim().min(1).max(200)).max(20).optional(),researchFiles:LX.optional()}},async({site:e,days:t,limit:n,minImpressions:r,brandTerms:i,includeBrand:a,refresh:o,researchFiles:s})=>{try{let c=s?await TN({site:e,days:t,limit:n,minImpressions:r,brandTerms:i,includeBrand:a,refresh:o,researchFiles:s}):await TN({site:e,days:t,limit:n,minImpressions:r,brandTerms:i,includeBrand:a,refresh:o});return gX(c.summary.verdict,c)}catch(e){return $(e)}}),e.registerTool(`seo_decaying`,{description:`Find query/page click declines observed in both retained GSC windows and investigation signals`,inputSchema:{...xX([`site`,`days`,`limit`,`includeBrand`,`refresh`]),days:A.number().int().min(1).max(548).optional(),limit:A.number().int().min(1).max(100).optional(),comparison:A.enum([`previous-period`,`year-over-year`]).optional(),minDropPct:A.number().min(0).max(100).optional(),minPreviousClicks:A.number().min(0).max(1e9).optional(),minClickLoss:A.number().min(0).max(1e9).optional(),brandTerms:A.array(A.string().trim().min(1).max(200)).max(20).optional()}},async({site:e,days:t,limit:n,comparison:r,minDropPct:i,minPreviousClicks:a,minClickLoss:o,brandTerms:s,includeBrand:c,refresh:l})=>{try{let u=await HN({site:e,days:t,limit:n,comparison:r,minDropPct:i,minPreviousClicks:a,minClickLoss:o,brandTerms:s,includeBrand:c,refresh:l});return gX(u.summary.verdict,u)}catch(e){return $(e)}}),e.registerTool(`seo_quick_wins`,{description:`Find quick-win CTR/position opportunities`,inputSchema:{...xX([`site`,`days`,`limit`,`minImpressions`,`verifyContent`,`verifyLimit`,`includeBrand`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),days:A.number().int().min(1).max(548).optional(),limit:A.number().int().min(1).max(100).optional(),minImpressions:A.number().int().min(0).max(1e9).optional(),verifyLimit:A.number().int().min(0).max(100).optional(),brandTerms:A.array(A.string().trim().min(1).max(200)).max(20).optional(),fetchConcurrency:A.number().int().min(1).max(16).optional(),fetchIntervalCap:A.number().int().min(1).max(60).optional(),fetchIntervalMs:A.number().int().min(100).max(6e4).optional()}},async({site:e,days:n,limit:r,minImpressions:i,brandTerms:a,verifyContent:o,verifyLimit:s,includeBrand:c,js:l,fetchConcurrency:u,fetchIntervalCap:d,fetchIntervalMs:f,refresh:p})=>{try{let m=await(t.quickWinsReport??dP)({site:e,days:n,limit:r,minImpressions:i,brandTerms:a,verifyContent:o,verifyLimit:s,includeBrand:c,js:yX(l,void 0),rate:AX({fetchConcurrency:u,fetchIntervalCap:d,fetchIntervalMs:f}),refresh:p});return gX(m.summary.verdict,m)}catch(e){return $(e)}}),e.registerTool(`seo_internal_links`,{description:`Find verified internal-link review candidates for a target URL`,inputSchema:{...xX([`site`,`refresh`]),targetUrl:A.string().url().refine(e=>/^https?:\/\//.test(e),`Use an HTTP(S) URL.`),startDate:A.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),endDate:A.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional()}},async({site:e,targetUrl:n,startDate:r,endDate:i,refresh:a})=>{try{let o=await(t.internalLinksReport??TI)({site:e,targetUrl:n,startDate:r,endDate:i,refresh:a});return gX(o.summary.verdict,o)}catch(e){return $(e)}}),e.registerTool(`seo_ctr_underperformers`,{description:`Find high-impression queries underperforming CTR expectations`,inputSchema:{...xX([`site`,`minImpressions`,`limit`,`includeBrand`,`refresh`]),site:A.string().trim().min(1),minImpressions:A.number().int().min(1).max(1e9).optional(),limit:A.number().int().min(1).max(100).optional(),brandTerms:A.array(A.string().trim().min(1).max(200)).max(20).optional()}},async({site:e,minImpressions:n,limit:r,brandTerms:i,includeBrand:a,refresh:o})=>{try{let s=await(t.ctrUnderperformersReport??yj)({site:e,minImpressions:n,limit:r,brandTerms:i,includeBrand:a,refresh:o});return gX(s.summary.verdict,s)}catch(e){return $(e)}}),e.registerTool(`seo_query_cluster`,{description:`Cluster queries by token overlap`,inputSchema:{...xX([`site`,`includeBrand`,`minImpressions`,`limit`,`refresh`]),site:A.string().trim().min(1),scope:A.string().trim().min(1).max(2e3).optional(),minImpressions:A.number().int().min(1).max(1e9).optional(),limit:A.number().int().min(1).max(100).optional(),brandTerms:A.array(A.string().trim().min(1).max(200)).max(20).optional()}},async({site:e,scope:n,brandTerms:r,includeBrand:i,minImpressions:a,limit:o,refresh:s})=>{try{let c=await(t.queryClusterReport??uR)({site:e,scope:n,brand:r?.[0],brandTerms:r,includeBrand:i,minImpressions:a,limit:o,refresh:s});return gX(c.summary.verdict,c)}catch(e){return $(e)}})}const zX={"ai-referrals":{readOrder:[`dataStatus, range, methodology, and dataSource partialReasons`,`possiblyTruncated and per-query statuses`,`selection.landingPages before treating landingPages as complete`,`sources observedSessionSources for attribution evidence`],doNotClaim:[`An empty result is not proof that no AI system sent or cited the site.`,`Referral sessions did not necessarily cause conversions and are not all AI traffic.`,`totalUsers is not additive and must not be reconstructed by summing rows.`],verify:`Compare complete like-for-like Google Analytics periods and check whether high-session landing pages answer the referring context.`,related:[]},"audit-page":{readOrder:[`fetchDiagnostics, warnings, and the final fetched URL`,`observed page fields and structured-data findings`,`issues and recommendations`],doNotClaim:[`One page cannot support a sitewide conclusion.`,`Title pixel width is a review estimator, not a Google limit.`,`The fetched version is not proof that Google indexed that version.`],verify:`Re-fetch the URL after the edit and confirm the observed field changed.`,related:[{id:`redirect-trace`,reason:`Debugs the redirect chain.`},{id:`performance-audit`,reason:`Adds page speed evidence.`},{id:`content-optimization`,reason:`Builds a query-led brief.`}]},"audit-urls":{readOrder:[`requested versus attempted, fetched, failed, retained, and omitted counts`,`topFixes AND reviewObservations together; the two lists are the complete grouped issue inventory, so carry every group from both into findings`,`response evidence and issue summaries`,`requestEvidenceStatus, warnings, and caveats`],doNotClaim:[`A successful sample does not prove the same template works everywhere.`,`A failed request may be transient network, not a persistent defect.`,`A bounded audit is never complete site coverage.`],verify:`Re-run the identical URL list after deployment; a URL dropped from the request is not a verified fix.`,related:[{id:`audit-page`,reason:`Inspects one page in depth.`},{id:`site-crawl`,reason:`Discovers pages instead.`},{id:`redirect-trace`,reason:`Traces a redirecting URL.`}]},cannibalisation:{readOrder:[`dataStatus and both source.pageExposure and source.propertyDemand with validation counts and completeness`,`selection to see why groups were excluded or suppressed`,`per-page clicks, impressions, position, impression share, reviewContext, and HHI`,`priority.score and suggestedOwnerUrl`,`dataSource plus evidence.imports file dates, hashes, and row quality when the run used researchFiles`],doNotClaim:[`URL overlap is a review candidate, not proven harmful cannibalisation.`,`suggestedOwnerUrl is a low-confidence mechanical pick that requires intent review.`,`priority.score is a heuristic, not estimated click lift, and a partial source cannot support an all-clear.`,`Research-import rows are provider estimates that support multiple-ranking-URL claims only, not traffic or Search Console-verified cannibalisation.`],verify:`Compare intent and live SERPs for the overlapping URLs before consolidating anything.`,related:[{id:`query-clusters`,reason:`Groups related query themes.`},{id:`internal-links`,reason:`Clarifies link ownership.`},{id:`content-optimization`,reason:`Differentiates page intent.`}]},"content-optimization":{readOrder:[`sourceReport dataStatus, selection, benchmark.possiblyTruncated, and verification.status`,`summary.score and primaryIntent as heuristics`,`topActions separating technical-check and unverified from verified observations`,`intentMix and the source query metrics`],doNotClaim:[`estimatedClickLift and score are prioritisation heuristics, not forecasts or quality grades.`,`Query wording is not a content mandate.`,`Adding suggested wording is not guaranteed traffic.`],verify:`Fetch the page after the edit and confirm the missing answer block or clearer framing is present.`,related:[{id:`page-opportunities`,reason:`Adds query-level opportunities.`},{id:`internal-links`,reason:`Finds contextual links.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`}]},"crawler-rules":{readOrder:[`each rule id, title, and category`,`default severity as triage metadata`,`guidance metadata`],doNotClaim:[`Listing a rule does not mean the site triggered it or that the convention is a search-engine requirement.`,`Default severity is generic triage metadata, not actual priority.`,`Similarly named rules may not share source semantics.`],verify:`Pass the exact rule id to explain-crawl-issue, then check the matching issues in a site crawl.`,related:[{id:`explain-crawl-issue`,reason:`Returns the rule contract.`}]},"ctr-underperformers":{readOrder:[`dataStatus, range, source.completeness, possiblyTruncated, and validation counts`,`brand terms used, then selection before the queue; rows at average position 4 or worse belong to quick-wins`,`per-item query, URL, impressions, position, observed CTR, target CTR, benchmark source, and queryFlags`,`estimated shortfall`],doNotClaim:[`The shortfall is directional prioritisation math, not a traffic forecast.`,`Page-one average position hides day, device, geography, and result-feature variation.`,`A partial empty result is not an all-clear.`],verify:`Inspect the current SERP and displayed title link, then compare a complete later period after testing framing.`,related:[{id:`quick-wins`,reason:`Ranks position 4-10 opportunities.`},{id:`page-opportunities`,reason:`Reviews one URL.`},{id:`content-optimization`,reason:`Builds a page brief.`}]},"decaying-pages":{readOrder:[`dataStatus, ranges, and source.completeness`,`current and previous fetched rows, caps, truncation, and invalid rows in selection`,`summary.observedRetainedQueryClickLoss versus the returned subset`,`per-item clicks, impressions, CTR, position, and signals`],doNotClaim:[`A diagnosis such as lost_position or lost_ctr labels correlated movement, not a cause.`,`Missing retained rows are not zero traffic.`,`Do not sum capped rows into a property-wide loss.`],verify:`Check deployments, live indexability, and SERP composition for the affected URLs before editing.`,related:[{id:`refresh-priorities`,reason:`Combines decline signals.`},{id:`segment-impact`,reason:`Shows where movement concentrates.`}]},"explain-crawl-issue":{readOrder:[`category, default severity, and why it matters`,`fix steps and ignored impact`,`verification method and agent hints`],doNotClaim:[`Guidance describes the checked condition, not a search-engine penalty or guaranteed ranking effect.`,`Default severity is generic prioritization metadata, not actual urgency.`,`The rule definition alone does not prove any page triggered it.`],verify:`Pair the definition with the matching issues from a site crawl and confirm the per-URL evidence.`,related:[{id:`crawler-rules`,reason:`Finds a rule id.`},{id:`top-fixes`,reason:`Ranks the fix queue.`}]},"index-coverage":{readOrder:[`sources completeness, rowLimit, rowLimitReached, date range, and invalid rows`,`retainedSearchVisibility and crawlableWithoutRetainedSearchVisibility`,`blockedOrNonIndexable, sitemapOnly, searchConsoleOnly, and templateReview`,`each group count, returned, and omitted`],doNotClaim:[`A page is not indexed because it had Search Analytics visibility, nor unindexed because no row appeared.`,`A missing Search Analytics row is not proof a page is unindexed.`,`Do not turn a limited or incomplete source into a whole-site coverage percentage.`],verify:`Run seo page --url on representative URLs to collect exact URL Inspection verdicts.`,related:[{id:`site-crawl`,reason:`Provides the source crawl.`}]},"internal-links":{readOrder:[`dataStatus, target verification, aliases, canonical, and technical signals`,`source completeness and selection attempted, checked, failed, unchecked, and exclusions`,`per-item exact versus lexical matches and linkEvidence`,`per-item placement: the sentence where a link fits, its anchors, and contentSimilarity`],doNotClaim:[`The live check stops at 40 source pages, so unchecked candidates can remain and absence is not proven.`,`Query overlap does not prove a link belongs or that adding one improves rankings.`,`Priority is a heuristic, not estimated impact.`,`Placement sentences, anchors and contentSimilarity are text heuristics; they do not prove the link helps a reader.`],verify:`Read the source passage, add one contextual link if the target is genuinely useful, and re-crawl to confirm it.`,related:[{id:`cannibalisation`,reason:`Checks URL overlap.`},{id:`content-optimization`,reason:`Builds a page brief.`},{id:`page-opportunities`,reason:`Reviews one URL.`}]},"link-recovery":{readOrder:[`range and summary.checked with severity totals`,`per-item original and final URL, GSC metrics, issue lists, and redirect trace`,`chain status, final-page indexability, canonicals, and warnings`],doNotClaim:[`clicksAtRisk and impressionsAtRisk describe the checked period, not a forecast of loss or recovery.`,`Prior visibility orders the queue but does not prove fixing a URL restores traffic.`,`Failed checks or selection limits constrain coverage.`],verify:`Add one direct 301 to the closest equivalent destination only after confirming the page should still exist, then re-trace.`,related:[{id:`redirect-trace`,reason:`Traces one URL chain.`},{id:`decaying-pages`,reason:`Shows click declines.`},{id:`audit-urls`,reason:`Runs bounded checks.`}]},"page-opportunities":{readOrder:[`dataStatus, range, source.targetRowsFetched, selection, and benchmark`,`benchmark.possiblyTruncated`,`verification.status and reason`,`per-item query metrics, opportunity type, and benchmark and verification evidence`],doNotClaim:[`Only verified results support live-page coverage observations.`,`estimatedCtrClickShortfall is a directional calculation, not a click forecast.`,`summary.opportunities is a review queue, not a defect count, and partial data is not an all-clear.`],verify:`Inspect the live SERP and resolve any status or indexability contradiction before editing.`,related:[{id:`content-optimization`,reason:`Builds a page brief.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`},{id:`internal-links`,reason:`Finds contextual links.`}]},"performance-audit":{readOrder:[`dataStatus, source, labDataStatus, and fieldDataStatus`,`Lighthouse score, lab metrics, and labInsights`,`CrUX fieldData.metrics with scope, formFactor, and collectionPeriod`,`fetch-fallback fields when source is fetch-fallback`],doNotClaim:[`Origin-level CrUX data is not page-level evidence.`,`A fetch-fallback duration is the local fetch workflow, not TTFB, LCP, CLS, TBT, or INP, and never earns a score.`,`Do not combine lab and field values into a new score, compare mobile with desktop as equal populations, or claim a ranking outcome.`],verify:`Reproduce the relevant lab issue and re-run the audit after the change.`,related:[{id:`audit-page`,reason:`Runs an on-page audit.`},{id:`site-crawl`,reason:`Builds the site inventory.`}]},"query-clusters":{readOrder:[`summary cluster and query counts, clicks, impressions, threshold, limit, and brand filtering`,`per-cluster member queries, pages, demand, and performance`,`each cluster recommendation`],doNotClaim:[`Token overlap does not prove shared intent, justify a new page, or establish that current URLs compete.`,`Page-two clusters do not claim a CTR-only click lift.`,`Queries below the threshold or outside the cap are outside the conclusion, not absent demand.`],verify:`Check whether a cluster maps to one intent before changing section structure or navigation.`,related:[{id:`cannibalisation`,reason:`Checks URL overlap.`},{id:`content-optimization`,reason:`Builds a page brief.`}]},"quick-wins":{readOrder:[`dataStatus, date range, source row cap, possiblyTruncated, selection.invalidRows, and filters`,`methodology and each item benchmark confidence before using targetCtr`,`estimatedCtrClickShortfall and priority`,`verification requested, attempted, verified, failed, and technical counts`],doNotClaim:[`estimatedCtrClickShortfall and priority score are heuristics, explicitly not estimated lift.`,`Average position is not a stable rank, and an unverified item cannot support a content-coverage conclusion.`,`Filtered or capped evidence is not an all-clear.`],verify:`Inspect the live SERP, test clearer snippet framing, then compare a later complete window.`,related:[{id:`ctr-underperformers`,reason:`Adds CTR peer evidence.`},{id:`page-opportunities`,reason:`Reviews one URL.`},{id:`striking-distance`,reason:`Finds rows near page one.`}]},"redirect-trace":{readOrder:[`chain in order with requested URL, status, Location, resolved next, and duration`,`finalUrl versus finalPage and summary.finalStatus`,`summary.issues`,`metaRobots, xRobotsTag, canonical, and warnings`],doNotClaim:[`The trace is one observation from the machine and time that ran it, and CDNs, geography, cookies, or later deploys can differ.`,`A canonical elsewhere or a 302 can be intentional.`,`JavaScript rendering affects final-page extraction, not the HTTP chain.`],verify:`Re-run the trace after deployment and confirm the intended destination and status.`,related:[{id:`link-recovery`,reason:`Prioritises search-value URLs.`},{id:`audit-page`,reason:`Audits the final page.`},{id:`audit-urls`,reason:`Runs bounded checks.`}]},"refresh-priorities":{readOrder:[`workflow steps and skipped states`,`per-item source, impactKind, score breakdown, date window, completeness, verification status, and rationale`,`the top few URLs manually`],doNotClaim:[`A click decline, low CTR, second-page position, and Google Analytics session signal have different semantics and are not interchangeable.`,`Missing Google Analytics or failed fetches stay unavailable, not zero-weight proof.`,`The score is not expected clicks, revenue, ranking lift, or causal confidence.`],verify:`Confirm query intent, current content, and internal links for the top URLs before choosing a bounded edit.`,related:[{id:`decaying-pages`,reason:`Shows click declines.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`},{id:`second-page`,reason:`Finds rows near page one.`}]},"search-performance-overview":{readOrder:[`workflow envelope with summary, steps, actions, and output`,`report dataStatus, skipped sections, and partial reasons`,`priorities`,`nested anomaly, update, segment, decay, cannibalisation, striking-distance, and quick-win results`],doNotClaim:[`One complete section must not hide a failed or capped neighbour.`,`Sparse data may legitimately skip a section.`,`Update overlap, opportunity scores, average position, and timing are investigation signals, not causation or forecasts.`],verify:`Run the focused report named in actions and confirm affected URLs and provider dates before editing.`,related:[{id:`segment-impact`,reason:`Shows where movement sits.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`},{id:`striking-distance`,reason:`Finds rows near page one.`}]},"second-page":{readOrder:[`source completeness, date range, selection, methodology, provenance, and brand filtering`,`per-item impressions, clicks, CTR, and average position`,`the priority value`],doNotClaim:[`Average position is aggregated across searches, locations, devices, and time and is not an exact rank.`,`Retained limits mean the output is not a complete inventory.`,`Priority is a transparent heuristic, not expected click lift, and one row is not cannibalisation.`],verify:`Inspect the live page and search intent and confirm the query suits the URL before one defensible change.`,related:[{id:`striking-distance`,reason:`Covers positions 11-20.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`},{id:`page-opportunities`,reason:`Reviews one URL.`}]},"segment-impact":{readOrder:[`before, after, and rangeDays`,`dataStatus and source.before, source.after, and completeness for caps and truncation`,`selection invalid, duplicate, conflicting, matched, unmatched, returned, and limited rows`,`per-item clickDelta, impressionDelta, and positionDelta, then unmatchedSegments`],doNotClaim:[`A positive positionDelta is worse because a larger average position is lower in results.`,`unmatchedSegments are retained in one window only and are not gains from or losses to zero.`,`A limited or truncated result cannot support an inventory-wide winner or loser.`],verify:`Audit the top matched movers pages and query intent before drawing a segment conclusion.`,related:[{id:`traffic-anomaly`,reason:`Confirms movement first.`},{id:`decaying-pages`,reason:`Shows click declines.`},{id:`update-postmortem`,reason:`Frames movement around an update.`}]},"setup-check":{readOrder:[`ok`,`each checks entry status, distinguishing fail from warn, with detail and fix`,`generatedAt`],doNotClaim:[`A passing result means local prerequisites look present, not that a token is still accepted by Google or that the account can access a property.`,`Missing saved defaults are usually warnings because explicit parameters can replace them.`,`A setup pass is not evidence about rankings, indexing, or site health.`],verify:`Apply the fix on a failed check, re-run setup-check, then run a small read-only report for the intended property.`,related:[{id:`search-performance-overview`,reason:`First report once setup passes.`}]},"site-crawl":{readOrder:[`config.strategy first; use health before full on large or unknown sites`,`status, requestEvidenceStatus, attempted and fetched counts, failures, retained pages, and pageLimitReached`,`access crawler identity, blockedRequests, provider counts, and samples`,`data-source states`,`topFixes AND reviewObservations together; the two lists are the complete grouped issue inventory, so carry every group from both into findings`,`warnings and caveats, then opt-in pages, requests, and issues`],doNotClaim:[`A partial or capped crawl cannot support an all-clear or a definitive zero.`,`A crawl is not an index, traffic source, or guarantee of complete site coverage.`,`A health pass checks response access, status, and redirects only. It does not download page bodies or evaluate content, metadata, canonicals, indexability directives, internal links, or rendered HTML. For full crawls, state when JavaScript rendering was disabled.`,`A User-Agent can be spoofed. Never ask the user for a broad firewall bypass based on crawler identity alone.`],verify:`Re-run the same health configuration first. Use a full crawl only when the health evidence is clean and the question needs page-body analysis.`,related:[{id:`top-fixes`,reason:`Ranks the fix queue.`},{id:`index-coverage`,reason:`Checks coverage signals.`}]},"striking-distance":{readOrder:[`range, rangeDays, dataStatus, and source`,`source.possiblyTruncated and retained-row completeness`,`selection invalid, out-of-range, branded, below-threshold, eligible, returned, and limited`,`methodology, then per-item metrics and contentVerification`],doNotClaim:[`The 11-20 band is a heuristic boundary and average position is not a literal second results page.`,`Unverified or failed pages keep lower confidence.`,`The priority score is not expected traffic or ranking lift.`],verify:`Audit a small number of high-impression candidates and fix verified technical problems first.`,related:[{id:`second-page`,reason:`Covers positions 10-20.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`},{id:`page-opportunities`,reason:`Reviews one URL.`}]},"top-fixes":{readOrder:[`dataSources, summary, warnings, and caveats`,`per-item rule id, affected count, sample URLs, scoreFactors, and whyThisRanks`,`effort, fix guidance, and verification`],doNotClaim:[`Rank means highest among retained eligible findings, not globally highest, because the crawl or category may be capped.`,`Missing provider joins stay unavailable and a numeric zero is meaningful only when the source is complete.`,`This is not a forecast of rankings, traffic, or revenue.`],verify:`Repeat the same crawl configuration after implementation and confirm the rule no longer triggers.`,related:[{id:`explain-crawl-issue`,reason:`Explains the rule.`},{id:`site-crawl`,reason:`Provides the source crawl.`}]},"traffic-anomaly":{readOrder:[`coverage with requested dates, expected versus observed days, missing days, invalid rows, and status`,`anomalies with metric, baseline and comparison dates, percentChange, zScore, and significanceMethod`,`direction and significant`,`detection, changeDate and the detection thresholds: a step change compares every day before its change date with every day from it`],doNotClaim:[`Statistical unusualness does not identify a cause, diagnose a defect, or prove an external event affected the property.`,`A null percentage from a zero baseline differs from zero change.`,`Partial coverage can change the baseline.`],verify:`If movement is significant and coverage is adequate, run segment-impact for pages and queries.`,related:[{id:`segment-impact`,reason:`Shows where movement sits.`},{id:`update-correlation`,reason:`Adds update timing.`},{id:`decaying-pages`,reason:`Shows click declines.`}]},"update-correlation":{readOrder:[`classification with attribution and confidence, returned as not-established and none`,`anomalies, overlappingUpdates, and confounders`,`evidence, caveats, and source`],doNotClaim:[`Overlap cannot show the update caused a gain or loss even with large movement and no other recorded change.`,`update-overlap-without-significant-movement is not an impact result and no-update-overlap does not explain remaining movement.`,`Temporal overlap is not a penalty, reward, or confirmed effect.`],verify:`Test saved deploys, redirects, and content changes that overlap the window before attributing movement.`,related:[{id:`update-postmortem`,reason:`Maps winners and losers.`},{id:`segment-impact`,reason:`Shows where movement sits.`},{id:`traffic-anomaly`,reason:`Confirms movement first.`}]},"update-postmortem":{readOrder:[`workflow step statuses, finalized date windows, and source completeness`,`failed measurements, retained limits, and caveats`,`update, insights, templateMovement, and segments`],doNotClaim:[`The cause remains not established even when dates overlap.`,`Retained winners and losers are not a complete inventory when sources are capped or filtered.`,`Do not claim update causation, recovery probability, or future traffic.`],verify:`Inspect representative URLs from affected segments and reproduce technical changes before any rollback.`,related:[{id:`update-correlation`,reason:`Adds update timing.`},{id:`segment-impact`,reason:`Shows where movement sits.`}]}},BX={"ai-referrals":{name:`AI referral traffic`,description:`Find visits from known AI products in Google Analytics and see a ranked, bounded set of landing pages that received them.`,useWhen:[`You want measured AI referral traffic from Google Analytics.`,`You need the landing pages and sources behind those visits.`],avoidWhen:[`Google Analytics is not connected or does not track the site.`,`You want to measure citations or unclicked mentions inside AI answers.`],outcome:`A source and landing-page breakdown of identifiable AI referrals.`},"audit-page":{name:`Single-page SEO audit`,description:`Check one URL for response, indexability, metadata, headings, links, and page content evidence.`,useWhen:[`One page needs a technical review before you change it.`,`A broader report points to a specific URL.`],avoidWhen:[`You need to discover issues across a whole site.`,`The page requires a logged-in browser session.`],outcome:`A page-level audit that separates observed evidence from review advice.`},"audit-urls":{name:`Selected URL audit`,description:`Audit a specific list of pages without crawling the rest of the site.`,useWhen:[`You already know which URLs need checking.`,`You want a repeatable pre-release or post-release check for key pages.`],avoidWhen:[`You need the crawler to discover pages for you.`,`You only need a deep review of one page.`],outcome:`Consistent technical checks for each supplied URL.`},cannibalisation:{name:`Query and URL overlap`,description:`Find search queries that appear across several URLs and decide whether the overlap needs attention.`,useWhen:[`Several pages may be competing for the same search intent.`,`You want query-level evidence before merging or redirecting pages.`],avoidWhen:[`You plan to treat every multi-URL query as a problem.`,`The site has too little Search Console data for meaningful overlap.`],outcome:`A ranked review list of queries, URLs, and their share of search exposure.`},"content-optimization":{name:`Search-led content brief`,description:`Turn a page and its Search Console queries into a practical brief for improving relevance and coverage.`,useWhen:[`An existing page has search demand but needs a clearer improvement plan.`,`You want first-party query evidence beside the current page content.`],avoidWhen:[`The URL has no useful Search Console history.`,`You want generated copy or a traffic forecast.`],outcome:`A page brief with query evidence, content checks, and specific review points.`},"crawler-rules":{name:`Crawler rule catalog`,description:`Find the available technical check IDs and the evidence each crawler rule looks for.`,useWhen:[`You need a valid rule ID for another crawl report.`,`You want to see which technical checks are available by category.`],avoidWhen:[`You need affected pages or live crawl results.`],outcome:`A searchable catalog of crawler rules, severity, and guidance.`},"ctr-underperformers":{name:`CTR underperformers`,description:`Find high-impression queries whose click-through rate trails comparable queries at similar positions.`,useWhen:[`You want title or snippet review candidates backed by Search Console data.`,`You need to compare CTR fairly across similar average positions.`],avoidWhen:[`You want a promised click uplift.`,`The comparison groups have too little data.`],outcome:`A ranked list of query and page pairs with CTR comparison evidence.`},"decaying-pages":{name:`Pages losing search clicks`,description:`Find pages and queries with meaningful click declines across comparable Search Console periods.`,useWhen:[`You want to investigate a sustained organic search decline.`,`You need the pages and queries behind lost clicks.`],avoidWhen:[`The newer period is incomplete or not comparable.`,`You want to assume every decline is caused by old content.`],outcome:`A ranked investigation list with before-and-after search evidence.`},"explain-crawl-issue":{name:`Explain a crawl issue`,description:`Explain what one crawler rule means, why it may matter, and how to verify a fix.`,useWhen:[`A crawl returned a rule ID you do not recognize.`,`You need implementation and verification guidance before creating work.`],avoidWhen:[`You need the URLs affected by the rule.`,`You have not selected a valid crawler rule ID.`],outcome:`A plain-English rule explanation with fix and verification steps.`},"index-coverage":{name:`Index coverage signals`,description:`Compare the pages your site exposes with pages that had Google Search visibility, then choose representative URLs for URL Inspection.`,useWhen:[`You need to find crawlable pages that did not appear in the Search Console results returned for the selected period.`,`You want a focused review list before spending URL Inspection quota.`],avoidWhen:[`You need proof that a URL is indexed or excluded. Use URL Inspection for that URL.`,`The site blocks crawlers, so the crawl cannot list its pages.`],outcome:`Cross-source URL groups with clear evidence limits and a representative review queue for URL Inspection.`},"internal-links":{name:`Internal link opportunities`,description:`Find relevant pages that could add a useful internal link to a target URL.`,useWhen:[`A target page needs stronger internal discovery or contextual links.`,`You want candidate source pages checked against their current content.`],avoidWhen:[`You want links added automatically.`,`The target and candidate pages do not share a clear topic or user need.`],outcome:`Verified source-page candidates with query and page evidence for review.`},"link-recovery":{name:`Recover broken search-value URLs`,description:`Find URLs that previously earned search clicks but now fail, redirect poorly, or block indexing.`,useWhen:[`You suspect valuable URLs broke during a migration or release.`,`You want to prioritize technical recovery using Search Console evidence.`],avoidWhen:[`You want a backlink report.`,`You have no Search Console page history for the site.`],outcome:`A ranked recovery list with current URL checks and prior search value.`},"page-opportunities":{name:`Opportunities for one page`,description:`Find Search Console queries and page evidence that point to useful improvements for one URL.`,useWhen:[`You want to improve an existing page using its own search demand.`,`You need query themes and page checks in one result.`],avoidWhen:[`The page has no useful Search Console data.`,`You want a guaranteed traffic gain.`],outcome:`A ranked page improvement list tied to real queries and current content.`},"performance-audit":{name:`Page performance audit`,description:`Run Lighthouse lab checks and add CrUX field Core Web Vitals when that data is available.`,useWhen:[`You need actionable performance diagnostics for a page.`,`You want lab findings kept separate from real-user field data.`],avoidWhen:[`You want Lighthouse scores presented as field Core Web Vitals.`,`The page cannot be fetched from the local machine.`],outcome:`Lab diagnostics plus clearly labelled field metrics when available.`},"query-clusters":{name:`Search query clusters`,description:`Group related Search Console queries so repeated demand themes are easier to review.`,useWhen:[`A large query list needs a clearer topic structure.`,`You want to find repeated wording within a site section.`],avoidWhen:[`You need semantic or intent classification beyond shared query terms.`,`You want clusters turned into new pages automatically.`],outcome:`Stable query groups with the search demand behind each theme.`},"quick-wins":{name:`Page-one CTR opportunities`,description:`Find page-one query and URL pairs whose CTR deserves a closer look.`,useWhen:[`You want high-impression title and snippet review candidates.`,`You need page-one opportunities ranked from Search Console data.`],avoidWhen:[`You want a promised click gain.`,`You plan to treat a CTR heuristic as a Google requirement.`],outcome:`A ranked review queue with CTR, position, impressions, and comparison evidence.`},"redirect-trace":{name:`Redirect trace`,description:`Follow every redirect hop and check the final page, indexability, and canonical signals.`,useWhen:[`A URL redirects unexpectedly or through several hops.`,`You need to verify the final destination after a migration.`],avoidWhen:[`You need to discover redirect issues across a whole site.`,`The URL requires a signed-in browser session.`],outcome:`The complete redirect chain with final response and page checks.`},"refresh-priorities":{name:`Content refresh priorities`,description:`Combine search declines and near-term opportunities into a ranked content review queue.`,useWhen:[`You need to decide which existing pages to review first.`,`You want several Search Console signals ranked in one queue.`],avoidWhen:[`You need a technical crawl plan.`,`You want the ranking treated as a traffic forecast.`],outcome:`A focused list of pages and queries to investigate next, with reasons.`},"search-performance-overview":{name:`Search performance overview`,description:`Find where Google Search performance changed and choose the next focused report to inspect it.`,useWhen:[`You are starting an investigation and do not yet know which pages or queries moved.`,`You want one view of declines, gains, overlap, and near-term opportunities.`],avoidWhen:[`You already know the exact question and can run a focused report.`,`You need a technical crawl without Search Console analysis.`],outcome:`A clear search performance summary with a short list of next reports.`},"second-page":{name:`Second-page opportunities`,description:`Find URLs averaging positions 11 to 20 and see the queries behind each opportunity.`,useWhen:[`You want existing pages that may deserve closer review near page one.`,`You need page-level evidence across all matching queries.`],avoidWhen:[`You want average position treated as a fixed rank.`,`You need proof that a change will move the page to page one.`],outcome:`A ranked URL list with query, click, impression, and position evidence.`},"segment-impact":{name:`Search impact by segment`,description:`Compare page or query groups across equal periods to find which parts of a site moved.`,useWhen:[`A traffic change may be concentrated in one directory, page type, or query group.`,`You need to separate broad movement from a local segment issue.`],avoidWhen:[`The periods are incomplete or not comparable.`,`Missing Search Console rows would be mistaken for zero activity.`],outcome:`A segment comparison showing where clicks and impressions changed.`},"setup-check":{name:`Check local setup`,description:`Check Google login, scopes, local configuration, and saved defaults before running reports.`,useWhen:[`Authentication or site selection is failing.`,`You want to verify the local setup before investigating report errors.`],avoidWhen:[`You need SEO findings rather than a setup check.`],outcome:`A local setup status with the exact problems that need fixing.`},"site-crawl":{name:`Sitemap health pass and technical site crawl`,description:`Start with a lightweight sitemap health pass, then run a full technical crawl only when page bodies and content-level evidence are needed.`,useWhen:[`You need a fast first check of sitemap URLs, statuses, redirects, robots decisions, or access blocks.`,`You need to discover technical issues across linked pages.`,`You want a crawl snapshot for later filtering or comparison.`],avoidWhen:[`You only need to check one page or a known URL list.`,`Do not run a full crawl on a large or unknown site before health=true, or when important content requires browser rendering that is not enabled.`],outcome:`A fast sitemap response gate or a full crawl summary with page evidence, technical findings, crawler identity and access guidance.`},"striking-distance":{name:`Queries near page one`,description:`Find Search Console query and page pairs averaging positions 11 to 20.`,useWhen:[`You want existing search demand close to page one.`,`You need a compact list of queries and URLs for content review.`],avoidWhen:[`You want average position treated as an exact daily rank.`,`You need a promised ranking or click gain.`],outcome:`A ranked list of near-page-one query and URL pairs with search evidence.`},"top-fixes":{name:`Top technical SEO fixes`,description:`Turn crawl findings into a short, ranked queue of technical issues to investigate first.`,useWhen:[`A crawl contains too many findings to review at once.`,`You need representative URLs and reasons for the highest priorities.`],avoidWhen:[`You need every affected URL for one rule.`,`You plan to treat rank as proof of business impact.`],outcome:`A focused technical fix queue with issue evidence and example URLs.`},"traffic-anomaly":{name:`Unusual search traffic changes`,description:`Find recent clicks or impressions that moved beyond the site's normal Search Console pattern.`,useWhen:[`You want an early signal of an unusual search change.`,`You need to know whether recent movement stands out from normal variation.`],avoidWhen:[`There is too little history for a useful baseline.`,`You want the report to identify the cause of the change.`],outcome:`A statistical movement signal with the dates, baseline, and limits shown.`},"update-correlation":{name:`Google update correlation`,description:`Compare search movement dates with official Google ranking update windows.`,useWhen:[`A traffic change overlaps a confirmed Google ranking update.`,`You need a timeline before investigating affected pages and queries.`],avoidWhen:[`You want overlap presented as proof of causation.`,`The traffic window does not cover the update dates.`],outcome:`A traffic and update timeline with overlaps clearly labelled as correlation.`},"update-postmortem":{name:`Google update impact review`,description:`Find the pages and queries that gained or lost around a confirmed Google ranking update.`,useWhen:[`You need winners and losers around a known update window.`,`You want to compare affected segments and known site changes.`],avoidWhen:[`You want the report to claim the update caused every change.`,`The comparison periods are incomplete or contain major unrecorded changes.`],outcome:`A post-update review of winners, losers, confounders, and next checks.`}};function VX(e){let t=BX[e],n=zX[e];if(!(!t||!n))return{...t,...n}}function HX(e){e.registerTool(`seo_audit_page`,{description:`Run a single-page technical and content audit`,inputSchema:{url:A.string().url(),site:A.string().optional(),js:A.boolean().optional(),refresh:A.boolean().optional()}},async({url:e,site:t,js:n,refresh:r})=>{try{let i=await gS({url:e,site:t,js:yX(n,`auto`),refresh:r});return gX(`Audit complete for ${e}. Found ${i.issues.length} issues.`,i)}catch(e){return $(e)}})}const UX=xX([`verifyContent`,`verifyLimit`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]);function WX(e){return{verifyContent:e.verifyContent,verifyLimit:e.verifyLimit,js:yX(e.js,void 0),rate:AX({fetchConcurrency:e.fetchConcurrency,fetchIntervalCap:e.fetchIntervalCap,fetchIntervalMs:e.fetchIntervalMs}),refresh:e.refresh}}function GX(e){e.registerTool(`seo_second_page`,{description:`Find URLs with GSC average position above 10 through 20 and return evidence-grounded investigation prompts`,inputSchema:{...xX([`site`,`range`,`minImpressions`,`limit`,`includeBrand`]),...UX,range:A.number().int().min(1).max(548).optional(),minImpressions:A.number().int().min(0).max(1e9).optional(),limit:A.number().int().min(1).max(100).optional(),verifyLimit:A.number().int().min(0).max(100).optional(),brandTerms:A.array(A.string().trim().min(1).max(200)).max(20).optional(),fetchConcurrency:A.number().int().min(1).max(16).optional(),fetchIntervalCap:A.number().int().min(1).max(60).optional(),fetchIntervalMs:A.number().int().min(100).max(6e4).optional()}},async({site:e,range:t,minImpressions:n,limit:r,includeBrand:i,brandTerms:a,...o})=>{try{let s=await $R({site:e,range:t,minImpressions:n,limit:r,includeBrand:i,brandTerms:a,...WX(o)});return gX(s.summary.verdict,s)}catch(e){return $(e)}})}function KX(e){HX(e),GX(e)}function qX(e){let t=Oz(e),n=hX({...e,presentation:t});return gX(e.summary,n,{markdown:kz(e)})}function JX(e){e.registerTool(`seo_workflow_diagnose_property`,{description:`Run the full agent workflow for property diagnosis and next actions`,inputSchema:{...xX([`site`,`days`,`recentDays`,`limit`,`includeBrand`,`refresh`])}},async({site:e,days:t,recentDays:n,limit:r,includeBrand:i,refresh:a})=>{try{return qX(await yz({site:e,days:t,recentDays:n,limit:r,includeBrand:i,refresh:a}))}catch(e){return $(e)}}),e.registerTool(`seo_workflow_update_postmortem`,{description:`Run winner/loser postmortem analysis for recent Google update exposure`,inputSchema:{...xX([`site`,`days`,`recentDays`,`limit`,`includeBrand`,`refresh`]),knownConfounders:A.array(A.string()).optional()}},async({site:e,days:t,recentDays:n,limit:r,includeBrand:i,knownConfounders:a,refresh:o})=>{try{return qX(await aB({site:e,days:t,recentDays:n,limit:r,includeBrand:i,knownConfounders:a,refresh:o}))}catch(e){return $(e)}}),e.registerTool(`seo_workflow_refresh_priorities`,{description:`Rank decay, striking-distance, quick-win, cannibalisation, and diagnosis signals into an action queue`,inputSchema:{...xX([`site`,`days`,`recentDays`,`limit`,`includeBrand`,`verifyContent`,`verifyLimit`,`refresh`]),googleAnalyticsPropertyId:A.string().optional()}},async({site:e,days:t,recentDays:n,limit:r,includeBrand:i,googleAnalyticsPropertyId:a,verifyContent:o,verifyLimit:s,refresh:c})=>{try{return qX(await Hz({site:e,days:t,recentDays:n,limit:r,includeBrand:i,googleAnalyticsPropertyId:a,verifyContent:o,verifyLimit:s,refresh:c}))}catch(e){return $(e)}})}const YX=[`ai-search`,`crawl`,`diagnosis`,`monitoring`,`opportunities`,`reporting`,`setup`,`workflows`],XX=[],ZX=[{category:`setup`,register:MX,names:[`seo_doctor`]},{category:`diagnosis`,register:MX,names:[`seo_segment_impact`,`seo_striking_distance`,`seo_traffic_anomaly`,`seo_update_correlate`]},{category:`opportunities`,register:RX,names:[`seo_cannibal`,`seo_ctr_underperformers`,`seo_decaying`,`seo_internal_links`,`seo_query_cluster`,`seo_quick_wins`]},{category:`ai-search`,register:CX,names:[`seo_ai_referrals`,`seo_content_optimization`,`seo_page_opportunities`,`seo_performance_audit`]},{category:`crawl`,register:jX,names:[`seo_audit_urls`,`seo_crawl_site`,`seo_explain_issue`,`seo_list_rules`,`seo_top_fixes`]},{category:`monitoring`,register:NX,names:[`seo_index_coverage`,`seo_link_recover`,`seo_redirect_trace`]},{category:`reporting`,register:KX,names:[`seo_audit_page`,`seo_second_page`]},{category:`workflows`,register:JX,names:[`seo_workflow_diagnose_property`,`seo_workflow_refresh_priorities`,`seo_workflow_update_postmortem`]}],QX={cannibal:`cannibalisation`,decaying:`decaying-pages`,"crawl-site":`site-crawl`,"link-recover":`link-recovery`,"query-cluster":`query-clusters`,"workflow-refresh-priorities":`refresh-priorities`,"workflow-update-postmortem":`update-postmortem`,"workflow-diagnose-property":`search-performance-overview`,doctor:`setup-check`,"update-correlate":`update-correlation`,"list-rules":`crawler-rules`,"explain-issue":`explain-crawl-issue`};function $X(e){let t=e.replace(/^seo_/,``).replaceAll(`_`,`-`);return QX[t]??t}function eZ(e,t){return e.id<t.id?-1:+(e.id>t.id)}function tZ(e){let t=new Map;return e({registerTool(e,n,r){t.set(e,{inputSchema:n.inputSchema,handler:r})}}),t}function nZ(e){return e instanceof A.ZodObject?e:A.strictObject(e??{})}function rZ(){let e=new Map,t=XX.map(e=>{let t=VX(e.id);if(!t)throw Error(`MCP report registry is missing guidance for ${e.id}.`);return{...e,...t}});for(let n of ZX){let r=e.get(n.register);r||(r=tZ(n.register),e.set(n.register,r));for(let e of n.names){let i=r.get(e);if(!i)throw Error(`MCP report registry references missing tool ${e}.`);let a=$X(e),o=VX(a);if(!o)throw Error(`MCP report registry is missing guidance for ${a}.`);t.push({id:a,category:n.category,...o,inputSchema:nZ(i.inputSchema),handler:i.handler})}}return t.sort(eZ)}const iZ=rZ(),aZ=new Set(iZ.map(e=>e.id)),oZ=Object.keys(BX).filter(e=>!aZ.has(e));if(oZ.length>0)throw Error(`MCP report guidance references unknown reports: ${oZ.join(`, `)}.`);const sZ=new Map(iZ.map(e=>[e.id,e]));function cZ(e){return iZ.filter(t=>!e||t.category===e).map(({id:e,name:t,description:n,category:r})=>({id:e,category:r,name:t,description:n}))}function lZ(e){return sZ.get(e)}function uZ(e){return e.issues.map(e=>`${e.path.length>0?e.path.join(`.`):`input`}: ${e.message}`).join(`; `)}const dZ={"affected-urls":`seo crawl`,"agent-readiness":null,"ai-mention-research":null,"ai-prompt-observations":null,"ai-readiness":null,"ai-search-scorecard":null,"bing-webmaster-overview":null,"community-intent":null,"compare-crawls":`seo crawl`,"competitive-opportunities":`seo research`,"competitor-keyword-gap":`seo research competitors`,"crawl-diff":`seo crawl`,"crawl-history":`seo crawl`,"crawl-report":`seo crawl`,"domain-overview":`seo research ranked_keywords`,"domain-rating":`seo research`,"entity-readiness":null,"generate-llms-txt":null,"geo-gaps":null,"index-coverage-plan":`seo index`,"index-monitor":`seo index`,"index-watch":`seo page --url <url>`,"keyword-metrics":`seo research keyword_metrics`,"keyword-opportunities":`seo research`,"keyword-research":`seo research keyword_metrics`,"link-evidence":`seo research backlinks`,"llms-txt-audit":null,"local-search-demand":null,"measure-change":`seo compare --date <date>`,"monthly-action-plan":`seo report`,"monthly-report":`seo report`,"narrative-report":`seo report`,"okf-build":null,"okf-validate":null,"pseo-audit":null,"pseo-opportunities":null,"pseo-patterns":null,"rank-tracking":null,"ranked-keywords":`seo research ranked_keywords`,"ranking-pages":`seo research ranked_keywords`,"saved-keywords":null,"seo-to-ai-query":null,"serp-competitors":`seo research competitors`,"serp-results":`seo research serp`,"server-log-analysis":null,"technical-watch":`seo crawl`};function fZ(e){if(Object.hasOwn(dZ,e)){let t=dZ[e];throw new N(`INVALID_INPUT`,t?`The ${e} report was removed. Use \`${t}\` instead.`:`The ${e} report was removed. Run \`seo help\` for the commands.`)}let t=lZ(e);if(!t)throw new N(`INVALID_INPUT`,`Unknown report: ${e}.`);return t}function pZ(e){return cZ(e)}function mZ(e){let t=fZ(e);return{id:t.id,category:t.category,name:t.name,description:t.description,useWhen:t.useWhen,avoidWhen:t.avoidWhen,outcome:t.outcome,readOrder:t.readOrder,doNotClaim:t.doNotClaim,verify:t.verify,related:t.related,agentWorkflow:{actionView:{mcp:{id:t.id,view:`actions`},cli:`seo reports run ${t.id} --params '<json>' --actions-only --json`},readOrder:[`findings.coverage and report-level caveats`,`findings.items in returned priority order`,`inventories row by row when present`],completion:`Use each finding type and its allowed outcomes. Fix items support fixed, deferred, or not-needed. Review items support changed, no-change, or deferred. Verify changed items and rerun this report before closing them.`},inputSchema:A.toJSONSchema(t.inputSchema)}}async function hZ(e,t={},n={}){let r=fZ(e),i=r.inputSchema.safeParse(t);if(!i.success)throw new N(`INVALID_INPUT`,`Invalid parameters for ${e}: ${uZ(i.error)}`);let a=await r.handler(i.data);if(a.isError||!a.structuredContent)return a;let o={reportId:r.id,verify:r.verify},s=n.view===`actions`?gt(a.structuredContent,o):a.structuredContent;return{...a,structuredContent:hX(s)}}const gZ={readOnlyHint:!0,destructiveHint:!1,openWorldHint:!0};function _Z(e){return{content:[{type:`text`,text:e}]}}async function vZ(e,t,n,r){let i=n?xH(e,{section:typeof t.section==`string`?t.section:void 0,action:typeof t.action==`string`?t.action:void 0}):null;i&&n&&fi(i,n());try{let e=await r();return i&&n&&(e.isError?mi(i,e.structuredContent?.error,n()):pi(i,n())),e}catch(e){return i&&n&&mi(i,e,n()),$(fU(e))}}function yZ(e,t={}){let n={deps:rU({call:kH}),resolveSite:e=>uU(e),keys:cU,refreshClicky:lU,drKey:null,accounts:sU,signIn:To.signIn,connect:"run `seo login` to use your seoskill.dev account (Google, Bing and keys in one place), or `seo auth login`, `seo providers bing connect` and `seo providers dataforseo connect` or `seo providers ahrefs connect` on this machine only."};for(let r of DH)e.registerTool(r.name,{title:r.title,description:r.description,inputSchema:r.input.shape,annotations:gZ},async e=>vZ(r.command,e,t.telemetry,async()=>_Z((await OH(r,n,e)).text)));e.registerTool(`seo_crawl`,{title:`Crawl a site`,description:`Crawls a site from this machine and returns technical issues and the URLs they affect. The crawl is saved locally for later reports.`,inputSchema:{url:A.url()},annotations:gZ},async({url:e})=>vZ(`crawl`,{},t.telemetry,()=>hZ(`site-crawl`,{url:e,saveReport:!0}))),e.registerTool(`seo_internal_links`,{title:`Internal link opportunities`,description:`Pages of the same site that could link to a target page, from Search Console and live page checks on this machine. Each one names the sentence where the link fits and anchor text from it. Takes the target URL and optional dates (default: the last 90 days).`,inputSchema:{url:A.url(),start_date:A.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe(`YYYY-MM-DD. Optional; send with end_date.`),end_date:A.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe(`YYYY-MM-DD. Optional; send with start_date.`)},annotations:gZ},async({url:e,start_date:n,end_date:r})=>vZ(`internal-links`,{},t.telemetry,async()=>{try{return await hZ(`internal-links`,{site:await uU(e),targetUrl:e,startDate:n,endDate:r})}catch(e){return $(fU(e))}}))}function bZ(){for(let e of[`../skills/seo/SKILL.md`,`../../../skills/seo/SKILL.md`])try{return w(new URL(e,import.meta.url),`utf8`)}catch{}return null}function xZ(e={}){let t=new QY({name:`seo`,version:Rr},{capabilities:{logging:{}},instructions:`SEO Skill reads the person's own Search Console, Google Analytics, Bing Webmaster Tools, Clicky and optional keyword accounts, and returns facts with their dates and limits. It gives no advice.
347
+ deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),_Y=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z(),n=Q();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),vY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=NJ(),n=Z(),r=EJ(),i=Q();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),yY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=zJ(),n=NJ(),r=Q(),i=vY();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),bY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=NJ(),n=Z(),r=Q(),i=Q();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),xY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),SY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:NJ().validateUnion,error:{message:`must match a schema in anyOf`}}})),CY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z(),n=Q();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),wY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),TY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z(),n=Q(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),EY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Q();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),DY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=dY(),n=pY(),r=fY(),i=mY(),a=hY(),o=gY(),s=_Y(),c=vY(),l=yY(),u=bY(),d=xY(),f=SY(),p=CY(),m=wY(),h=TY(),g=EY();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),OY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),kY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[OY().default]})),AY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),jY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ZJ(),n=uY(),r=DY(),i=kY(),a=AY();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),MY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),NY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z(),n=MY(),r=HJ(),i=VJ(),a=Q();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),PY=j(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),FY=j(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=JJ(),r=jY(),i=NY(),a=PY(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var l=zJ();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=Z();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var d=BJ();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=VJ();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),IY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:ee,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-+(d<0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}let b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function C(e){return Number.isInteger(e)}function w(){return!0}let T=/[^\\]\\Z/;function ee(e){if(T.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),LY=j((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=FY(),n=Z(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),RY=j(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=IY(),r=LY(),i=Z(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),zY=ze(FY(),1),BY=ze(RY(),1);function VY(){let e=new zY.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,BY.default)(e),e}var HY=class{constructor(e){this._ajv=e??VY()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},UY=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},IK,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`);break}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},nq,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function WY(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`);break;default:break}}function GY(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var KY=class extends xJ{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(SK.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new HY,this.setRequestHandler(aG,e=>this._oninitialize(e)),this.setNotificationHandler(cG,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(wK,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=SK.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new UY(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=CJ(this._capabilities,e)}setRequestHandler(e,t){let n=pW(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=yW(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=dW(bK,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new Y(J.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=dW(vG,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new Y(J.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=dW(vK,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new Y(J.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){GY(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&WY(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:xW.includes(t)?t:bW,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},KW)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},LK,t):this.request({method:`sampling/createMessage`,params:e},IK,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},nq,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},nq,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new Y(J.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof Y?e:new Y(J.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},fq,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const qY=Symbol.for(`mcp.completable`);function JY(e){return!!e&&typeof e==`object`&&qY in e}function YY(e){return e[qY]?.complete}var XY;(function(e){e.Completable=`McpCompletable`})(XY||={});const ZY=/^[A-Za-z0-9._-]{1,128}$/;function QY(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!ZY.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function $Y(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function eX(e){let t=QY(e);return $Y(e,t.warnings),t.isValid}var tX=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}};function nX(e,t){let n=0,r=[e];for(;r.length>0;){let e=r.pop();if(!(typeof e!=`object`||!e))if(Array.isArray(e))for(let i of e){if(++n>t)return n;typeof i==`object`&&i&&r.push(i)}else for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;if(++n>t)return n;let a=e[i];typeof a==`object`&&a&&r.push(a)}}return n}function rX(e){if(e!==void 0&&e!==1/0){if(typeof e!=`number`||Number.isNaN(e)||e<1)throw RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}}var iX=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new KY(e,t),this._maxToolInputElements=rX(t?.maxToolInputElements)}get experimental(){return this._experimental||={tasks:new tX(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(dX(gK)),this.server.assertCanSetRequestHandler(dX(bK)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(gK,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=mW(t.inputSchema);return e?vJ(e,{strictUnions:!0,pipeStrategy:`input`}):aX})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=mW(t.outputSchema);e&&(n.outputSchema=vJ(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(bK,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new Y(J.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Y(J.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new Y(J.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new Y(J.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof Y&&e.code===J.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(this._maxToolInputElements!==void 0&&nX(t,this._maxToolInputElements)>this._maxToolInputElements)throw new Y(J.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let r=await fW(mW(e.inputSchema)??e.inputSchema,t??{});if(!r.success){let e=gW(`error`in r?r.error:`Unknown error`);throw new Y(J.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new Y(J.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await fW(mW(e.outputSchema),t.structuredContent);if(!r.success){let e=gW(`error`in r?r.error:`Unknown error`);throw new Y(J.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}else{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}else{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new Y(J.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(dX(oq)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(oq,async e=>{switch(e.params.ref.type){case`ref/prompt`:return sq(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return cq(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Y(J.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new Y(J.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new Y(J.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return pX;let r=pW(n.argsSchema)?.[e.params.argument.name];if(!JY(r))return pX;let i=YY(r);return i?fX(await i(e.params.argument.value,e.params.context)):pX}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return pX;throw new Y(J.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?fX(await r(e.params.argument.value,e.params.context)):pX}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(dX(IG)),this.server.assertCanSetRequestHandler(dX(RG)),this.server.assertCanSetRequestHandler(dX(HG)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(IG,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(RG,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(HG,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new Y(J.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new Y(J.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(dX($G)),this.server.assertCanSetRequestHandler(dX(nK)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler($G,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?uX(t.argsSchema):void 0}))})),this.server.setRequestHandler(nK,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Y(J.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Y(J.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await fW(mW(n.argsSchema),e.params.arguments??{});if(!r.success){let t=gW(`error`in r?r.error:`Unknown error`);throw new Y(J.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}else{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let o={title:t,description:n,argsSchema:r===void 0?void 0:uW(r),callback:i,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=o)),t.title!==void 0&&(o.title=t.title),t.description!==void 0&&(o.description=t.description),t.argsSchema!==void 0&&(o.argsSchema=uW(t.argsSchema)),t.callback!==void 0&&(o.callback=t.callback),t.enabled!==void 0&&(o.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=o,r&&Object.values(r).some(e=>JY(e instanceof a?e._def?.innerType:e))&&this.setCompletionRequestHandler(),o}_createRegisteredTool(e,t,n,r,i,a,o,s,c){eX(e);let l={title:t,description:n,inputSchema:lX(r),outputSchema:lX(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&eX(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=uW(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=uW(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i,a;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(cX(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!cX(t[0])&&(a=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=t.shift()}}let o=t[0];return this._createRegisteredTool(e,void 0,n,r,i,a,{taskSupport:`forbidden`},void 0,o)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};const aX={type:`object`,properties:{}};function oX(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function sX(e){return`_def`in e||`_zod`in e||oX(e)}function cX(e){return typeof e!=`object`||!e||sX(e)?!1:Object.keys(e).length===0||Object.values(e).some(oX)}function lX(e){if(e){if(cX(e))return uW(e);if(!sX(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function uX(e){let t=pW(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:_W(t),required:!vW(t)})):[]}function dX(e){let t=pW(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=yW(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function fX(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const pX={completion:{values:[],hasMore:!1}};var mX=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??10485760}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
348
+ `);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),hX(t)}clear(){this._buffer=void 0}};function hX(e){return GW.parse(JSON.parse(e))}function gX(e){return JSON.stringify(e)+`
349
+ `}var _X=class{constructor(e=Ae.stdin,t=Ae.stdout,n){this._stdin=e,this._stdout=t,this._started=!1,this._ondata=e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(e){this.onerror?.(e),this.close().catch(()=>{})}},this._onerror=e=>{this.onerror?.(e)},this._readBuffer=new mX({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=gX(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};function vX(e){return Buffer.byteLength(JSON.stringify(e))}function yX(e){let t=vX(e);for(;e.outputBudget.returnedBytes!==t;)e.outputBudget.returnedBytes=t,t=vX(e);return t}function bX(e,t,n,r){if(typeof e==`string`)return e.length<=n.stringLimit?e:(r.push({path:t,kind:`string`,available:e.length,returned:n.stringLimit}),`${e.slice(0,Math.max(1,n.stringLimit-3)).trimEnd()}...`);if(Array.isArray(e))return e.length>n.arrayLimit&&r.push({path:t,kind:`array`,available:e.length,returned:n.arrayLimit}),e.slice(0,n.arrayLimit).map((e,i)=>bX(e,`${t}[${i}]`,n,r));if(!e||typeof e!=`object`)return e;let i={};for(let[a,o]of Object.entries(e)){let e=t?`${t}.${a}`:a;if(!t&&n.preserveAgentContract&&(a===`findings`||a===`inventories`)){i[a]=o;continue}if(a===`markdown`){r.push({path:e,kind:`field`});continue}i[a]=bX(o,e,n,r)}return i}function xX(e,t={}){let n=t.maxBytes??98304,r=e,i=e.findings,a=i?.schemaVersion===1&&i.scope===`returned-report`&&Array.isArray(i.items),o=vX(r),s={...r,outputBudget:{schemaVersion:1,maxBytes:n,originalBytes:o,returnedBytes:0,truncated:!1,omissions:[],omissionsTruncated:!1,detail:`The complete structured report fits within the agent output budget.`}};if(yX(s)<=n)return s;let c=[{arrayLimit:10,stringLimit:4e3,preserveAgentContract:a},{arrayLimit:5,stringLimit:2e3,preserveAgentContract:a},{arrayLimit:3,stringLimit:1e3,preserveAgentContract:a},{arrayLimit:1,stringLimit:500,preserveAgentContract:a}];for(let e of c){let t=[],i={...bX(r,``,e,t),outputBudget:{schemaVersion:1,maxBytes:n,originalBytes:o,returnedBytes:0,truncated:t.length>0,arrayLimit:e.arrayLimit,stringLimit:e.stringLimit,omissions:t.slice(0,100),omissionsTruncated:t.length>100,detail:`Counts, provenance, caveats, and compact evidence are retained. Run the related focused report when more rows are needed.`}};if(yX(i)<=n)return i}let l={...gt(r),outputBudget:{schemaVersion:1,maxBytes:n,originalBytes:o,returnedBytes:0,truncated:!0,fallback:!0,omissionsTruncated:!1,omissions:[{path:`reportBody`,kind:`field`}],detail:`The detailed report exceeded the budget, so the complete findings and retained inventories are returned instead.`}};if(yX(l)<=n)return l;throw Error(`The complete findings and inventories exceed the ${n}-byte agent output budget. Run a focused report with a narrower bounded scope; actionable rows were not truncated.`)}function $(e){let t=xt(e);return{content:[{type:`text`,text:`Error: ${t.error.message}`}],structuredContent:t,isError:!0}}function SX(e,t,n={}){return{content:[{type:`text`,text:n.markdown??e}],structuredContent:t}}function CX(e){e.registerTool(`seo_list_providers`,{description:`List provider packages installed through the seo CLI. Package installation requires human approval in a terminal.`,inputSchema:{},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async()=>{try{let e=await PU();return SX(`${e.installed.length} provider packages are installed.`,e)}catch(e){return $(e)}}),e.registerTool(`seo_describe_provider`,{description:`Describe one installed provider, its shared capabilities, and its agent action schemas`,inputSchema:{id:A.string().trim().min(1).max(64)},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async({id:e})=>{try{let t=await FU(e);return SX(`${t.id}: ${t.description}`,t)}catch(e){return $(e)}}),e.registerTool(`seo_run_provider`,{description:`Run one action from an installed provider after reading its schema with seo_describe_provider`,inputSchema:{id:A.string().trim().min(1).max(64),action:A.string().trim().min(1).max(64),account:A.record(A.string(),A.string()).optional(),params:A.record(A.string(),A.unknown()).optional(),refresh:A.boolean().optional()},annotations:{readOnlyHint:!1,destructiveHint:!1}},async({id:e,action:t,account:n,params:r,refresh:i})=>{try{let a=await AU({providerId:e,actionId:t,account:n??jU(e),params:r??{},refresh:i});return SX(`Provider ${e} completed action ${t}.`,xX(a))}catch(e){return $(e)}})}const wX=A.iso.date(`Use a YYYY-MM-DD date.`);function TX(e,t){return e===void 0?t:e}const EX={site:{mcp:`site`,schema:A.string()},days:{mcp:`days`,schema:A.number().optional()},recentDays:{mcp:`recentDays`,schema:A.number().optional()},range:{mcp:`range`,schema:A.number().optional()},limit:{mcp:`limit`,schema:A.number().optional()},checkLimit:{mcp:`checkLimit`,schema:A.number().optional()},minImpressions:{mcp:`minImpressions`,schema:A.number().optional()},includeBrand:{mcp:`includeBrand`,schema:A.boolean().optional()},verifyContent:{mcp:`verifyContent`,schema:A.boolean().optional()},verifyLimit:{mcp:`verifyLimit`,schema:A.number().optional()},js:{mcp:`js`,schema:A.boolean().optional()},fetchConcurrency:{mcp:`fetchConcurrency`,schema:A.number().optional()},fetchIntervalCap:{mcp:`fetchIntervalCap`,schema:A.number().optional()},fetchIntervalMs:{mcp:`fetchIntervalMs`,schema:A.number().optional()},refresh:{mcp:`refresh`,schema:A.boolean().optional()}};function DX(e){return Object.fromEntries(e.map(e=>{let t=EX[e];return[t.mcp,t.schema]}))}const OX=A.union([wX,A.string().regex(/^(?:today|yesterday|\d+daysAgo)$/)]).describe(`Use YYYY-MM-DD or a Google Analytics relative date.`);function kX(e,t={}){e.registerTool(`seo_ai_referrals`,{description:`Find AI referral traffic detected in Google Analytics. maxRows bounds retained provider rows; resultLimit bounds returned landing pages.`,inputSchema:{property:A.string().trim().min(1),startDate:OX.optional(),endDate:OX.optional(),maxRows:A.number().int().min(1).max(1e5).describe(`Maximum retained Google Analytics rows. If limit is also supplied, both values must match.`).optional(),limit:A.number().int().min(1).max(1e5).describe(`Legacy alias for maxRows. If maxRows is also supplied, both values must match.`).optional(),resultLimit:A.number().int().min(1).max(1e3).describe(`Maximum ranked landing pages returned. Defaults to 25.`).optional(),refresh:A.boolean().optional()}},async({property:e,startDate:n,endDate:r,maxRows:i,limit:a,resultLimit:o,refresh:s})=>{try{if(i!==void 0&&a!==void 0&&i!==a)throw new N(`INVALID_INPUT`,`maxRows and the legacy limit option must match when both are provided.`);let c=await(t.aiReferralsReport??js)({property:e,startDate:n,endDate:r,maxRows:i,limit:a,resultLimit:o,refresh:s});return SX(`${q(c.summary.sessions,`AI referral session`)} detected across ${q(c.summary.sources,`source`)}; evidence is ${c.dataStatus}.`,c)}catch(e){return $(e)}}),e.registerTool(`seo_page_opportunities`,{description:`Find first-party traffic growth opportunities for one URL from GSC and page content`,inputSchema:{...DX([`site`,`days`,`limit`,`minImpressions`,`includeBrand`,`verifyContent`,`refresh`,`js`]),days:A.number().int().min(1).max(548).optional(),limit:A.number().int().min(1).max(100).optional(),minImpressions:A.number().int().positive().optional(),url:A.string().url()}},async({site:e,url:n,days:r,limit:i,minImpressions:a,includeBrand:o,verifyContent:s,refresh:c,js:l})=>{try{let u=await(t.pageOpportunitiesReport??bw)({site:e,url:n,days:r,limit:i,minImpressions:a,includeBrand:o,verifyContent:s,refresh:c,js:TX(l,`auto`)});return SX(u.summary.verdict,u)}catch(e){return $(e)}}),e.registerTool(`seo_content_optimization`,{description:`Build a content optimization brief for one URL from first-party GSC queries and page content checks`,inputSchema:{...DX([`site`,`days`,`limit`,`minImpressions`,`includeBrand`,`verifyContent`,`refresh`,`js`]),days:A.number().int().min(1).max(548).optional(),limit:A.number().int().min(1).max(100).optional(),minImpressions:A.number().int().positive().optional(),url:A.string().url()}},async({site:e,url:n,days:r,limit:i,minImpressions:a,includeBrand:o,verifyContent:s,refresh:c,js:l})=>{try{let u=await(t.contentOptimizationReport??Aw)({site:e,url:n,days:r,limit:i,minImpressions:a,includeBrand:o,verifyContent:s,refresh:c,js:TX(l,`auto`)});return SX(u.summary.verdict,u)}catch(e){return $(e)}}),e.registerTool(`seo_performance_audit`,{description:`Run a local Lighthouse lab audit and optional device-specific CrUX field Core Web Vitals. Configure CrUX with SEO_CRUX_API_KEY.`,inputSchema:{url:A.string().url(),strategy:A.enum([`mobile`,`desktop`]).optional(),refresh:A.boolean().optional()}},async({url:e,strategy:t,refresh:n})=>{try{let r=await UL({url:e,strategy:t,refresh:n});return SX(r.headline,r)}catch(e){return $(e)}})}function AX(e,t={}){let n=e.requestEvidenceStatus===`available`?`Processed ${e.requests.length} URL requests into ${e.summary.totalPages} unique documents.`:e.requestEvidenceStatus===`partial`?`Observed ${e.requests.length} URL requests and retained ${e.summary.totalPages} unique documents; some started requests were still in flight when the crawl stopped.`:`Loaded ${e.summary.totalPages} unique documents; request evidence is unavailable for this legacy report.`,r={id:e.id,definitionId:e.definitionId,headline:`${n} Found ${e.summary.highIssues} high, ${e.summary.mediumIssues} medium, and ${e.summary.lowIssues} low issues.`,status:e.status,requestEvidenceStatus:e.requestEvidenceStatus,configHash:e.configHash,config:e.config,access:e.access,summary:e.summary,dataSources:e.dataSources,ai:e.ai?{robotsTxt:e.ai.robotsTxt,llmsTxt:e.ai.llmsTxt,agentResources:e.ai.agentResources}:void 0,topFixes:FT(e,{limit:1e3}),reviewObservations:IT(e,{limit:1e3}),issueGroupsComplete:!0,warnings:e.warnings,caveats:e.caveats};return t.includeIssues&&(r.issues=e.issues),t.includePages&&(r.requests=e.requests,r.pages=e.pages),r}const jX=A.number().int().min(1).max(qT).optional(),MX=A.number().int().min(0).max(64).optional(),NX=A.number().int().min(1).max(16).optional(),PX=A.string().regex(/^\d{1,30}$/u).optional();function FX(e){if(e.googleAnalyticsPropertyId&&e.clickySiteId)throw new N(`INVALID_INPUT`,`Pass either googleAnalyticsPropertyId or clickySiteId, not both.`);return e.clickySiteId?{provider:`clicky`,siteId:e.clickySiteId}:void 0}function IX(e){if(e.fetchConcurrency!==void 0||e.fetchIntervalCap!==void 0||e.fetchIntervalMs!==void 0)return{concurrency:e.fetchConcurrency,intervalCap:e.fetchIntervalCap,intervalMs:e.fetchIntervalMs}}function LX(e){e.registerTool(`seo_crawl_site`,{description:`Run a site crawl. Start with health=true for a fast uncached sitemap status and redirect pass, especially on large or unknown sites. Run the full crawl second when content-level evidence is needed. The compact result includes crawler identity and access-block guidance.`,inputSchema:{url:A.string().url().optional().describe(`Site start URL. Optional when sitemapUrl supplies the health-pass scope.`),health:A.boolean().optional().describe(`Run the fast sitemap health pass before a full crawl. Downloads no page bodies and writes no page cache entries.`),sitemapUrl:A.string().url().optional().describe(`Explicit sitemap or sitemap index URL for the health pass.`),site:A.string().optional(),googleAnalyticsPropertyId:A.string().optional(),clickySiteId:PX,maxPages:jX,maxDepth:MX,concurrency:NX,fetchIntervalCap:A.number().int().positive().optional(),fetchIntervalMs:A.number().int().positive().optional(),refresh:A.boolean().optional(),include:A.array(A.string()).optional(),exclude:A.array(A.string()).optional(),useSitemap:A.boolean().optional(),respectRobots:A.boolean().optional(),js:A.boolean().optional(),includePages:A.boolean().optional(),includeIssues:A.boolean().optional()}},async({url:e,health:t,sitemapUrl:n,site:r,googleAnalyticsPropertyId:i,clickySiteId:a,maxPages:o,maxDepth:s,concurrency:c,fetchIntervalCap:l,fetchIntervalMs:u,refresh:d,include:f,exclude:p,useSitemap:m,respectRobots:h,js:g,includePages:_,includeIssues:v})=>{try{let y=FX({googleAnalyticsPropertyId:i,clickySiteId:a}),b=e??(n?new URL(`/`,n).toString():void 0);if(!b)throw new N(`INVALID_INPUT`,`Pass url or an explicit sitemapUrl.`);let x=await zA({url:b,mode:t||n?`sitemap`:`site`,strategy:t?`health`:`full`,sitemapUrl:n,site:r,googleAnalyticsPropertyId:i,analyticsConnection:y,maxPages:o,maxDepth:s,concurrency:c,refresh:d,fetchRate:IX({fetchConcurrency:c,fetchIntervalCap:l,fetchIntervalMs:u}),include:f,exclude:p,useSitemap:m,respectRobots:h,js:!!g});return SX(`${t?`Sitemap health pass`:`Crawl`} complete for ${b}. Found ${x.issues.length} issues across ${x.summary.totalPages} pages.`,AX(x,{includePages:_,includeIssues:v}))}catch(e){return $(e)}}),e.registerTool(`seo_audit_urls`,{description:`Audit an explicit list of URLs with technical SEO checks. The compact result separates prioritised fixes from review observations. Set includePages/includeIssues for raw data.`,inputSchema:{urls:A.array(A.string().url()).min(1).max(qT),site:A.string().optional(),googleAnalyticsPropertyId:A.string().optional(),clickySiteId:PX,maxPages:jX,concurrency:NX,fetchIntervalCap:A.number().int().positive().optional(),fetchIntervalMs:A.number().int().positive().optional(),refresh:A.boolean().optional(),includePages:A.boolean().optional(),includeIssues:A.boolean().optional()}},async({urls:e,site:t,googleAnalyticsPropertyId:n,clickySiteId:r,maxPages:i,concurrency:a,fetchIntervalCap:o,fetchIntervalMs:s,refresh:c,includePages:l,includeIssues:u})=>{try{let d=FX({googleAnalyticsPropertyId:n,clickySiteId:r}),f=await zA({url:e[0]??``,urls:e,mode:`list`,site:t,googleAnalyticsPropertyId:n,analyticsConnection:d,maxPages:i??e.length,concurrency:a,refresh:c,fetchRate:IX({fetchConcurrency:a,fetchIntervalCap:o,fetchIntervalMs:s}),useSitemap:!1});return SX(`URL audit complete. Found ${f.issues.length} issues across ${f.summary.totalPages} pages.`,AX(f,{includePages:l,includeIssues:u}))}catch(e){return $(e)}}),e.registerTool(`seo_top_fixes`,{description:`Return top technical SEO fixes for a URL by running a compact crawl.`,inputSchema:{url:A.string().url(),site:A.string().optional(),maxPages:jX,maxDepth:MX,fetchIntervalCap:A.number().int().positive().optional(),fetchIntervalMs:A.number().int().positive().optional(),refresh:A.boolean().optional(),category:A.string().optional(),limit:A.number().int().min(1).max(1e3).optional()}},async({url:e,site:t,maxPages:n,maxDepth:r,fetchIntervalCap:i,fetchIntervalMs:a,refresh:o,category:s,limit:c})=>{try{let l=await zA({url:e,site:t,maxPages:n,maxDepth:r,refresh:o,fetchRate:IX({fetchIntervalCap:i,fetchIntervalMs:a})}),u=FT(l,{category:s,limit:c}),d=l.status===`completed`?``:` Coverage is ${l.status}: ${q(l.summary.crawledUrls,`URL`)} crawled from ${q(l.summary.discoveredUrls,`discovered URL`)}. Review the returned warnings and caveats before treating this as sitewide.`;return SX(`Found ${q(u.length,`top fix group`)} for ${l.config.url}.${d}`,{url:l.config.url,reportId:l.id,summary:l.summary,dataSources:l.dataSources,topFixes:u,warnings:l.warnings,caveats:l.caveats})}catch(e){return $(e)}}),e.registerTool(`seo_explain_issue`,{description:`Explain a crawler rule in plain English: why it matters, how to fix it, and how to verify it.`,inputSchema:{ruleId:A.string()}},async({ruleId:e})=>{let t=Je(e);return t?SX(`Rule guidance for ${e}.`,t):$(`Unknown rule: ${e}`)}),e.registerTool(`seo_list_rules`,{description:`List crawler rule ids and guidance metadata. Use this before the explain-crawl-issue report when you need valid rule ids.`,inputSchema:{category:OE.optional()}},async({category:e})=>{let t=qe().filter(t=>!e||t.category===e);return SX(`Found ${q(t.length,`crawler rule`)}.`,{rules:t})})}function RX(e,t={}){e.registerTool(`seo_doctor`,{description:`Check the local database, auth, scopes, config, and defaults`,inputSchema:{}},async()=>{try{let e=await xU();return SX(e.ok?`Local seo setup is ready.`:`Local seo setup needs attention.`,e)}catch(e){return $(e)}}),e.registerTool(`seo_segment_impact`,{description:`Compare matched retained GSC segments across adjacent equal-length periods without treating missing rows as zero`,inputSchema:{site:A.string().trim().min(1),days:A.number().int().min(1).max(240).optional(),limit:A.number().int().min(1).max(100).optional(),refresh:A.boolean().optional(),dimension:A.enum([`page`,`query`,`country`,`device`]).optional(),compareDays:A.number().int().min(1).max(240).optional(),startDate:wX.optional(),endDate:wX.optional(),maxRows:A.number().int().min(1).max(25e4).optional(),unmatchedLimit:A.number().int().min(0).max(100).optional()}},async({site:e,dimension:n,days:r,compareDays:i,startDate:a,endDate:o,limit:s,maxRows:c,unmatchedLimit:l,refresh:u})=>{try{let d=await(t.segmentImpact??Hj)({site:e,dimension:n,days:r,compareDays:i,startDate:a,endDate:o,limit:s,maxRows:c,unmatchedLimit:l,refresh:u});return SX(d.summary.verdict,d)}catch(e){return $(e)}}),e.registerTool(`seo_striking_distance`,{description:`Find position 11-20 query/page opportunities from GSC`,inputSchema:{...DX([`site`,`days`,`minImpressions`,`limit`,`verifyContent`,`verifyLimit`,`includeBrand`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),days:A.number().int().min(1).max(548).optional(),minImpressions:A.number().int().min(0).max(1e9).optional(),limit:A.number().int().min(1).max(100).optional(),verifyLimit:A.number().int().min(0).max(100).optional(),brandTerms:A.array(A.string().trim().min(1).max(200)).max(20).optional(),fetchConcurrency:A.number().int().min(1).max(16).optional(),fetchIntervalCap:A.number().int().min(1).max(60).optional(),fetchIntervalMs:A.number().int().min(100).max(6e4).optional()}},async({site:e,days:t,minImpressions:n,limit:r,verifyContent:i,verifyLimit:a,includeBrand:o,brandTerms:s,js:c,fetchConcurrency:l,fetchIntervalCap:u,fetchIntervalMs:d,refresh:f})=>{try{let p=await MP({site:e,days:t,minImpressions:n,limit:r,verifyContent:i,verifyLimit:a,includeBrand:o,brandTerms:s,js:TX(c,void 0),rate:IX({fetchConcurrency:l,fetchIntervalCap:u,fetchIntervalMs:d}),refresh:f});return SX(p.summary.verdict,p)}catch(e){return $(e)}}),e.registerTool(`seo_traffic_anomaly`,{description:`Detect statistically significant recent GSC traffic movement`,inputSchema:{...DX([`site`,`days`,`recentDays`,`refresh`])}},async({site:e,days:t,recentDays:n,refresh:r})=>{try{let i=await oF({site:e,days:t,recentDays:n,refresh:r});return SX(`${i.anomalies.filter(e=>e.significant).length} significant anomalies found.`,i)}catch(e){return $(e)}}),e.registerTool(`seo_update_correlate`,{description:`Overlay recent traffic anomalies against official Google ranking update windows`,inputSchema:{...DX([`site`,`days`,`recentDays`,`refresh`]),paddingDays:A.number().optional()}},async({site:e,days:t,recentDays:n,paddingDays:r,refresh:i})=>{try{let a=await sF({site:e,days:t,recentDays:n,paddingDays:r,refresh:i});return SX(`Classification: ${a.classification}.`,a)}catch(e){return $(e)}})}function zX(e){e.registerTool(`seo_index_coverage`,{description:`Crawl the site, compare it and its sitemap with Search Console page results, then choose representative URLs for URL Inspection`,inputSchema:{site:A.string().min(1),url:A.string().url().optional().describe(`Start URL to crawl. Defaults to the home page.`),sitemaps:A.array(A.string().url()).min(1).max(20).optional(),days:A.number().int().min(1).max(548).optional(),rowLimit:A.number().int().min(1).max(25e4).optional(),maxSitemapUrls:A.number().int().min(1).max(25e4).optional(),itemsPerSection:A.number().int().min(1).max(1e3).optional(),templateClusters:A.number().int().min(1).max(200).optional(),templateSamples:A.number().int().min(1).max(25).optional(),refresh:A.boolean().optional()}},async({site:e,url:t,sitemaps:n,days:r,rowLimit:i,maxSitemapUrls:a,itemsPerSection:o,templateClusters:s,templateSamples:c,refresh:l})=>{try{let u=await iL({site:e,url:t,sitemaps:n,days:r,rowLimit:i,maxSitemapUrls:a,itemsPerSection:o,templateClusters:s,templateSamples:c,refresh:l});return SX(`${u.summary.retainedSearchVisibleUrls} URLs appeared in the returned Search Console data. ${u.summary.crawlableCandidatesWithoutRetainedSearchVisibility} crawlable URLs need evidence review before choosing representative URL Inspection checks.`,u)}catch(e){return $(e)}}),e.registerTool(`seo_redirect_trace`,{description:`Trace redirects and report final indexability/canonical issues for a URL`,inputSchema:{url:A.string().url(),maxHops:A.number().optional(),refresh:A.boolean().optional(),js:A.boolean().optional()}},async({url:e,maxHops:t,refresh:n,js:r})=>{try{let i=await sL({url:e,maxHops:t,refresh:n,js:TX(r,`auto`)});return SX(`Traced ${i.summary.hops} hops. Final status ${i.summary.finalStatus}. ${i.summary.issues.length} issues.`,i)}catch(e){return $(e)}}),e.registerTool(`seo_link_recover`,{description:`Find GSC search-value URLs that are now broken, blocked, or poorly redirected`,inputSchema:{...DX([`site`,`days`,`limit`,`minImpressions`,`refresh`,`js`]),minClicks:A.number().optional()}},async({site:e,days:t,limit:n,minClicks:r,minImpressions:i,refresh:a,js:o})=>{try{let s=await fL({site:e,days:t,limit:n,minClicks:r,minImpressions:i,refresh:a,js:TX(o,`auto`)});return SX(`Checked ${s.summary.checked} search-value URLs. ${s.summary.recoverable} recoverable issues.`,s)}catch(e){return $(e)}})}const BX=A.enum([`dataforseo`,`ahrefs`]),VX=e=>A.string().trim().min(1).max(500).describe(e).optional(),HX=A.strictObject({keyword:VX(`Source column containing the search query.`),url:VX(`Source column containing the ranking URL.`),position:VX(`Source column containing grouped position.`),absolutePosition:VX(`Source column containing absolute result position.`),searchVolume:VX(`Source column containing monthly search volume.`),keywordDifficulty:VX(`Source column containing keyword difficulty.`),cpc:VX(`Source column containing cost per click.`),paidCompetition:VX(`Source column containing paid competition.`),intent:VX(`Source column containing search intent.`),resultCount:VX(`Source column containing estimated result count.`),estimatedTraffic:VX(`Source column containing estimated monthly visits.`),resultType:VX(`Source column containing result type.`),searchVolumeUpdatedAt:VX(`Source column containing the search volume update date.`)}).superRefine((e,t)=>{let n=new Map;for(let[r,i]of Object.entries(e)){if(!i)continue;let e=rM(i),a=n.get(e);a?t.addIssue({code:`custom`,message:`Source column "${i}" is already mapped to "${a}".`,path:[r]}):n.set(e,r)}}).describe(`Optional canonical field to source column mapping. Named fields override automatic header matching.`),UX=A.array(A.strictObject({dataset:A.literal(`ranked-keywords`),file:A.string().trim().min(1).max(4096),provider:BX,exportedAt:A.string().trim().min(1).max(100),format:A.enum([`csv`,`json`,`jsonl`]).optional(),rowLimit:A.number().int().min(1).max(1e5).optional(),columns:HX.optional()})).min(1).max(4).describe(`One to four local ranked-keyword exports from the same provider and market.`);function WX(e,t={}){e.registerTool(`seo_cannibal`,{description:`Find multi-URL query exposure candidates for intent and technical review`,inputSchema:{...DX([`site`,`days`,`limit`,`minImpressions`,`includeBrand`,`refresh`]),days:A.number().int().min(1).max(548).optional(),limit:A.number().int().min(1).max(100).optional(),minImpressions:A.number().int().min(0).max(1e9).optional(),brandTerms:A.array(A.string().trim().min(1).max(200)).max(20).optional(),researchFiles:UX.optional()}},async({site:e,days:t,limit:n,minImpressions:r,brandTerms:i,includeBrand:a,refresh:o,researchFiles:s})=>{try{let c=s?await TN({site:e,days:t,limit:n,minImpressions:r,brandTerms:i,includeBrand:a,refresh:o,researchFiles:s}):await TN({site:e,days:t,limit:n,minImpressions:r,brandTerms:i,includeBrand:a,refresh:o});return SX(c.summary.verdict,c)}catch(e){return $(e)}}),e.registerTool(`seo_decaying`,{description:`Find query/page click declines observed in both retained GSC windows and investigation signals`,inputSchema:{...DX([`site`,`days`,`limit`,`includeBrand`,`refresh`]),days:A.number().int().min(1).max(548).optional(),limit:A.number().int().min(1).max(100).optional(),comparison:A.enum([`previous-period`,`year-over-year`]).optional(),minDropPct:A.number().min(0).max(100).optional(),minPreviousClicks:A.number().min(0).max(1e9).optional(),minClickLoss:A.number().min(0).max(1e9).optional(),brandTerms:A.array(A.string().trim().min(1).max(200)).max(20).optional()}},async({site:e,days:t,limit:n,comparison:r,minDropPct:i,minPreviousClicks:a,minClickLoss:o,brandTerms:s,includeBrand:c,refresh:l})=>{try{let u=await HN({site:e,days:t,limit:n,comparison:r,minDropPct:i,minPreviousClicks:a,minClickLoss:o,brandTerms:s,includeBrand:c,refresh:l});return SX(u.summary.verdict,u)}catch(e){return $(e)}}),e.registerTool(`seo_quick_wins`,{description:`Find quick-win CTR/position opportunities`,inputSchema:{...DX([`site`,`days`,`limit`,`minImpressions`,`verifyContent`,`verifyLimit`,`includeBrand`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]),days:A.number().int().min(1).max(548).optional(),limit:A.number().int().min(1).max(100).optional(),minImpressions:A.number().int().min(0).max(1e9).optional(),verifyLimit:A.number().int().min(0).max(100).optional(),brandTerms:A.array(A.string().trim().min(1).max(200)).max(20).optional(),fetchConcurrency:A.number().int().min(1).max(16).optional(),fetchIntervalCap:A.number().int().min(1).max(60).optional(),fetchIntervalMs:A.number().int().min(100).max(6e4).optional()}},async({site:e,days:n,limit:r,minImpressions:i,brandTerms:a,verifyContent:o,verifyLimit:s,includeBrand:c,js:l,fetchConcurrency:u,fetchIntervalCap:d,fetchIntervalMs:f,refresh:p})=>{try{let m=await(t.quickWinsReport??dP)({site:e,days:n,limit:r,minImpressions:i,brandTerms:a,verifyContent:o,verifyLimit:s,includeBrand:c,js:TX(l,void 0),rate:IX({fetchConcurrency:u,fetchIntervalCap:d,fetchIntervalMs:f}),refresh:p});return SX(m.summary.verdict,m)}catch(e){return $(e)}}),e.registerTool(`seo_internal_links`,{description:`Find verified internal-link review candidates for a target URL`,inputSchema:{...DX([`site`,`refresh`]),targetUrl:A.string().url().refine(e=>/^https?:\/\//.test(e),`Use an HTTP(S) URL.`),startDate:A.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),endDate:A.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional()}},async({site:e,targetUrl:n,startDate:r,endDate:i,refresh:a})=>{try{let o=await(t.internalLinksReport??TI)({site:e,targetUrl:n,startDate:r,endDate:i,refresh:a});return SX(o.summary.verdict,o)}catch(e){return $(e)}}),e.registerTool(`seo_ctr_underperformers`,{description:`Find high-impression queries underperforming CTR expectations`,inputSchema:{...DX([`site`,`minImpressions`,`limit`,`includeBrand`,`refresh`]),site:A.string().trim().min(1),minImpressions:A.number().int().min(1).max(1e9).optional(),limit:A.number().int().min(1).max(100).optional(),brandTerms:A.array(A.string().trim().min(1).max(200)).max(20).optional()}},async({site:e,minImpressions:n,limit:r,brandTerms:i,includeBrand:a,refresh:o})=>{try{let s=await(t.ctrUnderperformersReport??yj)({site:e,minImpressions:n,limit:r,brandTerms:i,includeBrand:a,refresh:o});return SX(s.summary.verdict,s)}catch(e){return $(e)}}),e.registerTool(`seo_query_cluster`,{description:`Cluster queries by token overlap`,inputSchema:{...DX([`site`,`includeBrand`,`minImpressions`,`limit`,`refresh`]),site:A.string().trim().min(1),scope:A.string().trim().min(1).max(2e3).optional(),minImpressions:A.number().int().min(1).max(1e9).optional(),limit:A.number().int().min(1).max(100).optional(),brandTerms:A.array(A.string().trim().min(1).max(200)).max(20).optional()}},async({site:e,scope:n,brandTerms:r,includeBrand:i,minImpressions:a,limit:o,refresh:s})=>{try{let c=await(t.queryClusterReport??uR)({site:e,scope:n,brand:r?.[0],brandTerms:r,includeBrand:i,minImpressions:a,limit:o,refresh:s});return SX(c.summary.verdict,c)}catch(e){return $(e)}})}const GX={"ai-referrals":{readOrder:[`dataStatus, range, methodology, and dataSource partialReasons`,`possiblyTruncated and per-query statuses`,`selection.landingPages before treating landingPages as complete`,`sources observedSessionSources for attribution evidence`],doNotClaim:[`An empty result is not proof that no AI system sent or cited the site.`,`Referral sessions did not necessarily cause conversions and are not all AI traffic.`,`totalUsers is not additive and must not be reconstructed by summing rows.`],verify:`Compare complete like-for-like Google Analytics periods and check whether high-session landing pages answer the referring context.`,related:[]},"audit-page":{readOrder:[`fetchDiagnostics, warnings, and the final fetched URL`,`observed page fields and structured-data findings`,`issues and recommendations`],doNotClaim:[`One page cannot support a sitewide conclusion.`,`Title pixel width is a review estimator, not a Google limit.`,`The fetched version is not proof that Google indexed that version.`],verify:`Re-fetch the URL after the edit and confirm the observed field changed.`,related:[{id:`redirect-trace`,reason:`Debugs the redirect chain.`},{id:`performance-audit`,reason:`Adds page speed evidence.`},{id:`content-optimization`,reason:`Builds a query-led brief.`}]},"audit-urls":{readOrder:[`requested versus attempted, fetched, failed, retained, and omitted counts`,`topFixes AND reviewObservations together; the two lists are the complete grouped issue inventory, so carry every group from both into findings`,`response evidence and issue summaries`,`requestEvidenceStatus, warnings, and caveats`],doNotClaim:[`A successful sample does not prove the same template works everywhere.`,`A failed request may be transient network, not a persistent defect.`,`A bounded audit is never complete site coverage.`],verify:`Re-run the identical URL list after deployment; a URL dropped from the request is not a verified fix.`,related:[{id:`audit-page`,reason:`Inspects one page in depth.`},{id:`site-crawl`,reason:`Discovers pages instead.`},{id:`redirect-trace`,reason:`Traces a redirecting URL.`}]},cannibalisation:{readOrder:[`dataStatus and both source.pageExposure and source.propertyDemand with validation counts and completeness`,`selection to see why groups were excluded or suppressed`,`per-page clicks, impressions, position, impression share, reviewContext, and HHI`,`priority.score and suggestedOwnerUrl`,`dataSource plus evidence.imports file dates, hashes, and row quality when the run used researchFiles`],doNotClaim:[`URL overlap is a review candidate, not proven harmful cannibalisation.`,`suggestedOwnerUrl is a low-confidence mechanical pick that requires intent review.`,`priority.score is a heuristic, not estimated click lift, and a partial source cannot support an all-clear.`,`Research-import rows are provider estimates that support multiple-ranking-URL claims only, not traffic or Search Console-verified cannibalisation.`],verify:`Compare intent and live SERPs for the overlapping URLs before consolidating anything.`,related:[{id:`query-clusters`,reason:`Groups related query themes.`},{id:`internal-links`,reason:`Clarifies link ownership.`},{id:`content-optimization`,reason:`Differentiates page intent.`}]},"content-optimization":{readOrder:[`sourceReport dataStatus, selection, benchmark.possiblyTruncated, and verification.status`,`summary.score and primaryIntent as heuristics`,`topActions separating technical-check and unverified from verified observations`,`intentMix and the source query metrics`],doNotClaim:[`estimatedClickLift and score are prioritisation heuristics, not forecasts or quality grades.`,`Query wording is not a content mandate.`,`Adding suggested wording is not guaranteed traffic.`],verify:`Fetch the page after the edit and confirm the missing answer block or clearer framing is present.`,related:[{id:`page-opportunities`,reason:`Adds query-level opportunities.`},{id:`internal-links`,reason:`Finds contextual links.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`}]},"crawler-rules":{readOrder:[`each rule id, title, and category`,`default severity as triage metadata`,`guidance metadata`],doNotClaim:[`Listing a rule does not mean the site triggered it or that the convention is a search-engine requirement.`,`Default severity is generic triage metadata, not actual priority.`,`Similarly named rules may not share source semantics.`],verify:`Pass the exact rule id to explain-crawl-issue, then check the matching issues in a site crawl.`,related:[{id:`explain-crawl-issue`,reason:`Returns the rule contract.`}]},"ctr-underperformers":{readOrder:[`dataStatus, range, source.completeness, possiblyTruncated, and validation counts`,`brand terms used, then selection before the queue; rows at average position 4 or worse belong to quick-wins`,`per-item query, URL, impressions, position, observed CTR, target CTR, benchmark source, and queryFlags`,`estimated shortfall`],doNotClaim:[`The shortfall is directional prioritisation math, not a traffic forecast.`,`Page-one average position hides day, device, geography, and result-feature variation.`,`A partial empty result is not an all-clear.`],verify:`Inspect the current SERP and displayed title link, then compare a complete later period after testing framing.`,related:[{id:`quick-wins`,reason:`Ranks position 4-10 opportunities.`},{id:`page-opportunities`,reason:`Reviews one URL.`},{id:`content-optimization`,reason:`Builds a page brief.`}]},"decaying-pages":{readOrder:[`dataStatus, ranges, and source.completeness`,`current and previous fetched rows, caps, truncation, and invalid rows in selection`,`summary.observedRetainedQueryClickLoss versus the returned subset`,`per-item clicks, impressions, CTR, position, and signals`],doNotClaim:[`A diagnosis such as lost_position or lost_ctr labels correlated movement, not a cause.`,`Missing retained rows are not zero traffic.`,`Do not sum capped rows into a property-wide loss.`],verify:`Check deployments, live indexability, and SERP composition for the affected URLs before editing.`,related:[{id:`refresh-priorities`,reason:`Combines decline signals.`},{id:`segment-impact`,reason:`Shows where movement concentrates.`}]},"explain-crawl-issue":{readOrder:[`category, default severity, and why it matters`,`fix steps and ignored impact`,`verification method and agent hints`],doNotClaim:[`Guidance describes the checked condition, not a search-engine penalty or guaranteed ranking effect.`,`Default severity is generic prioritization metadata, not actual urgency.`,`The rule definition alone does not prove any page triggered it.`],verify:`Pair the definition with the matching issues from a site crawl and confirm the per-URL evidence.`,related:[{id:`crawler-rules`,reason:`Finds a rule id.`},{id:`top-fixes`,reason:`Ranks the fix queue.`}]},"index-coverage":{readOrder:[`sources completeness, rowLimit, rowLimitReached, date range, and invalid rows`,`retainedSearchVisibility and crawlableWithoutRetainedSearchVisibility`,`blockedOrNonIndexable, sitemapOnly, searchConsoleOnly, and templateReview`,`each group count, returned, and omitted`],doNotClaim:[`A page is not indexed because it had Search Analytics visibility, nor unindexed because no row appeared.`,`A missing Search Analytics row is not proof a page is unindexed.`,`Do not turn a limited or incomplete source into a whole-site coverage percentage.`],verify:`Run seo page --url on representative URLs to collect exact URL Inspection verdicts.`,related:[{id:`site-crawl`,reason:`Provides the source crawl.`}]},"internal-links":{readOrder:[`dataStatus, target verification, aliases, canonical, and technical signals`,`source completeness and selection attempted, checked, failed, unchecked, and exclusions`,`per-item exact versus lexical matches and linkEvidence`,`per-item placement: the sentence where a link fits, its anchors, and contentSimilarity`],doNotClaim:[`The live check stops at 40 source pages, so unchecked candidates can remain and absence is not proven.`,`Query overlap does not prove a link belongs or that adding one improves rankings.`,`Priority is a heuristic, not estimated impact.`,`Placement sentences, anchors and contentSimilarity are text heuristics; they do not prove the link helps a reader.`],verify:`Read the source passage, add one contextual link if the target is genuinely useful, and re-crawl to confirm it.`,related:[{id:`cannibalisation`,reason:`Checks URL overlap.`},{id:`content-optimization`,reason:`Builds a page brief.`},{id:`page-opportunities`,reason:`Reviews one URL.`}]},"link-recovery":{readOrder:[`range and summary.checked with severity totals`,`per-item original and final URL, GSC metrics, issue lists, and redirect trace`,`chain status, final-page indexability, canonicals, and warnings`],doNotClaim:[`clicksAtRisk and impressionsAtRisk describe the checked period, not a forecast of loss or recovery.`,`Prior visibility orders the queue but does not prove fixing a URL restores traffic.`,`Failed checks or selection limits constrain coverage.`],verify:`Add one direct 301 to the closest equivalent destination only after confirming the page should still exist, then re-trace.`,related:[{id:`redirect-trace`,reason:`Traces one URL chain.`},{id:`decaying-pages`,reason:`Shows click declines.`},{id:`audit-urls`,reason:`Runs bounded checks.`}]},"page-opportunities":{readOrder:[`dataStatus, range, source.targetRowsFetched, selection, and benchmark`,`benchmark.possiblyTruncated`,`verification.status and reason`,`per-item query metrics, opportunity type, and benchmark and verification evidence`],doNotClaim:[`Only verified results support live-page coverage observations.`,`estimatedCtrClickShortfall is a directional calculation, not a click forecast.`,`summary.opportunities is a review queue, not a defect count, and partial data is not an all-clear.`],verify:`Inspect the live SERP and resolve any status or indexability contradiction before editing.`,related:[{id:`content-optimization`,reason:`Builds a page brief.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`},{id:`internal-links`,reason:`Finds contextual links.`}]},"performance-audit":{readOrder:[`dataStatus, source, labDataStatus, and fieldDataStatus`,`Lighthouse score, lab metrics, and labInsights`,`CrUX fieldData.metrics with scope, formFactor, and collectionPeriod`,`fetch-fallback fields when source is fetch-fallback`],doNotClaim:[`Origin-level CrUX data is not page-level evidence.`,`A fetch-fallback duration is the local fetch workflow, not TTFB, LCP, CLS, TBT, or INP, and never earns a score.`,`Do not combine lab and field values into a new score, compare mobile with desktop as equal populations, or claim a ranking outcome.`],verify:`Reproduce the relevant lab issue and re-run the audit after the change.`,related:[{id:`audit-page`,reason:`Runs an on-page audit.`},{id:`site-crawl`,reason:`Builds the site inventory.`}]},"query-clusters":{readOrder:[`summary cluster and query counts, clicks, impressions, threshold, limit, and brand filtering`,`per-cluster member queries, pages, demand, and performance`,`each cluster recommendation`],doNotClaim:[`Token overlap does not prove shared intent, justify a new page, or establish that current URLs compete.`,`Page-two clusters do not claim a CTR-only click lift.`,`Queries below the threshold or outside the cap are outside the conclusion, not absent demand.`],verify:`Check whether a cluster maps to one intent before changing section structure or navigation.`,related:[{id:`cannibalisation`,reason:`Checks URL overlap.`},{id:`content-optimization`,reason:`Builds a page brief.`}]},"quick-wins":{readOrder:[`dataStatus, date range, source row cap, possiblyTruncated, selection.invalidRows, and filters`,`methodology and each item benchmark confidence before using targetCtr`,`estimatedCtrClickShortfall and priority`,`verification requested, attempted, verified, failed, and technical counts`],doNotClaim:[`estimatedCtrClickShortfall and priority score are heuristics, explicitly not estimated lift.`,`Average position is not a stable rank, and an unverified item cannot support a content-coverage conclusion.`,`Filtered or capped evidence is not an all-clear.`],verify:`Inspect the live SERP, test clearer snippet framing, then compare a later complete window.`,related:[{id:`ctr-underperformers`,reason:`Adds CTR peer evidence.`},{id:`page-opportunities`,reason:`Reviews one URL.`},{id:`striking-distance`,reason:`Finds rows near page one.`}]},"redirect-trace":{readOrder:[`chain in order with requested URL, status, Location, resolved next, and duration`,`finalUrl versus finalPage and summary.finalStatus`,`summary.issues`,`metaRobots, xRobotsTag, canonical, and warnings`],doNotClaim:[`The trace is one observation from the machine and time that ran it, and CDNs, geography, cookies, or later deploys can differ.`,`A canonical elsewhere or a 302 can be intentional.`,`JavaScript rendering affects final-page extraction, not the HTTP chain.`],verify:`Re-run the trace after deployment and confirm the intended destination and status.`,related:[{id:`link-recovery`,reason:`Prioritises search-value URLs.`},{id:`audit-page`,reason:`Audits the final page.`},{id:`audit-urls`,reason:`Runs bounded checks.`}]},"refresh-priorities":{readOrder:[`workflow steps and skipped states`,`per-item source, impactKind, score breakdown, date window, completeness, verification status, and rationale`,`the top few URLs manually`],doNotClaim:[`A click decline, low CTR, second-page position, and Google Analytics session signal have different semantics and are not interchangeable.`,`Missing Google Analytics or failed fetches stay unavailable, not zero-weight proof.`,`The score is not expected clicks, revenue, ranking lift, or causal confidence.`],verify:`Confirm query intent, current content, and internal links for the top URLs before choosing a bounded edit.`,related:[{id:`decaying-pages`,reason:`Shows click declines.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`},{id:`second-page`,reason:`Finds rows near page one.`}]},"search-performance-overview":{readOrder:[`workflow envelope with summary, steps, actions, and output`,`report dataStatus, skipped sections, and partial reasons`,`priorities`,`nested anomaly, update, segment, decay, cannibalisation, striking-distance, and quick-win results`],doNotClaim:[`One complete section must not hide a failed or capped neighbour.`,`Sparse data may legitimately skip a section.`,`Update overlap, opportunity scores, average position, and timing are investigation signals, not causation or forecasts.`],verify:`Run the focused report named in actions and confirm affected URLs and provider dates before editing.`,related:[{id:`segment-impact`,reason:`Shows where movement sits.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`},{id:`striking-distance`,reason:`Finds rows near page one.`}]},"second-page":{readOrder:[`source completeness, date range, selection, methodology, provenance, and brand filtering`,`per-item impressions, clicks, CTR, and average position`,`the priority value`],doNotClaim:[`Average position is aggregated across searches, locations, devices, and time and is not an exact rank.`,`Retained limits mean the output is not a complete inventory.`,`Priority is a transparent heuristic, not expected click lift, and one row is not cannibalisation.`],verify:`Inspect the live page and search intent and confirm the query suits the URL before one defensible change.`,related:[{id:`striking-distance`,reason:`Covers positions 11-20.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`},{id:`page-opportunities`,reason:`Reviews one URL.`}]},"segment-impact":{readOrder:[`before, after, and rangeDays`,`dataStatus and source.before, source.after, and completeness for caps and truncation`,`selection invalid, duplicate, conflicting, matched, unmatched, returned, and limited rows`,`per-item clickDelta, impressionDelta, and positionDelta, then unmatchedSegments`],doNotClaim:[`A positive positionDelta is worse because a larger average position is lower in results.`,`unmatchedSegments are retained in one window only and are not gains from or losses to zero.`,`A limited or truncated result cannot support an inventory-wide winner or loser.`],verify:`Audit the top matched movers pages and query intent before drawing a segment conclusion.`,related:[{id:`traffic-anomaly`,reason:`Confirms movement first.`},{id:`decaying-pages`,reason:`Shows click declines.`},{id:`update-postmortem`,reason:`Frames movement around an update.`}]},"setup-check":{readOrder:[`ok`,`each checks entry status, distinguishing fail from warn, with detail and fix`,`generatedAt`],doNotClaim:[`A passing result means local prerequisites look present, not that a token is still accepted by Google or that the account can access a property.`,`Missing saved defaults are usually warnings because explicit parameters can replace them.`,`A setup pass is not evidence about rankings, indexing, or site health.`],verify:`Apply the fix on a failed check, re-run setup-check, then run a small read-only report for the intended property.`,related:[{id:`search-performance-overview`,reason:`First report once setup passes.`}]},"site-crawl":{readOrder:[`config.strategy first; use health before full on large or unknown sites`,`status, requestEvidenceStatus, attempted and fetched counts, failures, retained pages, and pageLimitReached`,`access crawler identity, blockedRequests, provider counts, and samples`,`data-source states`,`topFixes AND reviewObservations together; the two lists are the complete grouped issue inventory, so carry every group from both into findings`,`warnings and caveats, then opt-in pages, requests, and issues`],doNotClaim:[`A partial or capped crawl cannot support an all-clear or a definitive zero.`,`A crawl is not an index, traffic source, or guarantee of complete site coverage.`,`A health pass checks response access, status, and redirects only. It does not download page bodies or evaluate content, metadata, canonicals, indexability directives, internal links, or rendered HTML. For full crawls, state when JavaScript rendering was disabled.`,`A User-Agent can be spoofed. Never ask the user for a broad firewall bypass based on crawler identity alone.`],verify:`Re-run the same health configuration first. Use a full crawl only when the health evidence is clean and the question needs page-body analysis.`,related:[{id:`top-fixes`,reason:`Ranks the fix queue.`},{id:`index-coverage`,reason:`Checks coverage signals.`}]},"striking-distance":{readOrder:[`range, rangeDays, dataStatus, and source`,`source.possiblyTruncated and retained-row completeness`,`selection invalid, out-of-range, branded, below-threshold, eligible, returned, and limited`,`methodology, then per-item metrics and contentVerification`],doNotClaim:[`The 11-20 band is a heuristic boundary and average position is not a literal second results page.`,`Unverified or failed pages keep lower confidence.`,`The priority score is not expected traffic or ranking lift.`],verify:`Audit a small number of high-impression candidates and fix verified technical problems first.`,related:[{id:`second-page`,reason:`Covers positions 10-20.`},{id:`quick-wins`,reason:`Ranks CTR opportunities.`},{id:`page-opportunities`,reason:`Reviews one URL.`}]},"top-fixes":{readOrder:[`dataSources, summary, warnings, and caveats`,`per-item rule id, affected count, sample URLs, scoreFactors, and whyThisRanks`,`effort, fix guidance, and verification`],doNotClaim:[`Rank means highest among retained eligible findings, not globally highest, because the crawl or category may be capped.`,`Missing provider joins stay unavailable and a numeric zero is meaningful only when the source is complete.`,`This is not a forecast of rankings, traffic, or revenue.`],verify:`Repeat the same crawl configuration after implementation and confirm the rule no longer triggers.`,related:[{id:`explain-crawl-issue`,reason:`Explains the rule.`},{id:`site-crawl`,reason:`Provides the source crawl.`}]},"traffic-anomaly":{readOrder:[`coverage with requested dates, expected versus observed days, missing days, invalid rows, and status`,`anomalies with metric, baseline and comparison dates, percentChange, zScore, and significanceMethod`,`direction and significant`,`detection, changeDate and the detection thresholds: a step change compares every day before its change date with every day from it`],doNotClaim:[`Statistical unusualness does not identify a cause, diagnose a defect, or prove an external event affected the property.`,`A null percentage from a zero baseline differs from zero change.`,`Partial coverage can change the baseline.`],verify:`If movement is significant and coverage is adequate, run segment-impact for pages and queries.`,related:[{id:`segment-impact`,reason:`Shows where movement sits.`},{id:`update-correlation`,reason:`Adds update timing.`},{id:`decaying-pages`,reason:`Shows click declines.`}]},"update-correlation":{readOrder:[`classification with attribution and confidence, returned as not-established and none`,`anomalies, overlappingUpdates, and confounders`,`evidence, caveats, and source`],doNotClaim:[`Overlap cannot show the update caused a gain or loss even with large movement and no other recorded change.`,`update-overlap-without-significant-movement is not an impact result and no-update-overlap does not explain remaining movement.`,`Temporal overlap is not a penalty, reward, or confirmed effect.`],verify:`Test saved deploys, redirects, and content changes that overlap the window before attributing movement.`,related:[{id:`update-postmortem`,reason:`Maps winners and losers.`},{id:`segment-impact`,reason:`Shows where movement sits.`},{id:`traffic-anomaly`,reason:`Confirms movement first.`}]},"update-postmortem":{readOrder:[`workflow step statuses, finalized date windows, and source completeness`,`failed measurements, retained limits, and caveats`,`update, insights, templateMovement, and segments`],doNotClaim:[`The cause remains not established even when dates overlap.`,`Retained winners and losers are not a complete inventory when sources are capped or filtered.`,`Do not claim update causation, recovery probability, or future traffic.`],verify:`Inspect representative URLs from affected segments and reproduce technical changes before any rollback.`,related:[{id:`update-correlation`,reason:`Adds update timing.`},{id:`segment-impact`,reason:`Shows where movement sits.`}]}},KX={"ai-referrals":{name:`AI referral traffic`,description:`Find visits from known AI products in Google Analytics and see a ranked, bounded set of landing pages that received them.`,useWhen:[`You want measured AI referral traffic from Google Analytics.`,`You need the landing pages and sources behind those visits.`],avoidWhen:[`Google Analytics is not connected or does not track the site.`,`You want to measure citations or unclicked mentions inside AI answers.`],outcome:`A source and landing-page breakdown of identifiable AI referrals.`},"audit-page":{name:`Single-page SEO audit`,description:`Check one URL for response, indexability, metadata, headings, links, and page content evidence.`,useWhen:[`One page needs a technical review before you change it.`,`A broader report points to a specific URL.`],avoidWhen:[`You need to discover issues across a whole site.`,`The page requires a logged-in browser session.`],outcome:`A page-level audit that separates observed evidence from review advice.`},"audit-urls":{name:`Selected URL audit`,description:`Audit a specific list of pages without crawling the rest of the site.`,useWhen:[`You already know which URLs need checking.`,`You want a repeatable pre-release or post-release check for key pages.`],avoidWhen:[`You need the crawler to discover pages for you.`,`You only need a deep review of one page.`],outcome:`Consistent technical checks for each supplied URL.`},cannibalisation:{name:`Query and URL overlap`,description:`Find search queries that appear across several URLs and decide whether the overlap needs attention.`,useWhen:[`Several pages may be competing for the same search intent.`,`You want query-level evidence before merging or redirecting pages.`],avoidWhen:[`You plan to treat every multi-URL query as a problem.`,`The site has too little Search Console data for meaningful overlap.`],outcome:`A ranked review list of queries, URLs, and their share of search exposure.`},"content-optimization":{name:`Search-led content brief`,description:`Turn a page and its Search Console queries into a practical brief for improving relevance and coverage.`,useWhen:[`An existing page has search demand but needs a clearer improvement plan.`,`You want first-party query evidence beside the current page content.`],avoidWhen:[`The URL has no useful Search Console history.`,`You want generated copy or a traffic forecast.`],outcome:`A page brief with query evidence, content checks, and specific review points.`},"crawler-rules":{name:`Crawler rule catalog`,description:`Find the available technical check IDs and the evidence each crawler rule looks for.`,useWhen:[`You need a valid rule ID for another crawl report.`,`You want to see which technical checks are available by category.`],avoidWhen:[`You need affected pages or live crawl results.`],outcome:`A searchable catalog of crawler rules, severity, and guidance.`},"ctr-underperformers":{name:`CTR underperformers`,description:`Find high-impression queries whose click-through rate trails comparable queries at similar positions.`,useWhen:[`You want title or snippet review candidates backed by Search Console data.`,`You need to compare CTR fairly across similar average positions.`],avoidWhen:[`You want a promised click uplift.`,`The comparison groups have too little data.`],outcome:`A ranked list of query and page pairs with CTR comparison evidence.`},"decaying-pages":{name:`Pages losing search clicks`,description:`Find pages and queries with meaningful click declines across comparable Search Console periods.`,useWhen:[`You want to investigate a sustained organic search decline.`,`You need the pages and queries behind lost clicks.`],avoidWhen:[`The newer period is incomplete or not comparable.`,`You want to assume every decline is caused by old content.`],outcome:`A ranked investigation list with before-and-after search evidence.`},"explain-crawl-issue":{name:`Explain a crawl issue`,description:`Explain what one crawler rule means, why it may matter, and how to verify a fix.`,useWhen:[`A crawl returned a rule ID you do not recognize.`,`You need implementation and verification guidance before creating work.`],avoidWhen:[`You need the URLs affected by the rule.`,`You have not selected a valid crawler rule ID.`],outcome:`A plain-English rule explanation with fix and verification steps.`},"index-coverage":{name:`Index coverage signals`,description:`Compare the pages your site exposes with pages that had Google Search visibility, then choose representative URLs for URL Inspection.`,useWhen:[`You need to find crawlable pages that did not appear in the Search Console results returned for the selected period.`,`You want a focused review list before spending URL Inspection quota.`],avoidWhen:[`You need proof that a URL is indexed or excluded. Use URL Inspection for that URL.`,`The site blocks crawlers, so the crawl cannot list its pages.`],outcome:`Cross-source URL groups with clear evidence limits and a representative review queue for URL Inspection.`},"internal-links":{name:`Internal link opportunities`,description:`Find relevant pages that could add a useful internal link to a target URL.`,useWhen:[`A target page needs stronger internal discovery or contextual links.`,`You want candidate source pages checked against their current content.`],avoidWhen:[`You want links added automatically.`,`The target and candidate pages do not share a clear topic or user need.`],outcome:`Verified source-page candidates with query and page evidence for review.`},"link-recovery":{name:`Recover broken search-value URLs`,description:`Find URLs that previously earned search clicks but now fail, redirect poorly, or block indexing.`,useWhen:[`You suspect valuable URLs broke during a migration or release.`,`You want to prioritize technical recovery using Search Console evidence.`],avoidWhen:[`You want a backlink report.`,`You have no Search Console page history for the site.`],outcome:`A ranked recovery list with current URL checks and prior search value.`},"page-opportunities":{name:`Opportunities for one page`,description:`Find Search Console queries and page evidence that point to useful improvements for one URL.`,useWhen:[`You want to improve an existing page using its own search demand.`,`You need query themes and page checks in one result.`],avoidWhen:[`The page has no useful Search Console data.`,`You want a guaranteed traffic gain.`],outcome:`A ranked page improvement list tied to real queries and current content.`},"performance-audit":{name:`Page performance audit`,description:`Run Lighthouse lab checks and add CrUX field Core Web Vitals when that data is available.`,useWhen:[`You need actionable performance diagnostics for a page.`,`You want lab findings kept separate from real-user field data.`],avoidWhen:[`You want Lighthouse scores presented as field Core Web Vitals.`,`The page cannot be fetched from the local machine.`],outcome:`Lab diagnostics plus clearly labelled field metrics when available.`},"query-clusters":{name:`Search query clusters`,description:`Group related Search Console queries so repeated demand themes are easier to review.`,useWhen:[`A large query list needs a clearer topic structure.`,`You want to find repeated wording within a site section.`],avoidWhen:[`You need semantic or intent classification beyond shared query terms.`,`You want clusters turned into new pages automatically.`],outcome:`Stable query groups with the search demand behind each theme.`},"quick-wins":{name:`Page-one CTR opportunities`,description:`Find page-one query and URL pairs whose CTR deserves a closer look.`,useWhen:[`You want high-impression title and snippet review candidates.`,`You need page-one opportunities ranked from Search Console data.`],avoidWhen:[`You want a promised click gain.`,`You plan to treat a CTR heuristic as a Google requirement.`],outcome:`A ranked review queue with CTR, position, impressions, and comparison evidence.`},"redirect-trace":{name:`Redirect trace`,description:`Follow every redirect hop and check the final page, indexability, and canonical signals.`,useWhen:[`A URL redirects unexpectedly or through several hops.`,`You need to verify the final destination after a migration.`],avoidWhen:[`You need to discover redirect issues across a whole site.`,`The URL requires a signed-in browser session.`],outcome:`The complete redirect chain with final response and page checks.`},"refresh-priorities":{name:`Content refresh priorities`,description:`Combine search declines and near-term opportunities into a ranked content review queue.`,useWhen:[`You need to decide which existing pages to review first.`,`You want several Search Console signals ranked in one queue.`],avoidWhen:[`You need a technical crawl plan.`,`You want the ranking treated as a traffic forecast.`],outcome:`A focused list of pages and queries to investigate next, with reasons.`},"search-performance-overview":{name:`Search performance overview`,description:`Find where Google Search performance changed and choose the next focused report to inspect it.`,useWhen:[`You are starting an investigation and do not yet know which pages or queries moved.`,`You want one view of declines, gains, overlap, and near-term opportunities.`],avoidWhen:[`You already know the exact question and can run a focused report.`,`You need a technical crawl without Search Console analysis.`],outcome:`A clear search performance summary with a short list of next reports.`},"second-page":{name:`Second-page opportunities`,description:`Find URLs averaging positions 11 to 20 and see the queries behind each opportunity.`,useWhen:[`You want existing pages that may deserve closer review near page one.`,`You need page-level evidence across all matching queries.`],avoidWhen:[`You want average position treated as a fixed rank.`,`You need proof that a change will move the page to page one.`],outcome:`A ranked URL list with query, click, impression, and position evidence.`},"segment-impact":{name:`Search impact by segment`,description:`Compare page or query groups across equal periods to find which parts of a site moved.`,useWhen:[`A traffic change may be concentrated in one directory, page type, or query group.`,`You need to separate broad movement from a local segment issue.`],avoidWhen:[`The periods are incomplete or not comparable.`,`Missing Search Console rows would be mistaken for zero activity.`],outcome:`A segment comparison showing where clicks and impressions changed.`},"setup-check":{name:`Check local setup`,description:`Check Google login, scopes, local configuration, and saved defaults before running reports.`,useWhen:[`Authentication or site selection is failing.`,`You want to verify the local setup before investigating report errors.`],avoidWhen:[`You need SEO findings rather than a setup check.`],outcome:`A local setup status with the exact problems that need fixing.`},"site-crawl":{name:`Sitemap health pass and technical site crawl`,description:`Start with a lightweight sitemap health pass, then run a full technical crawl only when page bodies and content-level evidence are needed.`,useWhen:[`You need a fast first check of sitemap URLs, statuses, redirects, robots decisions, or access blocks.`,`You need to discover technical issues across linked pages.`,`You want a crawl snapshot for later filtering or comparison.`],avoidWhen:[`You only need to check one page or a known URL list.`,`Do not run a full crawl on a large or unknown site before health=true, or when important content requires browser rendering that is not enabled.`],outcome:`A fast sitemap response gate or a full crawl summary with page evidence, technical findings, crawler identity and access guidance.`},"striking-distance":{name:`Queries near page one`,description:`Find Search Console query and page pairs averaging positions 11 to 20.`,useWhen:[`You want existing search demand close to page one.`,`You need a compact list of queries and URLs for content review.`],avoidWhen:[`You want average position treated as an exact daily rank.`,`You need a promised ranking or click gain.`],outcome:`A ranked list of near-page-one query and URL pairs with search evidence.`},"top-fixes":{name:`Top technical SEO fixes`,description:`Turn crawl findings into a short, ranked queue of technical issues to investigate first.`,useWhen:[`A crawl contains too many findings to review at once.`,`You need representative URLs and reasons for the highest priorities.`],avoidWhen:[`You need every affected URL for one rule.`,`You plan to treat rank as proof of business impact.`],outcome:`A focused technical fix queue with issue evidence and example URLs.`},"traffic-anomaly":{name:`Unusual search traffic changes`,description:`Find recent clicks or impressions that moved beyond the site's normal Search Console pattern.`,useWhen:[`You want an early signal of an unusual search change.`,`You need to know whether recent movement stands out from normal variation.`],avoidWhen:[`There is too little history for a useful baseline.`,`You want the report to identify the cause of the change.`],outcome:`A statistical movement signal with the dates, baseline, and limits shown.`},"update-correlation":{name:`Google update correlation`,description:`Compare search movement dates with official Google ranking update windows.`,useWhen:[`A traffic change overlaps a confirmed Google ranking update.`,`You need a timeline before investigating affected pages and queries.`],avoidWhen:[`You want overlap presented as proof of causation.`,`The traffic window does not cover the update dates.`],outcome:`A traffic and update timeline with overlaps clearly labelled as correlation.`},"update-postmortem":{name:`Google update impact review`,description:`Find the pages and queries that gained or lost around a confirmed Google ranking update.`,useWhen:[`You need winners and losers around a known update window.`,`You want to compare affected segments and known site changes.`],avoidWhen:[`You want the report to claim the update caused every change.`,`The comparison periods are incomplete or contain major unrecorded changes.`],outcome:`A post-update review of winners, losers, confounders, and next checks.`}};function qX(e){let t=KX[e],n=GX[e];if(!(!t||!n))return{...t,...n}}function JX(e){e.registerTool(`seo_audit_page`,{description:`Run a single-page technical and content audit`,inputSchema:{url:A.string().url(),site:A.string().optional(),js:A.boolean().optional(),refresh:A.boolean().optional()}},async({url:e,site:t,js:n,refresh:r})=>{try{let i=await gS({url:e,site:t,js:TX(n,`auto`),refresh:r});return SX(`Audit complete for ${e}. Found ${i.issues.length} issues.`,i)}catch(e){return $(e)}})}const YX=DX([`verifyContent`,`verifyLimit`,`js`,`fetchConcurrency`,`fetchIntervalCap`,`fetchIntervalMs`,`refresh`]);function XX(e){return{verifyContent:e.verifyContent,verifyLimit:e.verifyLimit,js:TX(e.js,void 0),rate:IX({fetchConcurrency:e.fetchConcurrency,fetchIntervalCap:e.fetchIntervalCap,fetchIntervalMs:e.fetchIntervalMs}),refresh:e.refresh}}function ZX(e){e.registerTool(`seo_second_page`,{description:`Find URLs with GSC average position above 10 through 20 and return evidence-grounded investigation prompts`,inputSchema:{...DX([`site`,`range`,`minImpressions`,`limit`,`includeBrand`]),...YX,range:A.number().int().min(1).max(548).optional(),minImpressions:A.number().int().min(0).max(1e9).optional(),limit:A.number().int().min(1).max(100).optional(),verifyLimit:A.number().int().min(0).max(100).optional(),brandTerms:A.array(A.string().trim().min(1).max(200)).max(20).optional(),fetchConcurrency:A.number().int().min(1).max(16).optional(),fetchIntervalCap:A.number().int().min(1).max(60).optional(),fetchIntervalMs:A.number().int().min(100).max(6e4).optional()}},async({site:e,range:t,minImpressions:n,limit:r,includeBrand:i,brandTerms:a,...o})=>{try{let s=await $R({site:e,range:t,minImpressions:n,limit:r,includeBrand:i,brandTerms:a,...XX(o)});return SX(s.summary.verdict,s)}catch(e){return $(e)}})}function QX(e){JX(e),ZX(e)}function $X(e){let t=Oz(e),n=xX({...e,presentation:t});return SX(e.summary,n,{markdown:kz(e)})}function eZ(e){e.registerTool(`seo_workflow_diagnose_property`,{description:`Run the full agent workflow for property diagnosis and next actions`,inputSchema:{...DX([`site`,`days`,`recentDays`,`limit`,`includeBrand`,`refresh`])}},async({site:e,days:t,recentDays:n,limit:r,includeBrand:i,refresh:a})=>{try{return $X(await yz({site:e,days:t,recentDays:n,limit:r,includeBrand:i,refresh:a}))}catch(e){return $(e)}}),e.registerTool(`seo_workflow_update_postmortem`,{description:`Run winner/loser postmortem analysis for recent Google update exposure`,inputSchema:{...DX([`site`,`days`,`recentDays`,`limit`,`includeBrand`,`refresh`]),knownConfounders:A.array(A.string()).optional()}},async({site:e,days:t,recentDays:n,limit:r,includeBrand:i,knownConfounders:a,refresh:o})=>{try{return $X(await aB({site:e,days:t,recentDays:n,limit:r,includeBrand:i,knownConfounders:a,refresh:o}))}catch(e){return $(e)}}),e.registerTool(`seo_workflow_refresh_priorities`,{description:`Rank decay, striking-distance, quick-win, cannibalisation, and diagnosis signals into an action queue`,inputSchema:{...DX([`site`,`days`,`recentDays`,`limit`,`includeBrand`,`verifyContent`,`verifyLimit`,`refresh`]),googleAnalyticsPropertyId:A.string().optional()}},async({site:e,days:t,recentDays:n,limit:r,includeBrand:i,googleAnalyticsPropertyId:a,verifyContent:o,verifyLimit:s,refresh:c})=>{try{return $X(await Hz({site:e,days:t,recentDays:n,limit:r,includeBrand:i,googleAnalyticsPropertyId:a,verifyContent:o,verifyLimit:s,refresh:c}))}catch(e){return $(e)}})}const tZ=[`ai-search`,`crawl`,`diagnosis`,`monitoring`,`opportunities`,`reporting`,`setup`,`workflows`],nZ=[],rZ=[{category:`setup`,register:RX,names:[`seo_doctor`]},{category:`diagnosis`,register:RX,names:[`seo_segment_impact`,`seo_striking_distance`,`seo_traffic_anomaly`,`seo_update_correlate`]},{category:`opportunities`,register:WX,names:[`seo_cannibal`,`seo_ctr_underperformers`,`seo_decaying`,`seo_internal_links`,`seo_query_cluster`,`seo_quick_wins`]},{category:`ai-search`,register:kX,names:[`seo_ai_referrals`,`seo_content_optimization`,`seo_page_opportunities`,`seo_performance_audit`]},{category:`crawl`,register:LX,names:[`seo_audit_urls`,`seo_crawl_site`,`seo_explain_issue`,`seo_list_rules`,`seo_top_fixes`]},{category:`monitoring`,register:zX,names:[`seo_index_coverage`,`seo_link_recover`,`seo_redirect_trace`]},{category:`reporting`,register:QX,names:[`seo_audit_page`,`seo_second_page`]},{category:`workflows`,register:eZ,names:[`seo_workflow_diagnose_property`,`seo_workflow_refresh_priorities`,`seo_workflow_update_postmortem`]}],iZ={cannibal:`cannibalisation`,decaying:`decaying-pages`,"crawl-site":`site-crawl`,"link-recover":`link-recovery`,"query-cluster":`query-clusters`,"workflow-refresh-priorities":`refresh-priorities`,"workflow-update-postmortem":`update-postmortem`,"workflow-diagnose-property":`search-performance-overview`,doctor:`setup-check`,"update-correlate":`update-correlation`,"list-rules":`crawler-rules`,"explain-issue":`explain-crawl-issue`};function aZ(e){let t=e.replace(/^seo_/,``).replaceAll(`_`,`-`);return iZ[t]??t}function oZ(e,t){return e.id<t.id?-1:+(e.id>t.id)}function sZ(e){let t=new Map;return e({registerTool(e,n,r){t.set(e,{inputSchema:n.inputSchema,handler:r})}}),t}function cZ(e){return e instanceof A.ZodObject?e:A.strictObject(e??{})}function lZ(){let e=new Map,t=nZ.map(e=>{let t=qX(e.id);if(!t)throw Error(`MCP report registry is missing guidance for ${e.id}.`);return{...e,...t}});for(let n of rZ){let r=e.get(n.register);r||(r=sZ(n.register),e.set(n.register,r));for(let e of n.names){let i=r.get(e);if(!i)throw Error(`MCP report registry references missing tool ${e}.`);let a=aZ(e),o=qX(a);if(!o)throw Error(`MCP report registry is missing guidance for ${a}.`);t.push({id:a,category:n.category,...o,inputSchema:cZ(i.inputSchema),handler:i.handler})}}return t.sort(oZ)}const uZ=lZ(),dZ=new Set(uZ.map(e=>e.id)),fZ=Object.keys(KX).filter(e=>!dZ.has(e));if(fZ.length>0)throw Error(`MCP report guidance references unknown reports: ${fZ.join(`, `)}.`);const pZ=new Map(uZ.map(e=>[e.id,e]));function mZ(e){return uZ.filter(t=>!e||t.category===e).map(({id:e,name:t,description:n,category:r})=>({id:e,category:r,name:t,description:n}))}function hZ(e){return pZ.get(e)}function gZ(e){return e.issues.map(e=>`${e.path.length>0?e.path.join(`.`):`input`}: ${e.message}`).join(`; `)}const _Z={"affected-urls":`seo crawl`,"agent-readiness":null,"ai-mention-research":null,"ai-prompt-observations":null,"ai-readiness":null,"ai-search-scorecard":null,"bing-webmaster-overview":null,"community-intent":null,"compare-crawls":`seo crawl`,"competitive-opportunities":`seo research`,"competitor-keyword-gap":`seo research competitors`,"crawl-diff":`seo crawl`,"crawl-history":`seo crawl`,"crawl-report":`seo crawl`,"domain-overview":`seo research ranked_keywords`,"domain-rating":`seo research`,"entity-readiness":null,"generate-llms-txt":null,"geo-gaps":null,"index-coverage-plan":`seo index`,"index-monitor":`seo index`,"index-watch":`seo page --url <url>`,"keyword-metrics":`seo research keyword_metrics`,"keyword-opportunities":`seo research`,"keyword-research":`seo research keyword_metrics`,"link-evidence":`seo research backlinks`,"llms-txt-audit":null,"local-search-demand":null,"measure-change":`seo compare --date <date>`,"monthly-action-plan":`seo report`,"monthly-report":`seo report`,"narrative-report":`seo report`,"okf-build":null,"okf-validate":null,"pseo-audit":null,"pseo-opportunities":null,"pseo-patterns":null,"rank-tracking":null,"ranked-keywords":`seo research ranked_keywords`,"ranking-pages":`seo research ranked_keywords`,"saved-keywords":null,"seo-to-ai-query":null,"serp-competitors":`seo research competitors`,"serp-results":`seo research serp`,"server-log-analysis":null,"technical-watch":`seo crawl`};function vZ(e){if(Object.hasOwn(_Z,e)){let t=_Z[e];throw new N(`INVALID_INPUT`,t?`The ${e} report was removed. Use \`${t}\` instead.`:`The ${e} report was removed. Run \`seo help\` for the commands.`)}let t=hZ(e);if(!t)throw new N(`INVALID_INPUT`,`Unknown report: ${e}.`);return t}function yZ(e){return mZ(e)}function bZ(e){let t=vZ(e);return{id:t.id,category:t.category,name:t.name,description:t.description,useWhen:t.useWhen,avoidWhen:t.avoidWhen,outcome:t.outcome,readOrder:t.readOrder,doNotClaim:t.doNotClaim,verify:t.verify,related:t.related,agentWorkflow:{actionView:{mcp:{id:t.id,view:`actions`},cli:`seo reports run ${t.id} --params '<json>' --actions-only --json`},readOrder:[`findings.coverage and report-level caveats`,`findings.items in returned priority order`,`inventories row by row when present`],completion:`Use each finding type and its allowed outcomes. Fix items support fixed, deferred, or not-needed. Review items support changed, no-change, or deferred. Verify changed items and rerun this report before closing them.`},inputSchema:A.toJSONSchema(t.inputSchema)}}async function xZ(e,t={},n={}){let r=vZ(e),i=r.inputSchema.safeParse(t);if(!i.success)throw new N(`INVALID_INPUT`,`Invalid parameters for ${e}: ${gZ(i.error)}`);let a=await r.handler(i.data);if(a.isError||!a.structuredContent)return a;let o={reportId:r.id,verify:r.verify},s=n.view===`actions`?gt(a.structuredContent,o):a.structuredContent;return{...a,structuredContent:xX(s)}}const SZ={readOnlyHint:!0,destructiveHint:!1,openWorldHint:!0};function CZ(e){return{content:[{type:`text`,text:e}]}}async function wZ(e,t,n,r){let i=n?DH(e,{section:typeof t.section==`string`?t.section:void 0,action:typeof t.action==`string`?t.action:void 0}):null;i&&n&&fi(i,n());try{let e=await r();return i&&n&&(e.isError?mi(i,e.structuredContent?.error,n()):pi(i,n())),e}catch(e){return i&&n&&mi(i,e,n()),$(vU(e))}}function TZ(e,t={}){let n={deps:lU({call:FH}),resolveSite:e=>gU(e),keys:mU,refreshClicky:hU,drKey:null,accounts:pU,signIn:To.signIn,connect:"run `seo login` to use your seoskill.dev account (Google, Bing and keys in one place), or `seo auth login`, `seo providers bing connect` and `seo providers dataforseo connect` or `seo providers ahrefs connect` on this machine only."};for(let r of NH)e.registerTool(r.name,{title:r.title,description:r.description,inputSchema:r.input.shape,annotations:SZ},async e=>wZ(r.command,e,t.telemetry,async()=>CZ((await PH(r,n,e)).text)));e.registerTool(`seo_crawl`,{title:`Crawl a site`,description:`Crawls a site from this machine and returns technical issues and the URLs they affect. The crawl is saved locally for later reports.`,inputSchema:{url:A.url()},annotations:SZ},async({url:e})=>wZ(`crawl`,{},t.telemetry,()=>xZ(`site-crawl`,{url:e,saveReport:!0}))),e.registerTool(`seo_internal_links`,{title:`Internal link opportunities`,description:`Pages of the same site that could link to a target page, from Search Console and live page checks on this machine. Each one names the sentence where the link fits and anchor text from it. Takes the target URL and optional dates (default: the last 90 days).`,inputSchema:{url:A.url(),start_date:A.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe(`YYYY-MM-DD. Optional; send with end_date.`),end_date:A.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe(`YYYY-MM-DD. Optional; send with start_date.`)},annotations:SZ},async({url:e,start_date:n,end_date:r})=>wZ(`internal-links`,{},t.telemetry,async()=>{try{return await xZ(`internal-links`,{site:await gU(e),targetUrl:e,startDate:n,endDate:r})}catch(e){return $(vU(e))}}))}function EZ(){for(let e of[`../skills/seo/SKILL.md`,`../../../skills/seo/SKILL.md`])try{return w(new URL(e,import.meta.url),`utf8`)}catch{}return null}function DZ(e={}){let t=new iX({name:`seo`,version:Rr},{capabilities:{logging:{}},instructions:`SEO Skill reads the person's own Search Console, Google Analytics, Bing Webmaster Tools, Clicky and optional keyword accounts, and returns facts with their dates and limits. It gives no advice.
343
350
  1. seo_sites: the properties the connected accounts can read.
344
351
  2. seo_report: the main report. Run it without a section first; it shows the overview and every section's count and top rows. Then ask for the one section you need.
345
352
  3. seo_page for one URL, seo_compare for before and after a date, seo_index for pages that lost their clicks, seo_research for keyword, competitor and backlink data from the DataForSEO or Ahrefs key the person saved, seo_data for raw rows, including Google Analytics, Bing and Clicky.
346
- seo_crawl and seo_internal_links run on this machine. Keys and Google sign-in come from \`seo start\` and \`seo providers <name> connect\`.`}),n=()=>({clientName:t.server.getClientVersion()?.name});yZ(t,{telemetry:e.telemetry===!1?void 0:n}),_X(t);let r=bZ();if(r){let{name:e,uri:n,...i}=AH;t.registerResource(e,n,i,async e=>({contents:[{uri:e.href,mimeType:i.mimeType,text:r}]}))}return e.telemetry!==!1&&(t.server.oninitialized=()=>{ui(n())}),t}async function SZ(e={}){let t=xZ();if(e.test){process.stdout.write(`seo MCP server constructed successfully.
347
- `);return}let n=new dX;await t.connect(n)}export{gB as $,js as $t,tU as A,pi as An,Uk as At,xH as B,vn as Bn,WT as Bt,fU as C,Li as Cn,Hj as Ct,WH as D,Yr as Dn,hA as Dt,rU as E,ui as En,zA as Et,VH as F,Pr as Fn,gk as Ft,oH as G,yt as Gn,CT as Gt,vH as H,qt as Hn,VT as Ht,MH as I,Fr as In,_k as It,GV as J,bw as Jt,uH as K,Je as Kn,yT as Kt,LH as L,pr as Ln,zT as Lt,RH as M,fi as Mn,sk as Mt,UH as N,gi as Nn,vk as Nt,GH as O,ci as On,uA as Ot,HH as P,Rr as Pn,dk as Pt,hB as Q,Wx as Qt,IH as R,fr as Rn,UT as Rt,sU as S,Ri as Sn,TN as St,cU as T,si as Tn,yj as Tt,fH as U,N as Un,IT as Ut,mH as V,Ut as Vn,BT as Vt,aH as W,xt as Wn,FT as Wt,oV as X,eS as Xt,JB as Y,gS as Yt,qB as Z,qx as Zt,TU as _,Oi as _n,sF as _t,hZ as a,xo as an,cB as at,vU as b,zi as bn,dP as bt,nW as c,Sa as cn,vz as ct,UU as d,ya as dn,UL as dt,rs as en,fB as et,WU as f,va as fn,fL as ft,DU as g,yi as gn,oF as gt,OU as h,Ea as hn,TI as ht,mZ as i,To as in,sB as it,$H as j,mi as jn,Wk as jt,nU as k,hi as kn,Gk as kt,tW as l,Da as ln,$R as lt,kU as m,wa as mn,iL as mt,hX as n,$o as nn,oB as nt,pZ as o,fo as on,aB as ot,GU as p,ba as pn,sL as pt,jV as q,qe as qn,Aw as qt,xZ as r,Zo as rn,uB as rt,SZ as s,lo as sn,Hz as st,YX as t,ns as tn,mB as tt,JU as u,Ca as un,uR as ut,EU as v,Ci as vn,PP as vt,lU as w,ti as wn,q as wt,hU as x,Vi as xn,HN as xt,wU as y,Bi as yn,MP as yt,FH as z,Mn as zn,HT as zt};
348
- //# sourceMappingURL=dist-DkegfPAq.js.map
353
+ seo_crawl and seo_internal_links run on this machine. Keys and Google sign-in come from \`seo start\` and \`seo providers <name> connect\`.`}),n=()=>({clientName:t.server.getClientVersion()?.name});TZ(t,{telemetry:e.telemetry===!1?void 0:n}),CX(t);let r=EZ();if(r){let{name:e,uri:n,...i}=IH;t.registerResource(e,n,i,async e=>({contents:[{uri:e.href,mimeType:i.mimeType,text:r}]}))}return e.telemetry!==!1&&(t.server.oninitialized=()=>{ui(n())}),t}async function OZ(e={}){let t=DZ();if(e.test){process.stdout.write(`seo MCP server constructed successfully.
354
+ `);return}let n=new _X;await t.connect(n)}export{hB as $,Wx as $t,sU as A,hi as An,Gk as At,DH as B,Mn as Bn,HT as Bt,vU as C,Ri as Cn,TN as Ct,XH as D,ui as Dn,zA as Dt,lU as E,si as En,yj as Et,qH as F,Rr as Fn,dk as Ft,fH as G,xt as Gn,FT as Gt,wH as H,Ut as Hn,BT as Ht,RH as I,Pr as In,gk as It,ZV as J,qe as Jn,Aw as Jt,gH as K,yt as Kn,CT as Kt,UH as L,Fr as Ln,_k as Lt,WH as M,mi as Mn,Wk as Mt,YH as N,fi as Nn,sk as Nt,ZH as O,Yr as On,hA as Ot,JH as P,gi as Pn,vk as Pt,JB as Q,qx as Qt,HH as R,pr as Rn,zT as Rt,pU as S,Vi as Sn,HN as St,mU as T,ti as Tn,q as Tt,vH as U,qt as Un,VT as Ut,bH as V,vn as Vn,WT as Vt,dH as W,N as Wn,IT as Wt,QB as X,gS as Xt,XV as Y,bw as Yt,uV as Z,eS as Zt,jU as _,yi as _n,oF as _t,xZ as a,To as an,sB as at,wU as b,Bi as bn,MP as bt,cW as c,lo as cn,Hz as ct,YU as d,Ca as dn,uR as dt,js as en,gB as et,XU as f,ya as fn,UL as ft,NU as g,Ea as gn,TI as gt,PU as h,wa as hn,iL as ht,bZ as i,Zo as in,uB as it,aU as j,pi as jn,Uk as jt,cU as k,ci as kn,uA as kt,sW as l,Sa as ln,vz as lt,FU as m,ba as mn,sL as mt,xX as n,ns as nn,mB as nt,yZ as o,xo as on,cB as ot,ZU as p,va as pn,fL as pt,FV as q,Je as qn,yT as qt,DZ as r,$o as rn,oB as rt,OZ as s,fo as sn,aB as st,tZ as t,rs as tn,fB as tt,eW as u,Da as un,$R as ut,MU as v,Oi as vn,sF as vt,hU as w,Li as wn,Hj as wt,xU as x,zi as xn,dP as xt,AU as y,Ci as yn,PP as yt,VH as z,fr as zn,UT as zt};
355
+ //# sourceMappingURL=dist-B8MTNp_F.js.map