mcp-scraper 0.89.6 → 0.89.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +51 -1
  2. package/README.md +3 -3
  3. package/dist/{analytics-repository-4UA3WI3U.js → analytics-repository-UX6VU22H.js} +1 -1
  4. package/dist/bin/api-server.js +1 -1
  5. package/dist/bin/mcp-scraper-cli.js +1 -1
  6. package/dist/bin/mcp-scraper-core.js +1 -1
  7. package/dist/bin/mcp-scraper-install.js +1 -1
  8. package/dist/bin/mcp-stdio-server.js +1 -1
  9. package/dist/bin/paa-harvest.js +1 -1
  10. package/dist/{chunk-YCZKKSTT.js → chunk-2GRE4BAO.js} +1 -1
  11. package/dist/chunk-2PXP7TMY.js +1 -0
  12. package/dist/{chunk-3GP5CYZX.js → chunk-2TZBO52D.js} +1 -1
  13. package/dist/{chunk-H2I63VAD.js → chunk-2WWKTVCO.js} +1 -1
  14. package/dist/{chunk-ISZIA6NE.js → chunk-52XUWR3X.js} +1 -1
  15. package/dist/{chunk-Y3ITV2OK.js → chunk-5B42QVDC.js} +1 -1
  16. package/dist/{chunk-KKI2SNB2.js → chunk-7AC66V3T.js} +1 -1
  17. package/dist/{chunk-YQ5U5C2X.js → chunk-7BEWBRMT.js} +74 -55
  18. package/dist/{chunk-WUVMD6ZX.js → chunk-DKQZNSYM.js} +1 -1
  19. package/dist/{chunk-MZN4U5BL.js → chunk-E4ME7J6G.js} +1 -1
  20. package/dist/{chunk-C6JXNOSF.js → chunk-F4LIB772.js} +8 -8
  21. package/dist/{chunk-PPOI4C3Q.js → chunk-HR2A2WTL.js} +1 -1
  22. package/dist/{chunk-XLWNEVUZ.js → chunk-JHMI6HEO.js} +3 -3
  23. package/dist/{chunk-FVSXX43Z.js → chunk-JSNFZPPB.js} +1 -1
  24. package/dist/{chunk-3H7HU5JI.js → chunk-JVU2THSY.js} +1 -1
  25. package/dist/{chunk-VZTFJLOK.js → chunk-LZTDANNZ.js} +1 -1
  26. package/dist/{chunk-QPWPR5XG.js → chunk-M5QHXNFZ.js} +1 -1
  27. package/dist/{chunk-FKSTNWP6.js → chunk-PHBU6X5B.js} +1 -1
  28. package/dist/chunk-PVTKGAZL.js +1 -0
  29. package/dist/{chunk-H3QW5U67.js → chunk-Q4A2KIPZ.js} +3 -3
  30. package/dist/{chunk-G6GAIXXA.js → chunk-S3N55WHK.js} +4 -4
  31. package/dist/{chunk-WXOLIRFJ.js → chunk-VT6SLBOU.js} +1 -1
  32. package/dist/{chunk-Z45GM22P.js → chunk-XATD7HDY.js} +227 -227
  33. package/dist/{chunk-YQZGZBB4.js → chunk-XG6GCEUE.js} +1 -1
  34. package/dist/db-UKQ74OVT.js +1 -0
  35. package/dist/{extract-bundle-BTZQJTYV.js → extract-bundle-DI7OVLT5.js} +5 -5
  36. package/dist/{gmail-service-ZZDF52KK.js → gmail-service-ASX7YBC3.js} +1 -1
  37. package/dist/index.cjs +45 -45
  38. package/dist/index.d.cts +16 -0
  39. package/dist/index.d.ts +16 -0
  40. package/dist/index.js +1 -1
  41. package/dist/{lead-list-enrichment-repository-K4H5DMSF.js → lead-list-enrichment-repository-GPDHJVM3.js} +1 -1
  42. package/dist/{location-data-repository-KALKE3FG.js → location-data-repository-MXUNVDHW.js} +1 -1
  43. package/dist/{server-YVNOU3RK.js → server-EYSV2RRD.js} +702 -702
  44. package/dist/{site-extract-repository-FTTIOWAL.js → site-extract-repository-WADCAIYB.js} +1 -1
  45. package/dist/{stripe-event-worker-CURL3RYL.js → stripe-event-worker-ZPNWXX2T.js} +1 -1
  46. package/dist/worker-577GJULQ.js +1 -0
  47. package/package.json +1 -1
  48. package/dist/chunk-CULFQBFR.js +0 -1
  49. package/dist/db-IZ5UF33U.js +0 -1
  50. package/dist/worker-MUHILD2W.js +0 -1
@@ -1,4 +1,4 @@
1
- import{a as Q,d as Se}from"./chunk-YCZKKSTT.js";import{createHash as pe,createHmac as Yt,randomBytes as P,randomUUID as y}from"crypto";import{Pool as Wt}from"pg";var ct=[[/perplexity/i,"llm","Perplexity"],[/chatgpt|chat\.openai|openai/i,"llm","ChatGPT"],[/claude|anthropic/i,"llm","Claude"],[/\bgrok\b|xai/i,"llm","Grok"],[/ai[ _-]?overview|google[ _-]?ai|\bsge\b|gemini/i,"llm","Google AI Overview"],[/instagram/i,"social","Instagram"],[/facebook|\bfb\b|meta/i,"social","Facebook"],[/linkedin/i,"social","LinkedIn"],[/tiktok/i,"social","TikTok"],[/youtube|youtu\.be/i,"social","YouTube"],[/twitter|x\.com/i,"social","X"],[/\bg2\b|g2\.com/i,"review","G2"],[/trustpilot/i,"review","Trustpilot"],[/\bbbb\b|better business bureau/i,"review","BBB"],[/capterra/i,"review","Capterra"],[/yelp/i,"review","Yelp"],[/google|bing|duckduckgo|yahoo/i,"search","Search"]];function q(e,t=240){return typeof e=="string"&&e.trim()?e.trim().slice(0,t):null}function Ce(e){try{return e?new URL(e).hostname.replace(/^www\./,""):""}catch{return""}}function Re(e){let t=e.properties??{},i=q(e.source,180)||Ce(e.referrer)||"(direct)",n=q(e.medium,180)||(i==="(direct)"?"(none)":"referral"),s=e.clickIds??{},a=`${i} ${n} ${Ce(e.referrer)}`,r=i==="(direct)"?"direct":/email|newsletter/i.test(n)?"email":"referral",o=i==="(direct)"?"Direct":i;for(let[d,_,u]of ct)if(d.test(a)){r=_,o=u;break}return s.fbclid?(r="social",o=/instagram/i.test(a)?"Instagram":"Facebook"):s.ttclid?(r="social",o="TikTok"):s.rdt_cid?(r="social",o="Reddit"):s.gclid||s.gbraid||s.wbraid?(r="search",o="Google"):s.msclkid&&(r="search",o="Microsoft Ads"),{channelFamily:r,platform:o,source:i,medium:n,campaign:q(e.campaign),campaignId:q(t.campaign_id??t.utm_id),adSetId:q(t.adset_id??t.ad_set_id??t.adgroup_id??t.ad_group_id),adId:q(t.ad_id),creativeId:q(t.creative_id),placement:q(t.placement),term:q(t.utm_term),content:q(t.utm_content)}}import{createHash as yt,randomUUID as ee}from"crypto";import{createCipheriv as _t,createDecipheriv as ut,createHmac as fe,randomBytes as Et,scryptSync as lt,timingSafeEqual as Nt}from"crypto";var Z="xray1";function mt(){return process.env.ANALYTICS_RESTRICTED_DATA_SECRET?.trim()||Q()}function _e(e){return lt(mt(),`xray-restricted:${e}:v1`,32)}function De(e,t){let i=t.trim().slice(0,80);if(!i)throw new Error("analytics encryption purpose required");let n=Et(12),s=_t("aes-256-gcm",_e(i),n);s.setAAD(Buffer.from(`${Z}:${i}`,"utf8"));let a=Buffer.concat([s.update(e,"utf8"),s.final()]),r=s.getAuthTag();return[Z,Buffer.from(i,"utf8").toString("base64url"),n.toString("base64url"),r.toString("base64url"),a.toString("base64url")].join(".")}function Ue(e,t){try{let[i,n,s,a,r]=e.split(".");if(i!==Z||!n||!s||!a||!r)return null;let o=Buffer.from(n,"base64url").toString("utf8");if(o!==t)return null;let d=ut("aes-256-gcm",_e(o),Buffer.from(s,"base64url"));return d.setAAD(Buffer.from(`${Z}:${o}`,"utf8")),d.setAuthTag(Buffer.from(a,"base64url")),Buffer.concat([d.update(Buffer.from(r,"base64url")),d.final()]).toString("utf8")}catch{return null}}function bi(e,t){return fe("sha256",_e(`identity:${e}`)).update(t.trim().toLowerCase()).digest("hex")}function hi(e,t,i,n){return fe("sha256",n).update(`${e}.${t}.${i}`).digest("hex")}function xi(e,t){if(!e||e.length!==t.length)return!1;try{return Nt(Buffer.from(e),Buffer.from(t))}catch{return!1}}var we="enhanced_matching",pt=90,Tt=10,H=class extends Error{constructor(i,n,s){super(n);this.code=i;this.status=s;this.name="AnalyticsIdentityProfileError"}code;status};function te(e,t){return e?.trim().replace(/\s+/g," ").slice(0,t)||null}function Lt(e){if(!e)return null;let[t,i]=e.split("@");return!t||!i?null:`${t.slice(0,1)}${"*".repeat(Math.min(6,Math.max(2,t.length-1)))}@${i}`}function At(e){if(!e)return null;let t=e.replace(/\D/g,"");return t.length<4?null:`***-***-${t.slice(-4)}`}function ue(e){return yt("sha256").update(e).digest("hex")}async function ie(e,t){if(!t.signals.length)return;let i=t.signals.map(a=>a.kind),n=t.signals.map(a=>a.valueHmac);if((await e.query(`SELECT 1 FROM analytics_identity_tombstones
1
+ import{a as Q,d as Se}from"./chunk-2GRE4BAO.js";import{createHash as pe,createHmac as Yt,randomBytes as P,randomUUID as y}from"crypto";import{Pool as Wt}from"pg";var ct=[[/perplexity/i,"llm","Perplexity"],[/chatgpt|chat\.openai|openai/i,"llm","ChatGPT"],[/claude|anthropic/i,"llm","Claude"],[/\bgrok\b|xai/i,"llm","Grok"],[/ai[ _-]?overview|google[ _-]?ai|\bsge\b|gemini/i,"llm","Google AI Overview"],[/instagram/i,"social","Instagram"],[/facebook|\bfb\b|meta/i,"social","Facebook"],[/linkedin/i,"social","LinkedIn"],[/tiktok/i,"social","TikTok"],[/youtube|youtu\.be/i,"social","YouTube"],[/twitter|x\.com/i,"social","X"],[/\bg2\b|g2\.com/i,"review","G2"],[/trustpilot/i,"review","Trustpilot"],[/\bbbb\b|better business bureau/i,"review","BBB"],[/capterra/i,"review","Capterra"],[/yelp/i,"review","Yelp"],[/google|bing|duckduckgo|yahoo/i,"search","Search"]];function q(e,t=240){return typeof e=="string"&&e.trim()?e.trim().slice(0,t):null}function Ce(e){try{return e?new URL(e).hostname.replace(/^www\./,""):""}catch{return""}}function Re(e){let t=e.properties??{},i=q(e.source,180)||Ce(e.referrer)||"(direct)",n=q(e.medium,180)||(i==="(direct)"?"(none)":"referral"),s=e.clickIds??{},a=`${i} ${n} ${Ce(e.referrer)}`,r=i==="(direct)"?"direct":/email|newsletter/i.test(n)?"email":"referral",o=i==="(direct)"?"Direct":i;for(let[d,_,u]of ct)if(d.test(a)){r=_,o=u;break}return s.fbclid?(r="social",o=/instagram/i.test(a)?"Instagram":"Facebook"):s.ttclid?(r="social",o="TikTok"):s.rdt_cid?(r="social",o="Reddit"):s.gclid||s.gbraid||s.wbraid?(r="search",o="Google"):s.msclkid&&(r="search",o="Microsoft Ads"),{channelFamily:r,platform:o,source:i,medium:n,campaign:q(e.campaign),campaignId:q(t.campaign_id??t.utm_id),adSetId:q(t.adset_id??t.ad_set_id??t.adgroup_id??t.ad_group_id),adId:q(t.ad_id),creativeId:q(t.creative_id),placement:q(t.placement),term:q(t.utm_term),content:q(t.utm_content)}}import{createHash as yt,randomUUID as ee}from"crypto";import{createCipheriv as _t,createDecipheriv as ut,createHmac as fe,randomBytes as Et,scryptSync as lt,timingSafeEqual as Nt}from"crypto";var Z="xray1";function mt(){return process.env.ANALYTICS_RESTRICTED_DATA_SECRET?.trim()||Q()}function _e(e){return lt(mt(),`xray-restricted:${e}:v1`,32)}function De(e,t){let i=t.trim().slice(0,80);if(!i)throw new Error("analytics encryption purpose required");let n=Et(12),s=_t("aes-256-gcm",_e(i),n);s.setAAD(Buffer.from(`${Z}:${i}`,"utf8"));let a=Buffer.concat([s.update(e,"utf8"),s.final()]),r=s.getAuthTag();return[Z,Buffer.from(i,"utf8").toString("base64url"),n.toString("base64url"),r.toString("base64url"),a.toString("base64url")].join(".")}function Ue(e,t){try{let[i,n,s,a,r]=e.split(".");if(i!==Z||!n||!s||!a||!r)return null;let o=Buffer.from(n,"base64url").toString("utf8");if(o!==t)return null;let d=ut("aes-256-gcm",_e(o),Buffer.from(s,"base64url"));return d.setAAD(Buffer.from(`${Z}:${o}`,"utf8")),d.setAuthTag(Buffer.from(a,"base64url")),Buffer.concat([d.update(Buffer.from(r,"base64url")),d.final()]).toString("utf8")}catch{return null}}function bi(e,t){return fe("sha256",_e(`identity:${e}`)).update(t.trim().toLowerCase()).digest("hex")}function hi(e,t,i,n){return fe("sha256",n).update(`${e}.${t}.${i}`).digest("hex")}function xi(e,t){if(!e||e.length!==t.length)return!1;try{return Nt(Buffer.from(e),Buffer.from(t))}catch{return!1}}var we="enhanced_matching",pt=90,Tt=10,H=class extends Error{constructor(i,n,s){super(n);this.code=i;this.status=s;this.name="AnalyticsIdentityProfileError"}code;status};function te(e,t){return e?.trim().replace(/\s+/g," ").slice(0,t)||null}function Lt(e){if(!e)return null;let[t,i]=e.split("@");return!t||!i?null:`${t.slice(0,1)}${"*".repeat(Math.min(6,Math.max(2,t.length-1)))}@${i}`}function At(e){if(!e)return null;let t=e.replace(/\D/g,"");return t.length<4?null:`***-***-${t.slice(-4)}`}function ue(e){return yt("sha256").update(e).digest("hex")}async function ie(e,t){if(!t.signals.length)return;let i=t.signals.map(a=>a.kind),n=t.signals.map(a=>a.valueHmac);if((await e.query(`SELECT 1 FROM analytics_identity_tombstones
2
2
  WHERE site_id=$1 AND (kind,value_hmac) IN (
3
3
  SELECT * FROM unnest($2::text[],$3::text[])
4
4
  ) LIMIT 1`,[t.siteId,i,n])).rowCount)throw new H("analytics_identity_deleted","This identity cannot be automatically recreated.",410)}async function ne(e,t){let i=te(t.displayName,160),n=te(t.email,320)?.toLowerCase()??null,s=te(t.phone,40);if(!i&&!n&&!s)return!1;let r=(await e.query(`SELECT p.public_ref FROM analytics_people p
@@ -1,9 +1,9 @@
1
- import{c as be}from"./chunk-KJQXUZ4Y.js";import{b as T,l as ve}from"./chunk-3GP5CYZX.js";import{a as _e,c as ke,d as X,e as Re,f as Se}from"./chunk-WO3N5FH2.js";function xe(e){return e.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}import{mkdir as J,readFile as Ye,stat as Xe,writeFile as z}from"fs/promises";import{existsSync as Ze}from"fs";import{homedir as et,platform as tt}from"os";import{dirname as Z,join as U}from"path";import{execFile as rt}from"child_process";function ae(e){return e?.trim()||process.env.MCP_SCRAPER_OUTPUT_DIR?.trim()||U(et(),"Downloads","mcp-scraper")}function Ce(){return new Date().toISOString().replace(/[:.]/g,"-")}function se(e){return xe(e).replace(/^-+|-+$/g,"").slice(0,80)||"run"}var V=class e{constructor(t,n,r,i,s,a,l){this.workflowId=t;this.title=n;this.runId=r;this.baseDir=i;this.runDir=s;this.startedAt=a;this.input=l}workflowId;title;runId;baseDir;runDir;startedAt;input;artifacts=[];static async create(t,n,r,i,s){let a=new Date().toISOString(),l=s?.trim()||`${Ce()}-${se(t)}-${Math.random().toString(36).slice(2,8)}`,c=String(r.keyword??r.query??r.domain??r.state??t),p=ae(i),u=U(p,"workflows",t,`${Ce()}-${se(c)}-${se(l).slice(0,20)}`);return await J(u,{recursive:!0}),new e(t,n,l,p,u,a,r)}async remember(t,n,r,i){let s=await Xe(r).then(a=>a.size).catch(()=>{});return this.artifacts.push({kind:t,label:n,path:r,bytes:s,rows:i}),await ve({title:`${this.title} ${n}`,content:`artifact: ${r}`,source:`mcp-scraper-workflow:${this.workflowId}:${this.runId}`}),r}async writeJson(t,n,r){let i=U(this.runDir,n);return await J(Z(i),{recursive:!0}),await z(i,JSON.stringify(r,null,2),"utf8"),this.remember("json",t,i)}async writeText(t,n,r,i="markdown"){let s=U(this.runDir,n);return await J(Z(s),{recursive:!0}),await z(s,r,"utf8"),this.remember(i,t,s)}async writeCsv(t,n,r,i){let s=U(this.runDir,n);return await J(Z(s),{recursive:!0}),await z(s,be(r,i),"utf8"),this.remember("csv",t,s,i.length)}async writeHtml(t,n,r){return this.writeText(t,n,r,"html_report")}async writeManifest(t,n,r,i){let s={workflow:this.workflowId,title:this.title,runId:this.runId,status:t,startedAt:this.startedAt,completedAt:t==="running"?null:new Date().toISOString(),input:this.input,artifacts:this.artifacts,warnings:r,errors:i,counts:n},a=U(this.runDir,"manifest.json");return await z(a,JSON.stringify(s,null,2),"utf8"),await nt(s,a,this.baseDir),a}};function Ae(e=ae()){return U(e,"workflows","index.json")}async function Pe(e){let t=Ae(e);if(!Ze(t))return{runs:[]};try{return JSON.parse(await Ye(t,"utf8"))}catch{return{runs:[]}}}async function nt(e,t,n){if(e.status==="running")return;let r=Ae(n),i=await Pe(n),s=e.artifacts.find(l=>l.kind==="html_report")?.path??null,a={workflow:e.workflow,runId:e.runId,status:e.status,startedAt:e.startedAt,reportPath:s,manifestPath:t,summary:`${e.title} (${e.status})`};i.runs=[a,...i.runs.filter(l=>l.runId!==e.runId)].slice(0,200),await J(Z(r),{recursive:!0}),await z(r,JSON.stringify(i,null,2),"utf8")}async function $e(e){return(await Pe(ae(e))).runs}async function Ee(e,t){let n=await $e(t);return e==="last"?n[0]??null:n.find(r=>r.runId===e)??null}async function it(e,t){let n=await Ee(e,t);if(!n?.reportPath)throw new Error(`No report found for "${e}"`);return tt()==="darwin"&&await new Promise((r,i)=>{rt("open",[n.reportPath],s=>s?i(s):r())}),n.reportPath}import{readFile as At}from"fs/promises";import{z as dr}from"zod";var F=class{constructor(t,n,r=fetch,i={}){this.apiUrl=t;this.apiKey=n;this.fetchImpl=r;this.extraHeaders=i}apiUrl;apiKey;fetchImpl;extraHeaders;async post(t,n,r=18e4){let i=await this.fetchImpl(`${this.apiUrl.replace(/\/$/,"")}${t}`,{method:"POST",headers:{...this.extraHeaders,"Content-Type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:AbortSignal.timeout(r)}),s=await i.json().catch(()=>({}));if(!i.ok){let a=typeof s.error=="string"?s.error:`Workflow API ${t} failed with ${i.status}`;throw new Error(a)}return s}};import{z as D}from"zod";function I(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ot(e){let t=e.rows.map(n=>`<tr>${e.columns.map(r=>`<td>${I(n[r])}</td>`).join("")}</tr>`).join(`
1
+ import{c as be}from"./chunk-KJQXUZ4Y.js";import{b as T,l as ve}from"./chunk-2TZBO52D.js";import{a as _e,c as ke,d as X,e as Re,f as Se}from"./chunk-WO3N5FH2.js";function xe(e){return e.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}import{mkdir as J,readFile as Ye,stat as Xe,writeFile as z}from"fs/promises";import{existsSync as Ze}from"fs";import{homedir as et,platform as tt}from"os";import{dirname as Z,join as U}from"path";import{execFile as rt}from"child_process";function ae(e){return e?.trim()||process.env.MCP_SCRAPER_OUTPUT_DIR?.trim()||U(et(),"Downloads","mcp-scraper")}function Ce(){return new Date().toISOString().replace(/[:.]/g,"-")}function se(e){return xe(e).replace(/^-+|-+$/g,"").slice(0,80)||"run"}var V=class e{constructor(t,n,r,i,s,a,l){this.workflowId=t;this.title=n;this.runId=r;this.baseDir=i;this.runDir=s;this.startedAt=a;this.input=l}workflowId;title;runId;baseDir;runDir;startedAt;input;artifacts=[];static async create(t,n,r,i,s){let a=new Date().toISOString(),l=s?.trim()||`${Ce()}-${se(t)}-${Math.random().toString(36).slice(2,8)}`,c=String(r.keyword??r.query??r.domain??r.state??t),p=ae(i),u=U(p,"workflows",t,`${Ce()}-${se(c)}-${se(l).slice(0,20)}`);return await J(u,{recursive:!0}),new e(t,n,l,p,u,a,r)}async remember(t,n,r,i){let s=await Xe(r).then(a=>a.size).catch(()=>{});return this.artifacts.push({kind:t,label:n,path:r,bytes:s,rows:i}),await ve({title:`${this.title} ${n}`,content:`artifact: ${r}`,source:`mcp-scraper-workflow:${this.workflowId}:${this.runId}`}),r}async writeJson(t,n,r){let i=U(this.runDir,n);return await J(Z(i),{recursive:!0}),await z(i,JSON.stringify(r,null,2),"utf8"),this.remember("json",t,i)}async writeText(t,n,r,i="markdown"){let s=U(this.runDir,n);return await J(Z(s),{recursive:!0}),await z(s,r,"utf8"),this.remember(i,t,s)}async writeCsv(t,n,r,i){let s=U(this.runDir,n);return await J(Z(s),{recursive:!0}),await z(s,be(r,i),"utf8"),this.remember("csv",t,s,i.length)}async writeHtml(t,n,r){return this.writeText(t,n,r,"html_report")}async writeManifest(t,n,r,i){let s={workflow:this.workflowId,title:this.title,runId:this.runId,status:t,startedAt:this.startedAt,completedAt:t==="running"?null:new Date().toISOString(),input:this.input,artifacts:this.artifacts,warnings:r,errors:i,counts:n},a=U(this.runDir,"manifest.json");return await z(a,JSON.stringify(s,null,2),"utf8"),await nt(s,a,this.baseDir),a}};function Ae(e=ae()){return U(e,"workflows","index.json")}async function Pe(e){let t=Ae(e);if(!Ze(t))return{runs:[]};try{return JSON.parse(await Ye(t,"utf8"))}catch{return{runs:[]}}}async function nt(e,t,n){if(e.status==="running")return;let r=Ae(n),i=await Pe(n),s=e.artifacts.find(l=>l.kind==="html_report")?.path??null,a={workflow:e.workflow,runId:e.runId,status:e.status,startedAt:e.startedAt,reportPath:s,manifestPath:t,summary:`${e.title} (${e.status})`};i.runs=[a,...i.runs.filter(l=>l.runId!==e.runId)].slice(0,200),await J(Z(r),{recursive:!0}),await z(r,JSON.stringify(i,null,2),"utf8")}async function $e(e){return(await Pe(ae(e))).runs}async function Ee(e,t){let n=await $e(t);return e==="last"?n[0]??null:n.find(r=>r.runId===e)??null}async function it(e,t){let n=await Ee(e,t);if(!n?.reportPath)throw new Error(`No report found for "${e}"`);return tt()==="darwin"&&await new Promise((r,i)=>{rt("open",[n.reportPath],s=>s?i(s):r())}),n.reportPath}import{readFile as At}from"fs/promises";import{z as dr}from"zod";var F=class{constructor(t,n,r=fetch,i={}){this.apiUrl=t;this.apiKey=n;this.fetchImpl=r;this.extraHeaders=i}apiUrl;apiKey;fetchImpl;extraHeaders;async post(t,n,r=18e4){let i=await this.fetchImpl(`${this.apiUrl.replace(/\/$/,"")}${t}`,{method:"POST",headers:{...this.extraHeaders,"Content-Type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:AbortSignal.timeout(r)}),s=await i.json().catch(()=>({}));if(!i.ok){let a=typeof s.error=="string"?s.error:`Workflow API ${t} failed with ${i.status}`;throw new Error(a)}return s}};import{z as D}from"zod";function I(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ot(e){let t=e.rows.map(n=>`<tr>${e.columns.map(r=>`<td>${I(n[r])}</td>`).join("")}</tr>`).join(`
2
2
  `);return["<section>",`<h2>${I(e.title)}</h2>`,'<div class="table-wrap"><table>',`<thead><tr>${e.columns.map(n=>`<th>${I(n)}</th>`).join("")}</tr></thead>`,`<tbody>${t||`<tr><td colspan="${e.columns.length}">No rows</td></tr>`}</tbody>`,"</table></div>","</section>"].join(`
3
3
  `)}function P(e){let t=e.warnings?.length?`<section class="warnings"><h2>Warnings</h2><ul>${e.warnings.map(i=>`<li>${I(i)}</li>`).join("")}</ul></section>`:"",n=(e.sections??[]).map(i=>`<section><h2>${I(i.title)}</h2><p>${I(i.body)}</p></section>`).join(`
4
4
  `),r=(e.tables??[]).map(ot).join(`
5
5
  `);return["<!doctype html>",'<html lang="en">',"<head>",'<meta charset="utf-8">','<meta name="viewport" content="width=device-width, initial-scale=1">',`<title>${I(e.title)}</title>`,"<style>",':root{font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#172026;background:#f6f7f8}',"body{margin:0;padding:32px}main{max-width:1180px;margin:0 auto;background:#fff;border:1px solid #d9dee3;border-radius:8px;padding:28px}","h1{font-size:30px;line-height:1.15;margin:0 0 8px}h2{font-size:18px;margin:28px 0 12px}p{line-height:1.55;color:#3d4952}.sub{color:#66737f;margin:0 0 20px}",".summary{background:#eef6f8;border-left:4px solid #12829a;padding:14px 16px;margin:20px 0}.warnings{background:#fff7e8;border-left:4px solid #c87b00;padding:12px 16px}",".table-wrap{overflow:auto;border:1px solid #dfe5ea;border-radius:8px}table{border-collapse:collapse;width:100%;font-size:13px}th,td{border-bottom:1px solid #edf0f2;padding:9px 10px;text-align:left;vertical-align:top}th{background:#f3f5f7;color:#31404c;position:sticky;top:0}tr:last-child td{border-bottom:0}","</style>","</head>","<body><main>",`<h1>${I(e.title)}</h1>`,e.subtitle?`<p class="sub">${I(e.subtitle)}</p>`:"",`<div class="summary">${I(e.summary)}</div>`,t,n,r,"</main></body></html>"].join(`
6
- `)}var st=D.object({keyword:D.string().min(1),domain:D.string().optional(),location:D.string().optional(),maxQuestions:D.number().int().min(1).max(200).default(40),includeSerp:D.boolean().default(!0),includePaa:D.boolean().default(!0),includeAiOverview:D.boolean().default(!0),returnPartial:D.boolean().default(!0)});function G(e){if(!e)return null;try{return new URL(e.includes("://")?e:`https://${e}`).hostname.replace(/^www\./,"").toLowerCase()}catch{return e.replace(/^https?:\/\//,"").replace(/^www\./,"").split("/")[0]?.toLowerCase()||null}}function ce(e){return G(e)??""}function at(e,t,n){let r=G(e.domain),i=[];for(let s of t?.organicResults??[]){let a=G(s.domain)??ce(s.url);i.push({surface:"organic",position:s.position,title:s.title,url:s.url,domain:a,question:"",answer_excerpt:s.snippet??"",is_target:r?a===r:!1,is_competitor:r?a!==r:!0})}for(let s of n?.flat??[]){let a=s.source_cite??"",l=G(s.source_site??"")??(a?ce(a):"");i.push({surface:"paa",position:"",title:s.source_title??s.source_site??"",url:a,domain:l,question:s.question,answer_excerpt:(s.answer??"").slice(0,240),is_target:r?l===r:!1,is_competitor:r?!!(l&&l!==r):!!l})}for(let[s,a]of(t?.aiOverview?.citations??[]).entries()){let l=a.href??"",c=l?ce(l):"";i.push({surface:"ai_overview",position:s+1,title:a.text??"",url:l,domain:c,question:"",answer_excerpt:"",is_target:r?c===r:!1,is_competitor:r?!!(c&&c!==r):!!c})}return i}function ct(e,t){let n=new Map;for(let r of e){let i=String(r.domain??"");if(!i||i===t)continue;let s=n.get(i)??{organic:[],paa:0,ai:0,urls:new Set};r.surface==="organic"&&r.position&&s.organic.push(Number(r.position)),r.surface==="paa"&&(s.paa+=1),r.surface==="ai_overview"&&(s.ai+=1),r.url&&s.urls.add(String(r.url)),n.set(i,s)}return[...n.entries()].map(([r,i])=>({domain:r,organic_best_position:i.organic.length?Math.min(...i.organic):"",organic_count:i.organic.length,paa_mentions:i.paa,ai_overview_citations:i.ai,source_url_count:i.urls.size})).sort((r,i)=>Number(r.organic_best_position||999)-Number(i.organic_best_position||999))}var We={id:"agent-packet",title:"Agent-Ready SEO Packet",description:"Create an evidence folder for AI agents from live SERP/PAA/AI search surfaces.",inputSchema:st,createState:()=>({serp:null,paa:null,warnings:[]}),steps:[{id:"harvest-serp",title:"Harvest organic SERP + AI Overview",async run({input:e,state:t,ctx:n}){if(!e.includeSerp)return{state:t,output:{skipped:!0,reason:"includeSerp is false"}};try{let r=await n.client.post("/harvest/sync",{query:e.keyword,location:e.location,serpOnly:!0,includeAllSerpFeatures:!0,maxQuestions:1,format:"json"},62e4);return await n.artifacts.writeJson("SERP raw JSON","raw/serp.json",r),{state:{...t,serp:r},output:{organicResults:r.organicResults?.length??0,localPack:r.localPack?.length??0,aiOverviewDetected:!!r.aiOverview?.detected,aiOverviewCitations:r.aiOverview?.citations?.length??0}}}catch(r){let i=`SERP evidence unavailable: ${r instanceof Error?r.message:String(r)}`;return{state:{...t,warnings:[...t.warnings,i]},output:{error:i},warnings:[i]}}}},{id:"harvest-paa",title:"Harvest People Also Ask",async run({input:e,state:t,ctx:n}){if(!e.includePaa)return{state:t,output:{skipped:!0,reason:"includePaa is false"}};try{let r=await n.client.post("/harvest/sync",{query:e.keyword,location:e.location,maxQuestions:e.maxQuestions,format:"json"},735e3);return await n.artifacts.writeJson("PAA raw JSON","raw/paa.json",r),{state:{...t,paa:r},output:{paaQuestions:r.flat?.length??0}}}catch(r){let i=`PAA evidence unavailable: ${r instanceof Error?r.message:String(r)}`;return{state:{...t,warnings:[...t.warnings,i]},output:{error:i},warnings:[i]}}}},{id:"assemble",title:"Assemble evidence packet",async run({input:e,state:t,ctx:n}){let{serp:r,paa:i}=t,s=t.warnings;if(!r&&!i&&!e.returnPartial)throw new Error("No SEO evidence was collected");let a=at(e,r,i),l=G(e.domain),c=ct(a,l),p={input:e,serp:r??{status:"skipped"},paa:i??{status:"skipped"},target:{domain:l,organicPositions:a.filter(d=>d.surface==="organic"&&d.is_target).map(d=>Number(d.position)),citedInAiOverview:a.some(d=>d.surface==="ai_overview"&&d.is_target),citedInPaa:a.some(d=>d.surface==="paa"&&d.is_target)},competitors:c,warnings:s};await n.artifacts.writeJson("Evidence JSON","evidence.json",p),await n.artifacts.writeCsv("Sources CSV","sources.csv",["surface","position","title","url","domain","question","answer_excerpt","is_target","is_competitor"],a),await n.artifacts.writeCsv("Competitors CSV","competitors.csv",["domain","organic_best_position","organic_count","paa_mentions","ai_overview_citations","source_url_count"],c);let u=[`# SEO Evidence Brief: ${e.keyword}`,"",`Location: ${e.location??"not specified"}`,`Target domain: ${l??"not specified"}`,"","## Evidence Summary",`- Organic rows: ${a.filter(d=>d.surface==="organic").length}`,`- PAA rows: ${a.filter(d=>d.surface==="paa").length}`,`- AI Overview citations: ${a.filter(d=>d.surface==="ai_overview").length}`,`- Competitor domains: ${c.length}`,"","## Recommended Use","Use the CSV files as source of truth. Tie content recommendations to evidence rows and mark unsupported ideas as assumptions."].join(`
6
+ `)}var st=D.object({keyword:D.string().min(1),domain:D.string().optional(),location:D.string().optional(),maxQuestions:D.number().int().min(1).max(100).default(40),includeSerp:D.boolean().default(!0),includePaa:D.boolean().default(!0),includeAiOverview:D.boolean().default(!0),returnPartial:D.boolean().default(!0)});function G(e){if(!e)return null;try{return new URL(e.includes("://")?e:`https://${e}`).hostname.replace(/^www\./,"").toLowerCase()}catch{return e.replace(/^https?:\/\//,"").replace(/^www\./,"").split("/")[0]?.toLowerCase()||null}}function ce(e){return G(e)??""}function at(e,t,n){let r=G(e.domain),i=[];for(let s of t?.organicResults??[]){let a=G(s.domain)??ce(s.url);i.push({surface:"organic",position:s.position,title:s.title,url:s.url,domain:a,question:"",answer_excerpt:s.snippet??"",is_target:r?a===r:!1,is_competitor:r?a!==r:!0})}for(let s of n?.flat??[]){let a=s.source_cite??"",l=G(s.source_site??"")??(a?ce(a):"");i.push({surface:"paa",position:"",title:s.source_title??s.source_site??"",url:a,domain:l,question:s.question,answer_excerpt:(s.answer??"").slice(0,240),is_target:r?l===r:!1,is_competitor:r?!!(l&&l!==r):!!l})}for(let[s,a]of(t?.aiOverview?.citations??[]).entries()){let l=a.href??"",c=l?ce(l):"";i.push({surface:"ai_overview",position:s+1,title:a.text??"",url:l,domain:c,question:"",answer_excerpt:"",is_target:r?c===r:!1,is_competitor:r?!!(c&&c!==r):!!c})}return i}function ct(e,t){let n=new Map;for(let r of e){let i=String(r.domain??"");if(!i||i===t)continue;let s=n.get(i)??{organic:[],paa:0,ai:0,urls:new Set};r.surface==="organic"&&r.position&&s.organic.push(Number(r.position)),r.surface==="paa"&&(s.paa+=1),r.surface==="ai_overview"&&(s.ai+=1),r.url&&s.urls.add(String(r.url)),n.set(i,s)}return[...n.entries()].map(([r,i])=>({domain:r,organic_best_position:i.organic.length?Math.min(...i.organic):"",organic_count:i.organic.length,paa_mentions:i.paa,ai_overview_citations:i.ai,source_url_count:i.urls.size})).sort((r,i)=>Number(r.organic_best_position||999)-Number(i.organic_best_position||999))}var We={id:"agent-packet",title:"Agent-Ready SEO Packet",description:"Create an evidence folder for AI agents from live SERP/PAA/AI search surfaces.",inputSchema:st,createState:()=>({serp:null,paa:null,warnings:[]}),steps:[{id:"harvest-serp",title:"Harvest organic SERP + AI Overview",async run({input:e,state:t,ctx:n}){if(!e.includeSerp)return{state:t,output:{skipped:!0,reason:"includeSerp is false"}};try{let r=await n.client.post("/harvest/sync",{query:e.keyword,location:e.location,serpOnly:!0,includeAllSerpFeatures:!0,maxQuestions:1,format:"json"},62e4);return await n.artifacts.writeJson("SERP raw JSON","raw/serp.json",r),{state:{...t,serp:r},output:{organicResults:r.organicResults?.length??0,localPack:r.localPack?.length??0,aiOverviewDetected:!!r.aiOverview?.detected,aiOverviewCitations:r.aiOverview?.citations?.length??0}}}catch(r){let i=`SERP evidence unavailable: ${r instanceof Error?r.message:String(r)}`;return{state:{...t,warnings:[...t.warnings,i]},output:{error:i},warnings:[i]}}}},{id:"harvest-paa",title:"Harvest People Also Ask",async run({input:e,state:t,ctx:n}){if(!e.includePaa)return{state:t,output:{skipped:!0,reason:"includePaa is false"}};try{let r=await n.client.post("/harvest/sync",{query:e.keyword,location:e.location,maxQuestions:e.maxQuestions,format:"json"},735e3);return await n.artifacts.writeJson("PAA raw JSON","raw/paa.json",r),{state:{...t,paa:r},output:{paaQuestions:r.flat?.length??0}}}catch(r){let i=`PAA evidence unavailable: ${r instanceof Error?r.message:String(r)}`;return{state:{...t,warnings:[...t.warnings,i]},output:{error:i},warnings:[i]}}}},{id:"assemble",title:"Assemble evidence packet",async run({input:e,state:t,ctx:n}){let{serp:r,paa:i}=t,s=t.warnings;if(!r&&!i&&!e.returnPartial)throw new Error("No SEO evidence was collected");let a=at(e,r,i),l=G(e.domain),c=ct(a,l),p={input:e,serp:r??{status:"skipped"},paa:i??{status:"skipped"},target:{domain:l,organicPositions:a.filter(d=>d.surface==="organic"&&d.is_target).map(d=>Number(d.position)),citedInAiOverview:a.some(d=>d.surface==="ai_overview"&&d.is_target),citedInPaa:a.some(d=>d.surface==="paa"&&d.is_target)},competitors:c,warnings:s};await n.artifacts.writeJson("Evidence JSON","evidence.json",p),await n.artifacts.writeCsv("Sources CSV","sources.csv",["surface","position","title","url","domain","question","answer_excerpt","is_target","is_competitor"],a),await n.artifacts.writeCsv("Competitors CSV","competitors.csv",["domain","organic_best_position","organic_count","paa_mentions","ai_overview_citations","source_url_count"],c);let u=[`# SEO Evidence Brief: ${e.keyword}`,"",`Location: ${e.location??"not specified"}`,`Target domain: ${l??"not specified"}`,"","## Evidence Summary",`- Organic rows: ${a.filter(d=>d.surface==="organic").length}`,`- PAA rows: ${a.filter(d=>d.surface==="paa").length}`,`- AI Overview citations: ${a.filter(d=>d.surface==="ai_overview").length}`,`- Competitor domains: ${c.length}`,"","## Recommended Use","Use the CSV files as source of truth. Tie content recommendations to evidence rows and mark unsupported ideas as assumptions."].join(`
7
7
  `);await n.artifacts.writeText("Brief","brief.md",u),await n.artifacts.writeText("Agent tasks","tasks.md",["# Agent Tasks","","- [ ] Read `evidence.json` before writing recommendations.","- [ ] Compare the target domain against `competitors.csv`.","- [ ] Use `sources.csv` for citations and source-grounded page sections.","- [ ] Mark unsupported recommendations as assumptions."].join(`
8
8
  `)),await n.artifacts.writeText("Agent instructions","agent-instructions.md",["# Agent Instructions","","You are working from an MCP Scraper SEO evidence packet. Use `evidence.json` and CSV files as source of truth. Do not invent citations. If a recommendation is not supported by evidence, mark it as an assumption."].join(`
9
9
  `));let w=`${a.length} evidence rows and ${c.length} competitor domains collected.`,v=await n.artifacts.writeHtml("HTML report","report.html",P({title:"Agent-Ready SEO Packet",subtitle:`${e.keyword}${e.location?` \xB7 ${e.location}`:""}`,summary:w,warnings:s,tables:[{title:"Competitor Domains",columns:["domain","organic_best_position","organic_count","paa_mentions","ai_overview_citations","source_url_count"],rows:c.slice(0,50)},{title:"Evidence Sources",columns:["surface","position","title","domain","question","is_target"],rows:a.slice(0,100)}]})),f=s.length?"partial":"succeeded",b={sources:a.length,competitors:c.length};return await n.artifacts.writeManifest(f,b,s,[]),{state:t,output:{sources:a.length,competitors:c.length,status:f},summary:{title:"Agent-Ready SEO Packet",summary:w,status:f,counts:b,warnings:s,errors:[],reportPath:v}}}}]};import{z as q}from"zod";var lt=q.object({query:q.string().min(1),state:q.string().min(2).default("TN"),minPopulation:q.number().int().min(0).default(1e5),maxCities:q.number().int().min(1).max(100).default(25),maxResultsPerCity:q.number().int().min(1).max(50).default(20),concurrency:q.number().int().min(1).max(5).default(5),proxyMode:q.enum(["configured","none"]).default(T),saveCsv:q.boolean().default(!0)});function Q(e){let t=[];for(let n of e.cities){if(!n.results.length){t.push({source_query:e.query,source_location:n.location,city:n.city,state:n.state,population:n.population,result_position:null,business_name:null,review_stars:null,review_count:null,category:null,address:null,phone:null,website_url:null,place_url:null,cid:null,cid_decimal:null,result_status:n.status,error:n.error});continue}for(let r of n.results)t.push({source_query:e.query,source_location:n.location,city:n.city,state:n.state,population:n.population,result_position:r.position,business_name:r.name,review_stars:r.rating,review_count:r.reviewCount,category:r.category,address:r.address,phone:r.phone,website_url:r.websiteUrl,place_url:r.placeUrl,cid:r.cid,cid_decimal:r.cidDecimal,result_status:n.status,error:n.error})}return t}var K=["source_query","source_location","city","state","population","result_position","business_name","review_stars","review_count","category","address","phone","website_url","place_url","cid","cid_decimal","result_status","error"],Me={id:"directory",title:"Directory Workflow",description:"Select city markets and export Google Maps business candidates.",inputSchema:lt,async run(e,t){await t.artifacts.writeManifest("running",{},[],[]);let n=await t.client.post("/directory/run",{...e,background:!1},9e5);await t.artifacts.writeJson("Directory evidence","evidence.json",n);let r=Q(n);await t.artifacts.writeCsv("Directory CSV","exports/directory.csv",K,r);let i=n.cities.map(u=>({city:u.city,state:u.state,population:u.population,status:u.status,result_count:u.resultCount,error:u.error??""})),s=r.filter(u=>u.business_name).slice(0,100).map(u=>({city:u.city,position:u.result_position,business:u.business_name,rating:u.review_stars,reviews:u.review_count,category:u.category,website:u.website_url})),a=`${n.selectedCityCount} cities processed with ${n.totalResultCount} Maps results.`;await t.artifacts.writeText("Summary","summary.md",`# Directory Workflow
@@ -17,7 +17,7 @@ ${b}
17
17
  `));let f=`${i.selectedCityCount} cities, ${i.totalResultCount} Maps results, ${p.filter(g=>g.detail).length} hydrated profiles.`;await t.artifacts.writeText("Summary","summary.md",`# Local Competitive Audit
18
18
 
19
19
  ${f}
20
- `);let b=await t.artifacts.writeHtml("HTML report","report.html",P({title:"Local Competitive Audit",subtitle:`${e.query} \xB7 ${e.state}`,summary:f,warnings:n,tables:[{title:"City Opportunity",columns:["city","state","population","result_count","median_review_count","median_rating","top_three_average_review_count","top_categories","opportunity_score","difficulty_score"],rows:v},{title:"Hydrated Competitors",columns:["city","result_position","business_name","category","review_stars","review_count","hydrated","review_topics"],rows:u.slice(0,100)},{title:"Review Insights",columns:["city","business_name","topics","praise_terms","complaint_terms"],rows:w.slice(0,100)}]})),d=n.length||i.cities.some(g=>g.status==="failed")?"partial":"succeeded",k={cities:i.selectedCityCount,mapsResults:i.totalResultCount,hydratedProfiles:p.filter(g=>g.detail).length};return await t.artifacts.writeManifest(d,k,n,r),{title:"Local Competitive Audit",summary:f,status:d,counts:k,warnings:n,errors:r,reportPath:b}}};import{z as y}from"zod";var ft=new Set(["about","after","also","because","been","best","both","from","have","into","more","most","near","only","over","than","that","their","them","then","there","these","they","this","what","when","where","which","while","with","your","will","would","should","could","does","were","cost","costs"]);function $(e){if(!e)return null;try{return new URL(e.includes("://")?e:`https://${e}`).hostname.replace(/^www\./,"").toLowerCase()}catch{return e.replace(/^https?:\/\//,"").replace(/^www\./,"").split("/")[0]?.toLowerCase()||null}}function A(e){return $(e)??""}function H(e){if(e==null||e==="")return null;let t=Number(String(e).replace(/[^\d.]/g,""));return Number.isFinite(t)?t:null}function ue(e){let t=e.filter(n=>n!==null).sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]??null:null}function me(e,t=12){let n=new Map;for(let r of e.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/))r.length<4||ft.has(r)||n.set(r,(n.get(r)??0)+1);return[...n.entries()].sort((r,i)=>i[1]-r[1]||r[0].localeCompare(i[0])).slice(0,t).map(([r,i])=>`${r} (${i})`).join("; ")}function ht(e){let t=e.toLowerCase();return/\b(cost|price|pricing|charge|expensive|cheap)\b/.test(t)?"cost":/\b(best|top|recommended|reviews?|compare|versus|vs)\b/.test(t)?"comparison":/\b(how|steps?|process|way to)\b/.test(t)?"process":/\b(why|worth|important|benefit)\b/.test(t)?"why":/\b(near me|city|local|nearby)\b/.test(t)?"local":/\b(can|does|do|is|are|should|will)\b/.test(t)?"decision":"definition"}function ee(e){return(e?.flat??[]).filter(t=>t.question).map((t,n)=>{let r=t.source_cite??"",i=$(t.source_site??"")??A(r);return{position:n+1,intent:ht(t.question??""),question:t.question??"",answer_excerpt:(t.answer??"").slice(0,320),source_title:t.source_title??"",source_domain:i,source_url:r}})}function He(e){let t=new Map;for(let n of e){let r=String(n.source_domain??n.domain??"");if(!r)continue;let i=t.get(r)??{questions:0,urls:new Set,intents:new Map};i.questions+=n.question?1:0,(n.source_url||n.url)&&i.urls.add(String(n.source_url??n.url)),n.intent&&i.intents.set(String(n.intent),(i.intents.get(String(n.intent))??0)+1),t.set(r,i)}return[...t.entries()].map(([n,r])=>({domain:n,question_mentions:r.questions,source_url_count:r.urls.size,top_intents:[...r.intents.entries()].sort((i,s)=>s[1]-i[1]).map(([i,s])=>`${i} (${s})`).join("; ")})).sort((n,r)=>Number(r.question_mentions)-Number(n.question_mentions)||String(n.domain).localeCompare(String(r.domain)))}function Be(e){return(e??"").replace(/\s+/g," ").split(/(?<=[.!?])\s+/).map(t=>t.trim()).filter(t=>t.length>20).slice(0,20)}function Ne(e){let t=e.toLowerCase();return/\bis\b|\bare\b|\bmeans\b|\brefers to\b/.test(t)?"definition":/\binclude\b|\bconsider\b|\bfactors?\b|\bcriteria\b/.test(t)?"criteria":/\bfirst\b|\bthen\b|\bsteps?\b|\bprocess\b/.test(t)?"process":/\bvs\b|\bthan\b|\bcompare\b|\bdifference\b/.test(t)?"comparison":/\bcost\b|\bprice\b|\baverage\b|\brange\b/.test(t)?"cost":"claim"}function te(e,t){return{position:t.position??"",domain:t.domain,url:t.url,serp_title:t.title??"",page_title:e.title??"",h1:e.h1??"",meta_description:e.metaDescription??"",word_count:e.wordCount??"",heading_count:e.headings?.length??0,schema_types:(e.schemaTypes??[]).join("; ")}}async function pe(e,t,n){let r=new Array(e.length),i=0;async function s(){for(;i<e.length;){let a=i;i+=1,r[a]=await n(e[a],a)}}return await Promise.all(Array.from({length:Math.min(Math.max(1,t),e.length)},()=>s())),r}var yt=y.enum(["configured","none"]),vt=y.object({query:y.string().min(1),location:y.string().optional(),state:y.string().optional(),minPopulation:y.number().int().min(0).default(1e5),maxCities:y.number().int().min(1).max(100).default(5),maxResultsPerCity:y.number().int().min(1).max(50).default(20),hydrateTop:y.number().int().min(0).max(10).default(5),maxReviews:y.number().int().min(0).max(500).default(25),concurrency:y.number().int().min(1).max(5).default(5),proxyMode:yt.default(T),returnPartial:y.boolean().default(!0)}).refine(e=>e.location||e.state,{message:"Either location or state is required for map-comparison"}),_t=y.object({keyword:y.string().min(1),domain:y.string().optional(),url:y.string().url().optional(),location:y.string().optional(),maxResults:y.number().int().min(1).max(20).default(10),maxQuestions:y.number().int().min(1).max(200).default(40),extractTop:y.number().int().min(0).max(10).default(5),includePaa:y.boolean().default(!0),includeAiOverview:y.boolean().default(!0),returnPartial:y.boolean().default(!0)}),bt=y.object({keyword:y.string().min(1),location:y.string().optional(),maxQuestions:y.number().int().min(1).max(300).default(80),depth:y.number().int().min(1).max(6).default(3),returnPartial:y.boolean().default(!0)}),kt=y.object({keyword:y.string().min(1),domain:y.string().optional(),url:y.string().url().optional(),location:y.string().optional(),maxQuestions:y.number().int().min(1).max(200).default(40),extractTop:y.number().int().min(0).max(8).default(3),returnPartial:y.boolean().default(!0)});function Rt(e,t,n){return n.map(r=>({source_query:t,source_location:e,city:e.split(",")[0]?.trim()??e,state:e.split(",")[1]?.trim()??"",population:"",result_position:r.position,business_name:r.name,review_stars:r.rating??"",review_count:r.reviewCount??"",category:r.category??"",address:r.address??"",phone:r.phone??"",website_url:r.websiteUrl??"",place_url:r.placeUrl??"",cid:r.cid??"",cid_decimal:r.cidDecimal??"",result_status:"ok",error:""}))}function Je(e){let t=new Map;for(let n of e){let r=String(n.source_location??n.location??"");if(!r)continue;let i=t.get(r)??[];i.push(n),t.set(r,i)}return[...t.entries()].map(([n,r])=>{let i=r.map(c=>H(c.review_count)),s=r.map(c=>H(c.review_stars)),a=r.slice(0,3).map(c=>H(c.review_count)).filter(c=>c!==null),l=new Map;for(let c of r){let p=String(c.category??"");p&&l.set(p,(l.get(p)??0)+1)}return{source_location:n,result_count:r.filter(c=>c.business_name).length,median_review_count:ue(i)??"",median_rating:ue(s)??"",top_three_average_review_count:a.length?Math.round(a.reduce((c,p)=>c+p,0)/a.length):"",top_categories:[...l.entries()].sort((c,p)=>p[1]-c[1]).slice(0,5).map(([c,p])=>`${c} (${p})`).join("; "),websites_present:r.filter(c=>c.website_url).length}})}function St(e){let t=new Map;for(let n of Je(e))t.set(String(n.source_location),H(n.top_three_average_review_count)??0);return e.filter(n=>n.business_name).map(n=>{let r=H(n.review_count)??0,i=t.get(String(n.source_location))??0,s=!n.website_url,a=H(n.result_position)??999;return{source_location:n.source_location,result_position:n.result_position,business_name:n.business_name,category:n.category,review_stars:n.review_stars,review_count:n.review_count,review_gap_to_top3_average:i?Math.max(0,i-r):"",website_url:n.website_url,place_url:n.place_url,comparison_note:a<=3?"visible leader":s?"ranking without website":r<i?"review-light competitor":"visible competitor"}})}function xt(e,t){return(e?.organicResults??[]).map(n=>{let r=n.url??"",i=$(n.domain??"")??A(r);return{position:n.position??"",title:n.title??"",url:r,domain:i,snippet:n.snippet??"",is_target:t?i===t:!1}})}function Ct(e,t){let n=new Set((e?.headings??[]).map(s=>s.text.toLowerCase().replace(/[^a-z0-9\s]/g," ").trim())),r=new Set((e?.headings??[]).flatMap(s=>s.text.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(Boolean))),i=[];for(let{source:s,page:a}of t)for(let l of a.headings??[]){if(l.level>3||!l.text)continue;let c=l.text.toLowerCase().replace(/[^a-z0-9\s]/g," ").trim(),p=c.split(/\s+/).filter(v=>v.length>3),u=p.filter(v=>r.has(v)).length;(n.has(c)||u>=Math.max(2,Math.ceil(p.length/2)))&&e||i.push({source_position:s.position??"",source_domain:$(s.domain??"")??A(s.url),source_url:s.url??"",heading_level:l.level,competitor_heading:l.text,target_coverage:e?"not found in target headings":"no target page extracted",terms:me(l.text,6)})}return i.slice(0,150)}async function de(e,t,n,r){return pe(t.filter(i=>i.url),2,async(i,s)=>{try{let a=await e.client.post("/extract-url",{url:i.url},18e4);return await e.artifacts.writeJson(`${r} ${s+1}`,`raw/extract-url/${r.toLowerCase()}-${s+1}.json`,a),{source:i,page:a}}catch(a){return n.push(`Page extraction failed for ${i.url}: ${a instanceof Error?a.message:String(a)}`),null}}).then(i=>i.filter(s=>s!==null))}var ze={id:"map-comparison",title:"Maps Comparison",description:"Compare Google Maps competitors by rank, reviews, stars, categories, websites, and profile/review signals.",inputSchema:vt,async run(e,t){await t.artifacts.writeManifest("running",{},[],[]);let n=[],r,i=null,s=null;e.location?(s=await t.client.post("/maps/search",{query:e.query,location:e.location,maxResults:e.maxResultsPerCity,proxyMode:e.proxyMode},24e4),r=Rt(e.location,e.query,s.results),await t.artifacts.writeJson("Maps search raw JSON","raw/maps-search.json",s)):(i=await t.client.post("/directory/run",{query:e.query,state:e.state,minPopulation:e.minPopulation,maxCities:e.maxCities,maxResultsPerCity:e.maxResultsPerCity,concurrency:e.concurrency,proxyMode:e.proxyMode,saveCsv:!0,background:!1},9e5),r=Q(i),await t.artifacts.writeJson("Directory raw JSON","raw/directory-workflow.json",i),await t.artifacts.writeCsv("Directory CSV","exports/directory.csv",K,r),n.push(...i.warnings));let a=St(r),l=a.slice(0,e.hydrateTop*Math.max(1,e.location?1:e.maxCities)),p=(await pe(l,3,async(d,k)=>{try{let g=await t.client.post("/maps/place",{businessName:d.business_name,location:d.source_location,includeReviews:e.maxReviews>0,maxReviews:Math.max(1,e.maxReviews)},18e4);return await t.artifacts.writeJson(`${d.business_name} profile`,`raw/maps-place-intel/${k+1}-${String(d.business_name).toLowerCase().replace(/[^a-z0-9]+/g,"-")}.json`,g),{row:d,detail:g,error:""}}catch(g){let o=g instanceof Error?g.message:String(g);return n.push(`Profile hydration failed for ${d.business_name}: ${o}`),{row:d,detail:null,error:o}}})).map(({row:d,detail:k,error:g})=>({source_location:d.source_location,result_position:d.result_position,business_name:d.business_name,category:k?.category??d.category,review_stars:k?.rating??d.review_stars,review_count:k?.reviewCount??d.review_count,website_url:k?.website??d.website_url,review_topics:(k?.reviewTopics??[]).map(o=>`${o.label} (${o.count})`).join("; "),about_attributes:(k?.aboutAttributes??[]).map(o=>`${o.section}: ${o.attribute}`).join("; "),reviews_status:k?.reviewsStatus??"",error:g})),u=Je(r);await t.artifacts.writeCsv("Maps results CSV","maps-results.csv",["source_query","source_location","city","state","population","result_position","business_name","review_stars","review_count","category","address","phone","website_url","place_url","cid","cid_decimal","result_status","error"],r),await t.artifacts.writeCsv("Comparison CSV","map-comparison.csv",["source_location","result_position","business_name","category","review_stars","review_count","review_gap_to_top3_average","website_url","place_url","comparison_note"],a),await t.artifacts.writeCsv("Profile insights CSV","profile-insights.csv",["source_location","result_position","business_name","category","review_stars","review_count","website_url","review_topics","about_attributes","reviews_status","error"],p),await t.artifacts.writeJson("Maps comparison evidence","evidence.json",{input:e,directory:i,mapsSearch:s,rows:r,compareRows:a,profileRows:p,markets:u,warnings:n}),await t.artifacts.writeText("Brief","brief.md",[`# Maps Comparison: ${e.query}`,"",`Markets: ${u.map(d=>d.source_location).join(", ")}`,"","## How to Use","- Compare rank position against review count and category patterns.","- Treat review gaps and missing websites as opportunity signals, not guarantees.","- Use profile topics and attributes as evidence for local content and GBP improvements."].join(`
20
+ `);let b=await t.artifacts.writeHtml("HTML report","report.html",P({title:"Local Competitive Audit",subtitle:`${e.query} \xB7 ${e.state}`,summary:f,warnings:n,tables:[{title:"City Opportunity",columns:["city","state","population","result_count","median_review_count","median_rating","top_three_average_review_count","top_categories","opportunity_score","difficulty_score"],rows:v},{title:"Hydrated Competitors",columns:["city","result_position","business_name","category","review_stars","review_count","hydrated","review_topics"],rows:u.slice(0,100)},{title:"Review Insights",columns:["city","business_name","topics","praise_terms","complaint_terms"],rows:w.slice(0,100)}]})),d=n.length||i.cities.some(g=>g.status==="failed")?"partial":"succeeded",k={cities:i.selectedCityCount,mapsResults:i.totalResultCount,hydratedProfiles:p.filter(g=>g.detail).length};return await t.artifacts.writeManifest(d,k,n,r),{title:"Local Competitive Audit",summary:f,status:d,counts:k,warnings:n,errors:r,reportPath:b}}};import{z as y}from"zod";var ft=new Set(["about","after","also","because","been","best","both","from","have","into","more","most","near","only","over","than","that","their","them","then","there","these","they","this","what","when","where","which","while","with","your","will","would","should","could","does","were","cost","costs"]);function $(e){if(!e)return null;try{return new URL(e.includes("://")?e:`https://${e}`).hostname.replace(/^www\./,"").toLowerCase()}catch{return e.replace(/^https?:\/\//,"").replace(/^www\./,"").split("/")[0]?.toLowerCase()||null}}function A(e){return $(e)??""}function H(e){if(e==null||e==="")return null;let t=Number(String(e).replace(/[^\d.]/g,""));return Number.isFinite(t)?t:null}function ue(e){let t=e.filter(n=>n!==null).sort((n,r)=>n-r);return t.length?t[Math.floor(t.length/2)]??null:null}function me(e,t=12){let n=new Map;for(let r of e.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/))r.length<4||ft.has(r)||n.set(r,(n.get(r)??0)+1);return[...n.entries()].sort((r,i)=>i[1]-r[1]||r[0].localeCompare(i[0])).slice(0,t).map(([r,i])=>`${r} (${i})`).join("; ")}function ht(e){let t=e.toLowerCase();return/\b(cost|price|pricing|charge|expensive|cheap)\b/.test(t)?"cost":/\b(best|top|recommended|reviews?|compare|versus|vs)\b/.test(t)?"comparison":/\b(how|steps?|process|way to)\b/.test(t)?"process":/\b(why|worth|important|benefit)\b/.test(t)?"why":/\b(near me|city|local|nearby)\b/.test(t)?"local":/\b(can|does|do|is|are|should|will)\b/.test(t)?"decision":"definition"}function ee(e){return(e?.flat??[]).filter(t=>t.question).map((t,n)=>{let r=t.source_cite??"",i=$(t.source_site??"")??A(r);return{position:n+1,intent:ht(t.question??""),question:t.question??"",answer_excerpt:(t.answer??"").slice(0,320),source_title:t.source_title??"",source_domain:i,source_url:r}})}function He(e){let t=new Map;for(let n of e){let r=String(n.source_domain??n.domain??"");if(!r)continue;let i=t.get(r)??{questions:0,urls:new Set,intents:new Map};i.questions+=n.question?1:0,(n.source_url||n.url)&&i.urls.add(String(n.source_url??n.url)),n.intent&&i.intents.set(String(n.intent),(i.intents.get(String(n.intent))??0)+1),t.set(r,i)}return[...t.entries()].map(([n,r])=>({domain:n,question_mentions:r.questions,source_url_count:r.urls.size,top_intents:[...r.intents.entries()].sort((i,s)=>s[1]-i[1]).map(([i,s])=>`${i} (${s})`).join("; ")})).sort((n,r)=>Number(r.question_mentions)-Number(n.question_mentions)||String(n.domain).localeCompare(String(r.domain)))}function Be(e){return(e??"").replace(/\s+/g," ").split(/(?<=[.!?])\s+/).map(t=>t.trim()).filter(t=>t.length>20).slice(0,20)}function Ne(e){let t=e.toLowerCase();return/\bis\b|\bare\b|\bmeans\b|\brefers to\b/.test(t)?"definition":/\binclude\b|\bconsider\b|\bfactors?\b|\bcriteria\b/.test(t)?"criteria":/\bfirst\b|\bthen\b|\bsteps?\b|\bprocess\b/.test(t)?"process":/\bvs\b|\bthan\b|\bcompare\b|\bdifference\b/.test(t)?"comparison":/\bcost\b|\bprice\b|\baverage\b|\brange\b/.test(t)?"cost":"claim"}function te(e,t){return{position:t.position??"",domain:t.domain,url:t.url,serp_title:t.title??"",page_title:e.title??"",h1:e.h1??"",meta_description:e.metaDescription??"",word_count:e.wordCount??"",heading_count:e.headings?.length??0,schema_types:(e.schemaTypes??[]).join("; ")}}async function pe(e,t,n){let r=new Array(e.length),i=0;async function s(){for(;i<e.length;){let a=i;i+=1,r[a]=await n(e[a],a)}}return await Promise.all(Array.from({length:Math.min(Math.max(1,t),e.length)},()=>s())),r}var yt=y.enum(["configured","none"]),vt=y.object({query:y.string().min(1),location:y.string().optional(),state:y.string().optional(),minPopulation:y.number().int().min(0).default(1e5),maxCities:y.number().int().min(1).max(100).default(5),maxResultsPerCity:y.number().int().min(1).max(50).default(20),hydrateTop:y.number().int().min(0).max(10).default(5),maxReviews:y.number().int().min(0).max(500).default(25),concurrency:y.number().int().min(1).max(5).default(5),proxyMode:yt.default(T),returnPartial:y.boolean().default(!0)}).refine(e=>e.location||e.state,{message:"Either location or state is required for map-comparison"}),_t=y.object({keyword:y.string().min(1),domain:y.string().optional(),url:y.string().url().optional(),location:y.string().optional(),maxResults:y.number().int().min(1).max(20).default(10),maxQuestions:y.number().int().min(1).max(100).default(40),extractTop:y.number().int().min(0).max(10).default(5),includePaa:y.boolean().default(!0),includeAiOverview:y.boolean().default(!0),returnPartial:y.boolean().default(!0)}),bt=y.object({keyword:y.string().min(1),location:y.string().optional(),maxQuestions:y.number().int().min(1).max(100).default(80),depth:y.number().int().min(1).max(6).default(3),returnPartial:y.boolean().default(!0)}),kt=y.object({keyword:y.string().min(1),domain:y.string().optional(),url:y.string().url().optional(),location:y.string().optional(),maxQuestions:y.number().int().min(1).max(100).default(40),extractTop:y.number().int().min(0).max(8).default(3),returnPartial:y.boolean().default(!0)});function Rt(e,t,n){return n.map(r=>({source_query:t,source_location:e,city:e.split(",")[0]?.trim()??e,state:e.split(",")[1]?.trim()??"",population:"",result_position:r.position,business_name:r.name,review_stars:r.rating??"",review_count:r.reviewCount??"",category:r.category??"",address:r.address??"",phone:r.phone??"",website_url:r.websiteUrl??"",place_url:r.placeUrl??"",cid:r.cid??"",cid_decimal:r.cidDecimal??"",result_status:"ok",error:""}))}function Je(e){let t=new Map;for(let n of e){let r=String(n.source_location??n.location??"");if(!r)continue;let i=t.get(r)??[];i.push(n),t.set(r,i)}return[...t.entries()].map(([n,r])=>{let i=r.map(c=>H(c.review_count)),s=r.map(c=>H(c.review_stars)),a=r.slice(0,3).map(c=>H(c.review_count)).filter(c=>c!==null),l=new Map;for(let c of r){let p=String(c.category??"");p&&l.set(p,(l.get(p)??0)+1)}return{source_location:n,result_count:r.filter(c=>c.business_name).length,median_review_count:ue(i)??"",median_rating:ue(s)??"",top_three_average_review_count:a.length?Math.round(a.reduce((c,p)=>c+p,0)/a.length):"",top_categories:[...l.entries()].sort((c,p)=>p[1]-c[1]).slice(0,5).map(([c,p])=>`${c} (${p})`).join("; "),websites_present:r.filter(c=>c.website_url).length}})}function St(e){let t=new Map;for(let n of Je(e))t.set(String(n.source_location),H(n.top_three_average_review_count)??0);return e.filter(n=>n.business_name).map(n=>{let r=H(n.review_count)??0,i=t.get(String(n.source_location))??0,s=!n.website_url,a=H(n.result_position)??999;return{source_location:n.source_location,result_position:n.result_position,business_name:n.business_name,category:n.category,review_stars:n.review_stars,review_count:n.review_count,review_gap_to_top3_average:i?Math.max(0,i-r):"",website_url:n.website_url,place_url:n.place_url,comparison_note:a<=3?"visible leader":s?"ranking without website":r<i?"review-light competitor":"visible competitor"}})}function xt(e,t){return(e?.organicResults??[]).map(n=>{let r=n.url??"",i=$(n.domain??"")??A(r);return{position:n.position??"",title:n.title??"",url:r,domain:i,snippet:n.snippet??"",is_target:t?i===t:!1}})}function Ct(e,t){let n=new Set((e?.headings??[]).map(s=>s.text.toLowerCase().replace(/[^a-z0-9\s]/g," ").trim())),r=new Set((e?.headings??[]).flatMap(s=>s.text.toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(Boolean))),i=[];for(let{source:s,page:a}of t)for(let l of a.headings??[]){if(l.level>3||!l.text)continue;let c=l.text.toLowerCase().replace(/[^a-z0-9\s]/g," ").trim(),p=c.split(/\s+/).filter(v=>v.length>3),u=p.filter(v=>r.has(v)).length;(n.has(c)||u>=Math.max(2,Math.ceil(p.length/2)))&&e||i.push({source_position:s.position??"",source_domain:$(s.domain??"")??A(s.url),source_url:s.url??"",heading_level:l.level,competitor_heading:l.text,target_coverage:e?"not found in target headings":"no target page extracted",terms:me(l.text,6)})}return i.slice(0,150)}async function de(e,t,n,r){return pe(t.filter(i=>i.url),2,async(i,s)=>{try{let a=await e.client.post("/extract-url",{url:i.url},18e4);return await e.artifacts.writeJson(`${r} ${s+1}`,`raw/extract-url/${r.toLowerCase()}-${s+1}.json`,a),{source:i,page:a}}catch(a){return n.push(`Page extraction failed for ${i.url}: ${a instanceof Error?a.message:String(a)}`),null}}).then(i=>i.filter(s=>s!==null))}var ze={id:"map-comparison",title:"Maps Comparison",description:"Compare Google Maps competitors by rank, reviews, stars, categories, websites, and profile/review signals.",inputSchema:vt,async run(e,t){await t.artifacts.writeManifest("running",{},[],[]);let n=[],r,i=null,s=null;e.location?(s=await t.client.post("/maps/search",{query:e.query,location:e.location,maxResults:e.maxResultsPerCity,proxyMode:e.proxyMode},24e4),r=Rt(e.location,e.query,s.results),await t.artifacts.writeJson("Maps search raw JSON","raw/maps-search.json",s)):(i=await t.client.post("/directory/run",{query:e.query,state:e.state,minPopulation:e.minPopulation,maxCities:e.maxCities,maxResultsPerCity:e.maxResultsPerCity,concurrency:e.concurrency,proxyMode:e.proxyMode,saveCsv:!0,background:!1},9e5),r=Q(i),await t.artifacts.writeJson("Directory raw JSON","raw/directory-workflow.json",i),await t.artifacts.writeCsv("Directory CSV","exports/directory.csv",K,r),n.push(...i.warnings));let a=St(r),l=a.slice(0,e.hydrateTop*Math.max(1,e.location?1:e.maxCities)),p=(await pe(l,3,async(d,k)=>{try{let g=await t.client.post("/maps/place",{businessName:d.business_name,location:d.source_location,includeReviews:e.maxReviews>0,maxReviews:Math.max(1,e.maxReviews)},18e4);return await t.artifacts.writeJson(`${d.business_name} profile`,`raw/maps-place-intel/${k+1}-${String(d.business_name).toLowerCase().replace(/[^a-z0-9]+/g,"-")}.json`,g),{row:d,detail:g,error:""}}catch(g){let o=g instanceof Error?g.message:String(g);return n.push(`Profile hydration failed for ${d.business_name}: ${o}`),{row:d,detail:null,error:o}}})).map(({row:d,detail:k,error:g})=>({source_location:d.source_location,result_position:d.result_position,business_name:d.business_name,category:k?.category??d.category,review_stars:k?.rating??d.review_stars,review_count:k?.reviewCount??d.review_count,website_url:k?.website??d.website_url,review_topics:(k?.reviewTopics??[]).map(o=>`${o.label} (${o.count})`).join("; "),about_attributes:(k?.aboutAttributes??[]).map(o=>`${o.section}: ${o.attribute}`).join("; "),reviews_status:k?.reviewsStatus??"",error:g})),u=Je(r);await t.artifacts.writeCsv("Maps results CSV","maps-results.csv",["source_query","source_location","city","state","population","result_position","business_name","review_stars","review_count","category","address","phone","website_url","place_url","cid","cid_decimal","result_status","error"],r),await t.artifacts.writeCsv("Comparison CSV","map-comparison.csv",["source_location","result_position","business_name","category","review_stars","review_count","review_gap_to_top3_average","website_url","place_url","comparison_note"],a),await t.artifacts.writeCsv("Profile insights CSV","profile-insights.csv",["source_location","result_position","business_name","category","review_stars","review_count","website_url","review_topics","about_attributes","reviews_status","error"],p),await t.artifacts.writeJson("Maps comparison evidence","evidence.json",{input:e,directory:i,mapsSearch:s,rows:r,compareRows:a,profileRows:p,markets:u,warnings:n}),await t.artifacts.writeText("Brief","brief.md",[`# Maps Comparison: ${e.query}`,"",`Markets: ${u.map(d=>d.source_location).join(", ")}`,"","## How to Use","- Compare rank position against review count and category patterns.","- Treat review gaps and missing websites as opportunity signals, not guarantees.","- Use profile topics and attributes as evidence for local content and GBP improvements."].join(`
21
21
  `));let w=`${a.length} Maps competitors compared across ${u.length} market(s); ${p.filter(d=>!d.error).length} profiles hydrated.`,v=await t.artifacts.writeHtml("HTML report","report.html",P({title:"Maps Comparison",subtitle:`${e.query}${e.location?` \xB7 ${e.location}`:e.state?` \xB7 ${e.state}`:""}`,summary:w,warnings:n,tables:[{title:"Market Benchmarks",columns:["source_location","result_count","median_review_count","median_rating","top_three_average_review_count","top_categories","websites_present"],rows:u},{title:"Competitor Comparison",columns:["source_location","result_position","business_name","category","review_stars","review_count","review_gap_to_top3_average","comparison_note"],rows:a.slice(0,120)},{title:"Profile Insights",columns:["source_location","business_name","review_topics","about_attributes","error"],rows:p}]})),f=n.length?"partial":"succeeded",b={markets:u.length,competitors:a.length,hydratedProfiles:p.filter(d=>!d.error).length};return await t.artifacts.writeManifest(f,b,n,[]),{title:"Maps Comparison",summary:w,status:f,counts:b,warnings:n,errors:[],reportPath:v}}},Ve={id:"serp-comparison",title:"SERP Comparison",description:"Compare ranking pages, SERP features, PAA evidence, AI Overview citations, and page-level content gaps.",inputSchema:_t,async run(e,t){await t.artifacts.writeManifest("running",{},[],[]);let n=[],r=$(e.domain??e.url??null),i=await t.client.post("/harvest/sync",{query:e.keyword,location:e.location,serpOnly:!0,includeAllSerpFeatures:!0,maxQuestions:1,format:"json"},62e4);await t.artifacts.writeJson("SERP raw JSON","raw/serp.json",i);let s=null;if(e.includePaa)try{s=await t.client.post("/harvest/sync",{query:e.keyword,location:e.location,maxQuestions:e.maxQuestions,includeAllSerpFeatures:!0,format:"json"},735e3),await t.artifacts.writeJson("PAA raw JSON","raw/paa.json",s)}catch(m){n.push(`PAA evidence unavailable: ${m instanceof Error?m.message:String(m)}`)}let a=xt(i,r).slice(0,e.maxResults),l=(i.organicResults??[]).slice(0,e.maxResults),c=e.url?{position:0,title:"Target page",url:e.url,domain:A(e.url)}:l.find(m=>r&&($(m.domain??"")??A(m.url))===r),p=l.filter(m=>m.url&&m.url!==c?.url).filter(m=>!r||($(m.domain??"")??A(m.url))!==r).slice(0,e.extractTop),u=c?await de(t,[c],n,"Target"):[],w=e.extractTop>0?await de(t,p,n,"Competitor"):[],v=u[0]?.page??null,f=[...u.map(({source:m,page:x})=>te(x,{url:m.url??"",domain:$(m.domain??"")??A(m.url),position:m.position,title:m.title})),...w.map(({source:m,page:x})=>te(x,{url:m.url??"",domain:$(m.domain??"")??A(m.url),position:m.position,title:m.title}))],b=Ct(v,w),d=ee(s),k=(i.aiOverview?.citations??[]).map((m,x)=>({citation_position:x+1,citation_text:m.text??"",url:m.href??"",domain:A(m.href??""),is_target:r?A(m.href??"")===r:!1}));await t.artifacts.writeCsv("Organic results CSV","organic-results.csv",["position","title","url","domain","snippet","is_target"],a),await t.artifacts.writeCsv("Page comparison CSV","page-comparison.csv",["position","domain","url","serp_title","page_title","h1","meta_description","word_count","heading_count","schema_types"],f),await t.artifacts.writeCsv("Content gaps CSV","content-gaps.csv",["source_position","source_domain","source_url","heading_level","competitor_heading","target_coverage","terms"],b),await t.artifacts.writeCsv("PAA questions CSV","paa-questions.csv",["position","intent","question","answer_excerpt","source_title","source_domain","source_url"],d),await t.artifacts.writeCsv("AI Overview citations CSV","ai-overview-citations.csv",["citation_position","citation_text","url","domain","is_target"],k),await t.artifacts.writeJson("SERP comparison evidence","evidence.json",{input:e,serp:i,paa:s,organic:a,pageRows:f,gaps:b,questions:d,aiRows:k,warnings:n}),await t.artifacts.writeText("Writer brief","brief.md",[`# SERP Comparison Brief: ${e.keyword}`,"",`Target: ${r??e.url??"not specified"}`,`Location: ${e.location??"not specified"}`,"","## Recommended Actions","- Use `content-gaps.csv` to decide which missing sections deserve coverage.","- Use `paa-questions.csv` for FAQ and answer-block candidates.","- Use `ai-overview-citations.csv` to see whether the target is cited in AI Overview evidence.","- Treat extracted page headings as evidence, not a complete semantic analysis."].join(`
22
22
  `));let g=`${a.length} organic results, ${f.length} extracted pages, ${b.length} heading gaps, ${d.length} PAA questions.`,o=await t.artifacts.writeHtml("HTML report","report.html",P({title:"SERP Comparison",subtitle:`${e.keyword}${e.location?` \xB7 ${e.location}`:""}`,summary:g,warnings:n,tables:[{title:"Organic Results",columns:["position","title","domain","is_target"],rows:a},{title:"Page Comparison",columns:["position","domain","h1","word_count","heading_count","schema_types"],rows:f},{title:"Content Gaps",columns:["source_position","source_domain","competitor_heading","target_coverage","terms"],rows:b.slice(0,80)},{title:"PAA Questions",columns:["position","intent","question","source_domain"],rows:d.slice(0,80)}]})),h=n.length?"partial":"succeeded",R={organic:a.length,pages:f.length,gaps:b.length,questions:d.length,aiCitations:k.length};return await t.artifacts.writeManifest(h,R,n,[]),{title:"SERP Comparison",summary:g,status:h,counts:R,warnings:n,errors:[],reportPath:o}}},Fe={id:"paa-expansion-brief",title:"PAA Expansion Brief",description:"Expand People Also Ask questions into an evidence-backed writer brief, section map, and source table.",inputSchema:bt,async run(e,t){await t.artifacts.writeManifest("running",{},[],[]);let n=[],r=await t.client.post("/harvest/sync",{query:e.keyword,location:e.location,maxQuestions:e.maxQuestions,depth:e.depth,format:"json"},735e3);await t.artifacts.writeJson("PAA raw JSON","raw/paa.json",r);let i=ee(r),s=He(i),a=new Map;for(let w of i){let v=a.get(String(w.intent))??[];v.push(w),a.set(String(w.intent),v)}let l=[...a.entries()].map(([w,v])=>({recommended_section:w,question_count:v.length,sample_questions:v.slice(0,5).map(f=>f.question).join(" | "),source_domains:[...new Set(v.map(f=>f.source_domain).filter(Boolean))].slice(0,5).join("; "),terms:me(v.map(f=>`${f.question} ${f.answer_excerpt}`).join(" "),10)})).sort((w,v)=>Number(v.question_count)-Number(w.question_count));await t.artifacts.writeCsv("PAA questions CSV","paa-questions.csv",["position","intent","question","answer_excerpt","source_title","source_domain","source_url"],i),await t.artifacts.writeCsv("Source domains CSV","source-domains.csv",["domain","question_mentions","source_url_count","top_intents"],s),await t.artifacts.writeCsv("Section map CSV","section-map.csv",["recommended_section","question_count","sample_questions","source_domains","terms"],l),await t.artifacts.writeJson("PAA brief evidence","evidence.json",{input:e,paa:r,questions:i,sourceRows:s,sectionRows:l}),await t.artifacts.writeText("Writer brief","writer-brief.md",[`# PAA Expansion Brief: ${e.keyword}`,"",`Location: ${e.location??"not specified"}`,"","## Suggested Page Structure",...l.map(w=>`- ${w.recommended_section}: answer ${w.question_count} related question(s). Sample: ${w.sample_questions}`),"","## Writing Rules","- Answer the highest-frequency question in the first 60 words of each section.","- Use exact customer question language from `paa-questions.csv` for H2/H3 candidates.","- Use `source-domains.csv` to identify which source types Google is already rewarding.","- Do not invent citations; cite only rows that have a source URL."].join(`
23
23
  `));let c=`${i.length} PAA questions grouped into ${l.length} writing sections.`,p=await t.artifacts.writeHtml("HTML report","report.html",P({title:"PAA Expansion Brief",subtitle:`${e.keyword}${e.location?` \xB7 ${e.location}`:""}`,summary:c,warnings:n,tables:[{title:"Section Map",columns:["recommended_section","question_count","sample_questions","source_domains","terms"],rows:l},{title:"Questions",columns:["position","intent","question","source_domain"],rows:i.slice(0,120)},{title:"Source Domains",columns:["domain","question_mentions","source_url_count","top_intents"],rows:s}]})),u={questions:i.length,sections:l.length,sourceDomains:s.length};return await t.artifacts.writeManifest("succeeded",u,n,[]),{title:"PAA Expansion Brief",summary:c,status:"succeeded",counts:u,warnings:n,errors:[],reportPath:p}}},Ge={id:"ai-overview-language",title:"AI Overview Language Brief",description:"Turn AI Overview, citation, PAA, and ranking-page evidence into answer-block and citation-hook guidance.",inputSchema:kt,async run(e,t){await t.artifacts.writeManifest("running",{},[],[]);let n=[],r=$(e.domain??e.url??null),i=await t.client.post("/harvest/sync",{query:e.keyword,location:e.location,serpOnly:!0,includeAiOverview:!0,maxQuestions:1,format:"json"},62e4);await t.artifacts.writeJson("SERP raw JSON","raw/serp.json",i);let s=null;try{s=await t.client.post("/harvest/sync",{query:e.keyword,location:e.location,maxQuestions:e.maxQuestions,includeAiOverview:!0,format:"json"},735e3),await t.artifacts.writeJson("PAA raw JSON","raw/paa.json",s)}catch(o){n.push(`PAA evidence unavailable: ${o instanceof Error?o.message:String(o)}`)}let a=(i.aiOverview?.citations??[]).map((o,h)=>{let R=A(o.href??"");return{citation_position:h+1,citation_text:o.text??"",url:o.href??"",domain:R,is_target:r?R===r:!1}}),c=Be(i.aiOverview?.text).map((o,h)=>({position:h+1,claim_type:Ne(o),sentence:o,reusable_pattern:o.length>140?`${o.slice(0,140)}...`:o})),p=ee(s),u=(i.aiOverview?.citations??[]).filter(o=>o.href).map((o,h)=>({position:h+1,title:o.text,url:o.href,domain:A(o.href)})).slice(0,e.extractTop),v=(e.extractTop>0?await de(t,u,n,"Citation"):[]).map(({source:o,page:h})=>te(h,{url:o.url??"",domain:$(o.domain??"")??A(o.url),position:o.position,title:o.title})),f=[{block:"direct_answer",guidance:"Open with a 40-70 word answer that directly resolves the query before adding context.",evidence_basis:p[0]?.question??e.keyword},{block:"criteria_or_steps",guidance:"List the criteria, steps, or decision factors Google is already compressing into AI Overview language.",evidence_basis:c.filter(o=>["criteria","process"].includes(String(o.claim_type))).map(o=>o.sentence).slice(0,3).join(" | ")},{block:"citation_hook",guidance:"Add source-worthy details competitors can cite: definitions, numbers, examples, process details, and named entity relationships.",evidence_basis:a.map(o=>`${o.domain}: ${o.citation_text}`).slice(0,5).join(" | ")},{block:"faq_followups",guidance:"Use PAA phrasing for follow-up sections so the page answers adjacent questions in Google language.",evidence_basis:p.slice(0,5).map(o=>o.question).join(" | ")}];await t.artifacts.writeCsv("AI Overview citations CSV","ai-overview-citations.csv",["citation_position","citation_text","url","domain","is_target"],a),await t.artifacts.writeCsv("AI Overview claim patterns CSV","claim-patterns.csv",["position","claim_type","sentence","reusable_pattern"],c),await t.artifacts.writeCsv("Language guidance CSV","language-guidance.csv",["block","guidance","evidence_basis"],f),await t.artifacts.writeCsv("PAA questions CSV","paa-questions.csv",["position","intent","question","answer_excerpt","source_title","source_domain","source_url"],p),await t.artifacts.writeCsv("Extracted citation pages CSV","citation-pages.csv",["position","domain","url","serp_title","page_title","h1","meta_description","word_count","heading_count","schema_types"],v),await t.artifacts.writeJson("AI Overview language evidence","evidence.json",{input:e,serp:i,paa:s,citations:a,claimRows:c,languageRows:f,extractedRows:v,warnings:n}),await t.artifacts.writeText("Answer block template","answer-block-template.md",[`# AI Overview Language Brief: ${e.keyword}`,"",`AI Overview detected: ${i.aiOverview?.detected?"yes":"no"}`,`Target cited: ${r?a.some(o=>o.is_target)?"yes":"no":"target not specified"}`,"","## Direct Answer Block","Write one compact answer block that starts with the answer, not background. Keep it clear enough that Google could lift it as a standalone summary.","","## Suggested Follow-Up Blocks",...f.map(o=>`- ${o.block}: ${o.guidance}`),"","## Evidence to Mirror",...c.slice(0,8).map(o=>`- ${o.claim_type}: ${o.sentence}`),"","## Citation Hooks",...a.slice(0,8).map(o=>`- ${o.domain}: ${o.citation_text}`)].join(`
@@ -1,4 +1,4 @@
1
- import{b as O}from"./chunk-KJQXUZ4Y.js";import{t as N}from"./chunk-YQ5U5C2X.js";import{createHash as M,randomUUID as z}from"crypto";var D="us_zip_groups",K="us_census_places",P=25e3,k=["AL","AK","AZ","AR","CA","CO","CT","DE","DC","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"],$={AL:"01",AK:"02",AZ:"04",AR:"05",CA:"06",CO:"08",CT:"09",DE:"10",DC:"11",FL:"12",GA:"13",HI:"15",ID:"16",IL:"17",IN:"18",IA:"19",KS:"20",KY:"21",LA:"22",ME:"23",MD:"24",MA:"25",MI:"26",MN:"27",MS:"28",MO:"29",MT:"30",NE:"31",NV:"32",NH:"33",NJ:"34",NM:"35",NY:"36",NC:"37",ND:"38",OH:"39",OK:"40",OR:"41",PA:"42",RI:"44",SC:"45",SD:"46",TN:"47",TX:"48",UT:"49",VT:"50",VA:"51",WA:"53",WV:"54",WI:"55",WY:"56"},x=new Set(k),A=200,H=2e3,v=null,w=null;function b(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}function Y(t){if(t==null)return[];try{let o=JSON.parse(String(t));return Array.isArray(o)?o.map(String):[]}catch{return[]}}function C(t){return{id:String(t.id),kind:String(t.dataset_kind),sourceUrl:t.source_url==null?null:String(t.source_url),sha256:String(t.sha256),rowCount:Number(t.row_count??0),groupCount:Number(t.group_count??0),stateCount:Number(t.state_count??0),sourceRowCount:Number(t.source_row_count??t.row_count??0),rejectedRowCount:Number(t.rejected_row_count??0),zipCount:Number(t.zip_count??0),coveredStates:Y(t.covered_states_json),coverageComplete:Number(t.coverage_complete??0)===1,status:String(t.status),createdAt:String(t.created_at),completedAt:t.completed_at==null?null:String(t.completed_at),error:t.error==null?null:String(t.error)}}function F(t){return`${K}:${t}`}function X(t){let o=t?.trim();if(!o)return null;if(o.length>H)throw new Error(`sourceUrl must be ${H} characters or fewer`);let a;try{a=new URL(o)}catch{throw new Error("sourceUrl must be a valid URL")}return a.username="",a.password="",a.search="",a.hash="",a.toString()}function q(t){let o=t.trim();return/^\d{1,5}$/.test(o)?o.padStart(5,"0"):null}function f(t){let o=t.trim().toUpperCase();return x.has(o)?o:null}function y(t,o){for(let a of o){let r=t[a];if(r!==void 0)return r}return""}function g(t){if(t===void 0||t.trim()==="")return null;let o=Number(t);return Number.isFinite(o)&&o>=0?Math.trunc(o):null}function V(t){return/^Nashville-Davidson metropolitan government/i.test(t)?"Nashville":t.replace(/\s+(city|town|village|municipality|borough)$/i,"").trim()}function B(t,o){let a=O(t.replace(/^\uFEFF/,""));if(a.length===0)throw new Error("Census place CSV contains no data rows.");let r=new Set(Object.keys(a[0]??{}).map(e=>e.trim())),u=["SUMLEV","STATE","NAME","POPESTIMATE2020","POPESTIMATE2021","POPESTIMATE2022","POPESTIMATE2023","POPESTIMATE2024","POPESTIMATE2025"].filter(e=>!r.has(e));if(u.length>0)throw new Error(`Census place CSV is missing required columns: ${u.join(", ")}.`);let d=a.filter(e=>e.SUMLEV?.trim()==="162");if(o){let e=o.padStart(2,"0"),s=d.filter(l=>l.STATE?.trim().padStart(2,"0")!==e);if(s.length>0){let l=[...new Set(s.map(c=>c.STATE?.trim()||"(blank)"))].slice(0,5);throw new Error(`Census place CSV STATE does not match requested FIPS ${e}; received ${l.join(", ")}.`)}}let E=d.map(e=>{let s=e.NAME?.trim()??"";if(!s)return null;let l=V(s),c=b(l);if(!c)return null;let T={2020:g(e.POPESTIMATE2020),2021:g(e.POPESTIMATE2021),2022:g(e.POPESTIMATE2022),2023:g(e.POPESTIMATE2023),2024:g(e.POPESTIMATE2024),2025:g(e.POPESTIMATE2025)};return Object.values(T).every(m=>m===null)?null:{city:l,cityKey:c,censusName:s,estimatesBase2020:g(e.ESTIMATESBASE2020),populations:T}}).filter(e=>e!==null),p=new Map,i=e=>e.populations[2025]??e.populations[2024]??e.populations[2023]??e.populations[2022]??e.populations[2021]??e.populations[2020]??e.estimatesBase2020??-1;for(let e of E){let s=p.get(e.cityKey);(!s||i(e)>i(s)||i(e)===i(s)&&e.censusName.localeCompare(s.censusName)<0)&&p.set(e.cityKey,e)}let _=[...p.values()].sort((e,s)=>e.city.localeCompare(s.city));if(_.length===0)throw new Error("Census place CSV did not contain any valid place population rows.");return{sourceRowCount:a.length,places:_}}function W(t){let o=O(t.replace(/^\uFEFF/,""));if(o.length===0)throw new Error("Location ZIP CSV contains no data rows.");let a=o[0]??{},r=new Set(Object.keys(a).map(s=>s.trim().toLowerCase())),n=["state_abbr","state","state_id"].some(s=>r.has(s)),u=["city","primary_city"].some(s=>r.has(s)),d=["zipcode","zip","zip_code"].some(s=>r.has(s));if(!n||!u||!d)throw new Error("Location ZIP CSV must include state_abbr/state, city, and zipcode/zip columns.");let E=new Map,p=0,i=0,_=new Set,e=new Set;for(let s of o){let l=Object.fromEntries(Object.entries(s).map(([G,j])=>[G.trim().toLowerCase(),j])),c=f(y(l,["state_abbr","state","state_id"])),T=y(l,["city","primary_city"]).trim(),m=q(y(l,["zipcode","zip","zip_code"])),S=y(l,["county","county_name"]).trim();if(!c||!x.has(c)||!T||!m){i+=1;continue}let I=b(T);if(!I){i+=1;continue}let U=`${c}\0${I}`,L=E.get(U);L||(L={city:T,cityKey:I,state:c,zips:new Set,counties:new Set},E.set(U,L)),L.zips.add(m),S&&L.counties.add(S),_.add(c),e.add(m),p+=1}if(E.size===0)throw new Error("Location ZIP CSV did not contain any valid US city/ZIP rows.");return{sourceRowCount:o.length,rowCount:p,rejectedRowCount:i,zipCount:e.size,stateCount:_.size,coveredStates:[..._].sort(),groups:[...E.values()].map(s=>({city:s.city,cityKey:s.cityKey,state:s.state,zips:[...s.zips].sort(),counties:[...s.counties].sort()})).sort((s,l)=>s.state.localeCompare(l.state)||s.city.localeCompare(l.city))}}function J(t){let o=new Set(t.coveredStates),a=k.filter(n=>!o.has(n)),r=[];if(a.length>0&&r.push(`missing required states: ${a.join(", ")}`),t.zipCount<P&&r.push(`only ${t.zipCount} unique ZIPs; at least ${P} are required`),r.length>0)throw new Error(`Location ZIP snapshot is not nationwide and was not activated (${r.join("; ")}; ${t.rejectedRowCount} rejected rows).`)}async function R(){let t=N();v!==t&&(v=t,w=null),w||(w=(async()=>{await t.execute(`
1
+ import{b as O}from"./chunk-KJQXUZ4Y.js";import{t as N}from"./chunk-7BEWBRMT.js";import{createHash as M,randomUUID as z}from"crypto";var D="us_zip_groups",K="us_census_places",P=25e3,k=["AL","AK","AZ","AR","CA","CO","CT","DE","DC","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"],$={AL:"01",AK:"02",AZ:"04",AR:"05",CA:"06",CO:"08",CT:"09",DE:"10",DC:"11",FL:"12",GA:"13",HI:"15",ID:"16",IL:"17",IN:"18",IA:"19",KS:"20",KY:"21",LA:"22",ME:"23",MD:"24",MA:"25",MI:"26",MN:"27",MS:"28",MO:"29",MT:"30",NE:"31",NV:"32",NH:"33",NJ:"34",NM:"35",NY:"36",NC:"37",ND:"38",OH:"39",OK:"40",OR:"41",PA:"42",RI:"44",SC:"45",SD:"46",TN:"47",TX:"48",UT:"49",VT:"50",VA:"51",WA:"53",WV:"54",WI:"55",WY:"56"},x=new Set(k),A=200,H=2e3,v=null,w=null;function b(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}function Y(t){if(t==null)return[];try{let o=JSON.parse(String(t));return Array.isArray(o)?o.map(String):[]}catch{return[]}}function C(t){return{id:String(t.id),kind:String(t.dataset_kind),sourceUrl:t.source_url==null?null:String(t.source_url),sha256:String(t.sha256),rowCount:Number(t.row_count??0),groupCount:Number(t.group_count??0),stateCount:Number(t.state_count??0),sourceRowCount:Number(t.source_row_count??t.row_count??0),rejectedRowCount:Number(t.rejected_row_count??0),zipCount:Number(t.zip_count??0),coveredStates:Y(t.covered_states_json),coverageComplete:Number(t.coverage_complete??0)===1,status:String(t.status),createdAt:String(t.created_at),completedAt:t.completed_at==null?null:String(t.completed_at),error:t.error==null?null:String(t.error)}}function F(t){return`${K}:${t}`}function X(t){let o=t?.trim();if(!o)return null;if(o.length>H)throw new Error(`sourceUrl must be ${H} characters or fewer`);let a;try{a=new URL(o)}catch{throw new Error("sourceUrl must be a valid URL")}return a.username="",a.password="",a.search="",a.hash="",a.toString()}function q(t){let o=t.trim();return/^\d{1,5}$/.test(o)?o.padStart(5,"0"):null}function f(t){let o=t.trim().toUpperCase();return x.has(o)?o:null}function y(t,o){for(let a of o){let r=t[a];if(r!==void 0)return r}return""}function g(t){if(t===void 0||t.trim()==="")return null;let o=Number(t);return Number.isFinite(o)&&o>=0?Math.trunc(o):null}function V(t){return/^Nashville-Davidson metropolitan government/i.test(t)?"Nashville":t.replace(/\s+(city|town|village|municipality|borough)$/i,"").trim()}function B(t,o){let a=O(t.replace(/^\uFEFF/,""));if(a.length===0)throw new Error("Census place CSV contains no data rows.");let r=new Set(Object.keys(a[0]??{}).map(e=>e.trim())),u=["SUMLEV","STATE","NAME","POPESTIMATE2020","POPESTIMATE2021","POPESTIMATE2022","POPESTIMATE2023","POPESTIMATE2024","POPESTIMATE2025"].filter(e=>!r.has(e));if(u.length>0)throw new Error(`Census place CSV is missing required columns: ${u.join(", ")}.`);let d=a.filter(e=>e.SUMLEV?.trim()==="162");if(o){let e=o.padStart(2,"0"),s=d.filter(l=>l.STATE?.trim().padStart(2,"0")!==e);if(s.length>0){let l=[...new Set(s.map(c=>c.STATE?.trim()||"(blank)"))].slice(0,5);throw new Error(`Census place CSV STATE does not match requested FIPS ${e}; received ${l.join(", ")}.`)}}let E=d.map(e=>{let s=e.NAME?.trim()??"";if(!s)return null;let l=V(s),c=b(l);if(!c)return null;let T={2020:g(e.POPESTIMATE2020),2021:g(e.POPESTIMATE2021),2022:g(e.POPESTIMATE2022),2023:g(e.POPESTIMATE2023),2024:g(e.POPESTIMATE2024),2025:g(e.POPESTIMATE2025)};return Object.values(T).every(m=>m===null)?null:{city:l,cityKey:c,censusName:s,estimatesBase2020:g(e.ESTIMATESBASE2020),populations:T}}).filter(e=>e!==null),p=new Map,i=e=>e.populations[2025]??e.populations[2024]??e.populations[2023]??e.populations[2022]??e.populations[2021]??e.populations[2020]??e.estimatesBase2020??-1;for(let e of E){let s=p.get(e.cityKey);(!s||i(e)>i(s)||i(e)===i(s)&&e.censusName.localeCompare(s.censusName)<0)&&p.set(e.cityKey,e)}let _=[...p.values()].sort((e,s)=>e.city.localeCompare(s.city));if(_.length===0)throw new Error("Census place CSV did not contain any valid place population rows.");return{sourceRowCount:a.length,places:_}}function W(t){let o=O(t.replace(/^\uFEFF/,""));if(o.length===0)throw new Error("Location ZIP CSV contains no data rows.");let a=o[0]??{},r=new Set(Object.keys(a).map(s=>s.trim().toLowerCase())),n=["state_abbr","state","state_id"].some(s=>r.has(s)),u=["city","primary_city"].some(s=>r.has(s)),d=["zipcode","zip","zip_code"].some(s=>r.has(s));if(!n||!u||!d)throw new Error("Location ZIP CSV must include state_abbr/state, city, and zipcode/zip columns.");let E=new Map,p=0,i=0,_=new Set,e=new Set;for(let s of o){let l=Object.fromEntries(Object.entries(s).map(([G,j])=>[G.trim().toLowerCase(),j])),c=f(y(l,["state_abbr","state","state_id"])),T=y(l,["city","primary_city"]).trim(),m=q(y(l,["zipcode","zip","zip_code"])),S=y(l,["county","county_name"]).trim();if(!c||!x.has(c)||!T||!m){i+=1;continue}let I=b(T);if(!I){i+=1;continue}let U=`${c}\0${I}`,L=E.get(U);L||(L={city:T,cityKey:I,state:c,zips:new Set,counties:new Set},E.set(U,L)),L.zips.add(m),S&&L.counties.add(S),_.add(c),e.add(m),p+=1}if(E.size===0)throw new Error("Location ZIP CSV did not contain any valid US city/ZIP rows.");return{sourceRowCount:o.length,rowCount:p,rejectedRowCount:i,zipCount:e.size,stateCount:_.size,coveredStates:[..._].sort(),groups:[...E.values()].map(s=>({city:s.city,cityKey:s.cityKey,state:s.state,zips:[...s.zips].sort(),counties:[...s.counties].sort()})).sort((s,l)=>s.state.localeCompare(l.state)||s.city.localeCompare(l.city))}}function J(t){let o=new Set(t.coveredStates),a=k.filter(n=>!o.has(n)),r=[];if(a.length>0&&r.push(`missing required states: ${a.join(", ")}`),t.zipCount<P&&r.push(`only ${t.zipCount} unique ZIPs; at least ${P} are required`),r.length>0)throw new Error(`Location ZIP snapshot is not nationwide and was not activated (${r.join("; ")}; ${t.rejectedRowCount} rejected rows).`)}async function R(){let t=N();v!==t&&(v=t,w=null),w||(w=(async()=>{await t.execute(`
2
2
  CREATE TABLE IF NOT EXISTS location_data_imports (
3
3
  id TEXT PRIMARY KEY,
4
4
  dataset_kind TEXT NOT NULL,
@@ -1,4 +1,4 @@
1
- import{a as N}from"./chunk-YQZGZBB4.js";import{b as L,c as P}from"./chunk-HE45FFBU.js";import{h as $,t as x}from"./chunk-YQ5U5C2X.js";import{createWriteStream as Z,mkdirSync as ee,rmSync as te}from"fs";import{homedir as re}from"os";import{join as I,extname as k,basename as B}from"path";import{pipeline as ne}from"stream/promises";import{Readable as oe,Transform as ie}from"stream";var se=["doubleclick.net","googlesyndication.com","googletagmanager.com","google-analytics.com","googletagservices.com","adservice.google","googletag.","pagead2.googlesyndication","facebook.net/tr","connect.facebook.net","fbcdn.net/rsrc","analytics.twitter.com","static.ads-twitter.com","ads.twitter.com","t.co/i/adsct","pixel.advertising.com","hotjar.com","clarity.ms","quantserve.com","scorecardresearch.com","newrelic.com","nr-data.net","segment.io","segment.com","amplitude.com","mixpanel.com","heap.io","fullstory.com","moatads.com","criteo.com","adsrvr.org","rubiconproject.com","pubmatic.com","openx.net","appnexus.com","amazon-adsystem.com","media.net","yieldmo.com","triplelift.com","sharethrough.com","prebid.","smaato.net","indexworm.com","casalemedia.com","outbrain.com","taboola.com","revcontent.com","mgid.com","tawk.to","intercom.io","drift.com","hs-scripts.com","zopim.com","livechatinc.com","userlike.com","onetrust.com","cookielaw.org","cookieinformation.com","trustarc.com","/ads/","/ad/","/banner/","/banners/","/pixel/","/beacon/","/tracking/","/tracker/","/remarketing/","/conversion/","1x1.gif","spacer.gif","blank.gif","transparent.gif"],ae=new Set([".jpg",".jpeg",".png",".webp",".gif",".avif",".svg",".tiff"]),de=new Set([".mp4",".webm",".mov",".avi",".m4v",".ogv",".mkv"]),ce=new Set([".mp3",".wav",".ogg",".aac",".m4a",".flac",".opus"]);function le(e){let t=e.toLowerCase();return se.some(r=>t.includes(r))}function ue(e){return e.startsWith("data:")}function F(e){try{let t=k(new URL(e).pathname).toLowerCase();if(ae.has(t))return"image";if(de.has(t))return"video";if(ce.has(t))return"audio"}catch{}return null}function q(e){let t=e.toLowerCase();return t.startsWith("image/")?"image":t.startsWith("video/")?"video":t.startsWith("audio/")?"audio":null}function me(e,t){if(!e||ue(e))return null;try{return new URL(e,t).href}catch{return null}}function U(e,t){try{let r=new URL(e);return B(r.pathname).replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,80)||`asset-${t}`}catch{return`asset-${t}`}}function O(e,t){let r=e?.replace(/&(?:amp|#0?38|#x26);/gi,"&").replace(/\s+/g," ").trim();return r?r.slice(0,t):null}function ge(e){let t=e.match(/[-_/](\d{2,5})x(\d{2,5})(?=[._/?#-]|$)/i);return t?{width:Number(t[1]),height:Number(t[2])}:null}function pe(e){try{let t=new URL(e);t.hash="",t.pathname=t.pathname.replace(/-(?:\d{2,5}x\d{2,5}|scaled|e\d{6,})(?=\.[a-z0-9]{2,6}$)/i,"");for(let r of["w","width","h","height","resize"])t.searchParams.delete(r);return t.searchParams.sort(),t.href}catch{return e}}function S(e){let t=(e.width??0)*(e.height??0),r=e.discoveryMethods.some(g=>g.includes("lightbox"))?1e12:0,n=/-(?:\d{2,5}x\d{2,5}|scaled|e\d{6,})(?=\.[a-z0-9]{2,6}(?:[?#]|$))/i.test(e.url)?0:1e11;return r+n+t}function A(e,t){let r=e.get(t.url);if(!r){e.set(t.url,t);return}r.discoveryMethods=[...new Set([...r.discoveryMethods,...t.discoveryMethods])],r.altTexts=[...new Set([...r.altTexts,...t.altTexts])],r.contexts=[...new Set([...r.contexts,...t.contexts])],!r.type&&t.type&&(r.type=t.type),(t.width??0)*(t.height??0)>(r.width??0)*(r.height??0)&&(r.width=t.width,r.height=t.height)}function he(e,t){let r=new Map,n=(d,i,o=null,h,l,u)=>{let s=d?me(d.trim().replace(/&amp;/g,"&"),t):null;if(!s||le(s))return;let m=u??ge(s);A(r,{url:s,type:o??F(s),discoveryMethods:[i],altTexts:h?[h]:[],contexts:l?[l]:[],width:m?.width??null,height:m?.height??null})},g=(d,i,o,h)=>{for(let l of(d??"").split(",")){let[u,s]=l.trim().split(/\s+/);if(!u)continue;let m=s?.match(/^(\d+)w$/)?.[1];n(u,i,o,h,null,m?{width:Number(m),height:0}:null)}},a=(d,i="")=>{let o=d.$;for(let l of d.images){let u=l.attributes,s=O(l.alt,500),m=l.width&&l.height?{width:l.width,height:l.height}:null;for(let p of["src","data-src","data-lazy-src","data-original","data-bg","data-background","data-bg-url","data-lazy-bg","data-echo"]){let y=u[p];n(y,`static-${p}${i}`,"image",s,null,m)}g(u.srcset,`static-srcset${i}`,"image",s),g(u["data-srcset"],`static-data-srcset${i}`,"image",s)}o("source").each((l,u)=>{let s=o(u),m=s.attr("type")??"",p=m.startsWith("video/")?"video":m.startsWith("audio/")?"audio":"image";n(s.attr("src"),`static-source${i}`,p),g(s.attr("srcset"),`static-source-srcset${i}`,p)}),o("video,audio").each((l,u)=>{let s=o(u),m=u.tagName.toLowerCase();n(s.attr("src"),`static-${m}${i}`,m),m==="video"&&n(s.attr("poster"),`static-video-poster${i}`,"image")}),o("meta").each((l,u)=>{let s=o(u),m=(s.attr("property")??s.attr("name")??"").toLowerCase();(m==="og:image"||m==="og:image:url"||m==="twitter:image"||m==="twitter:image:src")&&n(s.attr("content"),`static-${m}${i}`,"image")}),o("link[href]").each((l,u)=>{let s=o(u);(s.attr("rel")??"").toLowerCase().split(/\s+/).some(p=>p==="icon"||p==="apple-touch-icon")&&n(s.attr("href"),`static-icon${i}`,"image")}),o("svg image").each((l,u)=>{let s=o(u);n(s.attr("href")??s.attr("xlink:href"),`static-svg-image${i}`,"image")}),o("a[href]").has("img").each((l,u)=>{let s=o(u),m=s.attr("href");if(m&&(/lightbox|gallery|fancybox|glightbox|swipebox|elementor-open-lightbox/i.test(`${s.attr("class")??""} ${s.attr("data-elementor-open-lightbox")??""}`)||/\.(?:avif|gif|jpe?g|png|svg|webp)(?:[?#]|$)/i.test(m))){let p=O(s.find("img").first().attr("alt"),500);n(m,`static-lightbox-target${i}`,"image",p)}});let h=o("style").toArray().map(l=>o(l).text());o("[style]").each((l,u)=>{h.push(o(u).attr("style")??"")});for(let l of h.join(`
1
+ import{a as N}from"./chunk-XG6GCEUE.js";import{b as L,c as P}from"./chunk-HE45FFBU.js";import{h as $,t as x}from"./chunk-7BEWBRMT.js";import{createWriteStream as Z,mkdirSync as ee,rmSync as te}from"fs";import{homedir as re}from"os";import{join as I,extname as k,basename as B}from"path";import{pipeline as ne}from"stream/promises";import{Readable as oe,Transform as ie}from"stream";var se=["doubleclick.net","googlesyndication.com","googletagmanager.com","google-analytics.com","googletagservices.com","adservice.google","googletag.","pagead2.googlesyndication","facebook.net/tr","connect.facebook.net","fbcdn.net/rsrc","analytics.twitter.com","static.ads-twitter.com","ads.twitter.com","t.co/i/adsct","pixel.advertising.com","hotjar.com","clarity.ms","quantserve.com","scorecardresearch.com","newrelic.com","nr-data.net","segment.io","segment.com","amplitude.com","mixpanel.com","heap.io","fullstory.com","moatads.com","criteo.com","adsrvr.org","rubiconproject.com","pubmatic.com","openx.net","appnexus.com","amazon-adsystem.com","media.net","yieldmo.com","triplelift.com","sharethrough.com","prebid.","smaato.net","indexworm.com","casalemedia.com","outbrain.com","taboola.com","revcontent.com","mgid.com","tawk.to","intercom.io","drift.com","hs-scripts.com","zopim.com","livechatinc.com","userlike.com","onetrust.com","cookielaw.org","cookieinformation.com","trustarc.com","/ads/","/ad/","/banner/","/banners/","/pixel/","/beacon/","/tracking/","/tracker/","/remarketing/","/conversion/","1x1.gif","spacer.gif","blank.gif","transparent.gif"],ae=new Set([".jpg",".jpeg",".png",".webp",".gif",".avif",".svg",".tiff"]),de=new Set([".mp4",".webm",".mov",".avi",".m4v",".ogv",".mkv"]),ce=new Set([".mp3",".wav",".ogg",".aac",".m4a",".flac",".opus"]);function le(e){let t=e.toLowerCase();return se.some(r=>t.includes(r))}function ue(e){return e.startsWith("data:")}function F(e){try{let t=k(new URL(e).pathname).toLowerCase();if(ae.has(t))return"image";if(de.has(t))return"video";if(ce.has(t))return"audio"}catch{}return null}function q(e){let t=e.toLowerCase();return t.startsWith("image/")?"image":t.startsWith("video/")?"video":t.startsWith("audio/")?"audio":null}function me(e,t){if(!e||ue(e))return null;try{return new URL(e,t).href}catch{return null}}function U(e,t){try{let r=new URL(e);return B(r.pathname).replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,80)||`asset-${t}`}catch{return`asset-${t}`}}function O(e,t){let r=e?.replace(/&(?:amp|#0?38|#x26);/gi,"&").replace(/\s+/g," ").trim();return r?r.slice(0,t):null}function ge(e){let t=e.match(/[-_/](\d{2,5})x(\d{2,5})(?=[._/?#-]|$)/i);return t?{width:Number(t[1]),height:Number(t[2])}:null}function pe(e){try{let t=new URL(e);t.hash="",t.pathname=t.pathname.replace(/-(?:\d{2,5}x\d{2,5}|scaled|e\d{6,})(?=\.[a-z0-9]{2,6}$)/i,"");for(let r of["w","width","h","height","resize"])t.searchParams.delete(r);return t.searchParams.sort(),t.href}catch{return e}}function S(e){let t=(e.width??0)*(e.height??0),r=e.discoveryMethods.some(g=>g.includes("lightbox"))?1e12:0,n=/-(?:\d{2,5}x\d{2,5}|scaled|e\d{6,})(?=\.[a-z0-9]{2,6}(?:[?#]|$))/i.test(e.url)?0:1e11;return r+n+t}function A(e,t){let r=e.get(t.url);if(!r){e.set(t.url,t);return}r.discoveryMethods=[...new Set([...r.discoveryMethods,...t.discoveryMethods])],r.altTexts=[...new Set([...r.altTexts,...t.altTexts])],r.contexts=[...new Set([...r.contexts,...t.contexts])],!r.type&&t.type&&(r.type=t.type),(t.width??0)*(t.height??0)>(r.width??0)*(r.height??0)&&(r.width=t.width,r.height=t.height)}function he(e,t){let r=new Map,n=(d,i,o=null,h,l,u)=>{let s=d?me(d.trim().replace(/&amp;/g,"&"),t):null;if(!s||le(s))return;let m=u??ge(s);A(r,{url:s,type:o??F(s),discoveryMethods:[i],altTexts:h?[h]:[],contexts:l?[l]:[],width:m?.width??null,height:m?.height??null})},g=(d,i,o,h)=>{for(let l of(d??"").split(",")){let[u,s]=l.trim().split(/\s+/);if(!u)continue;let m=s?.match(/^(\d+)w$/)?.[1];n(u,i,o,h,null,m?{width:Number(m),height:0}:null)}},a=(d,i="")=>{let o=d.$;for(let l of d.images){let u=l.attributes,s=O(l.alt,500),m=l.width&&l.height?{width:l.width,height:l.height}:null;for(let p of["src","data-src","data-lazy-src","data-original","data-bg","data-background","data-bg-url","data-lazy-bg","data-echo"]){let y=u[p];n(y,`static-${p}${i}`,"image",s,null,m)}g(u.srcset,`static-srcset${i}`,"image",s),g(u["data-srcset"],`static-data-srcset${i}`,"image",s)}o("source").each((l,u)=>{let s=o(u),m=s.attr("type")??"",p=m.startsWith("video/")?"video":m.startsWith("audio/")?"audio":"image";n(s.attr("src"),`static-source${i}`,p),g(s.attr("srcset"),`static-source-srcset${i}`,p)}),o("video,audio").each((l,u)=>{let s=o(u),m=u.tagName.toLowerCase();n(s.attr("src"),`static-${m}${i}`,m),m==="video"&&n(s.attr("poster"),`static-video-poster${i}`,"image")}),o("meta").each((l,u)=>{let s=o(u),m=(s.attr("property")??s.attr("name")??"").toLowerCase();(m==="og:image"||m==="og:image:url"||m==="twitter:image"||m==="twitter:image:src")&&n(s.attr("content"),`static-${m}${i}`,"image")}),o("link[href]").each((l,u)=>{let s=o(u);(s.attr("rel")??"").toLowerCase().split(/\s+/).some(p=>p==="icon"||p==="apple-touch-icon")&&n(s.attr("href"),`static-icon${i}`,"image")}),o("svg image").each((l,u)=>{let s=o(u);n(s.attr("href")??s.attr("xlink:href"),`static-svg-image${i}`,"image")}),o("a[href]").has("img").each((l,u)=>{let s=o(u),m=s.attr("href");if(m&&(/lightbox|gallery|fancybox|glightbox|swipebox|elementor-open-lightbox/i.test(`${s.attr("class")??""} ${s.attr("data-elementor-open-lightbox")??""}`)||/\.(?:avif|gif|jpe?g|png|svg|webp)(?:[?#]|$)/i.test(m))){let p=O(s.find("img").first().attr("alt"),500);n(m,`static-lightbox-target${i}`,"image",p)}});let h=o("style").toArray().map(l=>o(l).text());o("[style]").each((l,u)=>{h.push(o(u).attr("style")??"")});for(let l of h.join(`
2
2
  `).matchAll(/(?:background(?:-image)?\s*:\s*)?url\(\s*(?:["']|&quot;|&#0?34;|&apos;|&#0?39;)?([^"')&]+)(?:["']|&quot;|&#0?34;|&apos;|&#0?39;)?\s*\)/gi))n(l[1],`static-css-url${i}`,"image");for(let l of d.sourceHtml.matchAll(/["'](https?:\/\/[^"'\s<>]+\.(?:avif|gif|jpe?g|png|svg|webp|mp4|webm|mp3|ogg)(?:\?[^"'\s<>]*)?)["']/gi))n(l[1],`static-bare-url${i}`)},c=typeof e=="string"?P(e):e;return a(c),c.$("script").each((d,i)=>{let o=c.$(i).text(),h=o.replace(/\\u003[cC]/g,"<").replace(/\\u003[eE]/g,">").replace(/\\u0026/gi,"&").replace(/\\["']/g,l=>l.slice(1)).replace(/\\\//g,"/");h!==o&&/<(?:img|source|video|audio)\b/i.test(h)&&a(P(h),"-json-unescaped")}),[...r.values()]}function fe(e,t,r=100){let n=new Map;for(let a of e)A(n,a);for(let a of t?.assets??[])A(n,{...a,type:a.type});let g=new Map;for(let a of n.values()){let c=pe(a.url),d=g.get(c)??[];d.push(a),g.set(c,d)}return[...g.values()].map(a=>{let c=[...a].sort((i,o)=>S(o)-S(i)||i.url.localeCompare(o.url)),d={...c[0]};return d.discoveryMethods=[...new Set(a.flatMap(i=>i.discoveryMethods))],d.altTexts=[...new Set(a.flatMap(i=>i.altTexts))],d.contexts=[...new Set(a.flatMap(i=>i.contexts))],{...d,variants:c.slice(1).map(i=>i.url)}}).sort((a,c)=>S(c)-S(a)||a.url.localeCompare(c.url)).slice(0,Math.max(1,r))}async function ye(e,t,r,n={}){let g=Math.max(1,Math.min(n.maxBytes??52428800,104857600)),a=e,c=null;for(let p=0;p<=5;p++){let y=await L(a,{field:"media URL"});if(y.error||!y.parsed)throw new Error(y.error??"Media URL was rejected");if(c=await fetch(y.parsed.href,{signal:AbortSignal.timeout(15e3),redirect:"manual"}),c.status>=300&&c.status<400){let w=c.headers.get("location");if(!w)throw new Error(`HTTP ${c.status} redirect did not include Location`);a=new URL(w,y.parsed.href).href,c=null;continue}break}if(!c)throw new Error("Media download exceeded five redirects");if(!c.ok)throw new Error(`HTTP ${c.status}`);if(!c.body)throw new Error("Empty response body");let d=c.headers.get("content-type")?.split(";")[0].trim()??null;if(n.expectedType&&(!d||q(d)!==n.expectedType))throw new Error(`Expected ${n.expectedType} content but received ${d??"no content-type"}`);let i=Number(c.headers.get("content-length")??0);if(Number.isFinite(i)&&i>g)throw new Error(`Media asset exceeds ${g} byte limit`);let o=I(t,r);if(d&&!k(r)){let y={"image/jpeg":".jpg","image/png":".png","image/webp":".webp","image/gif":".gif","image/svg+xml":".svg","image/avif":".avif","video/mp4":".mp4","video/webm":".webm","audio/mpeg":".mp3","audio/ogg":".ogg","audio/wav":".wav"}[d];y&&(o=o+y)}let h=Z(o);await new Promise((p,y)=>{h.once("open",()=>p()),h.once("error",y)});let l=0,u=new ie({transform(p,y,w){let _=p.length;if(l+_>g){w(new Error(`Media asset exceeds ${g} byte limit`));return}if(n.consumeBytes&&!n.consumeBytes(_)){w(new Error("Media export total byte limit exceeded"));return}l+=_,w(null,p)}});try{await ne(oe.fromWeb(c.body),u,h)}catch(p){throw h.destroy(),te(o,{force:!0}),p}let{statSync:s}=await import("fs"),m=s(o).size;return{savedPath:o,sizeBytes:m,mimeType:d}}async function Le(e,t,r={}){let n=r.types??["image","video","audio"],g=new Set(n),a=he(e,t),c=Math.max(1,Math.min(r.maxAssets??100,250)),d=fe(a,r.rendered,2e3),i=d.slice(0,c),o=new Set([...a.map(f=>f.url),...(r.rendered?.assets??[]).map(f=>f.url)]).size,h=i.flatMap(f=>{let b=f.type??F(f.url);return b&&g.has(b)?[{...f,type:b}]:[]}),l=o-h.length,u=d.length>c,s=r.rendered?.exhausted===!0&&!u,m=u?"asset_limit":r.rendered?.stopReason??"render_unavailable",p=u?[`Media discovery found ${d.length} responsive families; only the requested ${c} records were retained.`]:r.rendered?r.rendered.exhausted?[]:[`Rendered media discovery stopped with ${r.rendered.stopReason}; the inventory may be incomplete.`]:["Rendered media discovery was unavailable; this manifest contains static-source evidence only."],y={pageUrl:t,staticFound:a.length,renderedFound:r.rendered?.assets.length??0,filteredCount:l,totalFound:o,completeness:s?"complete":"partial",exhausted:s,stopReason:m,scrollRounds:r.rendered?.scrollRounds??0,warnings:p,artifact:null};if(r.outputDir===null)return{...y,outputDir:null,assets:h.map((f,b)=>({...f,mimeType:null,filename:U(f.url,b),savedPath:null,sizeBytes:null,sha256:null,downloadStatus:"not_attempted",downloadError:null,inlinePreview:null}))};let w=(()=>{try{return new URL(t).hostname.replace(/^www\./,"")}catch{return"unknown"}})(),_=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),C=r.outputDir??I(re(),"Downloads","mcp-scraper","media",`${_}-${w}`);ee(C,{recursive:!0});let T=[];return await Promise.allSettled(h.map(async(f,b)=>{let R=U(f.url,b);try{let{savedPath:v,sizeBytes:Q,mimeType:D}=await ye(f.url,C,R),G=D?q(D)??f.type:f.type;T.push({...f,type:G,mimeType:D,filename:B(v),savedPath:v,sizeBytes:Q,sha256:null,downloadStatus:"downloaded",downloadError:null,inlinePreview:null})}catch(v){T.push({...f,mimeType:null,filename:R,savedPath:null,sizeBytes:null,sha256:null,downloadStatus:"failed",downloadError:v instanceof Error?v.message:"media_download_failed",inlinePreview:null})}})),T.sort((f,b)=>f.savedPath&&!b.savedPath?-1:!f.savedPath&&b.savedPath?1:f.url.localeCompare(b.url)),{...y,outputDir:C,assets:T}}var be=new Set(["browser_navigation_blocked","browser_navigation_failed","browser_timeout","browser_session_failed","browser_result_missing"]);function we(e){return e instanceof Error?e.code:void 0}function _e(e){return e instanceof Error?e.message:String(e)}function H(e){let t=e?.match(/^browser_http_(\d+)$/);return t?Number(t[1]):null}function ve(e){return e===404?"page_not_found":e===403?"page_forbidden":e===429?"page_rate_limited":e>=500&&e<=599?"page_server_error":"page_http_error"}function xe(e){let t=_e(e),r=we(e);if(N(e,t))return{errorCode:"vendor_unavailable",httpStatus:null,retryable:!0};let n=H(r)??H(t.match(/^(browser_http_\d+)/)?.[1]);return n!=null?{errorCode:ve(n),httpStatus:n,retryable:n===429||n>=500}:r==="browser_challenge_unresolved"||/^browser_challenge_unresolved/.test(t)?{errorCode:"bot_check_unresolved",httpStatus:null,retryable:!0}:r==="browser_response_too_large"||/exceeds \d+ byte limit/i.test(t)?{errorCode:"page_too_large",httpStatus:null,retryable:!1}:/browser (?:has been )?closed|context closed|target page, context or browser has been closed|session closed/i.test(t)?{errorCode:"browser_session_interrupted",httpStatus:null,retryable:!0}:be.has(r??"")||/timeout|navigation_failed|ERR_/i.test(t)?{errorCode:"page_unreachable",httpStatus:null,retryable:!0}:{errorCode:"extraction_failed",httpStatus:null,retryable:!1}}function j(e,t){switch(e){case"page_not_found":return`The page could not be found (HTTP ${t??404}). It may have been moved or deleted.`;case"page_forbidden":return`The site refused the request (HTTP ${t??403}).`;case"page_rate_limited":return"The site is rate-limiting requests right now (HTTP 429). Retrying after a short wait usually works.";case"page_server_error":return`The page's own server returned an error (HTTP ${t}). This is on the target site's side, not something a retry here can fix.`;case"page_http_error":return`The page returned an unexpected HTTP ${t} response.`;case"bot_check_unresolved":return"This site has automated-traffic protection (a bot/CAPTCHA check) that could not be resolved in time. Some sites are simply not extractable this way.";case"page_too_large":return"The page is larger than we can safely process.";case"page_unreachable":return"The page did not respond in time, or the connection could not be completed.";case"browser_session_interrupted":return"The browser session closed before extraction completed. A retry uses a fresh browser session.";case"vendor_unavailable":return"MCP Scraper's internal browser services require MCP Scraper team attention. Servers or IPs are down until this is fixed \u2014 this is not caused by your request. Please retry in a few minutes.";case"extraction_failed":return"The page could not be extracted. Please retry, or contact support if this persists for the same URL."}}function Ie(e,t={}){let r=j(e.errorCode,e.httpStatus);return{...$({errorCode:e.errorCode,retryable:e.retryable,chargeStatus:t.chargeStatus,details:{...t.details??{},...e.httpStatus!=null?{http_status:e.httpStatus}:{}}}),message:r,error:r}}function ke(e){return e.httpStatus===404?404:e.httpStatus===403?403:e.httpStatus===429?429:e.httpStatus!=null&&e.httpStatus>=500&&e.httpStatus<=599?500:e.httpStatus!=null?502:e.errorCode==="vendor_unavailable"?503:502}var Ee="wayback_capture_missing";function Be(e,t){if(e==null)return{failureCode:null,failureReason:null};if(e===Ee)return{failureCode:e,failureReason:t??null};let r=new Error(t??e);r.code=e;let n=xe(r);return{failureCode:n.errorCode,failureReason:j(n.errorCode,n.httpStatus)}}import{neon as Te}from"@neondatabase/serverless";var Se="jina",M=null,z=!1;function W(){return(process.env.JINA_EMBED_MODEL??"jina-embeddings-v5-omni-small").trim()}function Y(){return Number((process.env.JINA_EMBED_DIM??"1024").trim())}function J(){return!!(process.env.JINA_API_KEY?.trim()&&process.env.MEMORY_DATABASE_URL?.trim())}function E(){if(M)return M;let e=process.env.MEMORY_DATABASE_URL?.trim();if(!e)throw new Error("MEMORY_DATABASE_URL is not set; Commons semantic search needs the shared Postgres.");return M=Te(e),M}async function K(){if(z)return;let e=Y();await E().query("CREATE EXTENSION IF NOT EXISTS vector"),await E().query(`
3
3
  CREATE TABLE IF NOT EXISTS commons_index_vectors (
4
4
  document_id TEXT PRIMARY KEY,
@@ -1,4 +1,4 @@
1
- import{t as r}from"./chunk-YQ5U5C2X.js";import{createHash as b,randomUUID as O}from"crypto";var p="mcp-scraper/lead-list-enrichment.requested",A=new Set(["complete","partial","empty","failed","cancelled"]),U=new Set(["complete","failed","cancelled"]),T=10,g=360,S=60,h=null,m=null;function o(e,t,s){let n=e.trim();if(!n||n.length>s)throw new Error(`${t} is required and must be ${s} characters or fewer`);return n}function d(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function u(e){if(e==null)return null;try{return JSON.parse(String(e))}catch{return null}}function R(e){let t=new WeakSet,s=n=>{if(n===null||typeof n=="string"||typeof n=="boolean")return n;if(typeof n=="number"){if(!Number.isFinite(n))throw new Error("canonical fingerprint input must contain finite numbers");return Object.is(n,-0)?0:n}if(Array.isArray(n))return n.map(s);if(typeof n=="object"){if(t.has(n))throw new Error("canonical fingerprint input must not be cyclic");t.add(n);let i={};for(let _ of Object.keys(n).sort()){let c=n[_];c!==void 0&&(i[_]=s(c))}return t.delete(n),i}throw new Error(`canonical fingerprint input contains unsupported ${typeof n}`)};return JSON.stringify(s(e))}function y(e){return b("sha256").update(R(e)).digest("hex")}function I(e){return b("sha256").update(R(e)).digest("hex")}function j(){return{mapsAttempts:0,pageAttempts:0,pageSuccesses:0,serpSearches:0}}function E(e){let t=u(e.input_json);if(!t)throw new Error(`lead list enrichment job ${String(e.id??"")} has invalid durable input`);return{id:String(e.id),userId:Number(e.user_id),idempotencyKey:String(e.idempotency_key),requestFingerprint:String(e.request_fingerprint),input:t,status:String(e.status),totalRows:Number(e.total_rows??0),doneRows:Number(e.done_rows??0),failedRows:Number(e.failed_rows??0),cancelledRows:Number(e.cancelled_rows??0),usage:{mapsAttempts:Number(e.maps_attempts??0),pageAttempts:Number(e.page_attempts??0),pageSuccesses:Number(e.page_successes??0),serpSearches:Number(e.serp_searches??0)},concurrencyLockId:e.concurrency_lock_id==null?null:String(e.concurrency_lock_id),debitKey:String(e.debit_key),holdMc:Number(e.hold_mc??0),billedMc:e.billed_mc==null?null:Number(e.billed_mc),result:u(e.result_json),csvArtifact:u(e.csv_artifact_json),xlsxArtifact:u(e.xlsx_artifact_json),warnings:u(e.warnings_json)??[],cancelRequestedAt:e.cancel_requested_at==null?null:String(e.cancel_requested_at),errorCode:e.error_code==null?null:String(e.error_code),errorMessage:e.error_message==null?null:String(e.error_message),retryable:e.retryable==null?null:Number(e.retryable)===1,createdAt:String(e.created_at??""),startedAt:e.started_at==null?null:String(e.started_at),completedAt:e.completed_at==null?null:String(e.completed_at),updatedAt:String(e.updated_at??"")}}function w(e){return{jobId:String(e.job_id),ordinal:Number(e.ordinal),inputDigest:String(e.input_digest),status:String(e.status),result:u(e.result_json),usage:{mapsAttempts:Number(e.maps_attempts??0),pageAttempts:Number(e.page_attempts??0),pageSuccesses:Number(e.page_successes??0),serpSearches:Number(e.serp_searches??0)},errorCode:e.error_code==null?null:String(e.error_code),errorMessage:e.error_message==null?null:String(e.error_message),retryable:Number(e.retryable??0)===1,durationMs:Number(e.duration_ms??0),startedAt:e.started_at==null?null:String(e.started_at),completedAt:e.completed_at==null?null:String(e.completed_at),updatedAt:String(e.updated_at??"")}}function M(e){return{id:String(e.id),jobId:String(e.job_id),eventName:p,status:String(e.status),attempts:Number(e.attempts??0),claimToken:e.locked_by==null?null:String(e.locked_by),lockedUntil:e.locked_until==null?null:String(e.locked_until),nextAttemptAt:e.next_attempt_at==null?null:String(e.next_attempt_at),lastError:e.last_error==null?null:String(e.last_error),createdAt:String(e.created_at??""),dispatchedAt:e.dispatched_at==null?null:String(e.dispatched_at),updatedAt:String(e.updated_at??"")}}async function a(){let e=r();return h!==e&&(h=e,m=null),m||(m=(async()=>{await e.execute(`CREATE TABLE IF NOT EXISTS lead_list_enrichment_jobs (
1
+ import{t as r}from"./chunk-7BEWBRMT.js";import{createHash as b,randomUUID as O}from"crypto";var p="mcp-scraper/lead-list-enrichment.requested",A=new Set(["complete","partial","empty","failed","cancelled"]),U=new Set(["complete","failed","cancelled"]),T=10,g=360,S=60,h=null,m=null;function o(e,t,s){let n=e.trim();if(!n||n.length>s)throw new Error(`${t} is required and must be ${s} characters or fewer`);return n}function d(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${t} must be a non-negative safe integer`);return e}function u(e){if(e==null)return null;try{return JSON.parse(String(e))}catch{return null}}function R(e){let t=new WeakSet,s=n=>{if(n===null||typeof n=="string"||typeof n=="boolean")return n;if(typeof n=="number"){if(!Number.isFinite(n))throw new Error("canonical fingerprint input must contain finite numbers");return Object.is(n,-0)?0:n}if(Array.isArray(n))return n.map(s);if(typeof n=="object"){if(t.has(n))throw new Error("canonical fingerprint input must not be cyclic");t.add(n);let i={};for(let _ of Object.keys(n).sort()){let c=n[_];c!==void 0&&(i[_]=s(c))}return t.delete(n),i}throw new Error(`canonical fingerprint input contains unsupported ${typeof n}`)};return JSON.stringify(s(e))}function y(e){return b("sha256").update(R(e)).digest("hex")}function I(e){return b("sha256").update(R(e)).digest("hex")}function j(){return{mapsAttempts:0,pageAttempts:0,pageSuccesses:0,serpSearches:0}}function E(e){let t=u(e.input_json);if(!t)throw new Error(`lead list enrichment job ${String(e.id??"")} has invalid durable input`);return{id:String(e.id),userId:Number(e.user_id),idempotencyKey:String(e.idempotency_key),requestFingerprint:String(e.request_fingerprint),input:t,status:String(e.status),totalRows:Number(e.total_rows??0),doneRows:Number(e.done_rows??0),failedRows:Number(e.failed_rows??0),cancelledRows:Number(e.cancelled_rows??0),usage:{mapsAttempts:Number(e.maps_attempts??0),pageAttempts:Number(e.page_attempts??0),pageSuccesses:Number(e.page_successes??0),serpSearches:Number(e.serp_searches??0)},concurrencyLockId:e.concurrency_lock_id==null?null:String(e.concurrency_lock_id),debitKey:String(e.debit_key),holdMc:Number(e.hold_mc??0),billedMc:e.billed_mc==null?null:Number(e.billed_mc),result:u(e.result_json),csvArtifact:u(e.csv_artifact_json),xlsxArtifact:u(e.xlsx_artifact_json),warnings:u(e.warnings_json)??[],cancelRequestedAt:e.cancel_requested_at==null?null:String(e.cancel_requested_at),errorCode:e.error_code==null?null:String(e.error_code),errorMessage:e.error_message==null?null:String(e.error_message),retryable:e.retryable==null?null:Number(e.retryable)===1,createdAt:String(e.created_at??""),startedAt:e.started_at==null?null:String(e.started_at),completedAt:e.completed_at==null?null:String(e.completed_at),updatedAt:String(e.updated_at??"")}}function w(e){return{jobId:String(e.job_id),ordinal:Number(e.ordinal),inputDigest:String(e.input_digest),status:String(e.status),result:u(e.result_json),usage:{mapsAttempts:Number(e.maps_attempts??0),pageAttempts:Number(e.page_attempts??0),pageSuccesses:Number(e.page_successes??0),serpSearches:Number(e.serp_searches??0)},errorCode:e.error_code==null?null:String(e.error_code),errorMessage:e.error_message==null?null:String(e.error_message),retryable:Number(e.retryable??0)===1,durationMs:Number(e.duration_ms??0),startedAt:e.started_at==null?null:String(e.started_at),completedAt:e.completed_at==null?null:String(e.completed_at),updatedAt:String(e.updated_at??"")}}function M(e){return{id:String(e.id),jobId:String(e.job_id),eventName:p,status:String(e.status),attempts:Number(e.attempts??0),claimToken:e.locked_by==null?null:String(e.locked_by),lockedUntil:e.locked_until==null?null:String(e.locked_until),nextAttemptAt:e.next_attempt_at==null?null:String(e.next_attempt_at),lastError:e.last_error==null?null:String(e.last_error),createdAt:String(e.created_at??""),dispatchedAt:e.dispatched_at==null?null:String(e.dispatched_at),updatedAt:String(e.updated_at??"")}}async function a(){let e=r();return h!==e&&(h=e,m=null),m||(m=(async()=>{await e.execute(`CREATE TABLE IF NOT EXISTS lead_list_enrichment_jobs (
2
2
  id TEXT PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES users(id), idempotency_key TEXT NOT NULL,
3
3
  request_fingerprint TEXT NOT NULL, input_json TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'initializing',
4
4
  total_rows INTEGER NOT NULL DEFAULT 0, done_rows INTEGER NOT NULL DEFAULT 0,
@@ -1,4 +1,4 @@
1
- function S(r,e,t,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!o:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(r,t):o?o.value=t:e.set(r,t),t}function _(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}var ct=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return ct=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};function Ue(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var ve=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};var x=class extends Error{},I=class r extends x{constructor(e,t,n,o){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=o,this.error=t}static makeMessage(e,t,n){let o=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,t,n,o){if(!e||!o)return new K({message:n,cause:ve(t)});let s=t;return e===400?new fe(e,s,n,o):e===401?new de(e,s,n,o):e===403?new pe(e,s,n,o):e===404?new he(e,s,n,o):e===409?new me(e,s,n,o):e===422?new ye(e,s,n,o):e===429?new ge(e,s,n,o):e>=500?new we(e,s,n,o):new r(e,s,n,o)}},T=class extends I{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},K=class extends I{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},D=class extends K{constructor({message:e}={}){super({message:e??"Request timed out."})}},fe=class extends I{},de=class extends I{},pe=class extends I{},he=class extends I{},me=class extends I{},ye=class extends I{},ge=class extends I{},we=class extends I{};var Er=/^[a-z][a-z0-9+.-]*:/i,vt=r=>Er.test(r),$=r=>($=Array.isArray,$(r)),lt=$;function ut(r){return typeof r!="object"?{}:r??{}}function ft(r){if(!r)return!0;for(let e in r)return!1;return!0}function Dt(r,e){return Object.prototype.hasOwnProperty.call(r,e)}var Nt=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new x(`${r} must be an integer`);if(e<0)throw new x(`${r} must be a positive integer`);return e},Sr=r=>{if(typeof r=="number")return Math.round(r);if(typeof r=="string")return parseInt(r,10);throw new x(`Could not coerce ${r} (type: ${typeof r}) into a number`)};var Ir=r=>typeof r=="boolean"?r:typeof r=="string"?r==="true":!!r,Ht=r=>{if(r!=null)return Sr(r)};var dt=r=>{if(r!=null)return Ir(r)},Bt=r=>{try{return JSON.parse(r)}catch{return}};var Mt=r=>new Promise(e=>setTimeout(e,r));var W="0.93.0";function $r(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var Lr=()=>{let r=$r();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":Kt(Deno.build.os),"X-Stainless-Arch":qt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":Kt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":qt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Tr();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Tr(){if(typeof navigator>"u"||!navigator)return null;let r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${s}.${a}`}}}return null}var qt=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Kt=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),Wt,Xt=()=>Wt??(Wt=Lr());function zt(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new \u004b\u0065\u0072\u006e\u0065\u006c({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function pt(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function ze(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return pt({start(){},async pull(t){let{done:n,value:o}=await e.next();n?t.close():t.enqueue(o)},async cancel(){await e.return?.()}})}function ht(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Vt(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}var Jt=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var mt="RFC3986",yt=r=>String(r),gt={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:yt},Gt="RFC1738";var Ve=(r,e)=>(Ve=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ve(r,e)),v=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var wt=1024,Qt=(r,e,t,n,o)=>{if(r.length===0)return r;let s=r;if(typeof r=="symbol"?s=Symbol.prototype.toString.call(r):typeof r!="string"&&(s=String(r)),t==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let a="";for(let c=0;c<s.length;c+=wt){let f=s.length>=wt?s.slice(c,c+wt):s,d=[];for(let m=0;m<f.length;++m){let l=f.charCodeAt(m);if(l===45||l===46||l===95||l===126||l>=48&&l<=57||l>=65&&l<=90||l>=97&&l<=122||o===Gt&&(l===40||l===41)){d[d.length]=f.charAt(m);continue}if(l<128){d[d.length]=v[l];continue}if(l<2048){d[d.length]=v[192|l>>6]+v[128|l&63];continue}if(l<55296||l>=57344){d[d.length]=v[224|l>>12]+v[128|l>>6&63]+v[128|l&63];continue}m+=1,l=65536+((l&1023)<<10|f.charCodeAt(m)&1023),d[d.length]=v[240|l>>18]+v[128|l>>12&63]+v[128|l>>6&63]+v[128|l&63]}a+=d.join("")}return a};function Yt(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function bt(r,e){if($(r)){let t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}var er={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},tr=function(r,e){Array.prototype.push.apply(r,$(e)?e:[e])},Zt,R={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Qt,encodeValuesOnly:!1,format:mt,formatter:yt,indices:!1,serializeDate(r){return(Zt??(Zt=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function Cr(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var xt={};function rr(r,e,t,n,o,s,a,c,f,d,m,l,g,h,A,E,U,k){let b=r,J=k,G=0,it=!1;for(;(J=J.get(xt))!==void 0&&!it;){let L=J.get(r);if(G+=1,typeof L<"u"){if(L===G)throw new RangeError("Cyclic object value");it=!0}typeof J.get(xt)>"u"&&(G=0)}if(typeof d=="function"?b=d(e,b):b instanceof Date?b=g?.(b):t==="comma"&&$(b)&&(b=bt(b,function(L){return L instanceof Date?g?.(L):L})),b===null){if(s)return f&&!E?f(e,R.encoder,U,"key",h):e;b=""}if(Cr(b)||Yt(b)){if(f){let L=E?e:f(e,R.encoder,U,"key",h);return[A?.(L)+"="+A?.(f(b,R.encoder,U,"value",h))]}return[A?.(e)+"="+A?.(String(b))]}let q=[];if(typeof b>"u")return q;let Fe;if(t==="comma"&&$(b))E&&f&&(b=bt(b,f)),Fe=[{value:b.length>0?b.join(",")||null:void 0}];else if($(d))Fe=d;else{let L=Object.keys(b);Fe=m?L.sort(m):L}let kt=c?String(e).replace(/\./g,"%2E"):String(e),Xe=n&&$(b)&&b.length===1?kt+"[]":kt;if(o&&$(b)&&b.length===0)return Xe+"[]";for(let L=0;L<Fe.length;++L){let ue=Fe[L],Ft=typeof ue=="object"&&typeof ue.value<"u"?ue.value:b[ue];if(a&&Ft===null)continue;let at=l&&c?ue.replace(/\./g,"%2E"):ue,Rr=$(b)?typeof t=="function"?t(Xe,at):Xe:Xe+(l?"."+at:"["+at+"]");k.set(r,G);let Ut=new WeakMap;Ut.set(xt,k),tr(q,rr(Ft,Rr,t,n,o,s,a,c,t==="comma"&&E&&$(b)?null:f,d,m,l,g,h,A,E,U,Ut))}return q}function kr(r=R){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||R.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=mt;if(typeof r.format<"u"){if(!Ve(gt,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=gt[t],o=R.filter;(typeof r.filter=="function"||$(r.filter))&&(o=r.filter);let s;if(r.arrayFormat&&r.arrayFormat in er?s=r.arrayFormat:"indices"in r?s=r.indices?"indices":"repeat":s=R.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:R.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:R.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:R.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:R.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?R.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:R.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:R.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:R.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:R.encodeValuesOnly,filter:o,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:R.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:R.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:R.strictNullHandling}}function nr(r,e={}){let t=r,n=kr(e),o,s;typeof n.filter=="function"?(s=n.filter,t=s("",t)):$(n.filter)&&(s=n.filter,o=s);let a=[];if(typeof t!="object"||t===null)return"";let c=er[n.arrayFormat],f=c==="comma"&&n.commaRoundTrip;o||(o=Object.keys(t)),n.sort&&o.sort(n.sort);let d=new WeakMap;for(let g=0;g<o.length;++g){let h=o[g];n.skipNulls&&t[h]===null||tr(a,rr(t[h],h,c,f,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,d))}let m=a.join(n.delimiter),l=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?l+="utf8=%26%2310003%3B&":l+="utf8=%E2%9C%93&"),m.length>0?l+m:""}function or(r){return nr(r,{arrayFormat:"comma"})}function ar(r){let e=0;for(let o of r)e+=o.length;let t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var sr;function De(r){let e;return(sr??(e=new globalThis.TextEncoder,sr=e.encode.bind(e)))(r)}var ir;function _t(r){let e;return(ir??(e=new globalThis.TextDecoder,ir=e.decode.bind(e)))(r)}var j,C,Q=class{constructor(){j.set(this,void 0),C.set(this,void 0),S(this,j,new Uint8Array,"f"),S(this,C,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?De(e):e;S(this,j,ar([_(this,j,"f"),t]),"f");let n=[],o;for(;(o=Ur(_(this,j,"f"),_(this,C,"f")))!=null;){if(o.carriage&&_(this,C,"f")==null){S(this,C,o.index,"f");continue}if(_(this,C,"f")!=null&&(o.index!==_(this,C,"f")+1||o.carriage)){n.push(_t(_(this,j,"f").subarray(0,_(this,C,"f")-1))),S(this,j,_(this,j,"f").subarray(_(this,C,"f")),"f"),S(this,C,null,"f");continue}let s=_(this,C,"f")!==null?o.preceding-1:o.preceding,a=_t(_(this,j,"f").subarray(0,s));n.push(a),S(this,j,_(this,j,"f").subarray(o.index),"f"),S(this,C,null,"f")}return n}flush(){return _(this,j,"f").length?this.decode(`
1
+ function Ue(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var ve=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};var x=class extends Error{},I=class r extends x{constructor(e,t,n,o){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=o,this.error=t}static makeMessage(e,t,n){let o=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,t,n,o){if(!e||!o)return new K({message:n,cause:ve(t)});let s=t;return e===400?new fe(e,s,n,o):e===401?new de(e,s,n,o):e===403?new pe(e,s,n,o):e===404?new he(e,s,n,o):e===409?new me(e,s,n,o):e===422?new ye(e,s,n,o):e===429?new ge(e,s,n,o):e>=500?new we(e,s,n,o):new r(e,s,n,o)}},T=class extends I{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},K=class extends I{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},D=class extends K{constructor({message:e}={}){super({message:e??"Request timed out."})}},fe=class extends I{},de=class extends I{},pe=class extends I{},he=class extends I{},me=class extends I{},ye=class extends I{},ge=class extends I{},we=class extends I{};function S(r,e,t,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!o:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(r,t):o?o.value=t:e.set(r,t),t}function _(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}var ct=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return ct=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};var Er=/^[a-z][a-z0-9+.-]*:/i,vt=r=>Er.test(r),$=r=>($=Array.isArray,$(r)),lt=$;function ut(r){return typeof r!="object"?{}:r??{}}function ft(r){if(!r)return!0;for(let e in r)return!1;return!0}function Dt(r,e){return Object.prototype.hasOwnProperty.call(r,e)}var Nt=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new x(`${r} must be an integer`);if(e<0)throw new x(`${r} must be a positive integer`);return e},Sr=r=>{if(typeof r=="number")return Math.round(r);if(typeof r=="string")return parseInt(r,10);throw new x(`Could not coerce ${r} (type: ${typeof r}) into a number`)};var Ir=r=>typeof r=="boolean"?r:typeof r=="string"?r==="true":!!r,Ht=r=>{if(r!=null)return Sr(r)};var dt=r=>{if(r!=null)return Ir(r)},Bt=r=>{try{return JSON.parse(r)}catch{return}};var Mt=r=>new Promise(e=>setTimeout(e,r));var W="0.93.0";function $r(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var Lr=()=>{let r=$r();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":Kt(Deno.build.os),"X-Stainless-Arch":qt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":Kt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":qt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Tr();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Tr(){if(typeof navigator>"u"||!navigator)return null;let r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${s}.${a}`}}}return null}var qt=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Kt=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),Wt,Xt=()=>Wt??(Wt=Lr());function zt(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new \u004b\u0065\u0072\u006e\u0065\u006c({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function pt(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function ze(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return pt({start(){},async pull(t){let{done:n,value:o}=await e.next();n?t.close():t.enqueue(o)},async cancel(){await e.return?.()}})}function ht(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Vt(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}var Jt=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var mt="RFC3986",yt=r=>String(r),gt={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:yt},Gt="RFC1738";var Ve=(r,e)=>(Ve=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ve(r,e)),v=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var wt=1024,Qt=(r,e,t,n,o)=>{if(r.length===0)return r;let s=r;if(typeof r=="symbol"?s=Symbol.prototype.toString.call(r):typeof r!="string"&&(s=String(r)),t==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let a="";for(let c=0;c<s.length;c+=wt){let f=s.length>=wt?s.slice(c,c+wt):s,d=[];for(let m=0;m<f.length;++m){let l=f.charCodeAt(m);if(l===45||l===46||l===95||l===126||l>=48&&l<=57||l>=65&&l<=90||l>=97&&l<=122||o===Gt&&(l===40||l===41)){d[d.length]=f.charAt(m);continue}if(l<128){d[d.length]=v[l];continue}if(l<2048){d[d.length]=v[192|l>>6]+v[128|l&63];continue}if(l<55296||l>=57344){d[d.length]=v[224|l>>12]+v[128|l>>6&63]+v[128|l&63];continue}m+=1,l=65536+((l&1023)<<10|f.charCodeAt(m)&1023),d[d.length]=v[240|l>>18]+v[128|l>>12&63]+v[128|l>>6&63]+v[128|l&63]}a+=d.join("")}return a};function Yt(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function bt(r,e){if($(r)){let t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}var er={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},tr=function(r,e){Array.prototype.push.apply(r,$(e)?e:[e])},Zt,R={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Qt,encodeValuesOnly:!1,format:mt,formatter:yt,indices:!1,serializeDate(r){return(Zt??(Zt=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function Cr(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var xt={};function rr(r,e,t,n,o,s,a,c,f,d,m,l,g,h,A,E,U,k){let b=r,J=k,G=0,it=!1;for(;(J=J.get(xt))!==void 0&&!it;){let L=J.get(r);if(G+=1,typeof L<"u"){if(L===G)throw new RangeError("Cyclic object value");it=!0}typeof J.get(xt)>"u"&&(G=0)}if(typeof d=="function"?b=d(e,b):b instanceof Date?b=g?.(b):t==="comma"&&$(b)&&(b=bt(b,function(L){return L instanceof Date?g?.(L):L})),b===null){if(s)return f&&!E?f(e,R.encoder,U,"key",h):e;b=""}if(Cr(b)||Yt(b)){if(f){let L=E?e:f(e,R.encoder,U,"key",h);return[A?.(L)+"="+A?.(f(b,R.encoder,U,"value",h))]}return[A?.(e)+"="+A?.(String(b))]}let q=[];if(typeof b>"u")return q;let Fe;if(t==="comma"&&$(b))E&&f&&(b=bt(b,f)),Fe=[{value:b.length>0?b.join(",")||null:void 0}];else if($(d))Fe=d;else{let L=Object.keys(b);Fe=m?L.sort(m):L}let kt=c?String(e).replace(/\./g,"%2E"):String(e),Xe=n&&$(b)&&b.length===1?kt+"[]":kt;if(o&&$(b)&&b.length===0)return Xe+"[]";for(let L=0;L<Fe.length;++L){let ue=Fe[L],Ft=typeof ue=="object"&&typeof ue.value<"u"?ue.value:b[ue];if(a&&Ft===null)continue;let at=l&&c?ue.replace(/\./g,"%2E"):ue,Rr=$(b)?typeof t=="function"?t(Xe,at):Xe:Xe+(l?"."+at:"["+at+"]");k.set(r,G);let Ut=new WeakMap;Ut.set(xt,k),tr(q,rr(Ft,Rr,t,n,o,s,a,c,t==="comma"&&E&&$(b)?null:f,d,m,l,g,h,A,E,U,Ut))}return q}function kr(r=R){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||R.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=mt;if(typeof r.format<"u"){if(!Ve(gt,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=gt[t],o=R.filter;(typeof r.filter=="function"||$(r.filter))&&(o=r.filter);let s;if(r.arrayFormat&&r.arrayFormat in er?s=r.arrayFormat:"indices"in r?s=r.indices?"indices":"repeat":s=R.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:R.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:R.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:R.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:R.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?R.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:R.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:R.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:R.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:R.encodeValuesOnly,filter:o,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:R.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:R.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:R.strictNullHandling}}function nr(r,e={}){let t=r,n=kr(e),o,s;typeof n.filter=="function"?(s=n.filter,t=s("",t)):$(n.filter)&&(s=n.filter,o=s);let a=[];if(typeof t!="object"||t===null)return"";let c=er[n.arrayFormat],f=c==="comma"&&n.commaRoundTrip;o||(o=Object.keys(t)),n.sort&&o.sort(n.sort);let d=new WeakMap;for(let g=0;g<o.length;++g){let h=o[g];n.skipNulls&&t[h]===null||tr(a,rr(t[h],h,c,f,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,d))}let m=a.join(n.delimiter),l=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?l+="utf8=%26%2310003%3B&":l+="utf8=%E2%9C%93&"),m.length>0?l+m:""}function or(r){return nr(r,{arrayFormat:"comma"})}function ar(r){let e=0;for(let o of r)e+=o.length;let t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var sr;function De(r){let e;return(sr??(e=new globalThis.TextEncoder,sr=e.encode.bind(e)))(r)}var ir;function _t(r){let e;return(ir??(e=new globalThis.TextDecoder,ir=e.decode.bind(e)))(r)}var j,C,Q=class{constructor(){j.set(this,void 0),C.set(this,void 0),S(this,j,new Uint8Array,"f"),S(this,C,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?De(e):e;S(this,j,ar([_(this,j,"f"),t]),"f");let n=[],o;for(;(o=Ur(_(this,j,"f"),_(this,C,"f")))!=null;){if(o.carriage&&_(this,C,"f")==null){S(this,C,o.index,"f");continue}if(_(this,C,"f")!=null&&(o.index!==_(this,C,"f")+1||o.carriage)){n.push(_t(_(this,j,"f").subarray(0,_(this,C,"f")-1))),S(this,j,_(this,j,"f").subarray(_(this,C,"f")),"f"),S(this,C,null,"f");continue}let s=_(this,C,"f")!==null?o.preceding-1:o.preceding,a=_t(_(this,j,"f").subarray(0,s));n.push(a),S(this,j,_(this,j,"f").subarray(o.index),"f"),S(this,C,null,"f")}return n}flush(){return _(this,j,"f").length?this.decode(`
2
2
  `):[]}};j=new WeakMap,C=new WeakMap;Q.NEWLINE_CHARS=new Set([`
3
3
  `,"\r"]);Q.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ur(r,e){for(let o=e??0;o<r.length;o++){if(r[o]===10)return{preceding:o,index:o+1,carriage:!1};if(r[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function cr(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}var Ge={off:0,error:200,warn:300,info:400,debug:500},At=(r,e,t)=>{if(r){if(Dt(Ge,r))return r;P(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(Ge))}`)}};function Ne(){}function Je(r,e,t){return!e||Ge[r]>Ge[t]?Ne:e[r].bind(e)}var vr={error:Ne,warn:Ne,info:Ne,debug:Ne},lr=new WeakMap;function P(r){let e=r.logger,t=r.logLevel??"off";if(!e)return vr;let n=lr.get(e);if(n&&n[0]===t)return n[1];let o={error:Je("error",e,t),warn:Je("warn",e,t),info:Je("info",e,t),debug:Je("debug",e,t)};return lr.set(e,[t,o]),o}var N=r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r);var He,Qe=class r{constructor(e,t,n){this.iterator=e,He.set(this,void 0),this.controller=t,S(this,He,n,"f")}static fromSSEResponse(e,t,n){let o=!1,s=n?P(n):console;async function*a(){if(o)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let c=!1;try{for await(let f of Dr(e,t))try{yield JSON.parse(f.data)}catch(d){throw s.error("Could not parse message into JSON:",f.data),s.error("From chunk:",f.raw),d}c=!0}catch(f){if(Ue(f))return;throw f}finally{c||t.abort()}}return new r(a,t,n)}static fromReadableStream(e,t,n){let o=!1;async function*s(){let c=new Q,f=ht(e);for await(let d of f)for(let m of c.decode(d))yield m;for(let d of c.flush())yield d}async function*a(){if(o)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let c=!1;try{for await(let f of s())c||f&&(yield JSON.parse(f));c=!0}catch(f){if(Ue(f))return;throw f}finally{c||t.abort()}}return new r(a,t,n)}[(He=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),o=s=>({next:()=>{if(s.length===0){let a=n.next();e.push(a),t.push(a)}return s.shift()}});return[new r(()=>o(e),this.controller,_(this,He,"f")),new r(()=>o(t),this.controller,_(this,He,"f"))]}toReadableStream(){let e=this,t;return pt({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:s}=await t.next();if(s)return n.close();let a=De(JSON.stringify(o)+`
4
4
  `);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await t.return?.()}})}};async function*Dr(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new x("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new x("Attempted to iterate over a response with no body");let t=new Rt,n=new Q,o=ht(r.body);for await(let s of Nr(o))for(let a of n.decode(s)){let c=t.decode(a);c&&(yield c)}for(let s of n.flush()){let a=t.decode(s);a&&(yield a)}}async function*Nr(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?De(t):t,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=cr(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var Rt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
@@ -1 +1 @@
1
- import{a as m}from"./chunk-YQZGZBB4.js";import{b as n,g as o,h as i,ha as p,ia as d,j as l,ka as b,m as u,o as c}from"./chunk-YQ5U5C2X.js";function f(e){return e instanceof Error?e.message:String(e)}function y(e,t){return e instanceof DOMException&&(e.name==="TimeoutError"||e.name==="AbortError")?!0:/timeout|timed out|Timeout \d+ms exceeded|deadline/i.test(t)}function g(e){return/captcha|recaptcha|unusual traffic|google\.com\/sorry|blocked/i.test(e)}function S(e){return/ERR_TUNNEL_CONNECTION_FAILED|ERR_PROXY_CONNECTION_FAILED|ERR_SOCKS_CONNECTION_FAILED|tunnel connection failed|proxy connection failed|transport error: proxy/i.test(e)}function E(e){return/proxy unavailable|proxy_unavailable|connection_test_failed|did not return a proxy id|configured fallback/i.test(e)}function h(e){return/(?:spending|billing|organization|account).{0,80}(?:cap|limit|blocked|disabled)|(?:quota|capacity).{0,40}(?:reached|exceeded)|https?:\/\/\S*dashboard/i.test(e)}function v(e){return/browser (?:has been )?closed|context (?:has been )?closed|target page, context or browser has been closed|session closed|page has been closed/i.test(e)}function x(e){let t=f(e);return e instanceof u?{error_code:"request_aborted",error_type:"request_aborted",message:o("request_aborted"),retryable:!0,httpStatus:408,terminalStatus:"cancelled"}:e instanceof l||g(t)?{error_code:"captcha_exhausted",error_type:"captcha",message:o("captcha_exhausted"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:m(e,t)?{error_code:"vendor_unavailable",error_type:"service_unavailable",message:o("vendor_unavailable"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:e instanceof c?{error_code:"location_mismatch",error_type:"location_mismatch",message:o("location_mismatch"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:S(t)?{error_code:"proxy_tunnel_failed",error_type:"connection",message:o("proxy_tunnel_failed"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:E(t)?{error_code:"proxy_unavailable",error_type:"connection",message:o("proxy_unavailable"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:v(t)?{error_code:"browser_session_interrupted",error_type:"extraction",message:o("browser_session_interrupted"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:y(e,t)?{error_code:"harvest_timeout",error_type:"timeout",message:o("harvest_timeout"),retryable:!0,httpStatus:504,terminalStatus:"failed"}:h(t)?{error_code:"service_unavailable",error_type:"service_unavailable",message:n,retryable:!0,httpStatus:503,terminalStatus:"failed"}:{error_code:"extraction_failed",error_type:"extraction",message:n,retryable:!1,httpStatus:500,terminalStatus:"failed"}}function w(e){return JSON.stringify({error_code:e.error_code,error_type:e.error_type,message:e.message,retryable:e.retryable})}function _(e,t={}){let r=i({errorCode:e.error_code,errorType:e.error_type,retryable:e.retryable,retryAfterSeconds:t.retryAfterSeconds,chargeStatus:t.chargeStatus,details:t.details});return{error:r.message,...r}}function A(e,t={}){let{error:r,...a}=_(e,t);return a}function C(e,t={}){let r=x(e);return{body:_(r,t),status:r.httpStatus}}function D(e,t){return async r=>{if(r.type==="started"){await p({jobId:e,userId:t,attemptNumber:r.attemptNumber,maxAttempts:r.maxAttempts,query:r.query,location:r.location,maxQuestions:r.maxQuestions,startedAt:r.startedAt});return}if(r.type==="provider_session_started"){await d({jobId:e,attemptNumber:r.attemptNumber,browserProvider:r.provider,providerSessionId:r.providerSessionId,observedAt:r.observedAt});return}await b({jobId:e,attemptNumber:r.attemptNumber,outcome:r.outcome,\u006b\u0065\u0072\u006e\u0065\u006cSessionId:r.\u006b\u0065\u0072\u006e\u0065\u006cSessionId,questionCount:r.questionCount,durationMs:r.durationMs,error:r.error,willRetry:r.willRetry,\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted:r.cleanup.\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:r.cleanup.\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded,\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:r.cleanup.\u006b\u0065\u0072\u006e\u0065\u006cDeleteError,browserCloseSucceeded:r.cleanup.browserCloseSucceeded,browserCloseError:r.cleanup.browserCloseError,browserProvider:r.cleanup.provider??null,providerSessionId:r.cleanup.providerSessionId??null,providerLookupStatus:r.cleanup.providerSessionId?"pending":"not_applicable",providerErrorCode:r.cleanup.providerDisconnectObserved?"browser_session_interrupted":null,providerErrorMessage:r.cleanup.providerDisconnectMessage??null,providerReasonSource:r.cleanup.providerDisconnectObserved?"client_runtime":null,providerDisconnectObserved:r.cleanup.providerDisconnectObserved??!1,providerDisconnectMessage:r.cleanup.providerDisconnectMessage??null,debug:r.debug,completedAt:r.completedAt})}}async function I(e,t,r=3){for(let a=1;a<=r;a++){try{let s=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(1e4)});if(s.ok)return;console.warn(`[webhook] attempt ${a} \u2192 ${s.status} from ${e}`)}catch(s){console.warn(`[webhook] attempt ${a} failed:`,s instanceof Error?s.message:s)}a<r&&await new Promise(s=>setTimeout(s,1e3*a*2))}console.error(`[webhook] gave up after ${r} attempts for ${e}`)}export{x as a,w as b,_ as c,A as d,C as e,D as f,I as g};
1
+ import{a as m}from"./chunk-XG6GCEUE.js";import{b as n,g as o,h as i,ha as p,ia as d,j as l,ka as b,m as u,o as c}from"./chunk-7BEWBRMT.js";function f(e){return e instanceof Error?e.message:String(e)}function y(e,t){return e instanceof DOMException&&(e.name==="TimeoutError"||e.name==="AbortError")?!0:/timeout|timed out|Timeout \d+ms exceeded|deadline/i.test(t)}function g(e){return/captcha|recaptcha|unusual traffic|google\.com\/sorry|blocked/i.test(e)}function S(e){return/ERR_TUNNEL_CONNECTION_FAILED|ERR_PROXY_CONNECTION_FAILED|ERR_SOCKS_CONNECTION_FAILED|tunnel connection failed|proxy connection failed|transport error: proxy/i.test(e)}function E(e){return/proxy unavailable|proxy_unavailable|connection_test_failed|did not return a proxy id|configured fallback/i.test(e)}function h(e){return/(?:spending|billing|organization|account).{0,80}(?:cap|limit|blocked|disabled)|(?:quota|capacity).{0,40}(?:reached|exceeded)|https?:\/\/\S*dashboard/i.test(e)}function v(e){return/browser (?:has been )?closed|context (?:has been )?closed|target page, context or browser has been closed|session closed|page has been closed/i.test(e)}function x(e){let t=f(e);return e instanceof u?{error_code:"request_aborted",error_type:"request_aborted",message:o("request_aborted"),retryable:!0,httpStatus:408,terminalStatus:"cancelled"}:e instanceof l||g(t)?{error_code:"captcha_exhausted",error_type:"captcha",message:o("captcha_exhausted"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:m(e,t)?{error_code:"vendor_unavailable",error_type:"service_unavailable",message:o("vendor_unavailable"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:e instanceof c?{error_code:"location_mismatch",error_type:"location_mismatch",message:o("location_mismatch"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:S(t)?{error_code:"proxy_tunnel_failed",error_type:"connection",message:o("proxy_tunnel_failed"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:E(t)?{error_code:"proxy_unavailable",error_type:"connection",message:o("proxy_unavailable"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:v(t)?{error_code:"browser_session_interrupted",error_type:"extraction",message:o("browser_session_interrupted"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:y(e,t)?{error_code:"harvest_timeout",error_type:"timeout",message:o("harvest_timeout"),retryable:!0,httpStatus:504,terminalStatus:"failed"}:h(t)?{error_code:"service_unavailable",error_type:"service_unavailable",message:n,retryable:!0,httpStatus:503,terminalStatus:"failed"}:{error_code:"extraction_failed",error_type:"extraction",message:n,retryable:!1,httpStatus:500,terminalStatus:"failed"}}function w(e){return JSON.stringify({error_code:e.error_code,error_type:e.error_type,message:e.message,retryable:e.retryable})}function _(e,t={}){let r=i({errorCode:e.error_code,errorType:e.error_type,retryable:e.retryable,retryAfterSeconds:t.retryAfterSeconds,chargeStatus:t.chargeStatus,details:t.details});return{error:r.message,...r}}function A(e,t={}){let{error:r,...a}=_(e,t);return a}function C(e,t={}){let r=x(e);return{body:_(r,t),status:r.httpStatus}}function D(e,t){return async r=>{if(r.type==="started"){await p({jobId:e,userId:t,attemptNumber:r.attemptNumber,maxAttempts:r.maxAttempts,query:r.query,location:r.location,maxQuestions:r.maxQuestions,startedAt:r.startedAt});return}if(r.type==="provider_session_started"){await d({jobId:e,attemptNumber:r.attemptNumber,browserProvider:r.provider,providerSessionId:r.providerSessionId,observedAt:r.observedAt});return}await b({jobId:e,attemptNumber:r.attemptNumber,outcome:r.outcome,\u006b\u0065\u0072\u006e\u0065\u006cSessionId:r.\u006b\u0065\u0072\u006e\u0065\u006cSessionId,questionCount:r.questionCount,durationMs:r.durationMs,error:r.error,willRetry:r.willRetry,\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted:r.cleanup.\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:r.cleanup.\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded,\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:r.cleanup.\u006b\u0065\u0072\u006e\u0065\u006cDeleteError,browserCloseSucceeded:r.cleanup.browserCloseSucceeded,browserCloseError:r.cleanup.browserCloseError,browserProvider:r.cleanup.provider??null,providerSessionId:r.cleanup.providerSessionId??null,providerLookupStatus:r.cleanup.providerSessionId?"pending":"not_applicable",providerErrorCode:r.cleanup.providerDisconnectObserved?"browser_session_interrupted":null,providerErrorMessage:r.cleanup.providerDisconnectMessage??null,providerReasonSource:r.cleanup.providerDisconnectObserved?"client_runtime":null,providerDisconnectObserved:r.cleanup.providerDisconnectObserved??!1,providerDisconnectMessage:r.cleanup.providerDisconnectMessage??null,debug:r.debug,completedAt:r.completedAt})}}async function I(e,t,r=3){for(let a=1;a<=r;a++){try{let s=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(1e4)});if(s.ok)return;console.warn(`[webhook] attempt ${a} \u2192 ${s.status} from ${e}`)}catch(s){console.warn(`[webhook] attempt ${a} failed:`,s instanceof Error?s.message:s)}a<r&&await new Promise(s=>setTimeout(s,1e3*a*2))}console.error(`[webhook] gave up after ${r} attempts for ${e}`)}export{x as a,w as b,_ as c,A as d,C as e,D as f,I as g};
@@ -0,0 +1 @@
1
+ var o="0.89.9";export{o as a};