mcp-scraper 0.96.1 → 0.96.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +26 -1
  2. package/README.md +1 -1
  3. package/dist/actions-FKAX2PYT.js +1 -0
  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/bundle-7JMACIIR.js +1 -0
  11. package/dist/chunk-3HXMW2UJ.js +1 -0
  12. package/dist/{chunk-RN4VG3VH.js → chunk-42SLBGDI.js} +1 -1
  13. package/dist/{chunk-JHT6A4U6.js → chunk-4KHDV5E7.js} +1 -1
  14. package/dist/{chunk-FB4KBB5W.js → chunk-7ZR5IO3B.js} +2 -2
  15. package/dist/{chunk-HUNSEGUN.js → chunk-ANQ4JJVI.js} +43 -29
  16. package/dist/{chunk-SE4VKLEC.js → chunk-CFZXZKFT.js} +1 -1
  17. package/dist/{chunk-6BD75VKS.js → chunk-DJT2547J.js} +1 -1
  18. package/dist/chunk-E7I3OQHQ.js +203 -0
  19. package/dist/{chunk-HVQZRQRJ.js → chunk-GLCR4KJI.js} +16 -37
  20. package/dist/chunk-JGGQ3UX5.js +1 -0
  21. package/dist/chunk-JREMJRSS.js +1 -0
  22. package/dist/chunk-K3VDGJNK.js +1 -0
  23. package/dist/{chunk-H6MODA7W.js → chunk-MJOXIDKF.js} +5 -5
  24. package/dist/chunk-OY24ERPV.js +8 -0
  25. package/dist/{chunk-7WPCGRD7.js → chunk-P55O4IDC.js} +41 -34
  26. package/dist/{chunk-ZTMQEDIB.js → chunk-PANT6VEM.js} +1 -1
  27. package/dist/chunk-PKQHHCO4.js +20 -0
  28. package/dist/{chunk-RIHI3KH7.js → chunk-QYPSFZK3.js} +1 -1
  29. package/dist/{chunk-BPKTUCV7.js → chunk-U7BZ5KTE.js} +1 -1
  30. package/dist/{chunk-SFUOSJ3A.js → chunk-WBJ6Y7WP.js} +2 -2
  31. package/dist/dispatch-E6VTNHHS.js +1 -0
  32. package/dist/index.cjs +10 -10
  33. package/dist/index.js +1 -1
  34. package/dist/metering-YHZ46GV4.js +1 -0
  35. package/dist/queue-4XHYUV7J.js +1 -0
  36. package/dist/reconciliation-43CSC3XD.js +1 -0
  37. package/dist/repository-UKDA4IWP.js +1 -0
  38. package/dist/{server-DXZ27KQO.js → server-74VGVXA4.js} +840 -802
  39. package/dist/settlement-I5IBIK6U.js +1 -0
  40. package/dist/worker-L5NISZQV.js +1 -0
  41. package/package.json +1 -2
  42. package/dist/actions-R4EJDLRO.js +0 -1
  43. package/dist/bundle-FCXZMIRB.js +0 -1
  44. package/dist/chunk-5BKSKLHX.js +0 -1
  45. package/dist/chunk-5LYINW7Z.js +0 -8
  46. package/dist/chunk-CORWWDHL.js +0 -1
  47. package/dist/chunk-CVQUHVHX.js +0 -1
  48. package/dist/chunk-IY6ZUUY7.js +0 -173
  49. package/dist/chunk-RYX4FJVH.js +0 -1
  50. package/dist/chunk-UXNR3K6I.js +0 -1
  51. package/dist/dispatch-P7IY75LH.js +0 -1
  52. package/dist/metering-ZH2P62IC.js +0 -1
  53. package/dist/queue-AC4XKD6Z.js +0 -1
  54. package/dist/reconciliation-UZUZ6B74.js +0 -1
  55. package/dist/repository-4EC5EXVN.js +0 -1
  56. package/dist/settlement-6CS4JZTY.js +0 -1
  57. package/dist/worker-ATRD6VKM.js +0 -1
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var qo=Object.create;var hn=Object.defineProperty;var zo=Object.getOwnPropertyDescriptor;var $o=Object.getOwnPropertyNames;var jo=Object.getPrototypeOf,Qo=Object.prototype.hasOwnProperty;var Xo=(e,t)=>{for(var n in t)hn(e,n,{get:t[n],enumerable:!0})},ui=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of $o(t))!Qo.call(e,i)&&i!==n&&hn(e,i,{get:()=>t[i],enumerable:!(a=zo(t,i))||a.enumerable});return e};var gn=(e,t,n)=>(n=e!=null?qo(jo(e)):{},ui(t||!e||!e.__esModule?hn(n,"default",{value:e,enumerable:!0}):n,e)),Zo=e=>ui(hn({},"__esModule",{value:!0}),e);var hS={};Xo(hS,{VideoGenerator:()=>jn,buildClipPrompts:()=>Yn,harvest:()=>Bo});module.exports=Zo(hS);var At=class extends Error{constructor(t,n){super(`SERP provider mismatch: planned ${t}, observed ${n}`),this.name="SerpProviderMismatchError"}};function pn(e){return e==="\u0062\u0072\u0069\u0067\u0068\u0074_\u0064\u0061\u0074\u0061_browser_api"?"\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061":"\u006b\u0065\u0072\u006e\u0065\u006c"}function hi(e){return tr({intent:e.intent,\u0062\u0072\u0069\u0067\u0068\u0074\u0044\u0061\u0074\u0061Available:e.\u0062\u0072\u0069\u0067\u0068\u0074\u0044\u0061\u0074\u0061Available,\u006b\u0065\u0072\u006e\u0065\u006cAvailable:!0,persistent\u004b\u0065\u0072\u006e\u0065\u006cIdentityRequested:e.persistent\u004b\u0065\u0072\u006e\u0065\u006cIdentityRequested,retryIndex:e.retryIndex,priorTerminalReason:e.priorTerminalReason,allowedFallbacks:e.\u006b\u0065\u0072\u006e\u0065\u006cFallbackAvailable&&e.intent!=="\u006b\u0065\u0072\u006e\u0065\u006c"?["\u006b\u0065\u0072\u006e\u0065\u006c"]:[],timeoutMs:e.softDeadlineMs==null?4e5:Math.max(1,e.softDeadlineMs-Date.now())})}function gi(e){if(e.forceManagedSerp&&e.force\u004b\u0065\u0072\u006e\u0065\u006cSerp)throw new Error("forceManagedSerp and force\u004b\u0065\u0072\u006e\u0065\u006cSerp cannot both be true");return e.forceManagedSerp?"\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061":e.force\u004b\u0065\u0072\u006e\u0065\u006cSerp?"\u006b\u0065\u0072\u006e\u0065\u006c":"auto"}function wn(e,t){if(!t)throw new Error(`Requested SERP provider is unavailable: ${e}`);return e}function tr(e){if(!Number.isInteger(e.retryIndex)||e.retryIndex<0)throw new Error("retryIndex must be a non-negative integer");if(!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0)throw new Error("timeoutMs must be a positive number");let t,n;e.intent==="\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061"?(t=wn("\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061",e.\u0062\u0072\u0069\u0067\u0068\u0074\u0044\u0061\u0074\u0061Available),n="explicit_\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061"):e.intent==="\u006b\u0065\u0072\u006e\u0065\u006c"?(t=wn("\u006b\u0065\u0072\u006e\u0065\u006c",e.\u006b\u0065\u0072\u006e\u0065\u006cAvailable),n="explicit_\u006b\u0065\u0072\u006e\u0065\u006c"):e.persistent\u004b\u0065\u0072\u006e\u0065\u006cIdentityRequested?(t=wn("\u006b\u0065\u0072\u006e\u0065\u006c",e.\u006b\u0065\u0072\u006e\u0065\u006cAvailable),n="persistent_\u006b\u0065\u0072\u006e\u0065\u006c_identity"):e.\u0062\u0072\u0069\u0067\u0068\u0074\u0044\u0061\u0074\u0061Available?(t="\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061",n="managed_default"):(t=wn("\u006b\u0065\u0072\u006e\u0065\u006c",e.\u006b\u0065\u0072\u006e\u0065\u006cAvailable),n="\u006b\u0065\u0072\u006e\u0065\u006c_default");let a=e.allowedFallbacks.find(o=>o!==t&&(o==="\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061"?e.\u0062\u0072\u0069\u0067\u0068\u0074\u0044\u0061\u0074\u0061Available:e.\u006b\u0065\u0072\u006e\u0065\u006cAvailable)),i=e.retryIndex>0&&a?a:t,s=e.retryIndex===0?"primary":i===t?"same_provider_retry":"provider_fallback";return Object.freeze({plannedProvider:i,attemptKind:s,reasonCode:s==="primary"?n:s==="provider_fallback"?"provider_fallback":"same_provider_retry",retryIndex:e.retryIndex,priorTerminalReason:e.priorTerminalReason??null,timeoutMs:Math.floor(e.timeoutMs),fallbackAllowed:!!a})}function er(e,t){if(typeof e!="string")return null;let n=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return n?n.slice(0,t):null}function wi(e){let t=er(e,320);return t?t.replace(/\b(?:wss?|https?):\/\/\S+/gi,"[redacted endpoint]").replace(/\b(?:authorization|proxy-authorization):\s*\S+/gi,"$1: [redacted]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").slice(0,320):null}function xt(e){return wi(e)}function pi(e){if(typeof e!="string"||e.length===0||e.length>512||e.trim()!==e||/[\s\u0000-\u001f\u007f]/.test(e)||/:\/\//.test(e))throw new Error("\u0042\u0072\u0069\u0067\u0068\u0074 \u0044\u0061\u0074\u0061 did not return a valid browser session ID");return e}function Qn(e,t,n=new Date().toISOString()){let a=wi(t);return{source:e,message:a??e.replaceAll("_"," "),observedAt:n}}function nr(e){return{provider:e.provider,providerDisconnectObserved:e.disconnectObservation!==null,providerDisconnectMessage:e.disconnectObservation?.message??null}}function yi(e){return{...nr(e),providerSessionId:e.providerSessionId}}function mi(e,t,n,a){return new Proxy(e,{get(i,s,o){if(s==="launch")return async S=>{await t.start(n,"browser"),await i.launch(S);let U=i.getProviderSessionMetadata();if(await t.resource(n,"browser",U.providerSessionId,U.provider),!U.providerSessionId)throw new Error("Browser connection returned no attributable session identity");if(pn(U.provider)!==a)throw new At(a,U.provider);await t.assertActive(n)};let d=Reflect.get(i,s,o);return typeof d=="function"?d.bind(i):d}})}function Xn(e,t,n,a=null){let i=n.\u006b\u0065\u0072\u006e\u0065\u006cSessionId??n.providerSessionId??null,s=n.\u006b\u0065\u0072\u006e\u0065\u006cSessionId!=null?n.\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded===!0:n.physicalOutcome==="terminated",o=n.browserCloseSucceeded===!0&&n.localDisconnectSucceeded!==!1&&s,d=n.physicalOutcome==="not_started"&&n.browserCloseSucceeded===null,S={drained:n.extractionDrained===!0,effects:{browser:{resourceId:i,state:o?"terminated":d?"not_started":"unknown"},proxy:{resourceId:a,state:n.disposableProxyDeleted===!0?a===null?"not_started":"terminated":"unknown"}},details:{browserCloseSucceeded:n.browserCloseSucceeded??null,localDisconnectSucceeded:n.localDisconnectSucceeded??null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:n.\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded??null,browserCloseError:xt(n.browserCloseError),\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:xt(n.\u006b\u0065\u0072\u006e\u0065\u006cDeleteError),localDisconnectError:xt(n.localDisconnectError)}};return e.complete(t,S)}var or=require("crypto");var Ci=require("@libsql/client/http"),ar=process.env.TURSO_DATABASE_URL??"file:./paa-api.db",ir=process.env.TURSO_AUTH_TOKEN,Zn=null;function ze(){return Zn||(Zn=(0,Ci.createClient)({url:ar,authToken:ir})),Zn}var sr=require("crypto");var ta=class extends Error{constructor(){super("physical_permission_or_receipt_unknown"),this.name="PhysicalPermissionError"}};var rr=new WeakSet;function fi(e){let t=e&&typeof e=="object"?e.physicalExecution:void 0;if(t!==void 0){if(!t||typeof t!="object"||!rr.has(t))throw new ta;return t}}var yn="none";function ea(e){switch(e){case"day":return"qdr:d";case"week":return"qdr:w";case"month":return"qdr:m";case"year":return"qdr:y";default:return}}var L=require("zod");var na=L.z.object({query:L.z.string().min(1),location:L.z.string().optional(),gl:L.z.string().length(2).default("us"),hl:L.z.string().length(2).default("en"),device:L.z.enum(["desktop","mobile"]).default("desktop"),proxyMode:L.z.enum(["location","configured","none"]).default(yn),proxyZip:L.z.string().regex(/^\d{5}$/).optional(),keepDefaultProxy:L.z.boolean().optional(),requireUsEgress:L.z.boolean().optional(),maxAttempts:L.z.number().int().min(1).max(12).optional(),debug:L.z.boolean().default(!1),depth:L.z.number().int().min(1).max(30).default(3),maxQuestions:L.z.number().int().min(1).max(100).default(100),headless:L.z.boolean().default(!1),profileDir:L.z.string().optional(),proxy:L.z.string().url().optional(),\u006b\u0065\u0072\u006e\u0065\u006cApiKey:L.z.string().optional(),\u006b\u0065\u0072\u006e\u0065\u006cProxyId:L.z.string().optional(),\u006b\u0065\u0072\u006e\u0065\u006cProfileName:L.z.string().optional(),\u006b\u0065\u0072\u006e\u0065\u006cProfileSaveChanges:L.z.boolean().optional(),\u006b\u0065\u0072\u006e\u0065\u006cStealth:L.z.boolean().optional(),serpIdentity:L.z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/).optional(),\u006b\u0065\u0072\u006e\u0065\u006cProxyResolution:L.z.unknown().optional(),outputDir:L.z.string().default("./paa-output"),format:L.z.enum(["json","csv","both"]).default("both"),serpOnly:L.z.boolean().default(!1),questionsOnly:L.z.boolean().default(!1),questionGrowthRecoveryRounds:L.z.number().int().min(0).max(4).default(2),pages:L.z.number().int().min(1).max(2).default(1),includeAllSerpFeatures:L.z.boolean().default(!1),includeLocalPack:L.z.boolean().default(!1),includeForums:L.z.boolean().default(!1),includeVideos:L.z.boolean().default(!1),includeAiOverview:L.z.boolean().default(!1),includeWhatPeopleSaying:L.z.boolean().default(!1),includeShortVideos:L.z.boolean().default(!1),recency:L.z.enum(["day","week","month","year"]).optional(),softDeadlineMs:L.z.number().optional()}),ki=L.z.object({questionId:L.z.string().min(1),googleLinkId:L.z.string().nullable(),googleEvidenceId:L.z.string().nullable(),question:L.z.string().min(1),answer:L.z.string().optional(),answerExpansionIncomplete:L.z.boolean().optional(),sourceTitle:L.z.string().optional(),sourceSite:L.z.string().optional(),sourceCite:L.z.string().optional(),sources:L.z.array(L.z.object({title:L.z.string().nullable(),site:L.z.string().nullable(),description:L.z.string().nullable().optional(),url:L.z.string().min(1),rawUrl:L.z.string().min(1),resolvedUrl:L.z.string().nullable(),linkType:L.z.enum(["plain","google_url_redirect","google_goto_redirect"]),resolutionStatus:L.z.enum(["not_needed","resolved","unresolved","rejected"])})).default([])});function Mi(){return(process.env.BROWSER_SERVICE_API_KEY??process.env.\u004b\u0045\u0052\u004e\u0045\u004c_API_KEY)?.trim()||void 0}var Ut=require("fs"),Wt=gn(require("path"),1),Kt=gn(require("papaparse"),1);async function vi(e){if((process.env.NODE_ENV==="test"||process.env.VITEST)&&process.env.MCP_SCRAPER_ENABLE_MEMORY_LIBRARY_SINK_IN_TESTS!=="1")return;let t=process.env.MCP_SCRAPER_API_KEY?.trim(),n=(process.env.MCP_SCRAPER_BASE_URL??"https://mcpscraper.dev").replace(/\/$/,"");if(t)try{let a=await fetch(`${n}/memory/mcp-call`,{method:"POST",headers:{"content-type":"application/json","x-api-key":t},body:JSON.stringify({toolName:"libraryIngestTool",args:e})}),i=await a.json().catch(()=>null);(!a.ok||i?.ok===!1)&&console.warn("[memory-library-sink] ingest not accepted:",a.status,i?.error??"")}catch(a){console.warn("[memory-library-sink] ingest failed:",a?.message)}}var mn=class{async writeJSON(t,n){await Ut.promises.mkdir(n,{recursive:!0});let i=`${t.seed.toLowerCase().replace(/\W+/g,"-").slice(0,40)}-${Date.now()}.json`,s=Wt.default.join(n,i);return await Ut.promises.writeFile(s,JSON.stringify(t,null,2),"utf8"),await vi({title:`${t.seed} scrape`,content:JSON.stringify(t),source:`mcp-scraper:${s}`}),s}async writeCSV(t,n){await Ut.promises.mkdir(n,{recursive:!0});let i=(t[0]?.seed_query??"paa").toLowerCase().replace(/\W+/g,"-").slice(0,40),s=Kt.default.unparse(t.map(({sources:S,...U})=>({...U,sources_json:JSON.stringify(S)})),{header:!0}),o=`${i}-${Date.now()}.csv`,d=Wt.default.join(n,o);return await Ut.promises.writeFile(d,s,"utf8"),d}async writeVideoCSV(t,n,a){await Ut.promises.mkdir(a,{recursive:!0});let i=n.toLowerCase().replace(/\W+/g,"-").slice(0,40),s=Kt.default.unparse(t,{header:!0}),o=`${i}-videos-${Date.now()}.csv`,d=Wt.default.join(a,o);return await Ut.promises.writeFile(d,s,"utf8"),d}async writeForumCSV(t,n,a){await Ut.promises.mkdir(a,{recursive:!0});let i=n.toLowerCase().replace(/\W+/g,"-").slice(0,40),s=Kt.default.unparse(t,{header:!0}),o=`${i}-forums-${Date.now()}.csv`,d=Wt.default.join(a,o);return await Ut.promises.writeFile(d,s,"utf8"),d}async writeAIOverviewCSV(t,n,a,i){await Ut.promises.mkdir(i,{recursive:!0});let s=a.toLowerCase().replace(/\W+/g,"-").slice(0,40),o=t.map((c,r)=>({seed_query:a,response_text:r===0?n??"":"",citation_text:c.text,citation_href:c.href})),d=Kt.default.unparse(o,{header:!0}),S=`${s}-ai-overview-${Date.now()}.csv`,U=Wt.default.join(i,S);return await Ut.promises.writeFile(U,d,"utf8"),U}async writeAIModeCSV(t,n,a,i){await Ut.promises.mkdir(i,{recursive:!0});let s=a.toLowerCase().replace(/\W+/g,"-").slice(0,40),o=t.map((c,r)=>({seed_query:a,response_text:r===0?n??"":"",citation_text:c.text,citation_href:c.href})),d=Kt.default.unparse(o,{header:!0}),S=`${s}-ai-mode-${Date.now()}.csv`,U=Wt.default.join(i,S);return await Ut.promises.writeFile(U,d,"utf8"),U}async writeWhatPeopleSayingCSV(t,n,a){await Ut.promises.mkdir(a,{recursive:!0});let i=n.toLowerCase().replace(/\W+/g,"-").slice(0,40),s=t.map(U=>({seed_query:n,...U})),o=Kt.default.unparse(s,{header:!0}),d=`${i}-what-people-saying-${Date.now()}.csv`,S=Wt.default.join(a,d);return await Ut.promises.writeFile(S,o,"utf8"),S}};var Ti="Google returned a CAPTCHA. Run with --headless=false to re-warm the browser profile, then retry.";var lr=["request_aborted","captcha_exhausted","captcha_or_blocked","location_mismatch","proxy_tunnel_failed","proxy_unavailable","harvest_timeout","mcp_request_timeout","mcp_http_error","extraction_failed","concurrency_limit_exceeded","unauthorized","forbidden","invalid_request","rate_limited","upstream_rate_limited","insufficient_balance","service_unavailable","response_lost","vendor_unavailable","page_not_found","page_forbidden","page_rate_limited","page_server_error","page_http_error","bot_check_unresolved","page_too_large","page_unreachable","browser_session_interrupted","site_export_not_found","directory_job_not_found","site_export_format_unavailable","site_export_read_failed","site_export_image_not_found","image_url_invalid","image_url_not_https","image_host_unresolvable","image_host_blocked","image_redirect_invalid","image_source_unavailable","image_too_large","image_redirect_limit","image_base64_invalid","image_source_missing","image_source_ambiguous","image_source_type_invalid","image_artifact_not_found","image_page_too_large","page_image_not_found","page_image_candidates_unusable","image_format_unsupported","image_storage_unconfigured","featured_image_unhostable"],Sr=["request_aborted","captcha","location_mismatch","connection","timeout","extraction","concurrency_limit","unauthorized","forbidden","invalid_request","not_found","rate_limit","billing","service_unavailable"];var DS=new Set(lr),GS=new Set(Sr);function bi(e){return e.replace((new RegExp("https?:\\/\\/[^\\s]*(?:\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061|on\u006b\u0065\u0072\u006e\u0065\u006c|\u006b\u0065\u0072\u006e\u0065\u006c\\.sh)[^\\s]*", "gi")),"the service").replace(/bright\s*data/gi,"the service").replace((new RegExp("\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061", "gi")),"the service").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\.sh\\s+sessions?", "gi")),"sessions").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\.sh\\s+session", "gi")),"this session").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\.sh", "gi")),"the service").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\s+sessions?", "gi")),"sessions").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\s+session", "gi")),"this session").replace(/\b(?:sub|cus|sess|proxy)_[A-Za-z0-9_-]+\b/g,"[redacted]").replace((new RegExp("\\b(?:\u004b\u0045\u0052\u004e\u0045\u004c|\u0042\u0052\u0049\u0047\u0048\u0054\u0044\u0041\u0054\u0041|\u0042\u0052\u0049\u0047\u0048\u0054_\u0044\u0041\u0054\u0041)_[A-Z0-9_]*API_KEY\\b", "g")),"BROWSER_SERVICE_API_KEY").replace((new RegExp("\\b\u006b\u0065\u0072\u006e\u0065\u006c\\b", "gi")),"the service").replace(/ +/g," ").trim()}var et=class extends Error{constructor(n){super(`CAPTCHA detected. ${n}`);this.instructions=n}instructions;name="CaptchaError"},ct=class extends Error{constructor(n,a){super(n);this.cause=a}cause;name="ExtractionError"};var ut=class extends Error{name="RequestAbortedError";constructor(t="Request aborted before harvest completed"){super(t)}},Ot=class extends Error{name="PaaInteractionInterruptedError"},ge=class extends Error{name="LocationMismatchError";constructor(t="Google returned results for a different location than requested"){super(t)}};function rt(e,t,n,a,i){if(a==="m")throw new TypeError("Private method is not writable");if(a==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return a==="a"?i.call(e,n):i?i.value=n:t.set(e,n),n}function Q(e,t,n,a){if(n==="a"&&!a)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!a:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?a:n==="a"?a.call(e):a?a.value:t.get(e)}var aa=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return aa=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,a=>(+a^n()&15>>+a/4).toString(16))};function $e(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var je=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};var j=class extends Error{},lt=class e extends j{constructor(t,n,a,i){super(`${e.makeMessage(t,n,a)}`),this.status=t,this.headers=i,this.error=n}static makeMessage(t,n,a){let i=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):a;return t&&i?`${t} ${i}`:t?`${t} status code (no body)`:i||"(no status code or body)"}static generate(t,n,a,i){if(!t||!i)return new Lt({message:a,cause:je(n)});let s=n;return t===400?new we(t,s,a,i):t===401?new pe(t,s,a,i):t===403?new ye(t,s,a,i):t===404?new me(t,s,a,i):t===409?new Ce(t,s,a,i):t===422?new fe(t,s,a,i):t===429?new ke(t,s,a,i):t>=500?new Me(t,s,a,i):new e(t,s,a,i)}},ht=class extends lt{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}},Lt=class extends lt{constructor({message:t,cause:n}){super(void 0,void 0,t||"Connection error.",void 0),n&&(this.cause=n)}},vt=class extends Lt{constructor({message:t}={}){super({message:t??"Request timed out."})}},we=class extends lt{},pe=class extends lt{},ye=class extends lt{},me=class extends lt{},Ce=class extends lt{},fe=class extends lt{},ke=class extends lt{},Me=class extends lt{};var cr=/^[a-z][a-z0-9+.-]*:/i,Ni=e=>cr.test(e),St=e=>(St=Array.isArray,St(e)),ia=St;function sa(e){return typeof e!="object"?{}:e??{}}function oa(e){if(!e)return!0;for(let t in e)return!1;return!0}function Pi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var Ii=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new j(`${e} must be an integer`);if(t<0)throw new j(`${e} must be a positive integer`);return t},ur=e=>{if(typeof e=="number")return Math.round(e);if(typeof e=="string")return parseInt(e,10);throw new j(`Could not coerce ${e} (type: ${typeof e}) into a number`)};var hr=e=>typeof e=="boolean"?e:typeof e=="string"?e==="true":!!e,Ai=e=>{if(e!=null)return ur(e)};var ra=e=>{if(e!=null)return hr(e)},xi=e=>{try{return JSON.parse(e)}catch{return}};var Wi=e=>new Promise(t=>setTimeout(t,e));var Bt="0.93.0";function gr(){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 wr=()=>{let e=gr();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bt,"X-Stainless-OS":Li(Deno.build.os),"X-Stainless-Arch":Oi(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":Bt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bt,"X-Stainless-OS":Li(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Oi(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=pr();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function pr(){if(typeof navigator>"u"||!navigator)return null;let e=[{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:t,pattern:n}of e){let a=n.exec(navigator.userAgent);if(a){let i=a[1]||0,s=a[2]||0,o=a[3]||0;return{browser:t,version:`${i}.${s}.${o}`}}}return null}var Oi=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",Li=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),Bi,Ri=()=>Bi??(Bi=wr());function Ei(){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 da(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Cn(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return da({start(){},async pull(n){let{done:a,value:i}=await t.next();a?n.close():n.enqueue(i)},async cancel(){await t.return?.()}})}function la(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let n=await t.read();return n?.done&&t.releaseLock(),n}catch(n){throw t.releaseLock(),n}},async return(){let n=t.cancel();return t.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Hi(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var Fi=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});var Sa="RFC3986",Ua=e=>String(e),ca={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:Ua},_i="RFC1738";var fn=(e,t)=>(fn=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),fn(e,t)),kt=(()=>{let e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})();var ua=1024,Di=(e,t,n,a,i)=>{if(e.length===0)return e;let s=e;if(typeof e=="symbol"?s=Symbol.prototype.toString.call(e):typeof e!="string"&&(s=String(e)),n==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(d){return"%26%23"+parseInt(d.slice(2),16)+"%3B"});let o="";for(let d=0;d<s.length;d+=ua){let S=s.length>=ua?s.slice(d,d+ua):s,U=[];for(let c=0;c<S.length;++c){let r=S.charCodeAt(c);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===_i&&(r===40||r===41)){U[U.length]=S.charAt(c);continue}if(r<128){U[U.length]=kt[r];continue}if(r<2048){U[U.length]=kt[192|r>>6]+kt[128|r&63];continue}if(r<55296||r>=57344){U[U.length]=kt[224|r>>12]+kt[128|r>>6&63]+kt[128|r&63];continue}c+=1,r=65536+((r&1023)<<10|S.charCodeAt(c)&1023),U[U.length]=kt[240|r>>18]+kt[128|r>>12&63]+kt[128|r>>6&63]+kt[128|r&63]}o+=U.join("")}return o};function Gi(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function ha(e,t){if(St(e)){let n=[];for(let a=0;a<e.length;a+=1)n.push(t(e[a]));return n}return t(e)}var Ki={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},Yi=function(e,t){Array.prototype.push.apply(e,St(t)?t:[t])},Vi,st={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Di,encodeValuesOnly:!1,format:Sa,formatter:Ua,indices:!1,serializeDate(e){return(Vi??(Vi=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function Cr(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}var ga={};function Ji(e,t,n,a,i,s,o,d,S,U,c,r,l,u,h,w,g,C){let y=e,m=C,O=0,F=!1;for(;(m=m.get(ga))!==void 0&&!F;){let b=m.get(e);if(O+=1,typeof b<"u"){if(b===O)throw new RangeError("Cyclic object value");F=!0}typeof m.get(ga)>"u"&&(O=0)}if(typeof U=="function"?y=U(t,y):y instanceof Date?y=l?.(y):n==="comma"&&St(y)&&(y=ha(y,function(b){return b instanceof Date?l?.(b):b})),y===null){if(s)return S&&!w?S(t,st.encoder,g,"key",u):t;y=""}if(Cr(y)||Gi(y)){if(S){let b=w?t:S(t,st.encoder,g,"key",u);return[h?.(b)+"="+h?.(S(y,st.encoder,g,"value",u))]}return[h?.(t)+"="+h?.(String(y))]}let B=[];if(typeof y>"u")return B;let I;if(n==="comma"&&St(y))w&&S&&(y=ha(y,S)),I=[{value:y.length>0?y.join(",")||null:void 0}];else if(St(U))I=U;else{let b=Object.keys(y);I=c?b.sort(c):b}let K=d?String(t).replace(/\./g,"%2E"):String(t),D=a&&St(y)&&y.length===1?K+"[]":K;if(i&&St(y)&&y.length===0)return D+"[]";for(let b=0;b<I.length;++b){let k=I[b],A=typeof k=="object"&&typeof k.value<"u"?k.value:y[k];if(o&&A===null)continue;let T=r&&d?k.replace(/\./g,"%2E"):k,M=St(y)?typeof n=="function"?n(D,T):D:D+(r?"."+T:"["+T+"]");C.set(e,O);let q=new WeakMap;q.set(ga,C),Yi(B,Ji(A,M,n,a,i,s,o,d,n==="comma"&&w&&St(y)?null:S,U,c,r,l,u,h,w,g,q))}return B}function fr(e=st){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!="function")throw new TypeError("Encoder has to be a function.");let t=e.charset||st.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=Sa;if(typeof e.format<"u"){if(!fn(ca,e.format))throw new TypeError("Unknown format option provided.");n=e.format}let a=ca[n],i=st.filter;(typeof e.filter=="function"||St(e.filter))&&(i=e.filter);let s;if(e.arrayFormat&&e.arrayFormat in Ki?s=e.arrayFormat:"indices"in e?s=e.indices?"indices":"repeat":s=st.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let o=typeof e.allowDots>"u"?e.encodeDotInKeys?!0:st.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:st.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:st.allowEmptyArrays,arrayFormat:s,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:st.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?st.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:st.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:st.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:st.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:st.encodeValuesOnly,filter:i,format:n,formatter:a,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:st.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:st.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:st.strictNullHandling}}function qi(e,t={}){let n=e,a=fr(t),i,s;typeof a.filter=="function"?(s=a.filter,n=s("",n)):St(a.filter)&&(s=a.filter,i=s);let o=[];if(typeof n!="object"||n===null)return"";let d=Ki[a.arrayFormat],S=d==="comma"&&a.commaRoundTrip;i||(i=Object.keys(n)),a.sort&&i.sort(a.sort);let U=new WeakMap;for(let l=0;l<i.length;++l){let u=i[l];a.skipNulls&&n[u]===null||Yi(o,Ji(n[u],u,d,S,a.allowEmptyArrays,a.strictNullHandling,a.skipNulls,a.encodeDotInKeys,a.encode?a.encoder:null,a.filter,a.sort,a.allowDots,a.serializeDate,a.format,a.formatter,a.encodeValuesOnly,a.charset,U))}let c=o.join(a.delimiter),r=a.addQueryPrefix===!0?"?":"";return a.charsetSentinel&&(a.charset==="iso-8859-1"?r+="utf8=%26%2310003%3B&":r+="utf8=%E2%9C%93&"),c.length>0?r+c:""}function zi(e){return qi(e,{arrayFormat:"comma"})}function Qi(e){let t=0;for(let i of e)t+=i.length;let n=new Uint8Array(t),a=0;for(let i of e)n.set(i,a),a+=i.length;return n}var $i;function Qe(e){let t;return($i??(t=new globalThis.TextEncoder,$i=t.encode.bind(t)))(e)}var ji;function wa(e){let t;return(ji??(t=new globalThis.TextDecoder,ji=t.decode.bind(t)))(e)}var yt,mt,Yt=class{constructor(){yt.set(this,void 0),mt.set(this,void 0),rt(this,yt,new Uint8Array,"f"),rt(this,mt,null,"f")}decode(t){if(t==null)return[];let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Qe(t):t;rt(this,yt,Qi([Q(this,yt,"f"),n]),"f");let a=[],i;for(;(i=Mr(Q(this,yt,"f"),Q(this,mt,"f")))!=null;){if(i.carriage&&Q(this,mt,"f")==null){rt(this,mt,i.index,"f");continue}if(Q(this,mt,"f")!=null&&(i.index!==Q(this,mt,"f")+1||i.carriage)){a.push(wa(Q(this,yt,"f").subarray(0,Q(this,mt,"f")-1))),rt(this,yt,Q(this,yt,"f").subarray(Q(this,mt,"f")),"f"),rt(this,mt,null,"f");continue}let s=Q(this,mt,"f")!==null?i.preceding-1:i.preceding,o=wa(Q(this,yt,"f").subarray(0,s));a.push(o),rt(this,yt,Q(this,yt,"f").subarray(i.index),"f"),rt(this,mt,null,"f")}return a}flush(){return Q(this,yt,"f").length?this.decode(`
1
+ "use strict";var qo=Object.create;var hn=Object.defineProperty;var zo=Object.getOwnPropertyDescriptor;var $o=Object.getOwnPropertyNames;var jo=Object.getPrototypeOf,Qo=Object.prototype.hasOwnProperty;var Xo=(e,t)=>{for(var n in t)hn(e,n,{get:t[n],enumerable:!0})},ui=(e,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of $o(t))!Qo.call(e,i)&&i!==n&&hn(e,i,{get:()=>t[i],enumerable:!(a=zo(t,i))||a.enumerable});return e};var gn=(e,t,n)=>(n=e!=null?qo(jo(e)):{},ui(t||!e||!e.__esModule?hn(n,"default",{value:e,enumerable:!0}):n,e)),Zo=e=>ui(hn({},"__esModule",{value:!0}),e);var hS={};Xo(hS,{VideoGenerator:()=>jn,buildClipPrompts:()=>Yn,harvest:()=>Bo});module.exports=Zo(hS);var At=class extends Error{constructor(t,n){super(`SERP provider mismatch: planned ${t}, observed ${n}`),this.name="SerpProviderMismatchError"}};function pn(e){return e==="\u0062\u0072\u0069\u0067\u0068\u0074_\u0064\u0061\u0074\u0061_browser_api"?"\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061":"\u006b\u0065\u0072\u006e\u0065\u006c"}function hi(e){return tr({intent:e.intent,\u0062\u0072\u0069\u0067\u0068\u0074\u0044\u0061\u0074\u0061Available:e.\u0062\u0072\u0069\u0067\u0068\u0074\u0044\u0061\u0074\u0061Available,\u006b\u0065\u0072\u006e\u0065\u006cAvailable:!0,persistent\u004b\u0065\u0072\u006e\u0065\u006cIdentityRequested:e.persistent\u004b\u0065\u0072\u006e\u0065\u006cIdentityRequested,retryIndex:e.retryIndex,priorTerminalReason:e.priorTerminalReason,allowedFallbacks:e.\u006b\u0065\u0072\u006e\u0065\u006cFallbackAvailable&&e.intent!=="\u006b\u0065\u0072\u006e\u0065\u006c"?["\u006b\u0065\u0072\u006e\u0065\u006c"]:[],timeoutMs:e.softDeadlineMs==null?4e5:Math.max(1,e.softDeadlineMs-Date.now())})}function gi(e){if(e.forceManagedSerp&&e.force\u004b\u0065\u0072\u006e\u0065\u006cSerp)throw new Error("forceManagedSerp and force\u004b\u0065\u0072\u006e\u0065\u006cSerp cannot both be true");return e.forceManagedSerp?"\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061":e.force\u004b\u0065\u0072\u006e\u0065\u006cSerp?"\u006b\u0065\u0072\u006e\u0065\u006c":"auto"}function wn(e,t){if(!t)throw new Error(`Requested SERP provider is unavailable: ${e}`);return e}function tr(e){if(!Number.isInteger(e.retryIndex)||e.retryIndex<0)throw new Error("retryIndex must be a non-negative integer");if(!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0)throw new Error("timeoutMs must be a positive number");let t,n;e.intent==="\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061"?(t=wn("\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061",e.\u0062\u0072\u0069\u0067\u0068\u0074\u0044\u0061\u0074\u0061Available),n="explicit_\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061"):e.intent==="\u006b\u0065\u0072\u006e\u0065\u006c"?(t=wn("\u006b\u0065\u0072\u006e\u0065\u006c",e.\u006b\u0065\u0072\u006e\u0065\u006cAvailable),n="explicit_\u006b\u0065\u0072\u006e\u0065\u006c"):e.persistent\u004b\u0065\u0072\u006e\u0065\u006cIdentityRequested?(t=wn("\u006b\u0065\u0072\u006e\u0065\u006c",e.\u006b\u0065\u0072\u006e\u0065\u006cAvailable),n="persistent_\u006b\u0065\u0072\u006e\u0065\u006c_identity"):e.\u0062\u0072\u0069\u0067\u0068\u0074\u0044\u0061\u0074\u0061Available?(t="\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061",n="managed_default"):(t=wn("\u006b\u0065\u0072\u006e\u0065\u006c",e.\u006b\u0065\u0072\u006e\u0065\u006cAvailable),n="\u006b\u0065\u0072\u006e\u0065\u006c_default");let a=e.allowedFallbacks.find(o=>o!==t&&(o==="\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061"?e.\u0062\u0072\u0069\u0067\u0068\u0074\u0044\u0061\u0074\u0061Available:e.\u006b\u0065\u0072\u006e\u0065\u006cAvailable)),i=e.retryIndex>0&&a?a:t,s=e.retryIndex===0?"primary":i===t?"same_provider_retry":"provider_fallback";return Object.freeze({plannedProvider:i,attemptKind:s,reasonCode:s==="primary"?n:s==="provider_fallback"?"provider_fallback":"same_provider_retry",retryIndex:e.retryIndex,priorTerminalReason:e.priorTerminalReason??null,timeoutMs:Math.floor(e.timeoutMs),fallbackAllowed:!!a})}function er(e,t){if(typeof e!="string")return null;let n=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();return n?n.slice(0,t):null}function wi(e){let t=er(e,320);return t?t.replace(/\b(?:wss?|https?):\/\/\S+/gi,"[redacted endpoint]").replace(/\b(?:authorization|proxy-authorization):\s*\S+/gi,"$1: [redacted]").replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").slice(0,320):null}function xt(e){return wi(e)}function pi(e){if(typeof e!="string"||e.length===0||e.length>512||e.trim()!==e||/[\s\u0000-\u001f\u007f]/.test(e)||/:\/\//.test(e))throw new Error("\u0042\u0072\u0069\u0067\u0068\u0074 \u0044\u0061\u0074\u0061 did not return a valid browser session ID");return e}function Qn(e,t,n=new Date().toISOString()){let a=wi(t);return{source:e,message:a??e.replaceAll("_"," "),observedAt:n}}function nr(e){return{provider:e.provider,providerDisconnectObserved:e.disconnectObservation!==null,providerDisconnectMessage:e.disconnectObservation?.message??null}}function yi(e){return{...nr(e),providerSessionId:e.providerSessionId}}function mi(e,t,n,a){return new Proxy(e,{get(i,s,o){if(s==="launch")return async S=>{await t.start(n,"browser"),await i.launch(S);let U=i.getProviderSessionMetadata();if(await t.resource(n,"browser",U.providerSessionId,U.provider),!U.providerSessionId)throw new Error("Browser connection returned no attributable session identity");if(pn(U.provider)!==a)throw new At(a,U.provider);await t.assertActive(n)};let d=Reflect.get(i,s,o);return typeof d=="function"?d.bind(i):d}})}function Xn(e,t,n,a=null){let i=n.\u006b\u0065\u0072\u006e\u0065\u006cSessionId??n.providerSessionId??null,s=n.\u006b\u0065\u0072\u006e\u0065\u006cSessionId!=null?n.\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded===!0:n.physicalOutcome==="terminated",o=n.browserCloseSucceeded===!0&&n.localDisconnectSucceeded!==!1&&s,d=n.physicalOutcome==="not_started"&&n.browserCloseSucceeded===null,S={drained:n.extractionDrained===!0,effects:{browser:{resourceId:i,state:o?"terminated":d?"not_started":"unknown"},proxy:{resourceId:a,state:n.disposableProxyDeleted===!0?a===null?"not_started":"terminated":"unknown"}},details:{browserCloseSucceeded:n.browserCloseSucceeded??null,localDisconnectSucceeded:n.localDisconnectSucceeded??null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:n.\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded??null,browserCloseError:xt(n.browserCloseError),\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:xt(n.\u006b\u0065\u0072\u006e\u0065\u006cDeleteError),localDisconnectError:xt(n.localDisconnectError)}};return e.complete(t,S)}var or=require("crypto");var Ci=require("@libsql/client/http"),ar=process.env.TURSO_DATABASE_URL??"file:./paa-api.db",ir=process.env.TURSO_AUTH_TOKEN,Zn=null;function ze(){return Zn||(Zn=(0,Ci.createClient)({url:ar,authToken:ir})),Zn}var sr=require("crypto");var ta=class extends Error{constructor(){super("physical_permission_or_receipt_unknown"),this.name="PhysicalPermissionError"}},rr=new WeakSet;function fi(e){let t=e&&typeof e=="object"?e.physicalExecution:void 0;if(t!==void 0){if(!t||typeof t!="object"||!rr.has(t))throw new ta;return t}}var yn="none";function ea(e){switch(e){case"day":return"qdr:d";case"week":return"qdr:w";case"month":return"qdr:m";case"year":return"qdr:y";default:return}}var L=require("zod");var na=L.z.object({query:L.z.string().min(1),location:L.z.string().optional(),gl:L.z.string().length(2).default("us"),hl:L.z.string().length(2).default("en"),device:L.z.enum(["desktop","mobile"]).default("desktop"),proxyMode:L.z.enum(["location","configured","none"]).default(yn),proxyZip:L.z.string().regex(/^\d{5}$/).optional(),keepDefaultProxy:L.z.boolean().optional(),requireUsEgress:L.z.boolean().optional(),maxAttempts:L.z.number().int().min(1).max(12).optional(),debug:L.z.boolean().default(!1),depth:L.z.number().int().min(1).max(30).default(3),maxQuestions:L.z.number().int().min(1).max(100).default(100),headless:L.z.boolean().default(!1),profileDir:L.z.string().optional(),proxy:L.z.string().url().optional(),\u006b\u0065\u0072\u006e\u0065\u006cApiKey:L.z.string().optional(),\u006b\u0065\u0072\u006e\u0065\u006cProxyId:L.z.string().optional(),\u006b\u0065\u0072\u006e\u0065\u006cProfileName:L.z.string().optional(),\u006b\u0065\u0072\u006e\u0065\u006cProfileSaveChanges:L.z.boolean().optional(),\u006b\u0065\u0072\u006e\u0065\u006cStealth:L.z.boolean().optional(),serpIdentity:L.z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/).optional(),\u006b\u0065\u0072\u006e\u0065\u006cProxyResolution:L.z.unknown().optional(),outputDir:L.z.string().default("./paa-output"),format:L.z.enum(["json","csv","both"]).default("both"),serpOnly:L.z.boolean().default(!1),questionsOnly:L.z.boolean().default(!1),questionGrowthRecoveryRounds:L.z.number().int().min(0).max(4).default(2),pages:L.z.number().int().min(1).max(2).default(1),includeAllSerpFeatures:L.z.boolean().default(!1),includeLocalPack:L.z.boolean().default(!1),includeForums:L.z.boolean().default(!1),includeVideos:L.z.boolean().default(!1),includeAiOverview:L.z.boolean().default(!1),includeWhatPeopleSaying:L.z.boolean().default(!1),includeShortVideos:L.z.boolean().default(!1),recency:L.z.enum(["day","week","month","year"]).optional(),softDeadlineMs:L.z.number().optional()}),ki=L.z.object({questionId:L.z.string().min(1),googleLinkId:L.z.string().nullable(),googleEvidenceId:L.z.string().nullable(),question:L.z.string().min(1),answer:L.z.string().optional(),answerExpansionIncomplete:L.z.boolean().optional(),sourceTitle:L.z.string().optional(),sourceSite:L.z.string().optional(),sourceCite:L.z.string().optional(),sources:L.z.array(L.z.object({title:L.z.string().nullable(),site:L.z.string().nullable(),description:L.z.string().nullable().optional(),url:L.z.string().min(1),rawUrl:L.z.string().min(1),resolvedUrl:L.z.string().nullable(),linkType:L.z.enum(["plain","google_url_redirect","google_goto_redirect"]),resolutionStatus:L.z.enum(["not_needed","resolved","unresolved","rejected"])})).default([])});function Mi(){return(process.env.BROWSER_SERVICE_API_KEY??process.env.\u004b\u0045\u0052\u004e\u0045\u004c_API_KEY)?.trim()||void 0}var Ut=require("fs"),Wt=gn(require("path"),1),Kt=gn(require("papaparse"),1);async function vi(e){if((process.env.NODE_ENV==="test"||process.env.VITEST)&&process.env.MCP_SCRAPER_ENABLE_MEMORY_LIBRARY_SINK_IN_TESTS!=="1")return;let t=process.env.MCP_SCRAPER_API_KEY?.trim(),n=(process.env.MCP_SCRAPER_BASE_URL??"https://mcpscraper.dev").replace(/\/$/,"");if(t)try{let a=await fetch(`${n}/memory/mcp-call`,{method:"POST",headers:{"content-type":"application/json","x-api-key":t},body:JSON.stringify({toolName:"libraryIngestTool",args:e})}),i=await a.json().catch(()=>null);(!a.ok||i?.ok===!1)&&console.warn("[memory-library-sink] ingest not accepted:",a.status,i?.error??"")}catch(a){console.warn("[memory-library-sink] ingest failed:",a?.message)}}var mn=class{async writeJSON(t,n){await Ut.promises.mkdir(n,{recursive:!0});let i=`${t.seed.toLowerCase().replace(/\W+/g,"-").slice(0,40)}-${Date.now()}.json`,s=Wt.default.join(n,i);return await Ut.promises.writeFile(s,JSON.stringify(t,null,2),"utf8"),await vi({title:`${t.seed} scrape`,content:JSON.stringify(t),source:`mcp-scraper:${s}`}),s}async writeCSV(t,n){await Ut.promises.mkdir(n,{recursive:!0});let i=(t[0]?.seed_query??"paa").toLowerCase().replace(/\W+/g,"-").slice(0,40),s=Kt.default.unparse(t.map(({sources:S,...U})=>({...U,sources_json:JSON.stringify(S)})),{header:!0}),o=`${i}-${Date.now()}.csv`,d=Wt.default.join(n,o);return await Ut.promises.writeFile(d,s,"utf8"),d}async writeVideoCSV(t,n,a){await Ut.promises.mkdir(a,{recursive:!0});let i=n.toLowerCase().replace(/\W+/g,"-").slice(0,40),s=Kt.default.unparse(t,{header:!0}),o=`${i}-videos-${Date.now()}.csv`,d=Wt.default.join(a,o);return await Ut.promises.writeFile(d,s,"utf8"),d}async writeForumCSV(t,n,a){await Ut.promises.mkdir(a,{recursive:!0});let i=n.toLowerCase().replace(/\W+/g,"-").slice(0,40),s=Kt.default.unparse(t,{header:!0}),o=`${i}-forums-${Date.now()}.csv`,d=Wt.default.join(a,o);return await Ut.promises.writeFile(d,s,"utf8"),d}async writeAIOverviewCSV(t,n,a,i){await Ut.promises.mkdir(i,{recursive:!0});let s=a.toLowerCase().replace(/\W+/g,"-").slice(0,40),o=t.map((c,r)=>({seed_query:a,response_text:r===0?n??"":"",citation_text:c.text,citation_href:c.href})),d=Kt.default.unparse(o,{header:!0}),S=`${s}-ai-overview-${Date.now()}.csv`,U=Wt.default.join(i,S);return await Ut.promises.writeFile(U,d,"utf8"),U}async writeAIModeCSV(t,n,a,i){await Ut.promises.mkdir(i,{recursive:!0});let s=a.toLowerCase().replace(/\W+/g,"-").slice(0,40),o=t.map((c,r)=>({seed_query:a,response_text:r===0?n??"":"",citation_text:c.text,citation_href:c.href})),d=Kt.default.unparse(o,{header:!0}),S=`${s}-ai-mode-${Date.now()}.csv`,U=Wt.default.join(i,S);return await Ut.promises.writeFile(U,d,"utf8"),U}async writeWhatPeopleSayingCSV(t,n,a){await Ut.promises.mkdir(a,{recursive:!0});let i=n.toLowerCase().replace(/\W+/g,"-").slice(0,40),s=t.map(U=>({seed_query:n,...U})),o=Kt.default.unparse(s,{header:!0}),d=`${i}-what-people-saying-${Date.now()}.csv`,S=Wt.default.join(a,d);return await Ut.promises.writeFile(S,o,"utf8"),S}};var Ti="Google returned a CAPTCHA. Run with --headless=false to re-warm the browser profile, then retry.";var lr=["request_aborted","captcha_exhausted","captcha_or_blocked","location_mismatch","proxy_tunnel_failed","proxy_unavailable","harvest_timeout","mcp_request_timeout","mcp_http_error","extraction_failed","concurrency_limit_exceeded","unauthorized","forbidden","invalid_request","rate_limited","upstream_rate_limited","insufficient_balance","service_unavailable","response_lost","vendor_unavailable","page_not_found","page_forbidden","page_rate_limited","page_server_error","page_http_error","bot_check_unresolved","page_too_large","page_unreachable","browser_session_interrupted","site_export_not_found","directory_job_not_found","site_export_format_unavailable","site_export_read_failed","site_export_image_not_found","image_url_invalid","image_url_not_https","image_host_unresolvable","image_host_blocked","image_redirect_invalid","image_source_unavailable","image_too_large","image_redirect_limit","image_base64_invalid","image_source_missing","image_source_ambiguous","image_source_type_invalid","image_artifact_not_found","image_page_too_large","page_image_not_found","page_image_candidates_unusable","image_format_unsupported","image_storage_unconfigured","featured_image_unhostable"],Sr=["request_aborted","captcha","location_mismatch","connection","timeout","extraction","concurrency_limit","unauthorized","forbidden","invalid_request","not_found","rate_limit","billing","service_unavailable"];var _S=new Set(lr),GS=new Set(Sr);function bi(e){return e.replace((new RegExp("https?:\\/\\/[^\\s]*(?:\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061|on\u006b\u0065\u0072\u006e\u0065\u006c|\u006b\u0065\u0072\u006e\u0065\u006c\\.sh)[^\\s]*", "gi")),"the service").replace(/bright\s*data/gi,"the service").replace((new RegExp("\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061", "gi")),"the service").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\.sh\\s+sessions?", "gi")),"sessions").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\.sh\\s+session", "gi")),"this session").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\.sh", "gi")),"the service").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\s+sessions?", "gi")),"sessions").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\s+session", "gi")),"this session").replace(/\b(?:sub|cus|sess|proxy)_[A-Za-z0-9_-]+\b/g,"[redacted]").replace((new RegExp("\\b(?:\u004b\u0045\u0052\u004e\u0045\u004c|\u0042\u0052\u0049\u0047\u0048\u0054\u0044\u0041\u0054\u0041|\u0042\u0052\u0049\u0047\u0048\u0054_\u0044\u0041\u0054\u0041)_[A-Z0-9_]*API_KEY\\b", "g")),"BROWSER_SERVICE_API_KEY").replace((new RegExp("\\b\u006b\u0065\u0072\u006e\u0065\u006c\\b", "gi")),"the service").replace(/ +/g," ").trim()}var et=class extends Error{constructor(n){super(`CAPTCHA detected. ${n}`);this.instructions=n}instructions;name="CaptchaError"},ct=class extends Error{constructor(n,a){super(n);this.cause=a}cause;name="ExtractionError"};var ut=class extends Error{name="RequestAbortedError";constructor(t="Request aborted before harvest completed"){super(t)}},Ot=class extends Error{name="PaaInteractionInterruptedError"},ge=class extends Error{name="LocationMismatchError";constructor(t="Google returned results for a different location than requested"){super(t)}};function rt(e,t,n,a,i){if(a==="m")throw new TypeError("Private method is not writable");if(a==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return a==="a"?i.call(e,n):i?i.value=n:t.set(e,n),n}function Q(e,t,n,a){if(n==="a"&&!a)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!a:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?a:n==="a"?a.call(e):a?a.value:t.get(e)}var aa=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return aa=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,a=>(+a^n()&15>>+a/4).toString(16))};function $e(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var je=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};var j=class extends Error{},lt=class e extends j{constructor(t,n,a,i){super(`${e.makeMessage(t,n,a)}`),this.status=t,this.headers=i,this.error=n}static makeMessage(t,n,a){let i=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):a;return t&&i?`${t} ${i}`:t?`${t} status code (no body)`:i||"(no status code or body)"}static generate(t,n,a,i){if(!t||!i)return new Lt({message:a,cause:je(n)});let s=n;return t===400?new we(t,s,a,i):t===401?new pe(t,s,a,i):t===403?new ye(t,s,a,i):t===404?new me(t,s,a,i):t===409?new Ce(t,s,a,i):t===422?new fe(t,s,a,i):t===429?new ke(t,s,a,i):t>=500?new Me(t,s,a,i):new e(t,s,a,i)}},ht=class extends lt{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}},Lt=class extends lt{constructor({message:t,cause:n}){super(void 0,void 0,t||"Connection error.",void 0),n&&(this.cause=n)}},vt=class extends Lt{constructor({message:t}={}){super({message:t??"Request timed out."})}},we=class extends lt{},pe=class extends lt{},ye=class extends lt{},me=class extends lt{},Ce=class extends lt{},fe=class extends lt{},ke=class extends lt{},Me=class extends lt{};var cr=/^[a-z][a-z0-9+.-]*:/i,Ni=e=>cr.test(e),St=e=>(St=Array.isArray,St(e)),ia=St;function sa(e){return typeof e!="object"?{}:e??{}}function oa(e){if(!e)return!0;for(let t in e)return!1;return!0}function Pi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var Ii=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new j(`${e} must be an integer`);if(t<0)throw new j(`${e} must be a positive integer`);return t},ur=e=>{if(typeof e=="number")return Math.round(e);if(typeof e=="string")return parseInt(e,10);throw new j(`Could not coerce ${e} (type: ${typeof e}) into a number`)};var hr=e=>typeof e=="boolean"?e:typeof e=="string"?e==="true":!!e,Ai=e=>{if(e!=null)return ur(e)};var ra=e=>{if(e!=null)return hr(e)},xi=e=>{try{return JSON.parse(e)}catch{return}};var Wi=e=>new Promise(t=>setTimeout(t,e));var Bt="0.93.0";function gr(){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 wr=()=>{let e=gr();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bt,"X-Stainless-OS":Li(Deno.build.os),"X-Stainless-Arch":Oi(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":Bt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bt,"X-Stainless-OS":Li(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Oi(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=pr();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Bt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function pr(){if(typeof navigator>"u"||!navigator)return null;let e=[{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:t,pattern:n}of e){let a=n.exec(navigator.userAgent);if(a){let i=a[1]||0,s=a[2]||0,o=a[3]||0;return{browser:t,version:`${i}.${s}.${o}`}}}return null}var Oi=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",Li=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),Bi,Ri=()=>Bi??(Bi=wr());function Ei(){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 da(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Cn(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return da({start(){},async pull(n){let{done:a,value:i}=await t.next();a?n.close():n.enqueue(i)},async cancel(){await t.return?.()}})}function la(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let n=await t.read();return n?.done&&t.releaseLock(),n}catch(n){throw t.releaseLock(),n}},async return(){let n=t.cancel();return t.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Hi(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var Fi=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});var Sa="RFC3986",Ua=e=>String(e),ca={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:Ua},Di="RFC1738";var fn=(e,t)=>(fn=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),fn(e,t)),kt=(()=>{let e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})();var ua=1024,_i=(e,t,n,a,i)=>{if(e.length===0)return e;let s=e;if(typeof e=="symbol"?s=Symbol.prototype.toString.call(e):typeof e!="string"&&(s=String(e)),n==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(d){return"%26%23"+parseInt(d.slice(2),16)+"%3B"});let o="";for(let d=0;d<s.length;d+=ua){let S=s.length>=ua?s.slice(d,d+ua):s,U=[];for(let c=0;c<S.length;++c){let r=S.charCodeAt(c);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===Di&&(r===40||r===41)){U[U.length]=S.charAt(c);continue}if(r<128){U[U.length]=kt[r];continue}if(r<2048){U[U.length]=kt[192|r>>6]+kt[128|r&63];continue}if(r<55296||r>=57344){U[U.length]=kt[224|r>>12]+kt[128|r>>6&63]+kt[128|r&63];continue}c+=1,r=65536+((r&1023)<<10|S.charCodeAt(c)&1023),U[U.length]=kt[240|r>>18]+kt[128|r>>12&63]+kt[128|r>>6&63]+kt[128|r&63]}o+=U.join("")}return o};function Gi(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function ha(e,t){if(St(e)){let n=[];for(let a=0;a<e.length;a+=1)n.push(t(e[a]));return n}return t(e)}var Ki={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},Yi=function(e,t){Array.prototype.push.apply(e,St(t)?t:[t])},Vi,st={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:_i,encodeValuesOnly:!1,format:Sa,formatter:Ua,indices:!1,serializeDate(e){return(Vi??(Vi=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function Cr(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}var ga={};function Ji(e,t,n,a,i,s,o,d,S,U,c,r,l,u,h,w,g,C){let y=e,m=C,O=0,F=!1;for(;(m=m.get(ga))!==void 0&&!F;){let b=m.get(e);if(O+=1,typeof b<"u"){if(b===O)throw new RangeError("Cyclic object value");F=!0}typeof m.get(ga)>"u"&&(O=0)}if(typeof U=="function"?y=U(t,y):y instanceof Date?y=l?.(y):n==="comma"&&St(y)&&(y=ha(y,function(b){return b instanceof Date?l?.(b):b})),y===null){if(s)return S&&!w?S(t,st.encoder,g,"key",u):t;y=""}if(Cr(y)||Gi(y)){if(S){let b=w?t:S(t,st.encoder,g,"key",u);return[h?.(b)+"="+h?.(S(y,st.encoder,g,"value",u))]}return[h?.(t)+"="+h?.(String(y))]}let B=[];if(typeof y>"u")return B;let I;if(n==="comma"&&St(y))w&&S&&(y=ha(y,S)),I=[{value:y.length>0?y.join(",")||null:void 0}];else if(St(U))I=U;else{let b=Object.keys(y);I=c?b.sort(c):b}let K=d?String(t).replace(/\./g,"%2E"):String(t),_=a&&St(y)&&y.length===1?K+"[]":K;if(i&&St(y)&&y.length===0)return _+"[]";for(let b=0;b<I.length;++b){let k=I[b],A=typeof k=="object"&&typeof k.value<"u"?k.value:y[k];if(o&&A===null)continue;let T=r&&d?k.replace(/\./g,"%2E"):k,M=St(y)?typeof n=="function"?n(_,T):_:_+(r?"."+T:"["+T+"]");C.set(e,O);let q=new WeakMap;q.set(ga,C),Yi(B,Ji(A,M,n,a,i,s,o,d,n==="comma"&&w&&St(y)?null:S,U,c,r,l,u,h,w,g,q))}return B}function fr(e=st){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!="function")throw new TypeError("Encoder has to be a function.");let t=e.charset||st.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=Sa;if(typeof e.format<"u"){if(!fn(ca,e.format))throw new TypeError("Unknown format option provided.");n=e.format}let a=ca[n],i=st.filter;(typeof e.filter=="function"||St(e.filter))&&(i=e.filter);let s;if(e.arrayFormat&&e.arrayFormat in Ki?s=e.arrayFormat:"indices"in e?s=e.indices?"indices":"repeat":s=st.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let o=typeof e.allowDots>"u"?e.encodeDotInKeys?!0:st.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:st.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:st.allowEmptyArrays,arrayFormat:s,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:st.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?st.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:st.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:st.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:st.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:st.encodeValuesOnly,filter:i,format:n,formatter:a,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:st.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:st.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:st.strictNullHandling}}function qi(e,t={}){let n=e,a=fr(t),i,s;typeof a.filter=="function"?(s=a.filter,n=s("",n)):St(a.filter)&&(s=a.filter,i=s);let o=[];if(typeof n!="object"||n===null)return"";let d=Ki[a.arrayFormat],S=d==="comma"&&a.commaRoundTrip;i||(i=Object.keys(n)),a.sort&&i.sort(a.sort);let U=new WeakMap;for(let l=0;l<i.length;++l){let u=i[l];a.skipNulls&&n[u]===null||Yi(o,Ji(n[u],u,d,S,a.allowEmptyArrays,a.strictNullHandling,a.skipNulls,a.encodeDotInKeys,a.encode?a.encoder:null,a.filter,a.sort,a.allowDots,a.serializeDate,a.format,a.formatter,a.encodeValuesOnly,a.charset,U))}let c=o.join(a.delimiter),r=a.addQueryPrefix===!0?"?":"";return a.charsetSentinel&&(a.charset==="iso-8859-1"?r+="utf8=%26%2310003%3B&":r+="utf8=%E2%9C%93&"),c.length>0?r+c:""}function zi(e){return qi(e,{arrayFormat:"comma"})}function Qi(e){let t=0;for(let i of e)t+=i.length;let n=new Uint8Array(t),a=0;for(let i of e)n.set(i,a),a+=i.length;return n}var $i;function Qe(e){let t;return($i??(t=new globalThis.TextEncoder,$i=t.encode.bind(t)))(e)}var ji;function wa(e){let t;return(ji??(t=new globalThis.TextDecoder,ji=t.decode.bind(t)))(e)}var yt,mt,Yt=class{constructor(){yt.set(this,void 0),mt.set(this,void 0),rt(this,yt,new Uint8Array,"f"),rt(this,mt,null,"f")}decode(t){if(t==null)return[];let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Qe(t):t;rt(this,yt,Qi([Q(this,yt,"f"),n]),"f");let a=[],i;for(;(i=Mr(Q(this,yt,"f"),Q(this,mt,"f")))!=null;){if(i.carriage&&Q(this,mt,"f")==null){rt(this,mt,i.index,"f");continue}if(Q(this,mt,"f")!=null&&(i.index!==Q(this,mt,"f")+1||i.carriage)){a.push(wa(Q(this,yt,"f").subarray(0,Q(this,mt,"f")-1))),rt(this,yt,Q(this,yt,"f").subarray(Q(this,mt,"f")),"f"),rt(this,mt,null,"f");continue}let s=Q(this,mt,"f")!==null?i.preceding-1:i.preceding,o=wa(Q(this,yt,"f").subarray(0,s));a.push(o),rt(this,yt,Q(this,yt,"f").subarray(i.index),"f"),rt(this,mt,null,"f")}return a}flush(){return Q(this,yt,"f").length?this.decode(`
2
2
  `):[]}};yt=new WeakMap,mt=new WeakMap;Yt.NEWLINE_CHARS=new Set([`
3
3
  `,"\r"]);Yt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Mr(e,t){for(let i=t??0;i<e.length;i++){if(e[i]===10)return{preceding:i,index:i+1,carriage:!1};if(e[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function Xi(e){for(let a=0;a<e.length-1;a++){if(e[a]===10&&e[a+1]===10||e[a]===13&&e[a+1]===13)return a+2;if(e[a]===13&&e[a+1]===10&&a+3<e.length&&e[a+2]===13&&e[a+3]===10)return a+4}return-1}var Mn={off:0,error:200,warn:300,info:400,debug:500},pa=(e,t,n)=>{if(e){if(Pi(Mn,e))return e;ot(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Mn))}`)}};function Xe(){}function kn(e,t,n){return!t||Mn[e]>Mn[n]?Xe:t[e].bind(t)}var vr={error:Xe,warn:Xe,info:Xe,debug:Xe},Zi=new WeakMap;function ot(e){let t=e.logger,n=e.logLevel??"off";if(!t)return vr;let a=Zi.get(t);if(a&&a[0]===n)return a[1];let i={error:kn("error",t,n),warn:kn("warn",t,n),info:kn("info",t,n),debug:kn("debug",t,n)};return Zi.set(t,[n,i]),i}var Tt=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,n])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="api-key"||t.toLowerCase()==="x-api-key"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var Ze,vn=class e{constructor(t,n,a){this.iterator=t,Ze.set(this,void 0),this.controller=n,rt(this,Ze,a,"f")}static fromSSEResponse(t,n,a){let i=!1,s=a?ot(a):console;async function*o(){if(i)throw new j("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let d=!1;try{for await(let S of Tr(t,n))try{yield JSON.parse(S.data)}catch(U){throw s.error("Could not parse message into JSON:",S.data),s.error("From chunk:",S.raw),U}d=!0}catch(S){if($e(S))return;throw S}finally{d||n.abort()}}return new e(o,n,a)}static fromReadableStream(t,n,a){let i=!1;async function*s(){let d=new Yt,S=la(t);for await(let U of S)for(let c of d.decode(U))yield c;for(let U of d.flush())yield U}async function*o(){if(i)throw new j("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let d=!1;try{for await(let S of s())d||S&&(yield JSON.parse(S));d=!0}catch(S){if($e(S))return;throw S}finally{d||n.abort()}}return new e(o,n,a)}[(Ze=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],a=this.iterator(),i=s=>({next:()=>{if(s.length===0){let o=a.next();t.push(o),n.push(o)}return s.shift()}});return[new e(()=>i(t),this.controller,Q(this,Ze,"f")),new e(()=>i(n),this.controller,Q(this,Ze,"f"))]}toReadableStream(){let t=this,n;return da({async start(){n=t[Symbol.asyncIterator]()},async pull(a){try{let{value:i,done:s}=await n.next();if(s)return a.close();let o=Qe(JSON.stringify(i)+`
4
4
  `);a.enqueue(o)}catch(i){a.error(i)}},async cancel(){await n.return?.()}})}};async function*Tr(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new j("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 j("Attempted to iterate over a response with no body");let n=new ya,a=new Yt,i=la(e.body);for await(let s of br(i))for(let o of a.decode(s)){let d=n.decode(o);d&&(yield d)}for(let s of a.flush()){let o=n.decode(s);o&&(yield o)}}async function*br(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let a=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?Qe(n):n,i=new Uint8Array(t.length+a.length);i.set(t),i.set(a,t.length),t=i;let s;for(;(s=Xi(t))!==-1;)yield t.slice(0,s),t=t.slice(s)}t.length>0&&(yield t)}var ya=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
@@ -6,7 +6,7 @@
6
6
  ${s.map(l=>l.error).join(`
7
7
  `)}
8
8
  ${o}
9
- ${r}`)}return o},p=Er(ss);var qt=class extends W{create(t,n){return this._client.post("/org/api_keys",{body:t,...n})}retrieve(t,n={},a){return this._client.get(p`/org/api_keys/${t}`,{query:n,...a})}update(t,n,a){return this._client.patch(p`/org/api_keys/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/org/api_keys",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/org/api_keys/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}rotate(t,n={},a){return this._client.post(p`/org/api_keys/${t}/rotate`,{body:n,...a})}};var zt=class extends W{list(t={},n){return this._client.getAPIList("/apps",Y,{query:t,...n})}};var Te=class extends W{create(t,n){return this._client.post("/audit-logs/export/destinations",{body:t,...n})}retrieve(t,n){return this._client.get(p`/audit-logs/export/destinations/${t}`,n)}update(t,n,a){return this._client.patch(p`/audit-logs/export/destinations/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/audit-logs/export/destinations",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/audit-logs/export/destinations/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}test(t,n){return this._client.post(p`/audit-logs/export/destinations/${t}/test`,n)}};var Fr=6,_r=5e4,Dr=8e3,Ct=class extends j{};async function rs(e,t,n,a,i={}){if(!n||typeof n.write!="function")throw new TypeError("audit log download destination must provide write()");let{onProgress:s,maxTransferRetries:o=Fr,...d}=i;if(!Number.isInteger(o)||o<0)throw new TypeError("maxTransferRetries must be a non-negative integer");let S=d.timeout??a,U,c={bytesWritten:0,chunks:0,rows:0},r=new Set;for(;;){let l=await Gr(e,U?{...t,cursor:U}:t,d,o,S),{nextCursor:u,hasMore:h,rows:w}=Vr(l.headers,U);if(h&&u){if(r.has(u))throw new Ct("response repeated X-Next-Cursor header");r.add(u)}if(await Jr(n,l.body),U=u,c.bytesWritten+=l.body.byteLength,c.chunks+=1,c.rows+=w,s&&await s({...c,chunkRows:w}),!h)return c}}async function Gr(e,t,n,a,i){for(let s=0;;s+=1){let o=new AbortController,d=()=>o.abort();n.signal?.aborted?o.abort():n.signal?.addEventListener("abort",d,{once:!0});let S;try{S=await e(t,{...n,signal:o.signal})}catch(r){throw n.signal?.removeEventListener("abort",d),r}let U=!1,c=setTimeout(()=>{U=!0,o.abort()},i);try{let r=new Uint8Array(await S.arrayBuffer());if(clearTimeout(c),n.signal?.aborted)throw new ht;if(U)throw new vt;let l=S.headers.get("x-content-sha256");if(!l)throw new Ct("response missing X-Content-Sha256 header");let u=await Kr(r);if(n.signal?.aborted)throw new ht;if(u!==l)throw new Ct(`audit log chunk checksum mismatch (got ${u}, want ${l})`);return{body:r,headers:S.headers}}catch(r){if(n.signal?.aborted&&!(r instanceof ht)?r=new ht:U&&(r=new vt),s===a||r instanceof ht)throw r;await Yr(s+1,n.signal)}finally{clearTimeout(c),n.signal?.removeEventListener("abort",d)}}}function Vr(e,t){let n=e.get("x-has-more");if(n!=="true"&&n!=="false")throw new Ct("response missing or invalid X-Has-More header");let a=n==="true",i=e.get("x-row-count");if(i===null||!/^[0-9]+$/.test(i))throw new Ct("response missing or invalid X-Row-Count header");let s=Number(i);if(!Number.isSafeInteger(s)||s>_r)throw new Ct("response missing or invalid X-Row-Count header");let o=e.get("x-next-cursor")||void 0;if(a&&(!o||o===t))throw new Ct("response has invalid X-Next-Cursor header");if(!a&&o)throw new Ct("response returned a cursor after the final chunk");return{rows:s,nextCursor:o,hasMore:a}}async function Kr(e){let t=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}async function Yr(e,t){let n=Math.min(1e3*2**(e-1),Dr);await new Promise((a,i)=>{if(t?.aborted){i(new ht);return}let s=()=>{clearTimeout(o),i(new ht)},o=setTimeout(()=>{t?.removeEventListener("abort",s),a()},n);t?.addEventListener("abort",s,{once:!0})})}async function Jr(e,t){let n=0;for(;n<t.byteLength;){let a=await e.write(n===0?t:t.subarray(n));if(typeof a=="number"){n+=os(a,t.byteLength-n);continue}if(a&&typeof a=="object"&&"bytesWritten"in a){let i=a.bytesWritten;n+=os(i,t.byteLength-n);continue}return}}function os(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Ct("audit log download destination performed a short write");return e}var Rt=class extends W{constructor(){super(...arguments),this.exportDestinations=new Te(this._client)}list(t,n){return this._client.getAPIList("/audit-logs",Pn,{query:t,...n})}exportChunk(t,n){return this._client.get("/audit-logs/export/chunk",{query:t,...n,headers:N([{Accept:"application/octet-stream"},n?.headers]),__binaryResponse:!0})}download(t,n,a){return rs((i,s)=>this.exportChunk(i,s),t,n,this._client.timeout,a)}};Rt.ExportDestinations=Te;var be=class extends W{create(t,n){return this._client.post("/auth/connections",{body:t,...n})}retrieve(t,n){return this._client.get(p`/auth/connections/${t}`,n)}update(t,n,a){return this._client.patch(p`/auth/connections/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/auth/connections",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/auth/connections/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}follow(t,n){return this._client.get(p`/auth/connections/${t}/events`,{...n,headers:N([{Accept:"text/event-stream"},n?.headers]),stream:!0})}login(t,n={},a){return this._client.post(p`/auth/connections/${t}/login`,{body:n,...a})}submit(t,n,a){return this._client.post(p`/auth/connections/${t}/submit`,{body:n,...a})}timeline(t,n={},a){return this._client.getAPIList(p`/auth/connections/${t}/timeline`,Y,{query:n,...a})}};var Ne=class extends W{retrieve(t){return this._client.get("/auth/context",t)}};var Nt=class extends W{constructor(){super(...arguments),this.context=new Ne(this._client),this.connections=new be(this._client)}};Nt.Context=Ne;Nt.Connections=be;var $t=class extends W{create(t,n){return this._client.post("/browser_pools",{body:t,...n})}retrieve(t,n){return this._client.get(p`/browser_pools/${t}`,n)}update(t,n,a){return this._client.patch(p`/browser_pools/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/browser_pools",Y,{query:t,...n})}delete(t,n={},a){return this._client.delete(p`/browser_pools/${t}`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}acquire(t,n,a){return this._client.post(p`/browser_pools/${t}/acquire`,{body:n,...a})}flush(t,n){return this._client.post(p`/browser_pools/${t}/flush`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}release(t,n,a){return this._client.post(p`/browser_pools/${t}/release`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}};var Pe=class extends W{batch(t,n,a){return this._client.post(p`/browsers/${t}/computer/batch`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}captureScreenshot(t,n={},a){return this._client.post(p`/browsers/${t}/computer/screenshot`,{body:n,...a,headers:N([{Accept:"image/png"},a?.headers]),__binaryResponse:!0})}clickMouse(t,n,a){return this._client.post(p`/browsers/${t}/computer/click_mouse`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}dragMouse(t,n,a){return this._client.post(p`/browsers/${t}/computer/drag_mouse`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}getMousePosition(t,n){return this._client.post(p`/browsers/${t}/computer/get_mouse_position`,n)}moveMouse(t,n,a){return this._client.post(p`/browsers/${t}/computer/move_mouse`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}pressKey(t,n,a){return this._client.post(p`/browsers/${t}/computer/press_key`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}readClipboard(t,n){return this._client.post(p`/browsers/${t}/computer/clipboard/read`,n)}scroll(t,n,a){return this._client.post(p`/browsers/${t}/computer/scroll`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}setCursorVisibility(t,n,a){return this._client.post(p`/browsers/${t}/computer/cursor`,{body:n,...a})}typeText(t,n,a){return this._client.post(p`/browsers/${t}/computer/type`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}writeClipboard(t,n,a){return this._client.post(p`/browsers/${t}/computer/clipboard/write`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}};var Ie=class extends W{stream(t,n,a){return this._client.get(p`/browsers/${t}/logs/stream`,{query:n,...a,headers:N([{Accept:"text/event-stream"},a?.headers]),stream:!0})}};var Ae=class extends W{execute(t,n,a){return this._client.post(p`/browsers/${t}/playwright/execute`,{body:n,...a})}};var xe=class extends W{exec(t,n,a){return this._client.post(p`/browsers/${t}/process/exec`,{body:n,...a})}kill(t,n,a){let{id:i,...s}=n;return this._client.post(p`/browsers/${i}/process/${t}/kill`,{body:s,...a})}resize(t,n,a){let{id:i,...s}=n;return this._client.post(p`/browsers/${i}/process/${t}/resize`,{body:s,...a})}spawn(t,n,a){return this._client.post(p`/browsers/${t}/process/spawn`,{body:n,...a})}status(t,n,a){let{id:i}=n;return this._client.get(p`/browsers/${i}/process/${t}/status`,a)}stdin(t,n,a){let{id:i,...s}=n;return this._client.post(p`/browsers/${i}/process/${t}/stdin`,{body:s,...a})}stdoutStream(t,n,a){let{id:i}=n;return this._client.get(p`/browsers/${i}/process/${t}/stdout/stream`,{...a,headers:N([{Accept:"text/event-stream"},a?.headers]),stream:!0})}};var We=class extends W{list(t,n){return this._client.get(p`/browsers/${t}/replays`,n)}download(t,n,a){let{id:i}=n;return this._client.get(p`/browsers/${i}/replays/${t}`,{...a,headers:N([{Accept:"video/mp4"},a?.headers]),__binaryResponse:!0})}start(t,n={},a){return this._client.post(p`/browsers/${t}/replays`,{body:n,...a})}stop(t,n,a){let{id:i}=n;return this._client.post(p`/browsers/${i}/replays/${t}/stop`,{...a,headers:N([{Accept:"*/*"},a?.headers])})}};var Oe=class extends W{events(t,n={},a){return this._client.getAPIList(p`/browsers/${t}/telemetry/events`,Y,{query:n,...a})}stream(t,n={},a){let{"Last-Event-ID":i,...s}=n??{};return this._client.get(p`/browsers/${t}/telemetry/stream`,{query:s,...a,headers:N([{Accept:"text/event-stream",...i!=null?{"Last-Event-ID":i}:void 0},a?.headers]),stream:!0})}};var Le=class extends W{events(t,n,a){let{id:i}=n;return this._client.get(p`/browsers/${i}/fs/watch/${t}/events`,{...a,headers:N([{Accept:"text/event-stream"},a?.headers]),stream:!0})}start(t,n,a){return this._client.post(p`/browsers/${t}/fs/watch`,{body:n,...a})}stop(t,n,a){let{id:i}=n;return this._client.delete(p`/browsers/${i}/fs/watch/${t}`,{...a,headers:N([{Accept:"*/*"},a?.headers])})}};var jt=class extends W{constructor(){super(...arguments),this.watch=new Le(this._client)}createDirectory(t,n,a){return this._client.put(p`/browsers/${t}/fs/create_directory`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}deleteDirectory(t,n,a){return this._client.put(p`/browsers/${t}/fs/delete_directory`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}deleteFile(t,n,a){return this._client.put(p`/browsers/${t}/fs/delete_file`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}downloadDirZip(t,n,a){return this._client.get(p`/browsers/${t}/fs/download_dir_zip`,{query:n,...a,headers:N([{Accept:"application/zip"},a?.headers]),__binaryResponse:!0})}fileInfo(t,n,a){return this._client.get(p`/browsers/${t}/fs/file_info`,{query:n,...a})}listFiles(t,n,a){return this._client.get(p`/browsers/${t}/fs/list_files`,{query:n,...a})}move(t,n,a){return this._client.put(p`/browsers/${t}/fs/move`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}readFile(t,n,a){return this._client.get(p`/browsers/${t}/fs/read_file`,{query:n,...a,headers:N([{Accept:"application/octet-stream"},a?.headers]),__binaryResponse:!0})}setFilePermissions(t,n,a){return this._client.put(p`/browsers/${t}/fs/set_file_permissions`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}upload(t,n,a){return this._client.post(p`/browsers/${t}/fs/upload`,bt({body:n,...a,headers:N([{Accept:"*/*"},a?.headers])},this._client))}uploadZip(t,n,a){return this._client.post(p`/browsers/${t}/fs/upload_zip`,bt({body:n,...a,headers:N([{Accept:"*/*"},a?.headers])},this._client))}writeFile(t,n,a,i){let{path:s,mode:o}=a;return this._client.put(p`/browsers/${t}/fs/write_file`,{body:n,query:{path:s,mode:o},...i,headers:N([{"Content-Type":"application/octet-stream",Accept:"*/*"},i?.headers])})}};jt.Watch=Le;function xn(e,t){return`${e.replace(/\/+$/,"")}${t.startsWith("/")?t:`/${t}`}`}async function ds(e,t,n,a){let i=e.browserRouteCache.get(t);if(!i)throw new j(`browser route cache does not contain session ${t}; create, retrieve, or list the browser before calling browser.fetch`);let{url:s,method:o,headers:d,body:S,signal:U,duplex:c,timeout_ms:r}=id(n,a);sd(s);let l={url:s,jwt:i.jwt};r!==void 0&&(l.timeout_ms=r);let u=d.get("accept"),h={method:ad(o),path:xn(i.baseURL,"/curl/raw"),query:l,body:S,headers:N([{Authorization:null},u?{Accept:u}:{Accept:"*/*"},od(d)]),signal:U??null,__binaryResponse:!0};return c&&(h.fetchOptions={duplex:c}),e.request(h).asResponse()}function ad(e){let t=e.toLowerCase();if(!new Set(["get","post","put","patch","delete"]).has(t))throw new j(`browser.fetch unsupported HTTP method: ${e}`);return t}function id(e,t){let n=t&&"timeout_ms"in t?t.timeout_ms:void 0;if(e instanceof Request){let i=new Headers(e.headers);t?.headers&&new Headers(t.headers).forEach((U,c)=>{i.set(c,U)});let s={url:e.url,method:(t?.method??e.method)?.toUpperCase()||"GET",headers:i},o=t?.body??e.body;o!=null&&(s.body=o);let d=t?.signal??e.signal;return d!==void 0&&(s.signal=d),t?.duplex!==void 0&&(s.duplex=t.duplex),n!==void 0&&(s.timeout_ms=n),s}let a={url:e instanceof URL?e.href:String(e),method:(t?.method??"GET").toUpperCase(),headers:new Headers(t?.headers)};return t?.body!==void 0&&(a.body=t.body),t?.signal!==void 0&&(a.signal=t.signal),t?.duplex!==void 0&&(a.duplex=t.duplex),n!==void 0&&(a.timeout_ms=n),a}function sd(e){let t;try{t=new URL(e)}catch{throw new j(`browser.fetch target must be an absolute URL; received: ${e}`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new j(`browser.fetch only supports http(s) URLs; received: ${t.protocol}`)}function od(e){let t={};return e.forEach((n,a)=>{switch(a.toLowerCase()){case"accept":case"content-length":case"connection":case"keep-alive":case"proxy-authenticate":case"proxy-authorization":case"te":case"trailers":case"transfer-encoding":case"upgrade":return;default:t[a]=n}}),t}var wt=class extends W{constructor(){super(...arguments),this.telemetry=new Oe(this._client),this.replays=new We(this._client),this.fs=new jt(this._client),this.process=new xe(this._client),this.logs=new Ie(this._client),this.computer=new Pe(this._client),this.playwright=new Ae(this._client)}create(t={},n){return this._client.post("/browsers",{body:t,...n})}retrieve(t,n={},a){return this._client.get(p`/browsers/${t}`,{query:n,...a})}update(t,n,a){return this._client.patch(p`/browsers/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/browsers",Y,{query:t,...n})}curl(t,n,a){return this._client.post(p`/browsers/${t}/curl`,{body:n,...a})}fetch(t,n,a){return ds(this._client,t,n,a)}deleteByID(t,n){return this._client.delete(p`/browsers/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}loadExtensions(t,n,a){return this._client.post(p`/browsers/${t}/extensions`,bt({body:n,...a,headers:N([{Accept:"*/*"},a?.headers])},this._client))}};wt.Telemetry=Oe;wt.Replays=We;wt.Fs=jt;wt.Process=xe;wt.Logs=Ie;wt.Computer=Pe;wt.Playwright=Ae;var Qt=class extends W{create(t,n){return this._client.post("/org/credential_providers",{body:t,...n})}retrieve(t,n){return this._client.get(p`/org/credential_providers/${t}`,n)}update(t,n,a){return this._client.patch(p`/org/credential_providers/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/org/credential_providers",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/org/credential_providers/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}listItems(t,n){return this._client.get(p`/org/credential_providers/${t}/items`,n)}test(t,n){return this._client.post(p`/org/credential_providers/${t}/test`,n)}};var Xt=class extends W{create(t,n){return this._client.post("/credentials",{body:t,...n})}retrieve(t,n){return this._client.get(p`/credentials/${t}`,n)}update(t,n,a){return this._client.patch(p`/credentials/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/credentials",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/credentials/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}totpCode(t,n){return this._client.get(p`/credentials/${t}/totp-code`,n)}};var Zt=class extends W{create(t,n){return this._client.post("/deployments",bt({body:t,...n},this._client))}retrieve(t,n){return this._client.get(p`/deployments/${t}`,n)}list(t={},n){return this._client.getAPIList("/deployments",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/deployments/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}follow(t,n={},a){return this._client.get(p`/deployments/${t}/events`,{query:n,...a,headers:N([{Accept:"text/event-stream"},a?.headers]),stream:!0})}};var te=class extends W{list(t={},n){return this._client.getAPIList("/extensions",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/extensions/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}download(t,n){return this._client.get(p`/extensions/${t}`,{...n,headers:N([{Accept:"application/octet-stream"},n?.headers]),__binaryResponse:!0})}downloadFromChromeStore(t,n){return this._client.get("/extensions/from_chrome_store",{query:t,...n,headers:N([{Accept:"application/octet-stream"},n?.headers]),__binaryResponse:!0})}get(t,n){return this._client.get(p`/extensions/${t}/metadata`,n)}upload(t,n){return this._client.post("/extensions",bt({body:t,...n},this._client))}};var ee=class extends W{create(t,n){return this._client.post("/invocations",{body:t,...n})}retrieve(t,n){return this._client.get(p`/invocations/${t}`,n)}update(t,n,a){return this._client.patch(p`/invocations/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/invocations",Y,{query:t,...n})}deleteBrowsers(t,n){return this._client.delete(p`/invocations/${t}/browsers`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}follow(t,n={},a){return this._client.get(p`/invocations/${t}/events`,{query:n,...a,headers:N([{Accept:"text/event-stream"},a?.headers]),stream:!0})}listBrowsers(t,n){return this._client.get(p`/invocations/${t}/browsers`,n)}};var Be=class extends W{retrieve(t){return this._client.get("/org/entitlements",t)}};var Re=class extends W{retrieve(t){return this._client.get("/org/limits",t)}update(t,n){return this._client.patch("/org/limits",{body:t,...n})}};var Pt=class extends W{constructor(){super(...arguments),this.entitlements=new Be(this._client),this.limits=new Re(this._client)}};Pt.Entitlements=Be;Pt.Limits=Re;var ne=class extends W{create(t,n){return this._client.post("/profiles",{body:t,...n})}retrieve(t,n){return this._client.get(p`/profiles/${t}`,n)}update(t,n,a){return this._client.patch(p`/profiles/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/profiles",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/profiles/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}download(t,n={},a){return this._client.get(p`/profiles/${t}/download`,{query:n,...a,headers:N([{Accept:"application/octet-stream"},a?.headers]),__binaryResponse:!0})}};var Ee=class extends W{retrieve(t,n){return this._client.get(p`/org/projects/${t}/limits`,n)}update(t,n,a){return this._client.patch(p`/org/projects/${t}/limits`,{body:n,...a})}};var Et=class extends W{constructor(){super(...arguments),this.limits=new Ee(this._client)}create(t,n){return this._client.post("/org/projects",{body:t,...n})}retrieve(t,n){return this._client.get(p`/org/projects/${t}`,n)}update(t,n,a){return this._client.patch(p`/org/projects/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/org/projects",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/org/projects/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}};Et.Limits=Ee;var ae=class extends W{create(t,n){return this._client.post("/proxies",{body:t,...n})}retrieve(t,n){return this._client.get(p`/proxies/${t}`,n)}update(t,n,a){return this._client.patch(p`/proxies/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/proxies",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/proxies/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}check(t,n={},a){return this._client.post(p`/proxies/${t}/check`,{body:n,...a})}};var He=class extends W{create(t,n){return this._client.post("/telemetry/destinations",{body:t,...n})}retrieve(t,n){return this._client.get(p`/telemetry/destinations/${t}`,n)}update(t,n,a){return this._client.patch(p`/telemetry/destinations/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/telemetry/destinations",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/telemetry/destinations/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}};var Ht=class extends W{constructor(){super(...arguments),this.destinations=new He(this._client)}};Ht.Destinations=He;var an=class{constructor(){this.entries=new Map}get(t){return this.entries.get(t)}set(t){this.entries.set(t.sessionId,t)}delete(t){this.entries.delete(t)}clear(){this.entries.clear()}},ls="\u004b\u0045\u0052\u004e\u0045\u004c_BROWSER_ROUTING_SUBRESOURCES",cd=["curl","telemetry/stream"],ud=/^\/(?:v\d+\/)?browsers(?:\/[^/]+)?\/?$/,hd=/^\/(?:v\d+\/)?browser_pools\/[^/]+\/acquire\/?$/,gd=/^\/(?:v\d+\/)?browsers\/([^/]+)\/?$/,wd=/^\/(?:v\d+\/)?browser_pools\/[^/]+\/release\/?$/;function va(){let e=Id();return e===void 0?[...cd]:e.trim()===""?[]:e.split(",").map(t=>t.trim()).filter(Boolean)}function Ta(e,{apiBaseURL:t,subresources:n,cache:a}){let i=[...n].map(o=>o.trim().replace(/^\/+|\/+$/g,"")).filter(Boolean),s=new URL(t).origin;return async(o,d)=>{let S=new Request(o,d),U=pd(S,s),c=await vd(e,{input:o,init:d,request:S},s,i,a);return U&&await kd(c,a),await yd(S,c,s,a),c}}function pd(e,t){let n=new URL(e.url);return n.origin===t&&(ud.test(n.pathname)||hd.test(n.pathname))}async function yd(e,t,n,a){if(!t.ok)return;let i=new URL(e.url);if(i.origin!==n)return;let s=md(e,i.pathname)??await Cd(e,i.pathname);s&&a.delete(s)}function md(e,t){if(e.method.toUpperCase()!=="DELETE")return;let n=t.match(gd);return n&&decodeURIComponent(n[1]??"")||void 0}async function Cd(e,t){if(!(e.method.toUpperCase()!=="POST"||!wd.test(t)))try{let n=await e.clone().json();if(!n||typeof n!="object")return;let a=n.session_id;return typeof a=="string"&&a.trim()?a.trim():void 0}catch{return}}function fd(e){if(!e||typeof e!="object")return;let t=e,n=typeof t.session_id=="string"?t.session_id.trim():"",a=typeof t.base_url=="string"?t.base_url.trim():"";if(!n||!a)return;let i=typeof t.jwt=="string"?t.jwt.trim():"",s=typeof t.cdp_ws_url=="string"?t.cdp_ws_url:void 0,o=i||Pd(s)||"";if(o)return{sessionId:n,baseURL:a,jwt:o}}async function kd(e,t){if((e.headers.get("content-type")?.toLowerCase()??"").includes("application/json"))try{Ma(await e.clone().json(),t)}catch{}}function Ma(e,t){let n=fd(e);if(n&&t.set(n),Array.isArray(e)){for(let a of e)Ma(a,t);return}if(!(!e||typeof e!="object"))for(let a of Object.values(e))typeof a=="object"&&a!==null&&Ma(a,t)}function Md(e,t){let n=e.replace(/^\/+|\/+$/g,"");return t.some(a=>n===a||n.startsWith(a+"/"))}async function vd(e,{input:t,init:n,request:a},i,s,o){let d=new URL(a.url);if(d.origin!==i)return e(t,n);let S=d.pathname.match(/^\/(?:v\d+\/)?browsers\/([^/]+)\/([^/]+)(\/.*)?$/);if(!S)return e(t,n);let U=decodeURIComponent(S[1]??""),c=S[2]??"";if(!U||!Md(c+(S[3]??""),s))return e(t,n);let r=o.get(U);if(r===void 0)return e(t,n);let l=new URL(xn(r.baseURL,`/${c}${S[3]??""}`));d.searchParams.forEach((h,w)=>{w!=="jwt"&&l.searchParams.append(w,h)}),l.searchParams.get("jwt")||l.searchParams.set("jwt",r.jwt);let u=new Headers(a.headers);return u.delete("authorization"),e(l.toString(),Td(t,a,n,u))}function Td(e,t,n,a){let i=t.method.toUpperCase(),s={...n??{},method:i,headers:a,redirect:t.redirect,signal:n?.signal??(e instanceof Request?e.signal:void 0)};if(delete s.body,delete s.duplex,i!=="GET"&&i!=="HEAD"){let o=bd(t,n);o!==void 0&&(s.body=o),n?.duplex!==void 0?s.duplex=n.duplex:Nd(o)&&(s.duplex="half")}return s}function bd(e,t){return t?.body!==void 0&&t.body!==null?t.body:e.body??void 0}function Nd(e){return globalThis.ReadableStream&&e instanceof globalThis.ReadableStream||typeof e=="object"&&e!==null&&Symbol.asyncIterator in e}function Pd(e){if(e)try{return new URL(e).searchParams.get("jwt")??void 0}catch{return}}function Id(){if(typeof globalThis.process<"u"){let e=globalThis.process.env?.[ls];return typeof e=="string"?e:void 0}if(typeof globalThis.Deno<"u"){let e=globalThis.Deno.env?.get?.(ls);return typeof e=="string"?e:void 0}}var Wn=class{constructor(t){this.actions=new Map,this.name=t,Ss.registerApp(this)}action(t,n){let a;if(n.length===0)throw new Error("Action handlers must accept at least the context parameter");if(n.length===1){let i=n;a=async(s,o)=>i(s)}else a=n;return this.actions.set(t,{name:t,handler:a}),a}getActions(){return Array.from(this.actions.values())}getAction(t){return this.actions.get(t)}toJSON(){return{name:this.name,actions:this.getActions().map(t=>({name:t.name}))}}},ba=class{constructor(){this.apps=new Map}registerApp(t){this.apps.set(t.name,t)}getApps(){return Array.from(this.apps.values())}getAppByName(t){return this.apps.get(t)}export(){return{apps:this.getApps().map(t=>t.toJSON())}}exportJSON(){return JSON.stringify(this.export(),null,2)}},Ss=new ba;var Fe=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()||void 0};var Na,Pa,sn,Us,cs={production:"https://api.on\u006b\u0065\u0072\u006e\u0065\u006c.com/",development:"https://localhost:3001/"},V=class{constructor({baseURL:t=Fe("\u004b\u0045\u0052\u004e\u0045\u004c_BASE_URL"),apiKey:n=Fe("\u004b\u0045\u0052\u004e\u0045\u004c_API_KEY"),projectID:a=null,project:i=null,...s}={}){if(Na.add(this),sn.set(this,void 0),this.deployments=new Zt(this),this.apps=new zt(this),this.invocations=new ee(this),this.browsers=new wt(this),this.profiles=new ne(this),this.auth=new Nt(this),this.telemetry=new Ht(this),this.proxies=new ae(this),this.extensions=new te(this),this.browserPools=new $t(this),this.credentials=new Xt(this),this.projects=new Et(this),this.organization=new Pt(this),this.auditLogs=new Rt(this),this.apiKeys=new qt(this),this.credentialProviders=new Qt(this),typeof globalThis<"u"&&typeof globalThis.Bun<"u"&&globalThis.Bun.version&&!Fe("\u004b\u0045\u0052\u004e\u0045\u004c_SUPPRESS_BUN_WARNING")&&ot(this).warn("The Bun runtime was detected. Playwright may have CDP connection issues, proceed with caution. Suppress this warning by setting the \u004b\u0045\u0052\u004e\u0045\u004c_SUPPRESS_BUN_WARNING environment variable to true"),n===void 0)throw new j("The \u004b\u0045\u0052\u004e\u0045\u004c_API_KEY environment variable is missing or empty; either provide it, or instantiate the \u004b\u0065\u0072\u006e\u0065\u006c client with an apiKey option, like new \u004b\u0065\u0072\u006e\u0065\u006c({ apiKey: 'My API Key' }).");let o={apiKey:n,projectID:a,project:i,...s,baseURL:t,environment:s.environment??"production"};if(t&&s.environment)throw new j("Ambiguous URL; The `baseURL` option (or \u004b\u0045\u0052\u004e\u0045\u004c_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null");this.baseURL=o.baseURL||cs[o.environment||"production"],this.timeout=o.timeout??Pa.DEFAULT_TIMEOUT,this.logger=o.logger??console;let d="warn";this.logLevel=d,this.logLevel=pa(o.logLevel,"ClientOptions.logLevel",this)??pa(Fe("\u004b\u0045\u0052\u004e\u0045\u004c_LOG"),"process.env['\u004b\u0045\u0052\u004e\u0045\u004c_LOG']",this)??d,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.rawFetch=o.fetch??Ei(),this.browserRouteCache=new an,this.fetch=Ta(this.rawFetch,{apiBaseURL:this.baseURL,subresources:va(),cache:this.browserRouteCache}),rt(this,sn,Fi,"f");let S=Fe("\u004b\u0045\u0052\u004e\u0045\u004c_CUSTOM_HEADERS");if(S){let U={};for(let c of S.split(`
9
+ ${r}`)}return o},p=Er(ss);var qt=class extends W{create(t,n){return this._client.post("/org/api_keys",{body:t,...n})}retrieve(t,n={},a){return this._client.get(p`/org/api_keys/${t}`,{query:n,...a})}update(t,n,a){return this._client.patch(p`/org/api_keys/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/org/api_keys",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/org/api_keys/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}rotate(t,n={},a){return this._client.post(p`/org/api_keys/${t}/rotate`,{body:n,...a})}};var zt=class extends W{list(t={},n){return this._client.getAPIList("/apps",Y,{query:t,...n})}};var Te=class extends W{create(t,n){return this._client.post("/audit-logs/export/destinations",{body:t,...n})}retrieve(t,n){return this._client.get(p`/audit-logs/export/destinations/${t}`,n)}update(t,n,a){return this._client.patch(p`/audit-logs/export/destinations/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/audit-logs/export/destinations",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/audit-logs/export/destinations/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}test(t,n){return this._client.post(p`/audit-logs/export/destinations/${t}/test`,n)}};var Fr=6,Dr=5e4,_r=8e3,Ct=class extends j{};async function rs(e,t,n,a,i={}){if(!n||typeof n.write!="function")throw new TypeError("audit log download destination must provide write()");let{onProgress:s,maxTransferRetries:o=Fr,...d}=i;if(!Number.isInteger(o)||o<0)throw new TypeError("maxTransferRetries must be a non-negative integer");let S=d.timeout??a,U,c={bytesWritten:0,chunks:0,rows:0},r=new Set;for(;;){let l=await Gr(e,U?{...t,cursor:U}:t,d,o,S),{nextCursor:u,hasMore:h,rows:w}=Vr(l.headers,U);if(h&&u){if(r.has(u))throw new Ct("response repeated X-Next-Cursor header");r.add(u)}if(await Jr(n,l.body),U=u,c.bytesWritten+=l.body.byteLength,c.chunks+=1,c.rows+=w,s&&await s({...c,chunkRows:w}),!h)return c}}async function Gr(e,t,n,a,i){for(let s=0;;s+=1){let o=new AbortController,d=()=>o.abort();n.signal?.aborted?o.abort():n.signal?.addEventListener("abort",d,{once:!0});let S;try{S=await e(t,{...n,signal:o.signal})}catch(r){throw n.signal?.removeEventListener("abort",d),r}let U=!1,c=setTimeout(()=>{U=!0,o.abort()},i);try{let r=new Uint8Array(await S.arrayBuffer());if(clearTimeout(c),n.signal?.aborted)throw new ht;if(U)throw new vt;let l=S.headers.get("x-content-sha256");if(!l)throw new Ct("response missing X-Content-Sha256 header");let u=await Kr(r);if(n.signal?.aborted)throw new ht;if(u!==l)throw new Ct(`audit log chunk checksum mismatch (got ${u}, want ${l})`);return{body:r,headers:S.headers}}catch(r){if(n.signal?.aborted&&!(r instanceof ht)?r=new ht:U&&(r=new vt),s===a||r instanceof ht)throw r;await Yr(s+1,n.signal)}finally{clearTimeout(c),n.signal?.removeEventListener("abort",d)}}}function Vr(e,t){let n=e.get("x-has-more");if(n!=="true"&&n!=="false")throw new Ct("response missing or invalid X-Has-More header");let a=n==="true",i=e.get("x-row-count");if(i===null||!/^[0-9]+$/.test(i))throw new Ct("response missing or invalid X-Row-Count header");let s=Number(i);if(!Number.isSafeInteger(s)||s>Dr)throw new Ct("response missing or invalid X-Row-Count header");let o=e.get("x-next-cursor")||void 0;if(a&&(!o||o===t))throw new Ct("response has invalid X-Next-Cursor header");if(!a&&o)throw new Ct("response returned a cursor after the final chunk");return{rows:s,nextCursor:o,hasMore:a}}async function Kr(e){let t=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}async function Yr(e,t){let n=Math.min(1e3*2**(e-1),_r);await new Promise((a,i)=>{if(t?.aborted){i(new ht);return}let s=()=>{clearTimeout(o),i(new ht)},o=setTimeout(()=>{t?.removeEventListener("abort",s),a()},n);t?.addEventListener("abort",s,{once:!0})})}async function Jr(e,t){let n=0;for(;n<t.byteLength;){let a=await e.write(n===0?t:t.subarray(n));if(typeof a=="number"){n+=os(a,t.byteLength-n);continue}if(a&&typeof a=="object"&&"bytesWritten"in a){let i=a.bytesWritten;n+=os(i,t.byteLength-n);continue}return}}function os(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Ct("audit log download destination performed a short write");return e}var Rt=class extends W{constructor(){super(...arguments),this.exportDestinations=new Te(this._client)}list(t,n){return this._client.getAPIList("/audit-logs",Pn,{query:t,...n})}exportChunk(t,n){return this._client.get("/audit-logs/export/chunk",{query:t,...n,headers:N([{Accept:"application/octet-stream"},n?.headers]),__binaryResponse:!0})}download(t,n,a){return rs((i,s)=>this.exportChunk(i,s),t,n,this._client.timeout,a)}};Rt.ExportDestinations=Te;var be=class extends W{create(t,n){return this._client.post("/auth/connections",{body:t,...n})}retrieve(t,n){return this._client.get(p`/auth/connections/${t}`,n)}update(t,n,a){return this._client.patch(p`/auth/connections/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/auth/connections",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/auth/connections/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}follow(t,n){return this._client.get(p`/auth/connections/${t}/events`,{...n,headers:N([{Accept:"text/event-stream"},n?.headers]),stream:!0})}login(t,n={},a){return this._client.post(p`/auth/connections/${t}/login`,{body:n,...a})}submit(t,n,a){return this._client.post(p`/auth/connections/${t}/submit`,{body:n,...a})}timeline(t,n={},a){return this._client.getAPIList(p`/auth/connections/${t}/timeline`,Y,{query:n,...a})}};var Ne=class extends W{retrieve(t){return this._client.get("/auth/context",t)}};var Nt=class extends W{constructor(){super(...arguments),this.context=new Ne(this._client),this.connections=new be(this._client)}};Nt.Context=Ne;Nt.Connections=be;var $t=class extends W{create(t,n){return this._client.post("/browser_pools",{body:t,...n})}retrieve(t,n){return this._client.get(p`/browser_pools/${t}`,n)}update(t,n,a){return this._client.patch(p`/browser_pools/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/browser_pools",Y,{query:t,...n})}delete(t,n={},a){return this._client.delete(p`/browser_pools/${t}`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}acquire(t,n,a){return this._client.post(p`/browser_pools/${t}/acquire`,{body:n,...a})}flush(t,n){return this._client.post(p`/browser_pools/${t}/flush`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}release(t,n,a){return this._client.post(p`/browser_pools/${t}/release`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}};var Pe=class extends W{batch(t,n,a){return this._client.post(p`/browsers/${t}/computer/batch`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}captureScreenshot(t,n={},a){return this._client.post(p`/browsers/${t}/computer/screenshot`,{body:n,...a,headers:N([{Accept:"image/png"},a?.headers]),__binaryResponse:!0})}clickMouse(t,n,a){return this._client.post(p`/browsers/${t}/computer/click_mouse`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}dragMouse(t,n,a){return this._client.post(p`/browsers/${t}/computer/drag_mouse`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}getMousePosition(t,n){return this._client.post(p`/browsers/${t}/computer/get_mouse_position`,n)}moveMouse(t,n,a){return this._client.post(p`/browsers/${t}/computer/move_mouse`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}pressKey(t,n,a){return this._client.post(p`/browsers/${t}/computer/press_key`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}readClipboard(t,n){return this._client.post(p`/browsers/${t}/computer/clipboard/read`,n)}scroll(t,n,a){return this._client.post(p`/browsers/${t}/computer/scroll`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}setCursorVisibility(t,n,a){return this._client.post(p`/browsers/${t}/computer/cursor`,{body:n,...a})}typeText(t,n,a){return this._client.post(p`/browsers/${t}/computer/type`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}writeClipboard(t,n,a){return this._client.post(p`/browsers/${t}/computer/clipboard/write`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}};var Ie=class extends W{stream(t,n,a){return this._client.get(p`/browsers/${t}/logs/stream`,{query:n,...a,headers:N([{Accept:"text/event-stream"},a?.headers]),stream:!0})}};var Ae=class extends W{execute(t,n,a){return this._client.post(p`/browsers/${t}/playwright/execute`,{body:n,...a})}};var xe=class extends W{exec(t,n,a){return this._client.post(p`/browsers/${t}/process/exec`,{body:n,...a})}kill(t,n,a){let{id:i,...s}=n;return this._client.post(p`/browsers/${i}/process/${t}/kill`,{body:s,...a})}resize(t,n,a){let{id:i,...s}=n;return this._client.post(p`/browsers/${i}/process/${t}/resize`,{body:s,...a})}spawn(t,n,a){return this._client.post(p`/browsers/${t}/process/spawn`,{body:n,...a})}status(t,n,a){let{id:i}=n;return this._client.get(p`/browsers/${i}/process/${t}/status`,a)}stdin(t,n,a){let{id:i,...s}=n;return this._client.post(p`/browsers/${i}/process/${t}/stdin`,{body:s,...a})}stdoutStream(t,n,a){let{id:i}=n;return this._client.get(p`/browsers/${i}/process/${t}/stdout/stream`,{...a,headers:N([{Accept:"text/event-stream"},a?.headers]),stream:!0})}};var We=class extends W{list(t,n){return this._client.get(p`/browsers/${t}/replays`,n)}download(t,n,a){let{id:i}=n;return this._client.get(p`/browsers/${i}/replays/${t}`,{...a,headers:N([{Accept:"video/mp4"},a?.headers]),__binaryResponse:!0})}start(t,n={},a){return this._client.post(p`/browsers/${t}/replays`,{body:n,...a})}stop(t,n,a){let{id:i}=n;return this._client.post(p`/browsers/${i}/replays/${t}/stop`,{...a,headers:N([{Accept:"*/*"},a?.headers])})}};var Oe=class extends W{events(t,n={},a){return this._client.getAPIList(p`/browsers/${t}/telemetry/events`,Y,{query:n,...a})}stream(t,n={},a){let{"Last-Event-ID":i,...s}=n??{};return this._client.get(p`/browsers/${t}/telemetry/stream`,{query:s,...a,headers:N([{Accept:"text/event-stream",...i!=null?{"Last-Event-ID":i}:void 0},a?.headers]),stream:!0})}};var Le=class extends W{events(t,n,a){let{id:i}=n;return this._client.get(p`/browsers/${i}/fs/watch/${t}/events`,{...a,headers:N([{Accept:"text/event-stream"},a?.headers]),stream:!0})}start(t,n,a){return this._client.post(p`/browsers/${t}/fs/watch`,{body:n,...a})}stop(t,n,a){let{id:i}=n;return this._client.delete(p`/browsers/${i}/fs/watch/${t}`,{...a,headers:N([{Accept:"*/*"},a?.headers])})}};var jt=class extends W{constructor(){super(...arguments),this.watch=new Le(this._client)}createDirectory(t,n,a){return this._client.put(p`/browsers/${t}/fs/create_directory`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}deleteDirectory(t,n,a){return this._client.put(p`/browsers/${t}/fs/delete_directory`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}deleteFile(t,n,a){return this._client.put(p`/browsers/${t}/fs/delete_file`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}downloadDirZip(t,n,a){return this._client.get(p`/browsers/${t}/fs/download_dir_zip`,{query:n,...a,headers:N([{Accept:"application/zip"},a?.headers]),__binaryResponse:!0})}fileInfo(t,n,a){return this._client.get(p`/browsers/${t}/fs/file_info`,{query:n,...a})}listFiles(t,n,a){return this._client.get(p`/browsers/${t}/fs/list_files`,{query:n,...a})}move(t,n,a){return this._client.put(p`/browsers/${t}/fs/move`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}readFile(t,n,a){return this._client.get(p`/browsers/${t}/fs/read_file`,{query:n,...a,headers:N([{Accept:"application/octet-stream"},a?.headers]),__binaryResponse:!0})}setFilePermissions(t,n,a){return this._client.put(p`/browsers/${t}/fs/set_file_permissions`,{body:n,...a,headers:N([{Accept:"*/*"},a?.headers])})}upload(t,n,a){return this._client.post(p`/browsers/${t}/fs/upload`,bt({body:n,...a,headers:N([{Accept:"*/*"},a?.headers])},this._client))}uploadZip(t,n,a){return this._client.post(p`/browsers/${t}/fs/upload_zip`,bt({body:n,...a,headers:N([{Accept:"*/*"},a?.headers])},this._client))}writeFile(t,n,a,i){let{path:s,mode:o}=a;return this._client.put(p`/browsers/${t}/fs/write_file`,{body:n,query:{path:s,mode:o},...i,headers:N([{"Content-Type":"application/octet-stream",Accept:"*/*"},i?.headers])})}};jt.Watch=Le;function xn(e,t){return`${e.replace(/\/+$/,"")}${t.startsWith("/")?t:`/${t}`}`}async function ds(e,t,n,a){let i=e.browserRouteCache.get(t);if(!i)throw new j(`browser route cache does not contain session ${t}; create, retrieve, or list the browser before calling browser.fetch`);let{url:s,method:o,headers:d,body:S,signal:U,duplex:c,timeout_ms:r}=id(n,a);sd(s);let l={url:s,jwt:i.jwt};r!==void 0&&(l.timeout_ms=r);let u=d.get("accept"),h={method:ad(o),path:xn(i.baseURL,"/curl/raw"),query:l,body:S,headers:N([{Authorization:null},u?{Accept:u}:{Accept:"*/*"},od(d)]),signal:U??null,__binaryResponse:!0};return c&&(h.fetchOptions={duplex:c}),e.request(h).asResponse()}function ad(e){let t=e.toLowerCase();if(!new Set(["get","post","put","patch","delete"]).has(t))throw new j(`browser.fetch unsupported HTTP method: ${e}`);return t}function id(e,t){let n=t&&"timeout_ms"in t?t.timeout_ms:void 0;if(e instanceof Request){let i=new Headers(e.headers);t?.headers&&new Headers(t.headers).forEach((U,c)=>{i.set(c,U)});let s={url:e.url,method:(t?.method??e.method)?.toUpperCase()||"GET",headers:i},o=t?.body??e.body;o!=null&&(s.body=o);let d=t?.signal??e.signal;return d!==void 0&&(s.signal=d),t?.duplex!==void 0&&(s.duplex=t.duplex),n!==void 0&&(s.timeout_ms=n),s}let a={url:e instanceof URL?e.href:String(e),method:(t?.method??"GET").toUpperCase(),headers:new Headers(t?.headers)};return t?.body!==void 0&&(a.body=t.body),t?.signal!==void 0&&(a.signal=t.signal),t?.duplex!==void 0&&(a.duplex=t.duplex),n!==void 0&&(a.timeout_ms=n),a}function sd(e){let t;try{t=new URL(e)}catch{throw new j(`browser.fetch target must be an absolute URL; received: ${e}`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new j(`browser.fetch only supports http(s) URLs; received: ${t.protocol}`)}function od(e){let t={};return e.forEach((n,a)=>{switch(a.toLowerCase()){case"accept":case"content-length":case"connection":case"keep-alive":case"proxy-authenticate":case"proxy-authorization":case"te":case"trailers":case"transfer-encoding":case"upgrade":return;default:t[a]=n}}),t}var wt=class extends W{constructor(){super(...arguments),this.telemetry=new Oe(this._client),this.replays=new We(this._client),this.fs=new jt(this._client),this.process=new xe(this._client),this.logs=new Ie(this._client),this.computer=new Pe(this._client),this.playwright=new Ae(this._client)}create(t={},n){return this._client.post("/browsers",{body:t,...n})}retrieve(t,n={},a){return this._client.get(p`/browsers/${t}`,{query:n,...a})}update(t,n,a){return this._client.patch(p`/browsers/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/browsers",Y,{query:t,...n})}curl(t,n,a){return this._client.post(p`/browsers/${t}/curl`,{body:n,...a})}fetch(t,n,a){return ds(this._client,t,n,a)}deleteByID(t,n){return this._client.delete(p`/browsers/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}loadExtensions(t,n,a){return this._client.post(p`/browsers/${t}/extensions`,bt({body:n,...a,headers:N([{Accept:"*/*"},a?.headers])},this._client))}};wt.Telemetry=Oe;wt.Replays=We;wt.Fs=jt;wt.Process=xe;wt.Logs=Ie;wt.Computer=Pe;wt.Playwright=Ae;var Qt=class extends W{create(t,n){return this._client.post("/org/credential_providers",{body:t,...n})}retrieve(t,n){return this._client.get(p`/org/credential_providers/${t}`,n)}update(t,n,a){return this._client.patch(p`/org/credential_providers/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/org/credential_providers",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/org/credential_providers/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}listItems(t,n){return this._client.get(p`/org/credential_providers/${t}/items`,n)}test(t,n){return this._client.post(p`/org/credential_providers/${t}/test`,n)}};var Xt=class extends W{create(t,n){return this._client.post("/credentials",{body:t,...n})}retrieve(t,n){return this._client.get(p`/credentials/${t}`,n)}update(t,n,a){return this._client.patch(p`/credentials/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/credentials",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/credentials/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}totpCode(t,n){return this._client.get(p`/credentials/${t}/totp-code`,n)}};var Zt=class extends W{create(t,n){return this._client.post("/deployments",bt({body:t,...n},this._client))}retrieve(t,n){return this._client.get(p`/deployments/${t}`,n)}list(t={},n){return this._client.getAPIList("/deployments",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/deployments/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}follow(t,n={},a){return this._client.get(p`/deployments/${t}/events`,{query:n,...a,headers:N([{Accept:"text/event-stream"},a?.headers]),stream:!0})}};var te=class extends W{list(t={},n){return this._client.getAPIList("/extensions",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/extensions/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}download(t,n){return this._client.get(p`/extensions/${t}`,{...n,headers:N([{Accept:"application/octet-stream"},n?.headers]),__binaryResponse:!0})}downloadFromChromeStore(t,n){return this._client.get("/extensions/from_chrome_store",{query:t,...n,headers:N([{Accept:"application/octet-stream"},n?.headers]),__binaryResponse:!0})}get(t,n){return this._client.get(p`/extensions/${t}/metadata`,n)}upload(t,n){return this._client.post("/extensions",bt({body:t,...n},this._client))}};var ee=class extends W{create(t,n){return this._client.post("/invocations",{body:t,...n})}retrieve(t,n){return this._client.get(p`/invocations/${t}`,n)}update(t,n,a){return this._client.patch(p`/invocations/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/invocations",Y,{query:t,...n})}deleteBrowsers(t,n){return this._client.delete(p`/invocations/${t}/browsers`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}follow(t,n={},a){return this._client.get(p`/invocations/${t}/events`,{query:n,...a,headers:N([{Accept:"text/event-stream"},a?.headers]),stream:!0})}listBrowsers(t,n){return this._client.get(p`/invocations/${t}/browsers`,n)}};var Be=class extends W{retrieve(t){return this._client.get("/org/entitlements",t)}};var Re=class extends W{retrieve(t){return this._client.get("/org/limits",t)}update(t,n){return this._client.patch("/org/limits",{body:t,...n})}};var Pt=class extends W{constructor(){super(...arguments),this.entitlements=new Be(this._client),this.limits=new Re(this._client)}};Pt.Entitlements=Be;Pt.Limits=Re;var ne=class extends W{create(t,n){return this._client.post("/profiles",{body:t,...n})}retrieve(t,n){return this._client.get(p`/profiles/${t}`,n)}update(t,n,a){return this._client.patch(p`/profiles/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/profiles",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/profiles/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}download(t,n={},a){return this._client.get(p`/profiles/${t}/download`,{query:n,...a,headers:N([{Accept:"application/octet-stream"},a?.headers]),__binaryResponse:!0})}};var Ee=class extends W{retrieve(t,n){return this._client.get(p`/org/projects/${t}/limits`,n)}update(t,n,a){return this._client.patch(p`/org/projects/${t}/limits`,{body:n,...a})}};var Et=class extends W{constructor(){super(...arguments),this.limits=new Ee(this._client)}create(t,n){return this._client.post("/org/projects",{body:t,...n})}retrieve(t,n){return this._client.get(p`/org/projects/${t}`,n)}update(t,n,a){return this._client.patch(p`/org/projects/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/org/projects",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/org/projects/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}};Et.Limits=Ee;var ae=class extends W{create(t,n){return this._client.post("/proxies",{body:t,...n})}retrieve(t,n){return this._client.get(p`/proxies/${t}`,n)}update(t,n,a){return this._client.patch(p`/proxies/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/proxies",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/proxies/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}check(t,n={},a){return this._client.post(p`/proxies/${t}/check`,{body:n,...a})}};var He=class extends W{create(t,n){return this._client.post("/telemetry/destinations",{body:t,...n})}retrieve(t,n){return this._client.get(p`/telemetry/destinations/${t}`,n)}update(t,n,a){return this._client.patch(p`/telemetry/destinations/${t}`,{body:n,...a})}list(t={},n){return this._client.getAPIList("/telemetry/destinations",Y,{query:t,...n})}delete(t,n){return this._client.delete(p`/telemetry/destinations/${t}`,{...n,headers:N([{Accept:"*/*"},n?.headers])})}};var Ht=class extends W{constructor(){super(...arguments),this.destinations=new He(this._client)}};Ht.Destinations=He;var an=class{constructor(){this.entries=new Map}get(t){return this.entries.get(t)}set(t){this.entries.set(t.sessionId,t)}delete(t){this.entries.delete(t)}clear(){this.entries.clear()}},ls="\u004b\u0045\u0052\u004e\u0045\u004c_BROWSER_ROUTING_SUBRESOURCES",cd=["curl","telemetry/stream"],ud=/^\/(?:v\d+\/)?browsers(?:\/[^/]+)?\/?$/,hd=/^\/(?:v\d+\/)?browser_pools\/[^/]+\/acquire\/?$/,gd=/^\/(?:v\d+\/)?browsers\/([^/]+)\/?$/,wd=/^\/(?:v\d+\/)?browser_pools\/[^/]+\/release\/?$/;function va(){let e=Id();return e===void 0?[...cd]:e.trim()===""?[]:e.split(",").map(t=>t.trim()).filter(Boolean)}function Ta(e,{apiBaseURL:t,subresources:n,cache:a}){let i=[...n].map(o=>o.trim().replace(/^\/+|\/+$/g,"")).filter(Boolean),s=new URL(t).origin;return async(o,d)=>{let S=new Request(o,d),U=pd(S,s),c=await vd(e,{input:o,init:d,request:S},s,i,a);return U&&await kd(c,a),await yd(S,c,s,a),c}}function pd(e,t){let n=new URL(e.url);return n.origin===t&&(ud.test(n.pathname)||hd.test(n.pathname))}async function yd(e,t,n,a){if(!t.ok)return;let i=new URL(e.url);if(i.origin!==n)return;let s=md(e,i.pathname)??await Cd(e,i.pathname);s&&a.delete(s)}function md(e,t){if(e.method.toUpperCase()!=="DELETE")return;let n=t.match(gd);return n&&decodeURIComponent(n[1]??"")||void 0}async function Cd(e,t){if(!(e.method.toUpperCase()!=="POST"||!wd.test(t)))try{let n=await e.clone().json();if(!n||typeof n!="object")return;let a=n.session_id;return typeof a=="string"&&a.trim()?a.trim():void 0}catch{return}}function fd(e){if(!e||typeof e!="object")return;let t=e,n=typeof t.session_id=="string"?t.session_id.trim():"",a=typeof t.base_url=="string"?t.base_url.trim():"";if(!n||!a)return;let i=typeof t.jwt=="string"?t.jwt.trim():"",s=typeof t.cdp_ws_url=="string"?t.cdp_ws_url:void 0,o=i||Pd(s)||"";if(o)return{sessionId:n,baseURL:a,jwt:o}}async function kd(e,t){if((e.headers.get("content-type")?.toLowerCase()??"").includes("application/json"))try{Ma(await e.clone().json(),t)}catch{}}function Ma(e,t){let n=fd(e);if(n&&t.set(n),Array.isArray(e)){for(let a of e)Ma(a,t);return}if(!(!e||typeof e!="object"))for(let a of Object.values(e))typeof a=="object"&&a!==null&&Ma(a,t)}function Md(e,t){let n=e.replace(/^\/+|\/+$/g,"");return t.some(a=>n===a||n.startsWith(a+"/"))}async function vd(e,{input:t,init:n,request:a},i,s,o){let d=new URL(a.url);if(d.origin!==i)return e(t,n);let S=d.pathname.match(/^\/(?:v\d+\/)?browsers\/([^/]+)\/([^/]+)(\/.*)?$/);if(!S)return e(t,n);let U=decodeURIComponent(S[1]??""),c=S[2]??"";if(!U||!Md(c+(S[3]??""),s))return e(t,n);let r=o.get(U);if(r===void 0)return e(t,n);let l=new URL(xn(r.baseURL,`/${c}${S[3]??""}`));d.searchParams.forEach((h,w)=>{w!=="jwt"&&l.searchParams.append(w,h)}),l.searchParams.get("jwt")||l.searchParams.set("jwt",r.jwt);let u=new Headers(a.headers);return u.delete("authorization"),e(l.toString(),Td(t,a,n,u))}function Td(e,t,n,a){let i=t.method.toUpperCase(),s={...n??{},method:i,headers:a,redirect:t.redirect,signal:n?.signal??(e instanceof Request?e.signal:void 0)};if(delete s.body,delete s.duplex,i!=="GET"&&i!=="HEAD"){let o=bd(t,n);o!==void 0&&(s.body=o),n?.duplex!==void 0?s.duplex=n.duplex:Nd(o)&&(s.duplex="half")}return s}function bd(e,t){return t?.body!==void 0&&t.body!==null?t.body:e.body??void 0}function Nd(e){return globalThis.ReadableStream&&e instanceof globalThis.ReadableStream||typeof e=="object"&&e!==null&&Symbol.asyncIterator in e}function Pd(e){if(e)try{return new URL(e).searchParams.get("jwt")??void 0}catch{return}}function Id(){if(typeof globalThis.process<"u"){let e=globalThis.process.env?.[ls];return typeof e=="string"?e:void 0}if(typeof globalThis.Deno<"u"){let e=globalThis.Deno.env?.get?.(ls);return typeof e=="string"?e:void 0}}var Wn=class{constructor(t){this.actions=new Map,this.name=t,Ss.registerApp(this)}action(t,n){let a;if(n.length===0)throw new Error("Action handlers must accept at least the context parameter");if(n.length===1){let i=n;a=async(s,o)=>i(s)}else a=n;return this.actions.set(t,{name:t,handler:a}),a}getActions(){return Array.from(this.actions.values())}getAction(t){return this.actions.get(t)}toJSON(){return{name:this.name,actions:this.getActions().map(t=>({name:t.name}))}}},ba=class{constructor(){this.apps=new Map}registerApp(t){this.apps.set(t.name,t)}getApps(){return Array.from(this.apps.values())}getAppByName(t){return this.apps.get(t)}export(){return{apps:this.getApps().map(t=>t.toJSON())}}exportJSON(){return JSON.stringify(this.export(),null,2)}},Ss=new ba;var Fe=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()||void 0};var Na,Pa,sn,Us,cs={production:"https://api.on\u006b\u0065\u0072\u006e\u0065\u006c.com/",development:"https://localhost:3001/"},V=class{constructor({baseURL:t=Fe("\u004b\u0045\u0052\u004e\u0045\u004c_BASE_URL"),apiKey:n=Fe("\u004b\u0045\u0052\u004e\u0045\u004c_API_KEY"),projectID:a=null,project:i=null,...s}={}){if(Na.add(this),sn.set(this,void 0),this.deployments=new Zt(this),this.apps=new zt(this),this.invocations=new ee(this),this.browsers=new wt(this),this.profiles=new ne(this),this.auth=new Nt(this),this.telemetry=new Ht(this),this.proxies=new ae(this),this.extensions=new te(this),this.browserPools=new $t(this),this.credentials=new Xt(this),this.projects=new Et(this),this.organization=new Pt(this),this.auditLogs=new Rt(this),this.apiKeys=new qt(this),this.credentialProviders=new Qt(this),typeof globalThis<"u"&&typeof globalThis.Bun<"u"&&globalThis.Bun.version&&!Fe("\u004b\u0045\u0052\u004e\u0045\u004c_SUPPRESS_BUN_WARNING")&&ot(this).warn("The Bun runtime was detected. Playwright may have CDP connection issues, proceed with caution. Suppress this warning by setting the \u004b\u0045\u0052\u004e\u0045\u004c_SUPPRESS_BUN_WARNING environment variable to true"),n===void 0)throw new j("The \u004b\u0045\u0052\u004e\u0045\u004c_API_KEY environment variable is missing or empty; either provide it, or instantiate the \u004b\u0065\u0072\u006e\u0065\u006c client with an apiKey option, like new \u004b\u0065\u0072\u006e\u0065\u006c({ apiKey: 'My API Key' }).");let o={apiKey:n,projectID:a,project:i,...s,baseURL:t,environment:s.environment??"production"};if(t&&s.environment)throw new j("Ambiguous URL; The `baseURL` option (or \u004b\u0045\u0052\u004e\u0045\u004c_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null");this.baseURL=o.baseURL||cs[o.environment||"production"],this.timeout=o.timeout??Pa.DEFAULT_TIMEOUT,this.logger=o.logger??console;let d="warn";this.logLevel=d,this.logLevel=pa(o.logLevel,"ClientOptions.logLevel",this)??pa(Fe("\u004b\u0045\u0052\u004e\u0045\u004c_LOG"),"process.env['\u004b\u0045\u0052\u004e\u0045\u004c_LOG']",this)??d,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.rawFetch=o.fetch??Ei(),this.browserRouteCache=new an,this.fetch=Ta(this.rawFetch,{apiBaseURL:this.baseURL,subresources:va(),cache:this.browserRouteCache}),rt(this,sn,Fi,"f");let S=Fe("\u004b\u0045\u0052\u004e\u0045\u004c_CUSTOM_HEADERS");if(S){let U={};for(let c of S.split(`
10
10
  `)){let r=c.indexOf(":");r>=0&&(U[c.substring(0,r).trim()]=c.substring(r+1).trim())}o.defaultHeaders={...U,...o.defaultHeaders}}this._options=o,this.apiKey=n,this.projectID=a,this.project=i}withOptions(t){let n=new this.constructor({...this._options,environment:t.environment?t.environment:void 0,baseURL:t.environment?void 0:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.rawFetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,projectID:this.projectID,project:this.project,...t});return n.browserRouteCache=this.browserRouteCache,n.fetch=Ta(n.rawFetch,{apiBaseURL:n.baseURL,subresources:va(),cache:n.browserRouteCache}),n}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:n}){}async authHeaders(t){return N([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return zi(t)}getUserAgent(){return`${this.constructor.name}/JS ${Bt}`}defaultIdempotencyKey(){return`stainless-node-retry-${aa()}`}makeStatusError(t,n,a,i){return lt.generate(t,n,a,i)}buildURL(t,n,a){let i=!Q(this,Na,"m",Us).call(this)&&a||this.baseURL,s=Ni(t)?new URL(t):new URL(i+(i.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),o=this.defaultQuery(),d=Object.fromEntries(s.searchParams);return(!oa(o)||!oa(d))&&(n={...d,...o,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(s.search=this.stringifyQuery(n)),s.toString()}async prepareOptions(t){}async prepareRequest(t,{url:n,options:a}){}get(t,n){return this.methodRequest("get",t,n)}post(t,n){return this.methodRequest("post",t,n)}patch(t,n){return this.methodRequest("patch",t,n)}put(t,n){return this.methodRequest("put",t,n)}delete(t,n){return this.methodRequest("delete",t,n)}methodRequest(t,n,a){return this.request(Promise.resolve(a).then(i=>({method:t,path:n,...i})))}request(t,n=null){return new Jt(this,this.makeRequest(t,n,void 0))}async makeRequest(t,n,a){let i=await t,s=i.maxRetries??this.maxRetries;n==null&&(n=s),await this.prepareOptions(i);let{req:o,url:d,timeout:S}=await this.buildRequest(i,{retryCount:s-n});await this.prepareRequest(o,{url:d,options:i});let U="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),c=a===void 0?"":`, retryOf: ${a}`,r=Date.now();if(ot(this).debug(`[${U}] sending request`,Tt({retryOfRequestLogID:a,method:i.method,url:d,options:i,headers:o.headers})),i.signal?.aborted)throw new ht;let l=new AbortController,u=await this.fetchWithTimeout(d,o,S,l).catch(je),h=Date.now();if(u instanceof globalThis.Error){let g=`retrying, ${n} attempts remaining`;if(i.signal?.aborted)throw new ht;let C=$e(u)||/timed? ?out/i.test(String(u)+("cause"in u?String(u.cause):""));if(n)return ot(this).info(`[${U}] connection ${C?"timed out":"failed"} - ${g}`),ot(this).debug(`[${U}] connection ${C?"timed out":"failed"} (${g})`,Tt({retryOfRequestLogID:a,url:d,durationMs:h-r,message:u.message})),this.retryRequest(i,n,a??U);throw ot(this).info(`[${U}] connection ${C?"timed out":"failed"} - error; no more retries left`),ot(this).debug(`[${U}] connection ${C?"timed out":"failed"} (error; no more retries left)`,Tt({retryOfRequestLogID:a,url:d,durationMs:h-r,message:u.message})),C?new vt:new Lt({cause:u})}let w=`[${U}${c}] ${o.method} ${d} ${u.ok?"succeeded":"failed"} with status ${u.status} in ${h-r}ms`;if(!u.ok){let g=await this.shouldRetry(u);if(n&&g){let B=`retrying, ${n} attempts remaining`;return await Hi(u.body),ot(this).info(`${w} - ${B}`),ot(this).debug(`[${U}] response error (${B})`,Tt({retryOfRequestLogID:a,url:u.url,status:u.status,headers:u.headers,durationMs:h-r})),this.retryRequest(i,n,a??U,u.headers)}let C=g?"error; no more retries left":"error; not retryable";ot(this).info(`${w} - ${C}`);let y=await u.text().catch(B=>je(B).message),m=xi(y),O=m?void 0:y;throw ot(this).debug(`[${U}] response error (${C})`,Tt({retryOfRequestLogID:a,url:u.url,status:u.status,headers:u.headers,message:O,durationMs:Date.now()-r})),this.makeStatusError(u.status,m,O,u.headers)}return ot(this).info(w),ot(this).debug(`[${U}] response start`,Tt({retryOfRequestLogID:a,url:u.url,status:u.status,headers:u.headers,durationMs:h-r})),{response:u,options:i,controller:l,requestLogID:U,retryOfRequestLogID:a,startTime:r}}getAPIList(t,n,a){return this.requestAPIList(n,a&&"then"in a?a.then(i=>({method:"get",path:t,...i})):{method:"get",path:t,...a})}requestAPIList(t,n){let a=this.makeRequest(n,null,void 0);return new en(this,a,t)}async fetchWithTimeout(t,n,a,i){let{signal:s,method:o,...d}=n||{},S=this._makeAbort(i);s&&s.addEventListener("abort",S,{once:!0});let U=setTimeout(S,a),c=globalThis.ReadableStream&&d.body instanceof globalThis.ReadableStream||typeof d.body=="object"&&d.body!==null&&Symbol.asyncIterator in d.body,r={signal:i.signal,...c?{duplex:"half"}:{},method:"GET",...d};o&&(r.method=o.toUpperCase());try{return await this.fetch.call(void 0,t,r)}finally{clearTimeout(U)}}async shouldRetry(t){let n=t.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,n,a,i){let s,o=i?.get("retry-after-ms");if(o){let S=parseFloat(o);Number.isNaN(S)||(s=S)}let d=i?.get("retry-after");if(d&&!s){let S=parseFloat(d);Number.isNaN(S)?s=Date.parse(d)-Date.now():s=S*1e3}if(s===void 0){let S=t.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(n,S)}return await Wi(s),this.makeRequest(t,n-1,a)}calculateDefaultRetryTimeoutMillis(t,n){let s=n-t,o=Math.min(.5*Math.pow(2,s),8),d=1-Math.random()*.25;return o*d*1e3}async buildRequest(t,{retryCount:n=0}={}){let a={...t},{method:i,path:s,query:o,defaultBaseURL:d}=a,S=this.buildURL(s,o,d);"timeout"in a&&Ii("timeout",a.timeout),a.timeout=a.timeout??this.timeout;let{bodyHeaders:U,body:c}=this.buildBody({options:a}),r=await this.buildHeaders({options:t,method:i,bodyHeaders:U,retryCount:n});return{req:{method:i,headers:r,...a.signal&&{signal:a.signal},...globalThis.ReadableStream&&c instanceof globalThis.ReadableStream&&{duplex:"half"},...c&&{body:c},...this.fetchOptions??{},...a.fetchOptions??{}},url:S,timeout:a.timeout}}async buildHeaders({options:t,method:n,bodyHeaders:a,retryCount:i}){let s={};this.idempotencyHeader&&n!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=t.idempotencyKey);let o=N([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...Ri(),"X-\u004b\u0065\u0072\u006e\u0065\u006c-Project-Id":this.projectID,"X-\u004b\u0065\u0072\u006e\u0065\u006c-Project":this.project},await this.authHeaders(t),this._options.defaultHeaders,a,t.headers]);return this.validateHeaders(o),o.values}_makeAbort(t){return()=>t.abort()}buildBody({options:t}){let{body:n,headers:a}=t;if(!n)return n==null&&"body"in t?Q(this,sn,"f").call(this,{body:n,headers:N([a])}):{bodyHeaders:void 0,body:void 0};let i=N([a]);return ArrayBuffer.isView(n)||n instanceof ArrayBuffer||n instanceof DataView||typeof n=="string"&&i.values.has("content-type")||globalThis.Blob&&n instanceof globalThis.Blob||n instanceof FormData||n instanceof URLSearchParams||globalThis.ReadableStream&&n instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:n}:typeof n=="object"&&(Symbol.asyncIterator in n||Symbol.iterator in n&&"next"in n&&typeof n.next=="function")?{bodyHeaders:void 0,body:Cn(n)}:typeof n=="object"&&i.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(n)}:Q(this,sn,"f").call(this,{body:n,headers:i})}app(t){return new Wn(t)}};Pa=V,sn=new WeakMap,Na=new WeakSet,Us=function(){return this.baseURL!==cs[this._options.environment||"production"]};V.\u004b\u0065\u0072\u006e\u0065\u006c=Pa;V.DEFAULT_TIMEOUT=6e4;V.\u004b\u0065\u0072\u006e\u0065\u006cError=j;V.APIError=lt;V.APIConnectionError=Lt;V.APIConnectionTimeoutError=vt;V.APIUserAbortError=ht;V.NotFoundError=me;V.ConflictError=Ce;V.RateLimitError=ke;V.BadRequestError=we;V.AuthenticationError=pe;V.InternalServerError=Me;V.PermissionDeniedError=ye;V.UnprocessableEntityError=fe;V.toFile=An;V.Deployments=Zt;V.Apps=zt;V.Invocations=ee;V.Browsers=wt;V.Profiles=ne;V.Auth=Nt;V.Telemetry=Ht;V.Proxies=ae;V.Extensions=te;V.BrowserPools=$t;V.Credentials=Xt;V.Projects=Et;V.Organization=Pt;V.AuditLogs=Rt;V.APIKeys=qt;V.CredentialProviders=Qt;var us=require("crypto");var Ad="pr.oxylabs.io",xd=7777,Wd=10;function hs(){return process.env.OXYLABS_USERNAME?.trim()||void 0}function gs(){return process.env.OXYLABS_PASSWORD?.trim()||void 0}function Od(){return(process.env.OXYLABS_COUNTRY?.trim()||"US").toUpperCase()}function ws(){return!!(hs()&&gs())}function Ld(){let e="";for(let t=0;t<10;t++)e+=String((0,us.randomInt)(0,10));return e}function Bd(e={}){let t=hs();if(!t)return;let n=t.startsWith("customer-")?t:`customer-${t}`,a=(e.country?.trim()||Od()).toUpperCase(),i=e.sticky?`-sessid-${Ld()}-sesstime-${Wd}`:"";return`${n}-cc-${a}${i}`}function Ia(e){return e.replace(/pr\.oxylabs\.io(:\d+)?/gi,"backup proxy").replace(/oxylabs/gi,"backup proxy")}function Rd(e){return`mcp-backup-custom-${`${Date.now()}-${e??0}-${Math.random().toString(36).slice(2,8)}`}`}async function ps(e,t={}){let n=Bd({sticky:t.sticky}),a=gs();if(!n||!a)throw new Error("backup proxy pool is not configured");let i=new V({apiKey:e});try{let s=await i.proxies.create({type:"custom",name:Rd(t.attemptIndex),protocol:"http",config:{host:Ad,port:xd,username:n,password:a}});if(!s.id)throw new Error("backup proxy creation did not return a proxy id");return s.id}catch(s){let o=s instanceof Error?s.message:String(s);throw new Error(Ia(o))}}var ie={austin:"Austin,Texas,United States","new york":"New York,New York,United States","new york city":"New York,New York,United States",nyc:"New York,New York,United States","los angeles":"Los Angeles,California,United States",la:"Los Angeles,California,United States",chicago:"Chicago,Illinois,United States",houston:"Houston,Texas,United States",phoenix:"Phoenix,Arizona,United States",philadelphia:"Philadelphia,Pennsylvania,United States",philly:"Philadelphia,Pennsylvania,United States","san antonio":"San Antonio,Texas,United States",dallas:"Dallas,Texas,United States",miami:"Miami,Florida,United States",seattle:"Seattle,Washington,United States",denver:"Denver,Colorado,United States",loveland:"Loveland,Colorado,United States","loveland co":"Loveland,Colorado,United States","fort collins":"Fort Collins,Colorado,United States",boulder:"Boulder,Colorado,United States","colorado springs":"Colorado Springs,Colorado,United States",boston:"Boston,Massachusetts,United States",atlanta:"Atlanta,Georgia,United States","san francisco":"San Francisco,California,United States",sf:"San Francisco,California,United States",portland:"Portland,Oregon,United States","las vegas":"Las Vegas,Nevada,United States",minneapolis:"Minneapolis,Minnesota,United States",detroit:"Detroit,Michigan,United States",nashville:"Nashville,Tennessee,United States",charlotte:"Charlotte,North Carolina,United States",orlando:"Orlando,Florida,United States","san diego":"San Diego,California,United States",baltimore:"Baltimore,Maryland,United States",sacramento:"Sacramento,California,United States",columbus:"Columbus,Ohio,United States",indianapolis:"Indianapolis,Indiana,United States","san jose":"San Jose,California,United States","fort worth":"Fort Worth,Texas,United States",jacksonville:"Jacksonville,Florida,United States",memphis:"Memphis,Tennessee,United States",louisville:"Louisville,Kentucky,United States",raleigh:"Raleigh,North Carolina,United States",richmond:"Richmond,Virginia,United States","salt lake city":"Salt Lake City,Utah,United States",toronto:"Toronto,Ontario,Canada",vancouver:"Vancouver,British Columbia,Canada",montreal:"Montreal,Quebec,Canada",calgary:"Calgary,Alberta,Canada",ottawa:"Ottawa,Ontario,Canada",london:"London,England,United Kingdom",manchester:"Manchester,England,United Kingdom",birmingham:"Birmingham,England,United Kingdom",edinburgh:"Edinburgh,Scotland,United Kingdom",glasgow:"Glasgow,Scotland,United Kingdom",leeds:"Leeds,England,United Kingdom",sydney:"Sydney,New South Wales,Australia",melbourne:"Melbourne,Victoria,Australia",brisbane:"Brisbane,Queensland,Australia",perth:"Perth,Western Australia,Australia",adelaide:"Adelaide,South Australia,Australia",dublin:"Dublin,Leinster,Ireland"};var ys=`3, Nanjemoy,Maryland,United States
11
11
  Aaronsburg,Pennsylvania,United States
12
12
  Abbeville,Alabama,United States
@@ -21700,7 +21700,7 @@ Zuehl,Texas,United States
21700
21700
  Zumbrota,Minnesota,United States
21701
21701
  Zuni,New Mexico,United States
21702
21702
  Zwolle,Louisiana,United States`,ms={ad:"Andorra",ae:"United Arab Emirates",af:"Afghanistan",ag:"Antigua and Barbuda",al:"Albania",am:"Armenia",ao:"Angola",aq:"Antarctica",ar:"Argentina",as:"American Samoa",at:"Austria",au:"Australia",az:"Azerbaijan",ba:"Bosnia and Herzegovina",bb:"Barbados",bd:"Bangladesh",be:"Belgium",bf:"Burkina Faso",bg:"Bulgaria",bh:"Bahrain",bi:"Burundi",bj:"Benin",bl:"Saint Barthelemy",bn:"Brunei",bo:"Bolivia",bq:"Caribbean Netherlands",br:"Brazil",bs:"The Bahamas",bt:"Bhutan",bw:"Botswana",by:"Belarus",bz:"Belize",ca:"Canada",cc:"Cocos (Keeling) Islands",cd:"Democratic Republic of the Congo",cf:"Central African Republic",cg:"Republic of the Congo",ch:"Switzerland",ci:"Cote d'Ivoire",ck:"Cook Islands",cl:"Chile",cm:"Cameroon",cn:"China",co:"Colombia",cr:"Costa Rica",cv:"Cabo Verde",cw:"Curacao",cx:"Christmas Island",cy:"Cyprus",cz:"Czechia",de:"Germany",dj:"Djibouti",dk:"Denmark",dm:"Dominica",do:"Dominican Republic",dz:"Algeria",ec:"Ecuador",ee:"Estonia",eg:"Egypt",er:"Eritrea",es:"Spain",et:"Ethiopia",fi:"Finland",fj:"Fiji",fm:"Micronesia",fr:"France",ga:"Gabon",gb:"United Kingdom",gd:"Grenada",ge:"Georgia",gg:"Guernsey",gh:"Ghana",gm:"The Gambia",gn:"Guinea",gq:"Equatorial Guinea",gr:"Greece",gs:"South Georgia and the South Sandwich Islands",gt:"Guatemala",gu:"Guam",gw:"Guinea-Bissau",gy:"Guyana",hm:"Heard Island and McDonald Islands",hn:"Honduras",hr:"Croatia",ht:"Haiti",hu:"Hungary",id:"Indonesia",ie:"Ireland",il:"Israel",im:"Isle of Man",in:"India",iq:"Iraq",is:"Iceland",it:"Italy",je:"Jersey",jm:"Jamaica",jo:"Jordan",jp:"Japan",ke:"Kenya",kg:"Kyrgyzstan",kh:"Cambodia",ki:"Kiribati",km:"Comoros",kn:"Saint Kitts and Nevis",kr:"South Korea",kw:"Kuwait",kz:"Kazakhstan",la:"Laos",lb:"Lebanon",lc:"Saint Lucia",li:"Liechtenstein",lk:"Sri Lanka",lr:"Liberia",ls:"Lesotho",lt:"Lithuania",lu:"Luxembourg",lv:"Latvia",ly:"Libya",ma:"Morocco",mc:"Monaco",md:"Moldova",me:"Montenegro",mf:"Saint Martin",mg:"Madagascar",mh:"Marshall Islands",mk:"North Macedonia",ml:"Mali",mm:"Myanmar (Burma)",mn:"Mongolia",mp:"Northern Mariana Islands",mr:"Mauritania",mt:"Malta",mu:"Mauritius",mv:"Maldives",mw:"Malawi",mx:"Mexico",my:"Malaysia",mz:"Mozambique",na:"Namibia",nc:"New Caledonia",ne:"Niger",nf:"Norfolk Island",ng:"Nigeria",ni:"Nicaragua",nl:"Netherlands",no:"Norway",np:"Nepal",nr:"Nauru",nu:"Niue",nz:"New Zealand",om:"Oman",pa:"Panama",pe:"Peru",pf:"French Polynesia",pg:"Papua New Guinea",ph:"Philippines",pk:"Pakistan",pl:"Poland",pm:"Saint Pierre and Miquelon",pn:"Pitcairn Islands",pt:"Portugal",pw:"Palau",py:"Paraguay",qa:"Qatar",ro:"Romania",rs:"Serbia",ru:"Russia",rw:"Rwanda",sa:"Saudi Arabia",sb:"Solomon Islands",sc:"Seychelles",sd:"Sudan",se:"Sweden",sg:"Singapore",sh:"Saint Helena, Ascension and Tristan da Cunha",si:"Slovenia",sk:"Slovakia",sl:"Sierra Leone",sm:"San Marino",sn:"Senegal",so:"Somalia",sr:"Suriname",ss:"South Sudan",st:"Sao Tome and Principe",sv:"El Salvador",sx:"Sint Maarten",sy:"Syria",sz:"Eswatini",td:"Chad",tf:"French Southern and Antarctic Lands",tg:"Togo",th:"Thailand",tj:"Tajikistan",tk:"Tokelau",tl:"Timor-Leste",tm:"Turkmenistan",tn:"Tunisia",to:"Tonga",tr:"Turkiye",tt:"Trinidad and Tobago",tv:"Tuvalu",tz:"Tanzania",ua:"Ukraine",ug:"Uganda",um:"United States Minor Outlying Islands",us:"United States",uy:"Uruguay",uz:"Uzbekistan",va:"Vatican City",vc:"Saint Vincent and the Grenadines",ve:"Venezuela",vn:"Vietnam",vu:"Vanuatu",wf:"Wallis and Futuna",ws:"Samoa",ye:"Yemen",za:"South Africa",zm:"Zambia",zw:"Zimbabwe"};var Aa={AL:"Alabama",AK:"Alaska",AZ:"Arizona",AR:"Arkansas",CA:"California",CO:"Colorado",CT:"Connecticut",DE:"Delaware",DC:"District of Columbia",FL:"Florida",GA:"Georgia",HI:"Hawaii",ID:"Idaho",IL:"Illinois",IN:"Indiana",IA:"Iowa",KS:"Kansas",KY:"Kentucky",LA:"Louisiana",ME:"Maine",MD:"Maryland",MA:"Massachusetts",MI:"Michigan",MN:"Minnesota",MS:"Mississippi",MO:"Missouri",MT:"Montana",NE:"Nebraska",NV:"Nevada",NH:"New Hampshire",NJ:"New Jersey",NM:"New Mexico",NY:"New York",NC:"North Carolina",ND:"North Dakota",OH:"Ohio",OK:"Oklahoma",OR:"Oregon",PA:"Pennsylvania",PR:"Puerto Rico",RI:"Rhode Island",SC:"South Carolina",SD:"South Dakota",TN:"Tennessee",TX:"Texas",UT:"Utah",VT:"Vermont",VA:"Virginia",WA:"Washington",WV:"West Virginia",WI:"Wisconsin",WY:"Wyoming"};var xa=null,fs=null;function Ed(){if(xa)return;let e=new Map,t=new Map;for(let n of ys.split(`
21703
- `)){let a=n.trim();if(!a)continue;let i=a.toLowerCase();e.has(i)||e.set(i,a);let s=i.split(",",1)[0],o=t.get(s);o?o.push(a):t.set(s,[a])}for(let n of Object.values(ms)){let a=String(n).toLowerCase();e.has(a)||e.set(a,String(n))}xa=e,fs=t}function Hd(e){let t=[],n=e;do{let a=n&127;n>>>=7,n>0&&(a|=128),t.push(a)}while(n>0);return t}function ks(e){let t=Buffer.from(e,"utf8");return`w+${Buffer.concat([Buffer.from([8,2,16,32,34]),Buffer.from(Hd(t.length)),t]).toString("base64")}`}function Cs(){return{canonical:null,matched:!1,source:"unresolved",ambiguousCandidates:0}}function Ft(e,t){return{canonical:e,matched:!0,source:t,ambiguousCandidates:0}}function Wa(e){let t=e.toLowerCase().trim();if(!t)return Cs();if(ie[t])return Ft(ie[t],"alias");Ed();let n=xa,a=fs,i=n.get(t);if(i)return Ft(i,"exact");let s=n.get(`${t},united states`);if(s)return Ft(s,"state-or-country");let o=t.split(",");if(o.length>=2){let r=o[0].trim(),l=o.slice(1).join(",").trim(),u=Aa[l.toUpperCase()]??l,h=n.get(`${r},${u.toLowerCase()},united states`);if(h)return Ft(h,"city-state")}let d=t.match(/^(.*?)[\s,]+([a-z]{2})$/);if(d){let r=Aa[d[2].toUpperCase()];if(r){let l=n.get(`${d[1].trim()},${r.toLowerCase()},united states`);if(l)return Ft(l,"city-state")}}let S=a.get(t);if(S?.length===1)return Ft(S[0],"city-unique");if(S&&S.length>1)return{canonical:null,matched:!1,source:"unresolved",ambiguousCandidates:S.length};let U=o[0].trim();if(U!==t&&ie[U])return Ft(ie[U],"alias-partial");let c=t.replace(/\s+[a-z]{2}$/,"").trim();return c!==t&&ie[c]?Ft(ie[c],"alias-partial"):Cs()}function Ms(e){return Wa(e).canonical??e}var vs={alabama:"AL",alaska:"AK",arizona:"AZ",arkansas:"AR",california:"CA",colorado:"CO",connecticut:"CT",delaware:"DE",florida:"FL",georgia:"GA",hawaii:"HI",idaho:"ID",illinois:"IL",indiana:"IN",iowa:"IA",kansas:"KS",kentucky:"KY",louisiana:"LA",maine:"ME",maryland:"MD",massachusetts:"MA",michigan:"MI",minnesota:"MN",mississippi:"MS",missouri:"MO",montana:"MT",nebraska:"NE",nevada:"NV","new hampshire":"NH","new jersey":"NJ","new mexico":"NM","new york":"NY","north carolina":"NC","north dakota":"ND",ohio:"OH",oklahoma:"OK",oregon:"OR",pennsylvania:"PA","rhode island":"RI","south carolina":"SC","south dakota":"SD",tennessee:"TN",texas:"TX",utah:"UT",vermont:"VT",virginia:"VA",washington:"WA","west virginia":"WV",wisconsin:"WI",wyoming:"WY"},Fd={"atlanta|GA":"30303","austin|TX":"78701","baltimore|MD":"21201","boston|MA":"02108","boulder|CO":"80302","charlotte|NC":"28202","chicago|IL":"60601","colorado_springs|CO":"80903","columbus|OH":"43215","dallas|TX":"75201","denver|CO":"80202","detroit|MI":"48226","fort_collins|CO":"80524","fort_worth|TX":"76102","houston|TX":"77002","indianapolis|IN":"46204","jacksonville|FL":"32202","las_vegas|NV":"89101","los_angeles|CA":"90012","louisville|KY":"40202","loveland|CO":"80537","memphis|TN":"38103","miami|FL":"33131","minneapolis|MN":"55401","nashville|TN":"37203","new_york|NY":"10001","orlando|FL":"32801","philadelphia|PA":"19103","phoenix|AZ":"85004","portland|OR":"97205","raleigh|NC":"27601","richmond|VA":"23219","sacramento|CA":"95814","salt_lake_city|UT":"84101","san_antonio|TX":"78205","san_diego|CA":"92101","san_francisco|CA":"94103","san_jose|CA":"95113","seattle|WA":"98101"};function _d(e){return e?e.slice(-6):null}function gt(e,t,n,a,i,s=!1){return{\u006b\u0065\u0072\u006e\u0065\u006cProxyId:n,...s&&n?{disposableProxyId:n}:{},resolution:{source:e,proxyType:e==="disabled"?"none":e==="configured_fallback"?"configured":e==="mobile_created"?"mobile":e==="isp_created"?"isp":e==="backup_custom"?"custom":e==="location_created"||e==="location_reused"?"residential":"unknown",proxyMode:t,proxyIdPresent:!!n,proxyIdSuffix:_d(n),target:a,error:i,disposable:s}}}function Dd(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function Gd(e){return e.trim().toLowerCase().replace(/\./g,"").replace(/\s+/g," ")}function Vd(e){if(!e)return!0;let t=Gd(e);return t==="united states"||t==="united states of america"||t==="usa"||t==="us"}function Ts(e){let t=e.trim();if(/^[A-Za-z]{2}$/.test(t)){let n=t.toUpperCase();return Object.values(vs).includes(n)?n:null}return vs[Dd(t)]??null}function Kd(e){let n=e.normalize("NFKD").replace(/[^\x00-\x7F]/g,"").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean),a=n.join("_"),i=n.join("");return Array.from(new Set([a,i].filter(Boolean)))}function Dt(e,t,n){return n?`mcp-serp-residential-${e.toLowerCase()}-${t.toLowerCase()}-${n}`:`mcp-serp-residential-${e.toLowerCase()}-${t.toLowerCase()}`}function On(e,t){let n=`${Date.now()}-${t??0}-${Math.random().toString(36).slice(2,8)}`;return`${e}-fresh-${n}`}function Yd(e){return`mcp-serp-residential-us-zip-${e}`}function Jd(e,t){if(!e||t.toLowerCase()!=="us")return null;let n=Ms(e),a=n.split(",").map(U=>U.trim()).filter(Boolean);if(a.length>1&&Vd(a[a.length-1])&&(a=a.slice(0,-1)),a.length===1){let U=Ts(a[0]);return U?{canonicalLocation:n,level:"state",country:"US",state:U,city:"",cityCandidates:[],proxyName:Dt("US",U),config:{country:"US",state:U}}:null}let[i="",s=""]=a;if(!i||!s)return null;let o=Ts(s);if(!o)return null;let d=Kd(i),S=d[0];return S?{canonicalLocation:n,level:"city",country:"US",state:o,city:S,cityCandidates:d,proxyName:Dt("US",o,S),config:{country:"US",state:o,city:S}}:null}function qd(e){return`${e.city}|${e.state}`}function bs(e,t){return t&&/^\d{5}$/.test(t)?t:Fd[qd(e)]??null}function Ns(e,t){return{...e,level:"zip",zip:t,proxyName:Yd(t),config:{country:e.country,state:e.state,zip:t}}}function Oa(e,t){return{...e,proxyName:t}}function Ba(e,t,n){return t.level==="zip"?e?.country?.toUpperCase()===t.country&&e?.zip===t.zip:e?.country?.toUpperCase()===t.country&&e?.state?.toUpperCase()===t.state&&(n?e?.city===n:!e?.city)}function zd(e,t){return e.find(n=>n.type==="residential"&&n.status!=="unavailable"&&!!n.id&&(n.name===t.proxyName||Ba(n.config,t,t.level==="city"?t.city:void 0)))??null}function $d(e,t){for(let n of t.cityCandidates){let a=Dt(t.country,t.state,n),i=e.find(s=>s.type==="residential"&&s.status!=="unavailable"&&!!s.id&&(s.name===a||Ba(s.config,t,n)));if(i)return i}return null}function Ln(e){return{...e,level:"state",proxyName:Dt(e.country,e.state),config:{country:e.country,state:e.state}}}function jd(e,t){let n=Dt(t.country,t.state);return e.find(a=>a.type==="residential"&&a.status!=="unavailable"&&!!a.id&&(a.name===n||Ba(a.config,t)))??null}function Qd(e,t){return Ln(e)}function _t(e){return e instanceof Error?e.message:String(e)}function Xd(e,t,n){let a=[],i=bs(e,t);if(i){let o=Ns(e,i);a.push(Oa(o,On(o.proxyName,n)))}for(let o of e.cityCandidates){let d={...e,level:"city",city:o,proxyName:Dt(e.country,e.state,o),config:{country:e.country,state:e.state,city:o}};a.push(Oa(d,On(d.proxyName,n)))}let s=Ln(e);return a.push(Oa(s,On(s.proxyName,n))),a}async function La(e,t,n){if(e.backupOnExhaustion&&n.length>0&&e.\u006b\u0065\u0072\u006e\u0065\u006cApiKey&&ws())try{let a=await ps(e.\u006b\u0065\u0072\u006e\u0065\u006cApiKey,{attemptIndex:e.attemptIndex});return gt("backup_custom",e.proxyMode,a,t,null,!0)}catch(a){n.push(`backup: ${Ia(_t(a))}`)}return gt("configured_fallback",e.proxyMode,e.configured\u004b\u0065\u0072\u006e\u0065\u006cProxyId,t,n.join(" | "))}async function Zd(e,t,n){let a=[];for(let i of Xd(n,t.proxyZip,t.attemptIndex))try{let s=await e.proxies.create({type:"residential",name:i.proxyName,config:i.level==="zip"?{country:i.country,zip:i.zip}:i.config});if(s.id)return gt("location_created",t.proxyMode,s.id,i,null,!0);a.push(`${i.proxyName}: \u004b\u0065\u0072\u006e\u0065\u006c did not return a proxy id`)}catch(s){a.push(`${i.proxyName}: ${_t(s)}`)}if(process.env.\u004b\u0045\u0052\u004e\u0045\u004c_PROXY_TYPE!=="residential"){let i=Ln(n);try{let s=await e.proxies.create({type:"isp",name:On(`mcp-serp-isp-${i.country.toLowerCase()}-${(i.state??"").toLowerCase()}`,t.attemptIndex),config:{country:i.country,...i.state?{state:i.state}:{}}});if(s.id)return gt("isp_created",t.proxyMode,s.id,i,null,!0);a.push("isp: \u004b\u0065\u0072\u006e\u0065\u006c did not return a proxy id")}catch(s){a.push(`isp: ${_t(s)}`)}}return La(t,n,a)}async function Ps(e,t){if(!e||!t)return;await new V({apiKey:e}).proxies.delete(t)}async function Is(e){if(e.proxyMode==="none")return gt("disabled",e.proxyMode,void 0,null,null);if(e.proxyMode==="configured")return gt("configured_fallback",e.proxyMode,e.configured\u004b\u0065\u0072\u006e\u0065\u006cProxyId,null,null);let t=Jd(e.location,e.gl);if(!t||!e.\u006b\u0065\u0072\u006e\u0065\u006cApiKey)return gt("configured_fallback",e.proxyMode,e.configured\u004b\u0065\u0072\u006e\u0065\u006cProxyId,t,t?null:"location could not be normalized to a US city/state proxy target");let n=new V({apiKey:e.\u006b\u0065\u0072\u006e\u0065\u006cApiKey});try{let a=e.attemptIndex??0;if(e.fresh)return await Zd(n,e,t);if(a>=1){let c=Qd(t,a),r=[];try{let l=await n.proxies.create({type:"residential",name:c.proxyName,config:c.config});if(l.id)return gt("location_created",e.proxyMode,l.id,c,null);r.push(`${c.state}: \u004b\u0065\u0072\u006e\u0065\u006c did not return a proxy id`)}catch(l){r.push(`${c.state}: ${_t(l)}`)}return La(e,c,r)}let i=[];for await(let c of await n.proxies.list())i.push(c);let s=bs(t,e.proxyZip),o=[];if(s){let c=Ns(t,s),r=zd(i,c);if(r?.id)return gt("location_reused",e.proxyMode,r.id,c,null);try{let l=await n.proxies.create({type:"residential",name:c.proxyName,config:{country:c.country,zip:s}});if(l.id)return gt("location_created",e.proxyMode,l.id,c,null);o.push(`${s}: \u004b\u0065\u0072\u006e\u0065\u006c did not return a proxy id`)}catch(l){o.push(`${s}: ${_t(l)}`)}}let d=$d(i,t);if(d?.id)return gt("location_reused",e.proxyMode,d.id,t,o.join(" | ")||null);for(let c of t.cityCandidates)try{let r=await n.proxies.create({type:"residential",name:Dt(t.country,t.state,c),config:{country:t.country,state:t.state,city:c}});if(r.id)return gt("location_created",e.proxyMode,r.id,{...t,level:"city",city:c,proxyName:Dt(t.country,t.state,c),config:{country:t.country,state:t.state,city:c}},null);o.push(`${c}: \u004b\u0065\u0072\u006e\u0065\u006c did not return a proxy id`)}catch(r){o.push(`${c}: ${_t(r)}`)}let S=Ln(t),U=jd(i,S);if(U?.id)return gt("location_reused",e.proxyMode,U.id,S,o.join(" | "));try{let c=await n.proxies.create({type:"residential",name:S.proxyName,config:S.config});if(c.id)return gt("location_created",e.proxyMode,c.id,S,o.join(" | "));o.push(`${S.state}: \u004b\u0065\u0072\u006e\u0065\u006c did not return a proxy id`)}catch(c){o.push(`${S.state}: ${_t(c)}`)}return La(e,t,o)}catch(a){return gt("configured_fallback",e.proxyMode,e.configured\u004b\u0065\u0072\u006e\u0065\u006cProxyId,t,_t(a))}}var As=require("async_hooks"),xs="MCP_SCRAPER_ALLOW_HEADLESS_HARVEST_TEST",Ws=new As.AsyncLocalStorage;function Os(e,t){return Ws.run(e,t)}function se(){return Ws.getStore()}function Ra(){return process.env.\u0042\u0052\u0049\u0047\u0048\u0054\u0044\u0041\u0054\u0041_BROWSER_WSS?.trim()||null}function Ls(){return process.env.SERP_BROWSER_PROVIDER?.trim().toLowerCase()==="\u006b\u0065\u0072\u006e\u0065\u006c"?!1:!!Ra()}var Hn=require("playwright-extra"),Zs=gn(require("puppeteer-extra-plugin-stealth"),1),to=require("playwright");var dt={paaItem:".related-question-pair",captchaMarker:'#captcha-form, #recaptcha, form[action*="/sorry/"], .g-recaptcha, [data-sitekey]'},on={container:'div[jscontroller="HWk0Gf"]',sectionHeading:'.mgAbYb[role="heading"]',item:"a.rIRoqf"},rn={udm:"39",item:"a.rIRoqf",durationPattern:/^\d+:\d+$/,platforms:["YouTube","TikTok","Instagram","Facebook","X"]},Bs={section:".ULSxyf",item:"a.KYg7td.INpicf",title:".hyYc0c",source:".K4ETW"},Rs={sectionTag:"g-section-with-header",sectionHeadingText:"What people are saying",card:'.dRzkFf[role="listitem"]',cardLink:'a.WlydOe[jsname="YKoRaf"]',titleH1:"h1.WQWxe",titleDiv:".eAaXgc",popularCommentLabel:".qgdis",source:".sTl1Td",platformBadge:".appd0, .KrMNbf",ytChannel:".sjVJQd",ytDate:".PLq9Je",authorNote:".nDgy9d"},Es={root:"[data-lhcontainer][data-streaming-container][eid]",legacyRoot:'[data-hveid="CBMQAA"]',wrapper:".Fgyi2e",controller:'[jscontroller="AkrxPe"]',contentSubtree:'[data-subtree="mfc"]',header:".heWuVc",heading:".Fzsovc.cwYVJe.RJPOee",showMoreButton:'[aria-label="Show more AI Overview"]',sourcesPanel:".OZ9ddf.WAUd4",disclaimer:".DuQANe.MSJHRb"},Hs={root:'[data-hveid="CAUQAA"]',wrapper:".Fgyi2e",citations:'.Fgyi2e [data-hveid] a[jsname="pxBnId"]'},Fs={result:".wHYlTd.tF2Cxc",title:"h3.LC20lb",siteName:".VuuXrf",cite:"cite.tjvcx",snippet:".VwiC3b",redditCite:"cite.qLRx3b",ratingWrap:".Y0A0hc",ratingValue:".yi40Hd",reviewCount:".RDApEe"},_s={headingText:"Businesses",card:".w7Dbne",name:".OSrXXb",ratingValue:".yi40Hd",reviewCount:".RDApEe"},Ds="2026-05-07";async function Bn(e,t,n,a){let i,s=!1,o,d=()=>{},S=()=>a?.reason instanceof DOMException&&a.reason.name==="TimeoutError"?a.reason:new ut,U=()=>d(S()),c=new Promise((l,u)=>{d=u}),r=async l=>{let u;try{await Promise.race([l.close().catch(()=>{}),new Promise(h=>{u=setTimeout(h,2e3)})])}finally{u&&clearTimeout(u)}};if(a?.aborted)throw S();a?.addEventListener("abort",U,{once:!0}),o=setTimeout(()=>d(new DOMException("Optional pagination timed out","TimeoutError")),3e4);try{return await Promise.race([(async()=>{let l=await e.newPage();if(s)throw await r(l),new ut;if(i=l,await t(l),s)throw new ut;return n(l)})(),c])}finally{s=!0,o&&clearTimeout(o),a?.removeEventListener("abort",U),i&&await r(i)}}var Fa=require("crypto");var tl=166667e-10;var el=.00111,nl=4,al=4e-4;function _e(e,t){let n=process.env[e]?.trim();if(!n)return t;let a=Number(n);return Number.isFinite(a)&&a>=0?a:t}var il=_e("NANGO_USD_PER_CONNECTION_MONTH",1),sl=_e("NANGO_USD_PER_FUNCTION_RUN",1e-4),ol=_e("NANGO_USD_PER_PROXY_REQUEST",1e-4),rl=_e("NANGO_USD_PER_COMPUTE_SEC",2e-4),dl=_e("\u0042\u0052\u0049\u0047\u0048\u0054\u0044\u0041\u0054\u0041_BROWSER_USD_PER_GB",8),qg=_e("\u0042\u0052\u0049\u0047\u0048\u0054\u0044\u0041\u0054\u0041_SERP_USD_PER_REQUEST",.002836168);function Ea(e,t){return Math.max(0,e)/1e3*tl}function Gs(e,t){return e==="fal_wizper"?Math.max(0,t)/nl*el:e==="deepinfra_qwen"?Math.max(0,t)/1e3*al:e==="openrouter"||e==="mcp_memory_video"||e==="mcp_memory_ai"?Math.max(0,t):e==="nango_connection"?Math.max(0,t)*il:e==="nango_function_run"?Math.max(0,t)*sl:e==="nango_proxy_request"?Math.max(0,t)*ol:e==="nango_compute"?Math.max(0,t)*rl:e==="\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061_browser_api"?Math.max(0,t)/1e9*dl:0}var Ha=!1,dn=null;async function Vs(){if(!Ha)return dn||(dn=ll().finally(()=>{dn=null}),dn)}async function ll(){let e=ze(),t=await e.execute(`
21703
+ `)){let a=n.trim();if(!a)continue;let i=a.toLowerCase();e.has(i)||e.set(i,a);let s=i.split(",",1)[0],o=t.get(s);o?o.push(a):t.set(s,[a])}for(let n of Object.values(ms)){let a=String(n).toLowerCase();e.has(a)||e.set(a,String(n))}xa=e,fs=t}function Hd(e){let t=[],n=e;do{let a=n&127;n>>>=7,n>0&&(a|=128),t.push(a)}while(n>0);return t}function ks(e){let t=Buffer.from(e,"utf8");return`w+${Buffer.concat([Buffer.from([8,2,16,32,34]),Buffer.from(Hd(t.length)),t]).toString("base64")}`}function Cs(){return{canonical:null,matched:!1,source:"unresolved",ambiguousCandidates:0}}function Ft(e,t){return{canonical:e,matched:!0,source:t,ambiguousCandidates:0}}function Wa(e){let t=e.toLowerCase().trim();if(!t)return Cs();if(ie[t])return Ft(ie[t],"alias");Ed();let n=xa,a=fs,i=n.get(t);if(i)return Ft(i,"exact");let s=n.get(`${t},united states`);if(s)return Ft(s,"state-or-country");let o=t.split(",");if(o.length>=2){let r=o[0].trim(),l=o.slice(1).join(",").trim(),u=Aa[l.toUpperCase()]??l,h=n.get(`${r},${u.toLowerCase()},united states`);if(h)return Ft(h,"city-state")}let d=t.match(/^(.*?)[\s,]+([a-z]{2})$/);if(d){let r=Aa[d[2].toUpperCase()];if(r){let l=n.get(`${d[1].trim()},${r.toLowerCase()},united states`);if(l)return Ft(l,"city-state")}}let S=a.get(t);if(S?.length===1)return Ft(S[0],"city-unique");if(S&&S.length>1)return{canonical:null,matched:!1,source:"unresolved",ambiguousCandidates:S.length};let U=o[0].trim();if(U!==t&&ie[U])return Ft(ie[U],"alias-partial");let c=t.replace(/\s+[a-z]{2}$/,"").trim();return c!==t&&ie[c]?Ft(ie[c],"alias-partial"):Cs()}function Ms(e){return Wa(e).canonical??e}var vs={alabama:"AL",alaska:"AK",arizona:"AZ",arkansas:"AR",california:"CA",colorado:"CO",connecticut:"CT",delaware:"DE",florida:"FL",georgia:"GA",hawaii:"HI",idaho:"ID",illinois:"IL",indiana:"IN",iowa:"IA",kansas:"KS",kentucky:"KY",louisiana:"LA",maine:"ME",maryland:"MD",massachusetts:"MA",michigan:"MI",minnesota:"MN",mississippi:"MS",missouri:"MO",montana:"MT",nebraska:"NE",nevada:"NV","new hampshire":"NH","new jersey":"NJ","new mexico":"NM","new york":"NY","north carolina":"NC","north dakota":"ND",ohio:"OH",oklahoma:"OK",oregon:"OR",pennsylvania:"PA","rhode island":"RI","south carolina":"SC","south dakota":"SD",tennessee:"TN",texas:"TX",utah:"UT",vermont:"VT",virginia:"VA",washington:"WA","west virginia":"WV",wisconsin:"WI",wyoming:"WY"},Fd={"atlanta|GA":"30303","austin|TX":"78701","baltimore|MD":"21201","boston|MA":"02108","boulder|CO":"80302","charlotte|NC":"28202","chicago|IL":"60601","colorado_springs|CO":"80903","columbus|OH":"43215","dallas|TX":"75201","denver|CO":"80202","detroit|MI":"48226","fort_collins|CO":"80524","fort_worth|TX":"76102","houston|TX":"77002","indianapolis|IN":"46204","jacksonville|FL":"32202","las_vegas|NV":"89101","los_angeles|CA":"90012","louisville|KY":"40202","loveland|CO":"80537","memphis|TN":"38103","miami|FL":"33131","minneapolis|MN":"55401","nashville|TN":"37203","new_york|NY":"10001","orlando|FL":"32801","philadelphia|PA":"19103","phoenix|AZ":"85004","portland|OR":"97205","raleigh|NC":"27601","richmond|VA":"23219","sacramento|CA":"95814","salt_lake_city|UT":"84101","san_antonio|TX":"78205","san_diego|CA":"92101","san_francisco|CA":"94103","san_jose|CA":"95113","seattle|WA":"98101"};function Dd(e){return e?e.slice(-6):null}function gt(e,t,n,a,i,s=!1){return{\u006b\u0065\u0072\u006e\u0065\u006cProxyId:n,...s&&n?{disposableProxyId:n}:{},resolution:{source:e,proxyType:e==="disabled"?"none":e==="configured_fallback"?"configured":e==="mobile_created"?"mobile":e==="isp_created"?"isp":e==="backup_custom"?"custom":e==="location_created"||e==="location_reused"?"residential":"unknown",proxyMode:t,proxyIdPresent:!!n,proxyIdSuffix:Dd(n),target:a,error:i,disposable:s}}}function _d(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function Gd(e){return e.trim().toLowerCase().replace(/\./g,"").replace(/\s+/g," ")}function Vd(e){if(!e)return!0;let t=Gd(e);return t==="united states"||t==="united states of america"||t==="usa"||t==="us"}function Ts(e){let t=e.trim();if(/^[A-Za-z]{2}$/.test(t)){let n=t.toUpperCase();return Object.values(vs).includes(n)?n:null}return vs[_d(t)]??null}function Kd(e){let n=e.normalize("NFKD").replace(/[^\x00-\x7F]/g,"").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean),a=n.join("_"),i=n.join("");return Array.from(new Set([a,i].filter(Boolean)))}function _t(e,t,n){return n?`mcp-serp-residential-${e.toLowerCase()}-${t.toLowerCase()}-${n}`:`mcp-serp-residential-${e.toLowerCase()}-${t.toLowerCase()}`}function On(e,t){let n=`${Date.now()}-${t??0}-${Math.random().toString(36).slice(2,8)}`;return`${e}-fresh-${n}`}function Yd(e){return`mcp-serp-residential-us-zip-${e}`}function Jd(e,t){if(!e||t.toLowerCase()!=="us")return null;let n=Ms(e),a=n.split(",").map(U=>U.trim()).filter(Boolean);if(a.length>1&&Vd(a[a.length-1])&&(a=a.slice(0,-1)),a.length===1){let U=Ts(a[0]);return U?{canonicalLocation:n,level:"state",country:"US",state:U,city:"",cityCandidates:[],proxyName:_t("US",U),config:{country:"US",state:U}}:null}let[i="",s=""]=a;if(!i||!s)return null;let o=Ts(s);if(!o)return null;let d=Kd(i),S=d[0];return S?{canonicalLocation:n,level:"city",country:"US",state:o,city:S,cityCandidates:d,proxyName:_t("US",o,S),config:{country:"US",state:o,city:S}}:null}function qd(e){return`${e.city}|${e.state}`}function bs(e,t){return t&&/^\d{5}$/.test(t)?t:Fd[qd(e)]??null}function Ns(e,t){return{...e,level:"zip",zip:t,proxyName:Yd(t),config:{country:e.country,state:e.state,zip:t}}}function Oa(e,t){return{...e,proxyName:t}}function Ba(e,t,n){return t.level==="zip"?e?.country?.toUpperCase()===t.country&&e?.zip===t.zip:e?.country?.toUpperCase()===t.country&&e?.state?.toUpperCase()===t.state&&(n?e?.city===n:!e?.city)}function zd(e,t){return e.find(n=>n.type==="residential"&&n.status!=="unavailable"&&!!n.id&&(n.name===t.proxyName||Ba(n.config,t,t.level==="city"?t.city:void 0)))??null}function $d(e,t){for(let n of t.cityCandidates){let a=_t(t.country,t.state,n),i=e.find(s=>s.type==="residential"&&s.status!=="unavailable"&&!!s.id&&(s.name===a||Ba(s.config,t,n)));if(i)return i}return null}function Ln(e){return{...e,level:"state",proxyName:_t(e.country,e.state),config:{country:e.country,state:e.state}}}function jd(e,t){let n=_t(t.country,t.state);return e.find(a=>a.type==="residential"&&a.status!=="unavailable"&&!!a.id&&(a.name===n||Ba(a.config,t)))??null}function Qd(e,t){return Ln(e)}function Dt(e){return e instanceof Error?e.message:String(e)}function Xd(e,t,n){let a=[],i=bs(e,t);if(i){let o=Ns(e,i);a.push(Oa(o,On(o.proxyName,n)))}for(let o of e.cityCandidates){let d={...e,level:"city",city:o,proxyName:_t(e.country,e.state,o),config:{country:e.country,state:e.state,city:o}};a.push(Oa(d,On(d.proxyName,n)))}let s=Ln(e);return a.push(Oa(s,On(s.proxyName,n))),a}async function La(e,t,n){if(e.backupOnExhaustion&&n.length>0&&e.\u006b\u0065\u0072\u006e\u0065\u006cApiKey&&ws())try{let a=await ps(e.\u006b\u0065\u0072\u006e\u0065\u006cApiKey,{attemptIndex:e.attemptIndex});return gt("backup_custom",e.proxyMode,a,t,null,!0)}catch(a){n.push(`backup: ${Ia(Dt(a))}`)}return gt("configured_fallback",e.proxyMode,e.configured\u004b\u0065\u0072\u006e\u0065\u006cProxyId,t,n.join(" | "))}async function Zd(e,t,n){let a=[];for(let i of Xd(n,t.proxyZip,t.attemptIndex))try{let s=await e.proxies.create({type:"residential",name:i.proxyName,config:i.level==="zip"?{country:i.country,zip:i.zip}:i.config});if(s.id)return gt("location_created",t.proxyMode,s.id,i,null,!0);a.push(`${i.proxyName}: \u004b\u0065\u0072\u006e\u0065\u006c did not return a proxy id`)}catch(s){a.push(`${i.proxyName}: ${Dt(s)}`)}if(process.env.\u004b\u0045\u0052\u004e\u0045\u004c_PROXY_TYPE!=="residential"){let i=Ln(n);try{let s=await e.proxies.create({type:"isp",name:On(`mcp-serp-isp-${i.country.toLowerCase()}-${(i.state??"").toLowerCase()}`,t.attemptIndex),config:{country:i.country,...i.state?{state:i.state}:{}}});if(s.id)return gt("isp_created",t.proxyMode,s.id,i,null,!0);a.push("isp: \u004b\u0065\u0072\u006e\u0065\u006c did not return a proxy id")}catch(s){a.push(`isp: ${Dt(s)}`)}}return La(t,n,a)}async function Ps(e,t){if(!e||!t)return;await new V({apiKey:e}).proxies.delete(t)}async function Is(e){if(e.proxyMode==="none")return gt("disabled",e.proxyMode,void 0,null,null);if(e.proxyMode==="configured")return gt("configured_fallback",e.proxyMode,e.configured\u004b\u0065\u0072\u006e\u0065\u006cProxyId,null,null);let t=Jd(e.location,e.gl);if(!t||!e.\u006b\u0065\u0072\u006e\u0065\u006cApiKey)return gt("configured_fallback",e.proxyMode,e.configured\u004b\u0065\u0072\u006e\u0065\u006cProxyId,t,t?null:"location could not be normalized to a US city/state proxy target");let n=new V({apiKey:e.\u006b\u0065\u0072\u006e\u0065\u006cApiKey});try{let a=e.attemptIndex??0;if(e.fresh)return await Zd(n,e,t);if(a>=1){let c=Qd(t,a),r=[];try{let l=await n.proxies.create({type:"residential",name:c.proxyName,config:c.config});if(l.id)return gt("location_created",e.proxyMode,l.id,c,null);r.push(`${c.state}: \u004b\u0065\u0072\u006e\u0065\u006c did not return a proxy id`)}catch(l){r.push(`${c.state}: ${Dt(l)}`)}return La(e,c,r)}let i=[];for await(let c of await n.proxies.list())i.push(c);let s=bs(t,e.proxyZip),o=[];if(s){let c=Ns(t,s),r=zd(i,c);if(r?.id)return gt("location_reused",e.proxyMode,r.id,c,null);try{let l=await n.proxies.create({type:"residential",name:c.proxyName,config:{country:c.country,zip:s}});if(l.id)return gt("location_created",e.proxyMode,l.id,c,null);o.push(`${s}: \u004b\u0065\u0072\u006e\u0065\u006c did not return a proxy id`)}catch(l){o.push(`${s}: ${Dt(l)}`)}}let d=$d(i,t);if(d?.id)return gt("location_reused",e.proxyMode,d.id,t,o.join(" | ")||null);for(let c of t.cityCandidates)try{let r=await n.proxies.create({type:"residential",name:_t(t.country,t.state,c),config:{country:t.country,state:t.state,city:c}});if(r.id)return gt("location_created",e.proxyMode,r.id,{...t,level:"city",city:c,proxyName:_t(t.country,t.state,c),config:{country:t.country,state:t.state,city:c}},null);o.push(`${c}: \u004b\u0065\u0072\u006e\u0065\u006c did not return a proxy id`)}catch(r){o.push(`${c}: ${Dt(r)}`)}let S=Ln(t),U=jd(i,S);if(U?.id)return gt("location_reused",e.proxyMode,U.id,S,o.join(" | "));try{let c=await n.proxies.create({type:"residential",name:S.proxyName,config:S.config});if(c.id)return gt("location_created",e.proxyMode,c.id,S,o.join(" | "));o.push(`${S.state}: \u004b\u0065\u0072\u006e\u0065\u006c did not return a proxy id`)}catch(c){o.push(`${S.state}: ${Dt(c)}`)}return La(e,t,o)}catch(a){return gt("configured_fallback",e.proxyMode,e.configured\u004b\u0065\u0072\u006e\u0065\u006cProxyId,t,Dt(a))}}var As=require("async_hooks"),xs="MCP_SCRAPER_ALLOW_HEADLESS_HARVEST_TEST",Ws=new As.AsyncLocalStorage;function Os(e,t){return Ws.run(e,t)}function se(){return Ws.getStore()}function Ra(){return process.env.\u0042\u0052\u0049\u0047\u0048\u0054\u0044\u0041\u0054\u0041_BROWSER_WSS?.trim()||null}function Ls(){return process.env.SERP_BROWSER_PROVIDER?.trim().toLowerCase()==="\u006b\u0065\u0072\u006e\u0065\u006c"?!1:!!Ra()}var Hn=require("playwright-extra"),Zs=gn(require("puppeteer-extra-plugin-stealth"),1),to=require("playwright");var dt={paaItem:".related-question-pair",captchaMarker:'#captcha-form, #recaptcha, form[action*="/sorry/"], .g-recaptcha, [data-sitekey]'},on={container:'div[jscontroller="HWk0Gf"]',sectionHeading:'.mgAbYb[role="heading"]',item:"a.rIRoqf"},rn={udm:"39",item:"a.rIRoqf",durationPattern:/^\d+:\d+$/,platforms:["YouTube","TikTok","Instagram","Facebook","X"]},Bs={section:".ULSxyf",item:"a.KYg7td.INpicf",title:".hyYc0c",source:".K4ETW"},Rs={sectionTag:"g-section-with-header",sectionHeadingText:"What people are saying",card:'.dRzkFf[role="listitem"]',cardLink:'a.WlydOe[jsname="YKoRaf"]',titleH1:"h1.WQWxe",titleDiv:".eAaXgc",popularCommentLabel:".qgdis",source:".sTl1Td",platformBadge:".appd0, .KrMNbf",ytChannel:".sjVJQd",ytDate:".PLq9Je",authorNote:".nDgy9d"},Es={root:"[data-lhcontainer][data-streaming-container][eid]",legacyRoot:'[data-hveid="CBMQAA"]',wrapper:".Fgyi2e",controller:'[jscontroller="AkrxPe"]',contentSubtree:'[data-subtree="mfc"]',header:".heWuVc",heading:".Fzsovc.cwYVJe.RJPOee",showMoreButton:'[aria-label="Show more AI Overview"]',sourcesPanel:".OZ9ddf.WAUd4",disclaimer:".DuQANe.MSJHRb"},Hs={root:'[data-hveid="CAUQAA"]',wrapper:".Fgyi2e",citations:'.Fgyi2e [data-hveid] a[jsname="pxBnId"]'},Fs={result:".wHYlTd.tF2Cxc",title:"h3.LC20lb",siteName:".VuuXrf",cite:"cite.tjvcx",snippet:".VwiC3b",redditCite:"cite.qLRx3b",ratingWrap:".Y0A0hc",ratingValue:".yi40Hd",reviewCount:".RDApEe"},Ds={headingText:"Businesses",card:".w7Dbne",name:".OSrXXb",ratingValue:".yi40Hd",reviewCount:".RDApEe"},_s="2026-05-07";async function Bn(e,t,n,a){let i,s=!1,o,d=()=>{},S=()=>a?.reason instanceof DOMException&&a.reason.name==="TimeoutError"?a.reason:new ut,U=()=>d(S()),c=new Promise((l,u)=>{d=u}),r=async l=>{let u;try{await Promise.race([l.close().catch(()=>{}),new Promise(h=>{u=setTimeout(h,2e3)})])}finally{u&&clearTimeout(u)}};if(a?.aborted)throw S();a?.addEventListener("abort",U,{once:!0}),o=setTimeout(()=>d(new DOMException("Optional pagination timed out","TimeoutError")),3e4);try{return await Promise.race([(async()=>{let l=await e.newPage();if(s)throw await r(l),new ut;if(i=l,await t(l),s)throw new ut;return n(l)})(),c])}finally{s=!0,o&&clearTimeout(o),a?.removeEventListener("abort",U),i&&await r(i)}}var Fa=require("crypto");var tl=166667e-10;var el=.00111,nl=4,al=4e-4;function De(e,t){let n=process.env[e]?.trim();if(!n)return t;let a=Number(n);return Number.isFinite(a)&&a>=0?a:t}var il=De("NANGO_USD_PER_CONNECTION_MONTH",1),sl=De("NANGO_USD_PER_FUNCTION_RUN",1e-4),ol=De("NANGO_USD_PER_PROXY_REQUEST",1e-4),rl=De("NANGO_USD_PER_COMPUTE_SEC",2e-4),dl=De("\u0042\u0052\u0049\u0047\u0048\u0054\u0044\u0041\u0054\u0041_BROWSER_USD_PER_GB",8),qg=De("\u0042\u0052\u0049\u0047\u0048\u0054\u0044\u0041\u0054\u0041_SERP_USD_PER_REQUEST",.002836168);function Ea(e,t){return Math.max(0,e)/1e3*tl}function Gs(e,t){return e==="fal_wizper"?Math.max(0,t)/nl*el:e==="deepinfra_qwen"?Math.max(0,t)/1e3*al:e==="openrouter"||e==="mcp_memory_video"||e==="mcp_memory_ai"?Math.max(0,t):e==="nango_connection"?Math.max(0,t)*il:e==="nango_function_run"?Math.max(0,t)*sl:e==="nango_proxy_request"?Math.max(0,t)*ol:e==="nango_compute"?Math.max(0,t)*rl:e==="\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061_browser_api"?Math.max(0,t)/1e9*dl:0}var Ha=!1,dn=null;async function Vs(){if(!Ha)return dn||(dn=ll().finally(()=>{dn=null}),dn)}async function ll(){let e=ze(),t=await e.execute(`
21704
21704
  SELECT
21705
21705
  (SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('\u006b\u0065\u0072\u006e\u0065\u006c_session_log', 'vendor_usage_log', 'cost_probe_runs')) = 3
21706
21706
  AND (SELECT COUNT(*) FROM pragma_table_info('\u006b\u0065\u0072\u006e\u0065\u006c_session_log') WHERE name IN ('proxy_source', 'proxy_type', 'method')) = 3
@@ -21770,10 +21770,10 @@ Zwolle,Louisiana,United States`,ms={ad:"Andorra",ae:"United Arab Emirates",af:"A
21770
21770
  )
21771
21771
  `),await e.execute("CREATE INDEX IF NOT EXISTS cost_probe_runs_tool ON cost_probe_runs(tool)");try{await e.execute("ALTER TABLE cost_probe_runs ADD COLUMN units REAL")}catch{}try{await e.execute("ALTER TABLE cost_probe_runs ADD COLUMN unit_type TEXT")}catch{}try{await e.execute("ALTER TABLE cost_probe_runs ADD COLUMN mode TEXT")}catch{}Ha=!0}async function Ks(e){try{await Vs();let t=se(),n=Math.max(0,e.closedAtMs-e.openedAtMs);await ze().execute({sql:`INSERT INTO \u006b\u0065\u0072\u006e\u0065\u006c_session_log
21772
21772
  (id, \u006b\u0065\u0072\u006e\u0065\u006c_session_id, op, source, probe_run_id, user_id, stealth, headless_sent, proxy_used, proxy_source, proxy_type, fallback, opened_at, closed_at, duration_ms, est_cost_usd_headless, est_cost_usd_headful, error, method)
21773
- VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,args:[(0,Fa.randomUUID)(),e.\u006b\u0065\u0072\u006e\u0065\u006cSessionId??null,t?.op??null,e.source,t?.probeRunId??null,t?.userId??null,Rn(e.stealth),Rn(e.headlessSent),Rn(e.proxyUsed),e.proxySource??null,e.proxyType??null,e.fallback?1:0,new Date(e.openedAtMs).toISOString(),new Date(e.closedAtMs).toISOString(),n,Ea(n,!1),Ea(n,!0),e.error??null,t?.subOp??null]})}catch(t){console.warn("[cost-telemetry] record\u004b\u0065\u0072\u006e\u0065\u006cSession failed:",t instanceof Error?t.message:String(t))}}async function _a(e){try{await Vs();let t=se();return(await ze().execute({sql:`INSERT OR IGNORE INTO vendor_usage_log
21773
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,args:[(0,Fa.randomUUID)(),e.\u006b\u0065\u0072\u006e\u0065\u006cSessionId??null,t?.op??null,e.source,t?.probeRunId??null,t?.userId??null,Rn(e.stealth),Rn(e.headlessSent),Rn(e.proxyUsed),e.proxySource??null,e.proxyType??null,e.fallback?1:0,new Date(e.openedAtMs).toISOString(),new Date(e.closedAtMs).toISOString(),n,Ea(n,!1),Ea(n,!0),e.error??null,t?.subOp??null]})}catch(t){console.warn("[cost-telemetry] record\u004b\u0065\u0072\u006e\u0065\u006cSession failed:",t instanceof Error?t.message:String(t))}}async function Da(e){try{await Vs();let t=se();return(await ze().execute({sql:`INSERT OR IGNORE INTO vendor_usage_log
21774
21774
  (id, op, probe_run_id, user_id, vendor, model, units, unit_type, est_cost_usd, error, method, source_key, provider_duration_ms, provider_captcha, provider_status)
21775
- VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,args:[(0,Fa.randomUUID)(),e.op??t?.op??null,e.probeRunId??t?.probeRunId??null,e.userId??t?.userId??null,e.vendor,e.model??null,e.units,e.unitType,Gs(e.vendor,e.units),e.error??null,e.method??t?.subOp??null,e.sourceKey??null,e.providerDurationMs??null,Rn(e.providerCaptcha),e.providerStatus??null]})).rowsAffected===1}catch(t){return console.warn("[cost-telemetry] recordVendorUsage failed:",t instanceof Error?t.message:String(t)),!1}}function Rn(e){return e==null?null:e?1:0}var Sl=/\b(?:HeadlessChrome|Chrome|Chromium|Firefox)\/\d+|\bVersion\/\d+.*\bSafari\//;async function Da(e){try{let t=await e.evaluate(()=>navigator.userAgent);return typeof t=="string"&&Sl.test(t)?t:null}catch{return null}}async function Ga(e){let t=null;try{let n=e.contexts().flatMap(a=>a.pages())[0];return n||(t=await e.newContext(),n=t.pages()[0]??await t.newPage()),await Da(n)}catch{return null}finally{t&&await t.close().catch(()=>{})}}function Ys(e){let{headless:t,viewport:n,userAgent:a,user_agent:i,...s}=e;return s}async function Js(e,t={}){return t.blockServiceWorkers?e.newContext({viewport:null,serviceWorkers:"block"}):e.contexts()[0]??await e.newContext({viewport:null})}async function qs(e){return e.pages()[0]??await e.newPage()}function oe(e){return e.reason??new DOMException("The operation was aborted.","AbortError")}async function nt(e,t){if(!t)return e;if(t.aborted)throw oe(t);let n,a=new Promise((i,s)=>{n=()=>s(oe(t)),t.addEventListener("abort",n,{once:!0})});e.catch(()=>{});try{return await Promise.race([e,a])}finally{n&&t.removeEventListener("abort",n)}}function zs(e,t){let n=AbortSignal.timeout(e);return t?AbortSignal.any([t,n]):n}function En(e={}){let t=e.nowMs??Date.now(),n=Math.max(0,e.waitMs??3e4);return Math.min(e.deadlineMs??1/0,t+n)}var aw=En({nowMs:0});async function $s(e){let t=En(e),n=async()=>{if(e.signal?.aborted)throw oe(e.signal);let i=t-Date.now();if(i<=0)return!0;let s;try{return await nt(Promise.race([e.observeChallenge(),new Promise(o=>{s=setTimeout(()=>o(!0),i)})]),e.signal)}finally{s&&clearTimeout(s)}},a=await n();if(!e.solverEnabled)return a;for(;a&&Date.now()<t;){let i;try{await nt(new Promise(s=>{i=setTimeout(s,Math.min(500,t-Date.now()))}),e.signal)}finally{i&&clearTimeout(i)}if(e.signal?.aborted)throw oe(e.signal);if(Date.now()>t)break;a=await n()}return a}var Ul=`#search h3, #rso h3, #search .related-question-pair, #rso .related-question-pair, #search ${on.item}, #rso ${on.item}, #search .isv-r, #rso .isv-r`,cl=75e3,ul=3e3;async function Va(e,t){if(t.signal?.aborted)throw new ut;let n=Math.min(Date.now()+cl,t.deadlineMs===void 0?1/0:t.deadlineMs-ul);if(n<=Date.now())throw new ct("Google search navigation has no remaining time");let a=zs(Math.max(1,n-Date.now()),t.signal),i=!1,s,o=async()=>{if(!await nt(js(e),a))return!1;if(i=!0,s??=En({deadlineMs:n}),await $s({solverEnabled:t.solverEnabled,deadlineMs:s,signal:a,observeChallenge:()=>js(e)}))throw new et("Google challenge did not clear within the remaining browser time.");return!0};try{await wl(e,{params:hl(t),deadlineMs:n,signal:a},o,gl);let d=()=>nt(pl(e,{query:t.query,deadlineMs:n,signal:a,readySelector:Ul},o),a);if(await d(),t.purpose==="paa"){let S=Math.min(n,Date.now()+4e3);await nt(e.waitForSelector(dt.paaItem,{state:"visible",timeout:Math.max(1,S-Date.now())}).catch(()=>null),a);for(let U=1;U<=6&&Date.now()<n&&(await o(),!await nt(e.locator(dt.paaItem).count(),a));U+=1)await nt(e.evaluate(c=>{window.scrollTo(0,document.body.scrollHeight*c)},U/6),a),await nt(new Promise(c=>setTimeout(c,Math.min(400,n-Date.now()))),a)}for(;Date.now()<n;){await d();let S=await nt(e.locator(dt.paaItem).count(),a)>0;if(!await o())return{hasPaa:S,challengeObserved:i}}throw new ct("Google search results did not reach a readable state")}catch(d){throw t.signal?.aborted?new ut:d instanceof et||d instanceof ct?d:d instanceof Error&&d.message==="Google search results did not reach a readable state"?new ct(d.message):d instanceof Error&&/^Google search (?:homepage|consent inspection|consent|search box readiness|search box inspection|search box focus|search box clear|query typing|suggestion dismissal|search parameters|search button inspection|search submit) (?:failed|timed out)$/.test(d.message)?new ct(d.message):d instanceof Error&&["Google homepage did not expose a visible search box","Google search form did not expose a visible Search button"].includes(d.message)?new ct(d.message):new ct(a.aborted?"Google search navigation timed out before results were ready":"Google homepage search interaction failed")}}async function js(e){if(/google\.[^/]+\/sorry(?:\/|\?|$)/i.test(e.url())||await e.locator(dt.captchaMarker).count())return!0;let t=await e.locator("body").innerText({timeout:1e3}).catch(()=>"");return/recaptcha|unusual traffic|are you a robot|about this page|detected unusual traffic/i.test(t.slice(0,3e3))}function hl(e){let t={...e.extraParams,q:e.query,gl:e.gl,hl:e.hl,pws:"0"};return e.tbs&&(t.tbs=e.tbs),e.uule&&(t.uule=e.uule),t}async function gl(e,t={}){let n=t.deadlineMs??Date.now()+1e4,a=async(d,S,U=8e3)=>{let c=Math.min(U,n-Date.now());if(t.signal?.aborted){let h=new Error("Google search navigation aborted");throw h.name="AbortError",h}if(c<=0)throw new Error("Google search navigation deadline exhausted");let r,l,u=new Promise((h,w)=>{r=setTimeout(()=>w(new Error(`Google search ${d} timed out`)),c),t.signal&&(l=()=>{let g=new Error("Google search navigation aborted");g.name="AbortError",w(g)},t.signal.addEventListener("abort",l,{once:!0}))});try{return await Promise.race([S(c),u])}catch{if(t.signal?.aborted){let h=new Error("Google search navigation aborted");throw h.name="AbortError",h}throw new Error(`Google search ${d} failed`)}finally{r&&clearTimeout(r),l&&t.signal?.removeEventListener("abort",l)}},i=/^(reject all|reject optional|continue without accepting|only necessary|alle ablehnen|tout refuser|rechazar todo|rifiuta tutto|rejeitar tudo|alles afwijzen)$/i;if(!await a("consent inspection",()=>e.evaluate(d=>{let S=new RegExp(d,"i");return/^consent\.google\./i.test(window.location.hostname)||!!document.querySelector("#W0wltc")||Array.from(document.querySelectorAll('button, [role="button"]')).some(U=>S.test(U.textContent?.trim()??""))},i.source),2e3))return!1;let o=e.locator("#W0wltc").or(e.getByRole("button",{name:i}));for(let d=0,S=await a("consent inspection",()=>o.count(),2e3);d<S;d+=1){let U=o.nth(d);if(await a("consent inspection",()=>U.isVisible(),2e3))return await a("consent",c=>U.click({timeout:c})),!0}if(/consent\.google\./i.test(e.url()))throw new Error("Google consent did not expose a reject option");return!1}async function wl(e,t,n,a){let i=async(u,h,w=8e3)=>{let g=Math.min(w,t.deadlineMs-Date.now());if(t.signal?.aborted){let O=new Error("Google search navigation aborted");throw O.name="AbortError",O}if(g<=0)throw new Error("Google search navigation deadline exhausted");let C,y,m=new Promise((O,F)=>{C=setTimeout(()=>F(new Error(`Google search ${u} timed out`)),g),t.signal&&(y=()=>{let B=new Error("Google search navigation aborted");B.name="AbortError",F(B)},t.signal.addEventListener("abort",y,{once:!0}))});try{return await Promise.race([h(g),m])}catch{if(t.signal?.aborted){let F=new Error("Google search navigation aborted");throw F.name="AbortError",F}throw new Error(`Google search ${u} failed`)}finally{C&&clearTimeout(C),y&&t.signal?.removeEventListener("abort",y)}},s=()=>a(e,t);await i("homepage",u=>e.goto("https://www.google.com",{waitUntil:"domcontentloaded",timeout:u}),15e3),await n(),await s(),await n();let o='textarea[name="q"], input[name="q"]';await i("search box readiness",u=>e.waitForSelector(o,{state:"visible",timeout:u}));let d=e.locator(o),S;for(let u=0,h=await i("search box inspection",()=>d.count());u<h;u+=1)if(await i("search box inspection",()=>d.nth(u).isVisible())){S=d.nth(u);break}if(!S)throw new Error("Google homepage did not expose a visible search box");let U=S;await i("search box focus",u=>U.click({timeout:u})),await i("search box clear",u=>U.fill("",{timeout:u}));for(let u of t.params.q)await i("query typing",h=>U.pressSequentially(u,{delay:35+Math.floor(Math.random()*65),timeout:h}));let c=U.locator("xpath=ancestor::form[1]");await i("search parameters",()=>c.evaluate((u,h)=>{if(!(u instanceof HTMLFormElement))throw new Error("Google search form is unavailable");u.method="get";for(let[g,C]of Object.entries(h)){if(g==="q")continue;let y=Array.from(u.querySelectorAll("input")).filter(m=>m.name===g);for(let m of y)m.value=C,m.disabled=!1;if(y.length===0){let m=document.createElement("input");m.type="hidden",m.name=g,m.value=C,u.appendChild(m)}}let w=new URL(u.action,location.href);for(let g of Object.keys(h))w.searchParams.delete(g);u.action=w.toString()},t.params));let r=c.locator('input[name="btnK"], button[name="btnK"], button[type="submit"]'),l=!1;for(let u=0,h=await i("search button inspection",()=>r.count());u<h;u+=1){let w=r.nth(u);if(await i("search button inspection",()=>w.isVisible())){await i("search submit",g=>w.click({timeout:g,noWaitAfter:!0})),l=!0;break}}if(!l)throw new Error("Google search form did not expose a visible Search button");await n(),await s(),await n()}async function pl(e,t,n){let a=t.readySelector.split(",").map(s=>`${s.trim()}:visible`).join(", "),i;for(;Date.now()<t.deadlineMs;){if(t.signal?.aborted)throw new Error("Google search navigation aborted");let s=await n();if((i===void 0||s===!0)&&(i=Math.min(t.deadlineMs,Date.now()+15e3)),Date.now()>=i)break;let o=!1;try{let S=new URL(e.url());o=/(^|\.)google\.[a-z.]+$/i.test(S.hostname)&&S.pathname==="/search"&&S.searchParams.get("q")===t.query}catch{}if(o){let S=await e.waitForSelector(a,{state:"visible",timeout:Math.min(500,Math.max(1,i-Date.now()))}).catch(()=>null),U=S?!1:await e.locator("body").innerText({timeout:Math.min(1e3,Math.max(1,i-Date.now()))}).then(c=>/did not match any documents|no results found/i.test(c)).catch(()=>!1);if(S||U){if(await n()===!0)continue;return}}if(t.signal?.aborted)throw new Error("Google search navigation aborted");let d=Math.min(200,i-Date.now(),t.deadlineMs-Date.now());d>0&&await e.waitForTimeout(d)}throw new Error("Google search results did not reach a readable state")}Hn.chromium.use((0,Zs.default)());var yl=180,ml=3e3,Cl=5e3,fl='#search, #rso, a[href] h3, [data-snhf], [role="main"]';function Ka(e,t){return e?Math.max(1,Math.min(t,e-Date.now())):t}function kl(e,t){let n=process.env[e];if(!n)return t;let a=Number(n);return Number.isInteger(a)&&a>0?a:t}function Ya(e){return e?e.slice(-6):null}function Qs(e,t){let n=(t??process.env.SERP_REDIRECT_BASE)?.trim().replace(/\/+$/,"");return n?`${n}/g/${Buffer.from(e,"utf8").toString("base64url")}`:e}function Ml(e){return e?/united states|u\.?s\.?a?\.?|^us$/i.test(e.trim()):!1}function De(e){return e instanceof Error?e.message:String(e)}function vl(e){return/\b409\b|conflict|already exists/i.test(De(e))}function Tl(e){return/\b404\b|not[ _-]?found|already (?:gone|deleted|closed)|does not exist/i.test(De(e))}async function bl(e,t){try{await e.profiles.create({name:t})}catch(n){if(!vl(n))throw n}}function Xs(e,t){return{viewport:e.viewport,locale:e.locale,...t?{userAgent:t}:{},...e.deviceScaleFactor?{deviceScaleFactor:e.deviceScaleFactor}:{},...e.isMobile!==void 0?{isMobile:e.isMobile}:{},...e.hasTouch!==void 0?{hasTouch:e.hasTouch}:{}}}async function re(e,t,n){let a;try{return await Promise.race([e,new Promise((i,s)=>{a=setTimeout(()=>s(new Error(`${n} timed out after ${t}ms`)),t)})])}finally{a&&clearTimeout(a)}}function Nl(e){let t=e.trim();if(!t)throw new Error("channelHandle is required");if(/^https?:\/\//i.test(t)||/^(www\.|m\.)?youtube\.com\//i.test(t)){let o=new URL(/^https?:\/\//i.test(t)?t:`https://${t}`);if(o.hostname.replace(/^www\./,"").replace(/^m\./,"").toLowerCase()!=="youtube.com")throw new Error("channel URL must be on youtube.com");let S=o.pathname.split("/").filter(Boolean),U=S[0]??"",c=S[1]??"";if(U.startsWith("@"))return`https://www.youtube.com/${U}/videos`;if(U==="channel"&&c)return`https://www.youtube.com/channel/${c}/videos`;if((U==="c"||U==="user")&&c)return`https://www.youtube.com/${U}/${c}/videos`;throw new Error("channel URL must be a YouTube handle, /channel/UC..., /c/..., or /user/... URL")}let i=t.replace(/^\/+/,"").replace(/\/+$/,"").replace(/\/videos$/i,"");if(/^UC[\w-]{20,}$/.test(i))return`https://www.youtube.com/channel/${i}/videos`;let s=i.startsWith("@")?i:`@${i}`;if(!/^@[\w.-]+$/.test(s))throw new Error("channelHandle must be an @handle, UC channel ID, or YouTube channel URL");return`https://www.youtube.com/${s}/videos`}var Fn=class{browser=null;context=null;page=null;\u006b\u0065\u0072\u006e\u0065\u006cClient=null;\u006b\u0065\u0072\u006e\u0065\u006cSessionId=null;\u006b\u0065\u0072\u006e\u0065\u006cOpenedAtMs=null;\u006b\u0065\u0072\u006e\u0065\u006cStealth=null;\u006b\u0065\u0072\u006e\u0065\u006cSolverEnabled=!1;operationDeadlineMs;\u006b\u0065\u0072\u006e\u0065\u006cProxyUsed=null;\u006b\u0065\u0072\u006e\u0065\u006cProxySource=null;\u006b\u0065\u0072\u006e\u0065\u006cProxyType=null;\u006b\u0065\u0072\u006e\u0065\u006cHeadlessSent=null;last\u004b\u0065\u0072\u006e\u0065\u006cBillingMode=null;last\u004b\u0065\u0072\u006e\u0065\u006cOpenedAtMs=null;last\u004b\u0065\u0072\u006e\u0065\u006cClosedAtMs=null;debugEnabled=!1;debugSnapshot={\u006b\u0065\u0072\u006e\u0065\u006c:null,context:null,networkLocation:null,serpNavigation:null};async launch(t){if(t.\u006b\u0065\u0072\u006e\u0065\u006cApiKey&&t.isMobile)throw new ct("\u004b\u0065\u0072\u006e\u0065\u006c acquisition requires a native desktop browser; mobile capture needs provider-native mobile support.");this.operationDeadlineMs=t.operationDeadlineMs,this.debugEnabled=t.debug===!0;let n=t.proxyMode??(t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId?"configured":"none"),a=t.isMobile?"mobile":"desktop";if(this.debugSnapshot={\u006b\u0065\u0072\u006e\u0065\u006c:null,context:{viewport:t.viewport,locale:t.locale,device:a,userAgent:null,deviceScaleFactor:t.deviceScaleFactor??null,isMobile:t.isMobile===!0,hasTouch:t.hasTouch===!0},networkLocation:null,serpNavigation:null},t.\u006b\u0065\u0072\u006e\u0065\u006cApiKey){this.\u006b\u0065\u0072\u006e\u0065\u006cClient=new V({apiKey:t.\u006b\u0065\u0072\u006e\u0065\u006cApiKey});let s=Number.isInteger(t.\u006b\u0065\u0072\u006e\u0065\u006cTimeoutSeconds)&&Number(t.\u006b\u0065\u0072\u006e\u0065\u006cTimeoutSeconds)>0?Number(t.\u006b\u0065\u0072\u006e\u0065\u006cTimeoutSeconds):kl("\u004b\u0045\u0052\u004e\u0045\u004c_BROWSER_TIMEOUT_SECONDS",yl),o=Math.min(s,600);t.\u006b\u0065\u0072\u006e\u0065\u006cProfileName&&t.\u006b\u0065\u0072\u006e\u0065\u006cProfileSaveChanges===!0&&await bl(this.\u006b\u0065\u0072\u006e\u0065\u006cClient,t.\u006b\u0065\u0072\u006e\u0065\u006cProfileName);let d=se();this.\u006b\u0065\u0072\u006e\u0065\u006cHeadlessSent=null,this.last\u004b\u0065\u0072\u006e\u0065\u006cBillingMode="headful",d?.headlessSentOut&&(d.headlessSentOut.value=this.\u006b\u0065\u0072\u006e\u0065\u006cHeadlessSent);let S=await this.\u006b\u0065\u0072\u006e\u0065\u006cClient.browsers.create(Ys({stealth:t.\u006b\u0065\u0072\u006e\u0065\u006cStealth===!0,timeout_seconds:o,...t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId?{proxy_id:t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId}:{},...t.\u006b\u0065\u0072\u006e\u0065\u006cProfileName?{profile:{name:t.\u006b\u0065\u0072\u006e\u0065\u006cProfileName,...typeof t.\u006b\u0065\u0072\u006e\u0065\u006cProfileSaveChanges=="boolean"?{save_changes:t.\u006b\u0065\u0072\u006e\u0065\u006cProfileSaveChanges}:{}}}:{}}));this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId=S.session_id,this.\u006b\u0065\u0072\u006e\u0065\u006cOpenedAtMs=Date.now(),this.last\u004b\u0065\u0072\u006e\u0065\u006cOpenedAtMs=this.\u006b\u0065\u0072\u006e\u0065\u006cOpenedAtMs,this.last\u004b\u0065\u0072\u006e\u0065\u006cClosedAtMs=null,this.\u006b\u0065\u0072\u006e\u0065\u006cStealth=typeof S.stealth=="boolean"?S.stealth:null,this.\u006b\u0065\u0072\u006e\u0065\u006cSolverEnabled=t.\u006b\u0065\u0072\u006e\u0065\u006cStealth===!0&&S.stealth!==!1,this.\u006b\u0065\u0072\u006e\u0065\u006cProxyUsed=typeof S.proxy_id=="string"?!!S.proxy_id:!!t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId,this.\u006b\u0065\u0072\u006e\u0065\u006cProxySource=t.\u006b\u0065\u0072\u006e\u0065\u006cProxyResolution?.source??null,this.\u006b\u0065\u0072\u006e\u0065\u006cProxyType=t.\u006b\u0065\u0072\u006e\u0065\u006cProxyResolution?.proxyType??null;let U=null,c=null;if(!t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId&&!t.keepDefaultProxy)try{await re(this.\u006b\u0065\u0072\u006e\u0065\u006cClient.browsers.update(this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId,{disable_default_proxy:!0}),5e3,`\u004b\u0065\u0072\u006e\u0065\u006c session ${this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId} disable default proxy`),U=!0}catch(l){U=!1,c=De(l)}let r={sessionId:this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId,proxyMode:n,requestedProxyIdPresent:!!t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId,requestedProxyIdSuffix:Ya(t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId),createdProxyIdPresent:typeof S.proxy_id=="string"?!!S.proxy_id:null,createdProxyIdSuffix:Ya(S.proxy_id),retrievedProxyIdPresent:null,retrievedProxyIdSuffix:null,retrievedProxyIdMatchesRequested:null,defaultProxyDisabled:U,defaultProxyDisableError:c,proxyResolution:t.\u006b\u0065\u0072\u006e\u0065\u006cProxyResolution??null,timeoutSeconds:o,stealth:typeof S.stealth=="boolean"?S.stealth:null,profilePresent:null,poolPresent:null,retrieveError:null};if(this.debugSnapshot.\u006b\u0065\u0072\u006e\u0065\u006c=r,console.info(JSON.stringify({event:"\u006b\u0065\u0072\u006e\u0065\u006c_browser_created",\u006b\u0065\u0072\u006e\u0065\u006c_session_id:this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId,timeout_seconds:o,proxy_mode:n,proxy_id_present:!!t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId,profile_name_present:!!t.\u006b\u0065\u0072\u006e\u0065\u006cProfileName,proxy_resolution_source:t.\u006b\u0065\u0072\u006e\u0065\u006cProxyResolution?.source})),this.debugEnabled&&await this.populate\u004b\u0065\u0072\u006e\u0065\u006cRetrieveDebug(r,t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId),this.browser=await to.chromium.connectOverCDP(S.cdp_ws_url),this.context=await Js(this.browser),this.page=await qs(this.context),await this.capture\u004b\u0065\u0072\u006e\u0065\u006cContextDebug(),await this.installEsbuildHelperShims(this.context),(this.debugEnabled||t.requireUsEgress)&&(this.debugSnapshot.networkLocation=await this.captureBrowserNetworkLocation()),t.requireUsEgress){let l=this.debugSnapshot.networkLocation?.country??null;if(!Ml(l))throw new et(`Non-US egress (${l??"unknown"}) \u2014 retrying with a fresh session`)}return}let i={headless:t.headless,proxy:t.proxy?{server:t.proxy}:void 0,...t.browserExecutablePath?{executablePath:t.browserExecutablePath}:{},...t.ignoreDefaultArgs?{ignoreDefaultArgs:t.ignoreDefaultArgs}:{}};if(t.profileDir)this.context=await Hn.chromium.launchPersistentContext(t.profileDir,{...i,...Xs(t)}),await this.installEsbuildHelperShims(this.context),this.page=await this.context.newPage(),this.debugSnapshot.context.userAgent=await Da(this.page);else{this.browser=await Hn.chromium.launch(i);let s=await Ga(this.browser);this.debugSnapshot.context.userAgent=s,this.context=await this.browser.newContext(Xs(t,s)),await this.installEsbuildHelperShims(this.context),this.page=await this.context.newPage()}this.debugEnabled&&(this.debugSnapshot.networkLocation=await this.captureBrowserNetworkLocation())}async capture\u004b\u0065\u0072\u006e\u0065\u006cContextDebug(){if(this.debugSnapshot.context={viewport:null,locale:null,device:"desktop",requestedDevice:"desktop",userAgent:null,deviceScaleFactor:null,isMobile:!1,hasTouch:!1},!this.page)return;let t=await this.page.evaluate(()=>({viewport:{width:window.innerWidth,height:window.innerHeight},locale:navigator.language,userAgent:navigator.userAgent,deviceScaleFactor:window.devicePixelRatio,isMobile:!1,hasTouch:navigator.maxTouchPoints>0})).catch(()=>null);!t||typeof t!="object"||!t.viewport||typeof t.viewport.width!="number"||typeof t.viewport.height!="number"||typeof t.locale!="string"||typeof t.userAgent!="string"||(this.debugSnapshot.context={...t,device:"desktop",requestedDevice:"desktop"})}async populate\u004b\u0065\u0072\u006e\u0065\u006cRetrieveDebug(t,n){if(!(!this.\u006b\u0065\u0072\u006e\u0065\u006cClient||!this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId))try{let a=await re(this.\u006b\u0065\u0072\u006e\u0065\u006cClient.browsers.retrieve(this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId),5e3,`\u004b\u0065\u0072\u006e\u0065\u006c session ${this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId} retrieve`);t.retrievedProxyIdPresent=typeof a.proxy_id=="string"?!!a.proxy_id:!1,t.retrievedProxyIdSuffix=Ya(a.proxy_id),t.retrievedProxyIdMatchesRequested=n?a.proxy_id===n:!a.proxy_id,t.timeoutSeconds=typeof a.timeout_seconds=="number"?a.timeout_seconds:t.timeoutSeconds,t.stealth=typeof a.stealth=="boolean"?a.stealth:t.stealth,t.profilePresent=!!a.profile,t.poolPresent=!!a.pool}catch(a){t.retrieveError=De(a)}}async captureBrowserNetworkLocation(){let t=(a,i="ipapi.co")=>({source:i,ip:null,city:null,region:null,country:null,org:null,timezone:null,error:a});if(!this.context)return t("browser context is not available");let n=null;try{n=await this.context.newPage();let a=await this.loadJsonInDebugPage(n,"https://ipwho.is/");if(a){let d=typeof a.connection=="object"&&a.connection!==null?a.connection:{};return{source:"ipwho.is",ip:typeof a.ip=="string"?a.ip:null,city:typeof a.city=="string"?a.city:null,region:typeof a.region=="string"?a.region:null,country:typeof a.country=="string"?a.country:null,org:typeof d.org=="string"?d.org:null,timezone:typeof a.timezone=="object"&&a.timezone!==null&&typeof a.timezone.id=="string"?a.timezone.id:null,error:null}}let i=await this.loadJsonInDebugPage(n,"https://api64.ipify.org?format=json");if(i)return{source:"api64.ipify.org",ip:typeof i.ip=="string"?i.ip:null,city:null,region:null,country:null,org:null,timezone:null,error:null};await re(n.goto("https://ipapi.co/json/",{waitUntil:"domcontentloaded",timeout:7e3}),8e3,"browser network location navigation");let s=await n.locator("body").innerText({timeout:2e3}),o=JSON.parse(s);return{source:"ipapi.co",ip:typeof o.ip=="string"?o.ip:null,city:typeof o.city=="string"?o.city:null,region:typeof o.region=="string"?o.region:null,country:typeof o.country_name=="string"?o.country_name:typeof o.country=="string"?o.country:null,org:typeof o.org=="string"?o.org:null,timezone:typeof o.timezone=="string"?o.timezone:null,error:null}}catch(a){return t(De(a))}finally{await n?.close().catch(()=>{})}}async loadJsonInDebugPage(t,n){try{await re(t.goto(n,{waitUntil:"domcontentloaded",timeout:7e3}),8e3,`browser network location navigation ${n}`);let a=await t.locator("body").innerText({timeout:2e3});return JSON.parse(a)}catch{return null}}async installEsbuildHelperShims(t){await t.addInitScript(()=>{let n=globalThis;typeof n.__name!="function"&&(n.__name=a=>a),typeof n.__publicField!="function"&&(n.__publicField=(a,i,s)=>(a[i]=s,s))})}async withTemporaryPage(t,n){if(!this.context)throw new Error("Browser context is not available");return Bn(this.context,async()=>{},t,n)}async navigateToSERP(t,n,a,i,s){let o=new URLSearchParams({q:t,gl:a,hl:i,pws:"0"});s?.tbs&&o.set("tbs",s.tbs),n&&o.set("uule",n);let d="https://www.google.com/search?"+o.toString(),S=Qs(d),U=s?.debug?{requestedUrl:d,finalUrl:null,title:null,bodySnippet:null,hasPaa:null,captchaDetected:null,googleSorryUrl:null,redirected:null}:null;if(U&&(this.debugSnapshot.serpNavigation=U),this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId){let r={deadlineMs:s?.deadlineMs??this.operationDeadlineMs,signal:s?.signal};try{let l=await Va(this.page,{query:t,gl:a,hl:i,uule:n??void 0,tbs:s?.tbs,purpose:s?.purpose,deadlineMs:s?.deadlineMs??this.operationDeadlineMs,signal:s?.signal,solverEnabled:this.\u006b\u0065\u0072\u006e\u0065\u006cSolverEnabled});return await this.updateSerpNavigationDebug(U,d,{hasPaa:l.hasPaa,captchaDetected:l.challengeObserved===!0},r),{hasPaa:l.hasPaa}}catch(l){throw await this.updateSerpNavigationDebug(U,d,{hasPaa:null,captchaDetected:l instanceof et?!0:null},r),l}}try{await this.page.goto(S,{waitUntil:"domcontentloaded",timeout:Ka(s?.deadlineMs,s?.purpose==="serp"?8e3:45e3)})}catch(r){await this.updateSerpNavigationDebug(U,d,{hasPaa:null,captchaDetected:null});let l=await this.captureDiagnostics(d);throw new ct(`page.goto failed: ${r.message} | ${l}`)}if(await this.isSerpChallengeVisible())throw await this.updateSerpNavigationDebug(U,d,{hasPaa:!1,captchaDetected:!0}),new et(this.captchaMessage());if(s?.purpose==="serp"){await this.page.waitForSelector(fl,{timeout:Ka(s.deadlineMs,1500)}).catch(()=>null);let r=await this.page.locator(dt.paaItem).count().catch(()=>0)>0;return await this.updateSerpNavigationDebug(U,d,{hasPaa:r,captchaDetected:!1}),{hasPaa:r}}if(await this.page.waitForSelector(dt.paaItem,{timeout:Ka(s?.deadlineMs,4e3)}).catch(()=>null))return await this.updateSerpNavigationDebug(U,d,{hasPaa:!0,captchaDetected:!1}),{hasPaa:!0};if(await this.isSerpChallengeVisible())throw await this.updateSerpNavigationDebug(U,d,{hasPaa:!1,captchaDetected:!0}),new et(this.captchaMessage());for(let r=1;r<=6;r++)if(await this.page.evaluate(u=>{window.scrollTo(0,document.body.scrollHeight*u)},r/6),await this.page.waitForTimeout(600),await this.page.locator(dt.paaItem).count()>0)return await this.updateSerpNavigationDebug(U,d,{hasPaa:!0,captchaDetected:!1}),{hasPaa:!0};return await this.updateSerpNavigationDebug(U,d,{hasPaa:!1,captchaDetected:!1}),{hasPaa:!1}}async isSerpChallengeVisible(){if(!this.page)return!1;if(await this.page.locator(dt.captchaMarker).count().catch(()=>0)>0)return!0;let n=this.page.url();if(/google\.[^/]+\/sorry\//i.test(n))return!0;let a=await this.page.evaluate(()=>(document.body?.innerText??"").replace(/\s+/g," ").trim().slice(0,1e3)).catch(()=>"");return/recaptcha|unusual traffic|are you a robot|about this page|detected unusual traffic/i.test(a)}async updateSerpNavigationDebug(t,n,a,i){if(!(!t||!this.page))try{let s=this.page.url();t.finalUrl=s,t.hasPaa=a.hasPaa,t.captchaDetected=a.captchaDetected,t.googleSorryUrl=/google\.[^/]+\/sorry\//i.test(s),t.redirected=s!==n;let o=Math.min(1e3,i?.deadlineMs===void 0?1e3:i.deadlineMs-Date.now());if(i&&(i.signal?.aborted||o<=0))return;let d=Promise.all([this.page.title().catch(()=>""),this.page.evaluate(()=>(document.body?.innerText??"").replace(/\s+/g," ").trim().slice(0,500)).catch(()=>"")]),[S,U]=i?await nt(re(d,o,"\u004b\u0065\u0072\u006e\u0065\u006c navigation debug"),i.signal):await d;t.title=S,t.bodySnippet=U,t.captchaDetected=a.captchaDetected??/recaptcha|unusual traffic|are you a robot/i.test(U)}catch(s){t.bodySnippet=`debug capture failed: ${De(s)}`}}async captureDiagnostics(t){try{let n=this.page.url(),a=await this.page.title().catch(()=>""),i=await this.page.evaluate(()=>(document.body?.innerText??"").replace(/\s+/g," ").trim().slice(0,400)).catch(()=>""),s=/consent\.google\./.test(n)||/before you continue/i.test(i),o=/recaptcha|unusual traffic|are you a robot/i.test(i),d=[s?"CONSENT_WALL":"",o?"BOT_CHALLENGE":"",n!==t?"REDIRECTED":""].filter(Boolean).join(",");return`intended=${t} | final=${n} | title="${a}" | flags=[${d}] | body="${i}"`}catch(n){return`diagnostics-failed: ${n.message}`}}captchaMessage(){return this.\u006b\u0065\u0072\u006e\u0065\u006cClient?"Google returned a CAPTCHA on this session \u2014 retrying with a fresh session.":Ti}async navigateTo(t){if(this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId){let i=new URL(t);if(/^(?:www\.)?google\.[a-z.]+$/i.test(i.hostname)&&i.pathname==="/search"&&i.searchParams.has("q")){await Va(this.page,{query:i.searchParams.get("q"),gl:i.searchParams.get("gl")??"us",hl:i.searchParams.get("hl")??"en",uule:i.searchParams.get("uule")??void 0,tbs:i.searchParams.get("tbs")??void 0,extraParams:Object.fromEntries([...i.searchParams].filter(([s])=>!["q","gl","hl","uule","tbs","pws"].includes(s))),purpose:"serp",deadlineMs:this.operationDeadlineMs,solverEnabled:this.\u006b\u0065\u0072\u006e\u0065\u006cSolverEnabled});return}}let n=process.env.ADS_ARRIVAL_REDIRECT_BASE?.trim(),a=n?Qs(t,n):t;try{if(await this.page.goto(a,{waitUntil:"domcontentloaded",timeout:45e3}),/google\.[^/]+\/search\?/i.test(t)&&await this.isSerpChallengeVisible())throw new et(this.captchaMessage())}catch(i){if(i instanceof et)throw i;let s=await this.captureDiagnostics(t);throw new ct(`page.goto failed: ${i.message} | ${s}`)}}async navigateToChannel(t){let n=Nl(t);try{await this.page.goto(n,{waitUntil:"networkidle",timeout:3e4})}catch(a){let i=await this.captureDiagnostics(n);throw new ct(`navigateToChannel failed: ${a.message} | ${i}`)}}async evaluate(t,n){return this.page.evaluate(t,n)}getPage(){return this.page}get\u004b\u0065\u0072\u006e\u0065\u006cSessionId(){return this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId}get\u004b\u0065\u0072\u006e\u0065\u006cMeteringEvidence(){return{sessionId:this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId??this.debugSnapshot.\u006b\u0065\u0072\u006e\u0065\u006c?.sessionId??null,billingMode:this.last\u004b\u0065\u0072\u006e\u0065\u006cBillingMode,openedAtMs:this.last\u004b\u0065\u0072\u006e\u0065\u006cOpenedAtMs,closedAtMs:this.last\u004b\u0065\u0072\u006e\u0065\u006cClosedAtMs}}getProviderSessionMetadata(){return{provider:this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId?"\u006b\u0065\u0072\u006e\u0065\u006c":"local",providerSessionId:this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId,disconnectObservation:null,billingMode:this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId?this.\u006b\u0065\u0072\u006e\u0065\u006cHeadlessSent?"headless":"headful":null}}getDebugSnapshot(){return this.debugSnapshot}async close(){if(this.browser){let t=this.browser,n=this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId,a=this.\u006b\u0065\u0072\u006e\u0065\u006cClient,i=this.\u006b\u0065\u0072\u006e\u0065\u006cOpenedAtMs,s=this.\u006b\u0065\u0072\u006e\u0065\u006cStealth,o=this.\u006b\u0065\u0072\u006e\u0065\u006cProxyUsed,d=this.\u006b\u0065\u0072\u006e\u0065\u006cProxySource,S=this.\u006b\u0065\u0072\u006e\u0065\u006cProxyType,U=this.\u006b\u0065\u0072\u006e\u0065\u006cHeadlessSent,c=this.getProviderSessionMetadata();if(this.browser=null,this.context=null,this.page=null,this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId=null,this.\u006b\u0065\u0072\u006e\u0065\u006cClient=null,this.\u006b\u0065\u0072\u006e\u0065\u006cSolverEnabled=!1,this.\u006b\u0065\u0072\u006e\u0065\u006cOpenedAtMs=null,this.\u006b\u0065\u0072\u006e\u0065\u006cHeadlessSent=null,this.\u006b\u0065\u0072\u006e\u0065\u006cProxySource=null,this.\u006b\u0065\u0072\u006e\u0065\u006cProxyType=null,a&&n){console.info(JSON.stringify({event:"\u006b\u0065\u0072\u006e\u0065\u006c_browser_delete_started",\u006b\u0065\u0072\u006e\u0065\u006c_session_id:n}));let r=re(a.browsers.deleteByID(n),Cl,`\u004b\u0065\u0072\u006e\u0065\u006c session ${n} delete`),l=re(t.close(),ml,`\u004b\u0065\u0072\u006e\u0065\u006c browser ${n} close`),[u,h]=await Promise.allSettled([r,l]);this.last\u004b\u0065\u0072\u006e\u0065\u006cClosedAtMs=Date.now(),i!=null&&Ks({\u006b\u0065\u0072\u006e\u0065\u006cSessionId:n,source:"browser_driver",stealth:s,headlessSent:U,proxyUsed:o,proxySource:d,proxyType:S,openedAtMs:i,closedAtMs:this.last\u004b\u0065\u0072\u006e\u0065\u006cClosedAtMs});let w=u.status==="rejected"&&Tl(u.reason),g={\u006b\u0065\u0072\u006e\u0065\u006cSessionId:n,\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted:!0,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:u.status==="fulfilled"||w,\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:u.status==="rejected"&&!w?u.reason instanceof Error?u.reason.message:String(u.reason):null,browserCloseSucceeded:h.status==="fulfilled",browserCloseError:h.status==="rejected"?h.reason instanceof Error?h.reason.message:String(h.reason):null,provider:c.provider,providerSessionId:c.providerSessionId,providerDisconnectObserved:!1,providerDisconnectMessage:null};return u.status==="rejected"&&!w?(console.warn(JSON.stringify({event:"\u006b\u0065\u0072\u006e\u0065\u006c_browser_delete_failed",\u006b\u0065\u0072\u006e\u0065\u006c_session_id:n,message:g.\u006b\u0065\u0072\u006e\u0065\u006cDeleteError})),console.warn(`\u004b\u0065\u0072\u006e\u0065\u006c session cleanup failed for ${n}:`,u.reason)):console.info(JSON.stringify({event:"\u006b\u0065\u0072\u006e\u0065\u006c_browser_delete_succeeded",\u006b\u0065\u0072\u006e\u0065\u006c_session_id:n})),h.status==="rejected"&&(console.warn(JSON.stringify({event:"\u006b\u0065\u0072\u006e\u0065\u006c_browser_close_failed",\u006b\u0065\u0072\u006e\u0065\u006c_session_id:n,message:g.browserCloseError})),console.warn(`\u004b\u0065\u0072\u006e\u0065\u006c browser close failed for ${n}:`,h.reason)),g}return await t.close(),{\u006b\u0065\u0072\u006e\u0065\u006cSessionId:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted:!1,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:null,browserCloseSucceeded:!0,browserCloseError:null,provider:c.provider,providerSessionId:c.providerSessionId,providerDisconnectObserved:!1,providerDisconnectMessage:null}}else if(this.context){let t=this.context;return this.context=null,this.page=null,await t.close(),{\u006b\u0065\u0072\u006e\u0065\u006cSessionId:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted:!1,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:null,browserCloseSucceeded:!0,browserCloseError:null,provider:"local",providerSessionId:null,providerDisconnectObserved:!1,providerDisconnectMessage:null}}return{\u006b\u0065\u0072\u006e\u0065\u006cSessionId:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted:!1,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:null,browserCloseSucceeded:null,browserCloseError:null,provider:"local",providerSessionId:null,providerDisconnectObserved:!1,providerDisconnectMessage:null}}};var no=require("playwright");var Pl=new Set(["image","media","font","stylesheet","ping"]),Il=["doubleclick.net","googleadservices.com","googlesyndication.com","google-analytics.com"],Al='#search, #rso, a[href] h3, [data-snhf], [role="main"]',xl=3e4,eo=1500,Wl=3e3,Ol=new Set(["https://www.google.com","https://www.gstatic.com","https://www.recaptcha.net","https://recaptcha.net"]);function _n(e){return e.origin==="https://www.google.com"&&/^\/sorry(?:\/|$)/.test(e.pathname)}function Ll(e,t){if(_n(e)||Ol.has(e.origin)&&/^\/recaptcha(?:\/|$)/.test(e.pathname))return!0;try{return _n(new URL(t))}catch{return!1}}function de(e,t){return e?Math.max(1,Math.min(t,e-Date.now())):t}async function Bl(e,t,n){let a=Math.min(Date.now()+Wl,n??1/0);if(Date.now()>=a)return!1;let i=e.request(),s=new AbortController;t.add(s);let o=new Promise((U,c)=>{s.signal.addEventListener("abort",()=>c(s.signal.reason),{once:!0})}),d=setTimeout(()=>{s.abort(new DOMException("Controller asset transfer timed out","TimeoutError"))},Math.max(0,a-Date.now())),S=!1;try{let U=i.headers();if(s.signal.aborted||Date.now()>=a)return!1;let c=await Promise.race([fetch(i.url(),{method:i.method(),signal:s.signal,redirect:"error",headers:{accept:U.accept??"*/*","accept-language":U["accept-language"]??"en-US,en;q=0.9","user-agent":U["user-agent"]??"Mozilla/5.0"},body:i.method()==="GET"||i.method()==="HEAD"?void 0:i.postData()}),o]);if(!c.ok||s.signal.aborted||Date.now()>=a)return!1;let r=Buffer.from(await Promise.race([c.arrayBuffer(),o]));if(s.signal.aborted||Date.now()>=a)return!1;let l={status:c.status,contentType:c.headers.get("content-type")??"application/octet-stream",headers:{"cache-control":"public, max-age=3600"},body:r};return clearTimeout(d),S=!0,await e.fulfill(l),!0}catch{return S}finally{clearTimeout(d),t.delete(s),s.abort()}}var Dn=class{constructor(t={}){this.resourcePolicy=t}resourcePolicy;browser=null;context=null;page=null;cdpSession=null;providerSessionId=null;disconnectObservation=null;closing=!1;connectionStarted=!1;closeReceipt=null;controllerAssetTransfers=new Set;operationDeadlineMs;observeDisconnect(t,n){this.closing||this.disconnectObservation||(this.disconnectObservation=Qn(t,n))}async launch(t){if(this.page)return;this.operationDeadlineMs=t.operationDeadlineMs,this.closing=!1,this.providerSessionId=null,this.disconnectObservation=null;let n=Ra();if(!n)throw new Error("SERP browser service is not configured");if(this.connectionStarted)throw new Error("Previous browser connection outcome is unresolved");if(this.closeReceipt)throw new Error("Browser driver has already been closed");this.connectionStarted=!0;try{this.browser=await no.chromium.connectOverCDP(n,{timeout:de(t.operationDeadlineMs,xl)})}catch(s){let o=(s instanceof Error?s.message:String(s)).replaceAll(n,"[redacted endpoint]");throw new Error(xt(o)??"\u0042\u0072\u0069\u0067\u0068\u0074 \u0044\u0061\u0074\u0061 browser connection failed")}this.context=this.browser.contexts()[0]??await this.browser.newContext(),await this.context.addInitScript(()=>{let s=globalThis;typeof s.__name!="function"&&(s.__name=o=>o),typeof s.__publicField!="function"&&(s.__publicField=(o,d,S)=>(o[d]=S,S))}),this.page=this.context.pages()[0]??await this.context.newPage(),this.browser.on("disconnected",()=>this.observeDisconnect("browser_disconnected")),this.context.on("close",()=>this.observeDisconnect("context_closed")),this.page.on("close",()=>this.observeDisconnect("page_closed")),this.page.on("crash",()=>this.observeDisconnect("page_crashed")),this.cdpSession=await this.context.newCDPSession(this.page);let i=await this.cdpSession.send("Browser.getSessionId");this.providerSessionId=pi(i?.sessionId),await this.setupPage(this.page),this.resourcePolicy.startupSettleMs&&await this.page.waitForTimeout(this.resourcePolicy.startupSettleMs)}async setupPage(t){this.resourcePolicy.nativeGoogleAssets||await t.route("**/*",async n=>{if(this.closing)return;let a=n.request(),i=a.resourceType(),s;try{s=new URL(a.url())}catch{await n.continue();return}if(s.origin==="https://www.google.com"&&(s.pathname==="/sgasync"||/^\/async(?:\/|$)/.test(s.pathname))||Ll(s,t.url())){await n.continue();return}let d=s.hostname.toLowerCase();if(!((s.origin==="https://www.google.com"||s.origin==="https://www.gstatic.com")&&(s.pathname.includes("/shared_dict/")||i==="script")&&await Bl(n,this.controllerAssetTransfers,this.operationDeadlineMs))&&!this.closing){if(Pl.has(i)&&!(i==="image"&&this.resourcePolicy.allowImages)&&!(i==="stylesheet"&&this.resourcePolicy.allowStylesheets)){await n.abort("blockedbyclient");return}if(Il.some(U=>d===U||d.endsWith(`.${U}`))){await n.abort("blockedbyclient");return}await n.continue()}})}async withTemporaryPage(t,n){if(!this.context||this.closing)throw new Error("Browser context is not available");return Bn(this.context,a=>this.setupPage(a),t,n)}async navigateToSERP(t,n,a,i,s){if(!this.page)throw new Error("Browser page is not available");let o=()=>{if(s?.signal?.aborted)throw oe(s.signal);if(s?.deadlineMs!=null&&Date.now()>=s.deadlineMs)throw new DOMException("Google navigation exceeded the work deadline","TimeoutError")};o();let d=new URLSearchParams({q:t,gl:a,hl:i,pws:"0"});if(s?.tbs&&d.set("tbs",s.tbs),n&&d.set("uule",n),await nt(this.page.goto(`https://www.google.com/search?${d}`,{waitUntil:"domcontentloaded",timeout:de(s?.deadlineMs,s?.purpose==="serp"?12e4:45e3)}),s?.signal),o(),_n(new URL(this.page.url()))&&this.cdpSession){let c=this.cdpSession,r,l=await nt(Promise.race([c.send("Captcha.solve",{detectTimeout:de(s?.deadlineMs,3e4)}).catch(()=>null),new Promise(u=>{r=setTimeout(()=>u(null),de(s?.deadlineMs,75e3))})]),s?.signal).finally(()=>{r&&clearTimeout(r)});o(),l?.status==="solve_finished"&&(await nt(this.page.waitForURL(u=>u.origin==="https://www.google.com"&&u.pathname==="/search",{timeout:de(s?.deadlineMs,25e3)}).catch(()=>{}),s?.signal),o())}if(s?.purpose==="serp")return await nt(this.page.waitForSelector(Al,{timeout:de(s.deadlineMs,8e3)}).catch(()=>null),s.signal),o(),{hasPaa:await nt(this.page.locator(dt.paaItem).count().catch(()=>0),s.signal)>0};if(_n(new URL(this.page.url())))throw new et("Google SERP returned a CAPTCHA \u2014 retrying with a fresh session.");let S=await nt(this.page.evaluate(c=>!!document.querySelector(c),dt.paaItem).catch(()=>!1),s?.signal);if(o(),S)return{hasPaa:!0};let U=!!await nt(this.page.waitForSelector(dt.paaItem,{state:"attached",timeout:de(s?.deadlineMs,8e3)}).catch(()=>null),s?.signal);return o(),{hasPaa:U}}async navigateTo(t){if(!this.page)throw new Error("Browser page is not available");await this.page.goto(t,{waitUntil:"load",timeout:45e3})}async navigateToChannel(){throw new Error("YouTube navigation is not supported by the SERP browser driver")}async evaluate(t,n){if(!this.page)throw new Error("Browser page is not available");return this.page.evaluate(t,n)}getPage(){if(!this.page)throw new Error("Browser page is not available");return this.page}get\u004b\u0065\u0072\u006e\u0065\u006cSessionId(){return null}get\u0042\u0072\u0069\u0067\u0068\u0074\u0044\u0061\u0074\u0061SessionId(){return this.providerSessionId}getProviderSessionMetadata(){return{provider:"\u0062\u0072\u0069\u0067\u0068\u0074_\u0064\u0061\u0074\u0061_browser_api",providerSessionId:this.providerSessionId,disconnectObservation:this.disconnectObservation}}getDebugSnapshot(){return{\u006b\u0065\u0072\u006e\u0065\u006c:null,context:null,networkLocation:null,serpNavigation:null}}async close(){return this.closeReceipt??=this.closePhysicalSession()}async closePhysicalSession(){this.closing=!0;for(let d of this.controllerAssetTransfers)d.abort(new DOMException("Browser is closing","AbortError"));let t=yi(this.getProviderSessionMetadata()),n=!1,a=null,i=null,s=null,o=async(d,S)=>{let U;try{await Promise.race([d(),new Promise((c,r)=>{U=setTimeout(()=>r(new Error(`${S} acknowledgement exceeded ${eo}ms`)),eo)})])}finally{U&&clearTimeout(U)}};if(this.connectionStarted)if(!this.browser)a="Browser connection outcome is unknown; no remote termination receipt";else{try{await o(async()=>{let d=this.cdpSession??(this.context&&this.page?await this.context.newCDPSession(this.page):null);if(!d)throw new Error("Remote browser termination channel is unavailable");await d.send("Browser.close")},"Remote browser close"),n=!0}catch(d){a=xt(d instanceof Error?d.message:String(d))??"Remote browser termination is unconfirmed",this.disconnectObservation??=Qn("browser_close_error",a)}try{await o(()=>this.browser.close(),"Local browser disconnect"),i=!0}catch(d){i=!1,s=xt(d instanceof Error?d.message:String(d))??"Local browser disconnect failed"}}return this.browser=null,this.context=null,this.page=null,this.cdpSession=null,{\u006b\u0065\u0072\u006e\u0065\u006cSessionId:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted:!1,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:null,browserCloseSucceeded:this.connectionStarted?n:null,browserCloseError:a,localDisconnectSucceeded:i,localDisconnectError:s,physicalOutcome:this.connectionStarted?n?"terminated":"unknown":"not_started",...t}}};function ao(e,t){return e.plannedProvider==="\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061"?new Dn({nativeGoogleAssets:t?.nativeGoogleAssets}):new Fn}var Z={container:".eJH8qe.adDDi",dataInitq:"[data-initq]",item:dt.paaItem,itemDataQ:"data-q",itemDataInitQ:"data-initq",itemQuestionEl:".JlqpRe",answerContainer:".bCOlv, .hgKElc, .wDYxhc, .LGOjhe, .fo7IQd, .fmW3u",aiAnswerBody:".pWvJNd",answerBody:".hgKElc, .LGOjhe, .fo7IQd, .fmW3u",answerControl:'button, [role="button"], a',answerEntity:".q224lc",citationBadge:".WBgIic",sourceCard:"[data-src-id]",sourceCardTitle:".vFyWT",sourceDescription:"[data-crb-snippet-text]",aiCitation:"a.PMDqCb[href]",aiSourceCard:"a.vIWmYe[href], a.Zbfntb[href]",sourceTitle:"h3",sourceSite:".VuuXrf",sourceCite:"cite",clickTarget:".JlqpRe",expandedClass:"aoRk1c",captchaMarker:dt.captchaMarker};var Ja={alabama:"AL",alaska:"AK",arizona:"AZ",arkansas:"AR",california:"CA",colorado:"CO",connecticut:"CT",delaware:"DE",florida:"FL",georgia:"GA",hawaii:"HI",idaho:"ID",illinois:"IL",indiana:"IN",iowa:"IA",kansas:"KS",kentucky:"KY",louisiana:"LA",maine:"ME",maryland:"MD",massachusetts:"MA",michigan:"MI",minnesota:"MN",mississippi:"MS",missouri:"MO",montana:"MT",nebraska:"NE",nevada:"NV","new hampshire":"NH","new jersey":"NJ","new mexico":"NM","new york":"NY","north carolina":"NC","north dakota":"ND",ohio:"OH",oklahoma:"OK",oregon:"OR",pennsylvania:"PA","rhode island":"RI","south carolina":"SC","south dakota":"SD",tennessee:"TN",texas:"TX",utah:"UT",vermont:"VT",virginia:"VA",washington:"WA","west virginia":"WV",wisconsin:"WI",wyoming:"WY","district of columbia":"DC"},Rl=[...Object.keys(Ja).map(e=>e.replace(/\s+/g,"\\s+")),...Object.values(Ja)].join("|"),El=new RegExp(`\\b([A-Z][A-Za-z]+(?:[\\s.-][A-Z][A-Za-z]+){0,4}),?\\s+(${Rl})\\b`,"gi");function so(e){if(!e)return null;let t=e.trim();return/^[A-Z]{2}$/i.test(t)?t.toUpperCase():Ja[t.toLowerCase()]??null}function oo(e){return e.replace(/\s+/g," ").trim().replace(/^.*\b(?:in|near|around|serving)\s+/i,"").toLowerCase().replace(/\b[a-z]/g,n=>n.toUpperCase())}function Hl(e){if(!e)return null;let[t="",n=""]=e.split(",").map(a=>a.trim());return{city:oo(t),regionCode:so(n),canonicalLocation:e}}function Fl(e,t,n,a){let i=oo(t),s=so(n);if(!i||!s)return;let o=`${i.toLowerCase()}|${s}`,d=e.get(o);if(d){d.count++,d.examples.length<3&&!d.examples.includes(a)&&d.examples.push(a);return}e.set(o,{city:i,regionCode:s,count:1,examples:[a]})}function _l(e){try{return decodeURIComponent(e)}catch{}try{return decodeURIComponent(e.replace(/%(?![0-9a-fA-F]{2})/g,"%25"))}catch{return e}}function io(e,t){let n=_l(t).replace(/[+/|_-]+/g," ");for(let a of n.matchAll(El))Fl(e,a[1]??"",a[2]??"",n.slice(0,180))}function ln(e,t,n){let a=Hl(e),i=new Map;for(let d of t)io(i,[d.title,d.snippet??"",d.cite??"",d.url].join(" "));for(let d of n)io(i,[d.name,...d.metadata,d.websiteUrl??"",d.directionsUrl??""].join(" "));let s=Array.from(i.values()).sort((d,S)=>S.count-d.count||d.city.localeCompare(S.city)).slice(0,8);return a?s.length===0?{status:"unknown",expected:a,candidates:[]}:{status:s.some(d=>d.city.toLowerCase()===a.city.toLowerCase()&&(a.regionCode==null||d.regionCode===a.regionCode))?"matched":"mismatch",expected:a,candidates:s}:{status:"not_requested",expected:null,candidates:s}}var Dl=/^(?:an error has occurred(?:[.!…]\s*)?(?:please try again later[.!…]?)?|loading|please wait|try again|something went wrong|an AI overview is not available for this search|can't generate an AI overview right now\.?\s*try again later\.?)[.!…\s]*$/i,Gl=/^(?:AI Overview|View all|Show more|Show less|Related Links|Ask anything in AI Mode|AI can make mistakes)[.!…\s]*$/i;function qa(e){return e.replace(/\u00a0/g," ").replace(/\s+/g," ").trim()}function Sn(e,t){if(!e)return;let n=qa(e.split(/\r?\n/).filter(i=>!Gl.test(qa(i))).join(`
21776
- `)),a=t?qa(t):"";return a&&n.toLowerCase().startsWith(a.toLowerCase())&&(n=n.slice(a.length).trim()),!n||Dl.test(n)?void 0:n}function le({selectors:e,onlyQuestion:t}){let n=l=>(l??"").replace(/\u00a0/g," ").replace(/\s+/g," ").trim(),a=l=>n(l).replace(/\s*\(\+\d+\)\s*-\s*View related links.*$/i,"").replace(/\s*(?:[-.]\s*)?Opens in new tab[.!]?$/i,"").trim(),i=(l,u)=>{if(l.matches(e.clickTarget)||l.getAttribute("aria-expanded")==="true")return!1;let h=l.closest(".biJ8pb")?.closest(".hICk5e[data-collapsed]");if(h&&(h.getAttribute("data-collapsed")!=="1"||u?.closest(".hICk5e[data-collapsed]")===h))return!1;let w=l.getAttribute("href");return w&&!/^(?:#|javascript:void\(0\);?$)/i.test(w)||l.closest(e.aiSourceCard+","+e.sourceCard)?!1:[l.getAttribute("aria-label"),l.textContent].map(n).some(C=>/^(?:(?:show|read|see) more(?: (?:AI Overview|(?:of )?(?:this |the )?answer))?|continue reading|expand(?: (?:this |the )?answer)?)(?:[.!…]|\s*[▼⌄+])?$/i.test(C))},s=(l,u=!1)=>l.hasAttribute("hidden")||l.getAttribute("aria-hidden")==="true"&&!u||/(?:display\s*:\s*none|visibility\s*:\s*hidden)/i.test(l.getAttribute("style")??""),o=l=>{let u=l.ownerDocument.defaultView?.getComputedStyle(l);return u?.display==="none"||u?.visibility==="hidden"},d=(l,u)=>!u?.matches(e.aiAnswerBody)||!u.closest(".hICk5e[data-collapsed]")||!l?.matches("span.mTEjhd > span.dteT0b > div[data-xpm-copy-root][data-xpm-math-type]")||!l.querySelector(":scope > div > math > semantics")?"":n(l.querySelector(':scope > img[data-xpm-latex][role="presentation"][aria-hidden="true"]')?.getAttribute("data-xpm-latex")),S=(l,u)=>{let h=l?.closest('div.Q9iar.bliT4d.KfKEse.xRMEde[role="list"]');return!!(u?.matches(e.aiAnswerBody)&&u.closest(".hICk5e[data-collapsed]")&&h&&u.contains(h)&&l?.matches('div.Q9iar.BPUOre.bliT4d.KfKEse.xRMEde[role="listitem"]')&&l.querySelector(":scope > div.Q9iar.BPUOre.ua6Thd.bliT4d.KfKEse.xRMEde"))},U=(l,u)=>{if(!u?.matches(e.aiAnswerBody)||!u.closest(".hICk5e[data-collapsed]")||!l.matches('span.jAOkJc[role="button"]')||!l.parentElement?.matches("u.wfWfIf.fxyaSe")||!l.parentElement.parentElement?.matches("span.iNqyIf"))return!1;let h=l.firstElementChild;return!!(h?.matches("span.iNqyIf")&&l.children.length===1&&n(l.textContent)===n(h.textContent))},c=(l,u)=>{if(!u?.matches(e.aiAnswerBody)||!u.closest(".hICk5e[data-collapsed]"))return!1;if(l.matches("li.Z1qcYe, div.WYczDe, span.iNqyIf, ol.T9WCjf.qkgVBf")||S(l,u)||l.matches("strong.rQesXe.MPyX")&&l.closest("div.n6owBd.awi2gc")&&S(l.closest('[role="listitem"]'),u))return!0;if(l.closest("span.iNqyIf")){if(l.matches("strong.rQesXe.MPyX"))return!0;let w=l.matches("span")?l.querySelector(":scope > a.H23r4e[href]"):null;if(w&&/^(?:https?:\/\/|\/goto\?url=|\/url\?)/i.test(w.getAttribute("href")??"")&&l.children.length===1&&n(l.textContent)===n(w.textContent)&&l.parentElement?.matches("span")&&/display\s*:\s*contents/i.test(l.parentElement.getAttribute("style")??""))return!0}if(!l.matches("div.tYHU1b"))return!1;let h=l.querySelector(":scope > div.ID94bb[id]");return h?Array.from(l.querySelectorAll('[role="button"][aria-expanded="true"][aria-controls]')).some(w=>{if(w.closest(".tYHU1b")!==l||w.getAttribute("aria-controls")!==h.id||n(w.textContent)!=="Show less")return!1;for(let g=w;g&&g!==l;g=g.parentElement)if(s(g)||o(g))return!1;return!0}):!1},r=(l,u,h)=>{if(!l||l!==u&&(s(l,c(l,u))||l.matches('style,script,noscript,button,[data-artifact-type="map"]')||l.matches('[role="button"]')&&!l.matches(e.answerEntity)&&!U(l,u)||l.matches(e.aiSourceCard+","+e.sourceCard+","+e.citationBadge)||h&&(l.matches("cite,"+e.sourceSite)||l.matches("a[href]")&&l.querySelector("h3"))))return"";let w=d(l,u);if(w)return w;let g=[];for(let C of l.childNodes)C.nodeType===Node.TEXT_NODE?g.push(C.textContent??""):C.nodeType===Node.ELEMENT_NODE&&g.push(r(C,u,h));return n(g.join(" "))};return Array.from(document.querySelectorAll(e.item)).flatMap((l,u)=>{let h=n(l.getAttribute(e.itemDataQ)||l.getAttribute(e.itemDataInitQ)||l.querySelector(e.itemQuestionEl)?.innerText||l.querySelector(e.itemQuestionEl)?.textContent);if(!h||t&&h!==n(t))return[];let w=l.classList.contains(e.expandedClass)||l.querySelector(e.clickTarget)?.getAttribute("aria-expanded")==="true",g=l.querySelector(e.answerContainer),C=g?.querySelector(e.aiAnswerBody)||(g?.matches(e.aiAnswerBody)?g:null)||g?.querySelector(e.answerBody)||(g?.matches(e.answerBody)?g:null),y=C||g,m=r(y,y,!C),O=/^(?:an error has occurred(?:[.!…]\s*)?(?:please try again later[.!…]?)?|loading|please wait|try again|something went wrong)[.!…\s]*$/i.test(m),F=[...Array.from((y||l).querySelectorAll("a[href]")),...Array.from(g?.querySelectorAll("a[href]")||[]),...Array.from(l.querySelectorAll(e.aiCitation+","+e.aiSourceCard))],B=!O&&(w&&m.length>=10||m.length>30&&F.some(P=>/^https?:\/\//i.test(P.href))),I=y?.matches(e.aiAnswerBody)&&y.closest(".hICk5e[data-collapsed]")?y:null,K=I&&Array.from(I.querySelectorAll('[hidden], [aria-hidden="true"], [style]')).some(P=>{if(!s(P)||!n(P.textContent))return!1;let G=P.closest('button, [role="button"]');if(G&&!U(G,I)||P.closest('[data-artifact-type="map"], .AQisZb, '+e.aiSourceCard+","+e.sourceCard+","+e.citationBadge))return!1;let v=P.closest("[data-xpm-copy-root][data-xpm-math-type]");return d(v,I)&&(P.closest("svg")?.parentElement===v||P.closest("math")?.parentElement?.parentElement===v)?!1:!c(P,I)||s(P,!0)}),D=I&&!K?I:null,b=Array.from(g?.querySelectorAll(e.answerControl)||[]),k=B?b.flatMap((P,G)=>{if(!i(P,D))return[];for(let v=P;v&&v!==g;v=v.parentElement)if(s(v)||o(v))return[];return[G]}):[],A=new Map;if(B)for(let P of F){if(!/^https?:\/\//i.test(P.href)||P.closest('[data-artifact-type="map"]'))continue;let G=P.closest(e.sourceCard),v=G?n(G.querySelector(e.sourceDescription)?.textContent):"",R=(G?n(G.querySelector(e.sourceCardTitle)?.textContent):"")||a(P.getAttribute("aria-label"))||n(P.querySelector("h3")?.textContent)||n(P.textContent),f=A.get(P.href);A.set(P.href,{title:G&&R?R:f?.title||R,rawHref:P.href,...v||f?.description?{description:v||f?.description}:{}})}let T=[...A.values()],M=B&&n(l.querySelector(e.sourceTitle)?.textContent)||void 0,q=B&&n(l.querySelector(e.sourceSite)?.textContent)||void 0;return M||=T.find(P=>P.title.length>2)?.title||T[0]?.title||void 0,[{googleLinkId:l.getAttribute("data-lk")||l.querySelector("[data-lk]")?.getAttribute("data-lk")||null,googleEvidenceId:l.getAttribute("data-ved")||l.querySelector("[data-ved]")?.getAttribute("data-ved")||null,question:h,answer:B?m:void 0,sourceTitle:M,sourceSite:q,sources:T,...k.length||B&&K||l.getAttribute("data-mcp-answer-expansion")==="pending"?{answerExpansionIncomplete:!0}:{},itemIndex:u,expanded:w,answerControls:k,...k.some(P=>b[P]?.getAttribute("data-mcp-answer-expansion")==="pending")?{answerControlPending:!0}:{}}]})}async function za(e,t,n,a){let i=Math.min(n.deadlineMs??1/0,Date.now()+1e4),s=()=>Math.max(0,i-Date.now()),o=n.dispatchClick??(u=>u()),d=async()=>(await e.evaluate(a,{selectors:n.selectors,onlyQuestion:t}))[0],S=await d(),U=async(u,h)=>n.signal?.aborted||s()<=0?!1:e.evaluate(({selectors:w,question:g,operation:C,controlIndex:y})=>{let m=K=>(K??"").replace(/\u00a0/g," ").replace(/\s+/g," ").trim(),O=Array.from(document.querySelectorAll(w.item)).find(K=>m(K.getAttribute(w.itemDataQ)||K.getAttribute(w.itemDataInitQ)||K.querySelector(w.itemQuestionEl)?.textContent)===m(g));if(!O)return!1;if(C==="clear")return O.removeAttribute("data-mcp-answer-expansion"),!0;let F=Array.from(O.querySelector(w.answerContainer)?.querySelectorAll(w.answerControl)||[]),B=F.filter(K=>K.getAttribute("data-mcp-answer-expansion")==="pending");if(C==="confirmed")return B.length>1?!1:(B[0]?.setAttribute("data-mcp-answer-expansion","confirmed"),!0);let I=y===void 0?void 0:F[y];return!I||B.length||I.matches(":disabled")||I.closest('[aria-disabled="true"]')?!1:(I.setAttribute("data-mcp-answer-expansion","pending"),I.setAttribute("data-mcp-answer-expansion-for",encodeURIComponent(g)),O.setAttribute("data-mcp-answer-expansion","pending"),!0)},{selectors:n.selectors,question:t,operation:u,controlIndex:h}).catch(()=>!1);async function c(u,h){let w=Date.now()+u.budgetMs,g,C=null,y=u.beforeAnswer;for(;Date.now()<w;){if(await new Promise(m=>window.setTimeout(m,Math.min(150,w-Date.now()))),g=h({selectors:u.selectors,onlyQuestion:u.onlyQuestion})[0],!g)return{acknowledged:!1,clearMarker:!1};if(g.answer!==y&&(y=g.answer,C=Date.now()),!g.answerControls.length&&g.answer){C??=Date.now();let m=g.answer!==u.beforeAnswer?300:1e3;if(Date.now()-C>=m)return{state:g,acknowledged:!0,clearMarker:!0}}else if(g.answerControls.length&&(g.answer!==u.beforeAnswer||!g.answerControlPending)&&(C??=Date.now(),Date.now()-C>=300))return{state:g,acknowledged:!0,clearMarker:!1}}return{state:g,acknowledged:!1,clearMarker:!1}}let r=new Function("input",`return (${c.toString()})(input, (${a.toString()}));`),l=async u=>{if(n.signal?.aborted||s()<=0)return!1;let h,w=new Promise(g=>{h=()=>g(void 0),n.signal?.addEventListener("abort",h,{once:!0})});try{let g=e.evaluate(r,{selectors:n.selectors,onlyQuestion:t,beforeAnswer:u,budgetMs:Math.min(2500,s())}),C=await Promise.race([g,w]);return!C||n.signal?.aborted||s()<=0?!1:(S=C.state,C.acknowledged&&(C.clearMarker?await U("clear"):!0))}finally{h&&n.signal?.removeEventListener("abort",h)}};if(S?.answerExpansionIncomplete&&!S.answerControls.length){await l(S.answer);return}for(let u=0;S?.answerControls.length&&u<8;u+=1){if(n.signal?.aborted||s()<=0)return;let h=S.answer,w=!1;try{if(S=await d(),!S?.answerControls.length)return;h=S.answer;let C=e.locator(n.selectors.item).nth(S.itemIndex);if(!S.expanded){if(n.allowOuterReopen===!1||(await o(async()=>{n.signal?.aborted||s()<=0||await C.locator(n.selectors.clickTarget).first().click({force:!0,noWaitAfter:!0,timeout:Math.min(1200,s())})}),s()<=0||n.signal?.aborted)||(await e.waitForTimeout(Math.min(250,s())),S=await d(),!S?.answerControls.length))return;h=S.answer}if(n.signal?.aborted||s()<=0)return;let y=S;await o(async()=>{if(n.signal?.aborted||s()<=0)return;let m=await U("pending",y.answerControls[0]);w=!0,m&&!n.signal?.aborted&&s()>0&&await e.locator(`[data-mcp-answer-expansion="pending"][data-mcp-answer-expansion-for="${encodeURIComponent(t)}"]`).first().click({force:!0,noWaitAfter:!0,timeout:Math.min(1200,s())}).catch(()=>{})})}catch{}if(!w||n.signal?.aborted||s()<=0||!await l(h)||!S?.answerControls.length||!await U("confirmed"))return}}async function ro(e){let t=e??{aio:{root:"[data-lhcontainer][data-streaming-container][eid]",legacyRoot:'[data-hveid="CBMQAA"]',wrapper:".Fgyi2e",controller:'[jscontroller="AkrxPe"]',contentSubtree:'[data-subtree="mfc"]',heading:".Fzsovc.cwYVJe.RJPOee",header:".heWuVc",showMoreButton:'[aria-label="Show more AI Overview"]',sourcesPanel:".OZ9ddf.WAUd4",disclaimer:".DuQANe.MSJHRb"},aim:{root:'[data-hveid="CAUQAA"]',wrapper:".Fgyi2e"},expandWaitMs:1500},n=window.google?.sn??"unknown",a=n==="aim"?"aim":n==="web"?"web":"unknown";function i(b){return b?(b.innerText??b.textContent??"").trim():""}function s(b){if(!b)return!1;let k=b.replace(/\s+/g," ").trim();return k.length>=16&&k.split(" ").filter(Boolean).length>=2}function o(b){let k=b.querySelector(t.aio.heading);if(i(k)==="AI Overview")return!0;let A=b.querySelector(t.aio.header);return!!i(A).split(/\n|\s{2,}/).some(T=>T.trim()==="AI Overview")}function d(){let k=Array.from(document.querySelectorAll(t.aio.root)).find(o);if(k)return k;if(t.aio.legacyRoot){let T=document.querySelector(t.aio.legacyRoot);if(T&&o(T))return T}let A=document.querySelectorAll(`${t.aio.heading}, h1, h2, h3, [role="heading"]`);for(let T of A){if(i(T)!=="AI Overview")continue;let M=T.parentElement;for(let q=0;q<8&&M;q++){if(M.matches(t.aio.root)||M.querySelector(t.aio.controller)||M.querySelector(t.aio.contentSubtree))return M;M=M.parentElement}return T.parentElement}return null}function S(b){if(!b)return null;let k=b.cloneNode(!0);k.querySelectorAll(["script","style","noscript","img","picture","video",t.aio.header,t.aio.showMoreButton,t.aio.sourcesPanel,t.aio.disclaimer,'[data-subtree="dfa"]',"[data-src-id]",'[role="dialog"]',".HWMcu",".bTFeG",".CyMdWb",".MFrAxb",".F0OfWd.hfWAgb",".x2qcTc.fZavHb",".SvjEff",".sR2MY",".lKuDef",".GSPQcc","a[href]","button",'[role="button"]'].join(",")).forEach(G=>G.remove());let A=document.createElement("div");A.style.position="fixed",A.style.left="-10000px",A.style.top="0",A.style.width=`${Math.max(320,Math.round(b.getBoundingClientRect?.().width||960))}px`,A.style.opacity="0",A.style.pointerEvents="none",A.append(k),document.body.append(A);let T=k.innerText||k.textContent||"";A.remove();let M=T.replace(/\r/g,"").replace(/[ \t]+\n/g,`
21775
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,args:[(0,Fa.randomUUID)(),e.op??t?.op??null,e.probeRunId??t?.probeRunId??null,e.userId??t?.userId??null,e.vendor,e.model??null,e.units,e.unitType,Gs(e.vendor,e.units),e.error??null,e.method??t?.subOp??null,e.sourceKey??null,e.providerDurationMs??null,Rn(e.providerCaptcha),e.providerStatus??null]})).rowsAffected===1}catch(t){return console.warn("[cost-telemetry] recordVendorUsage failed:",t instanceof Error?t.message:String(t)),!1}}function Rn(e){return e==null?null:e?1:0}var Sl=/\b(?:HeadlessChrome|Chrome|Chromium|Firefox)\/\d+|\bVersion\/\d+.*\bSafari\//;async function _a(e){try{let t=await e.evaluate(()=>navigator.userAgent);return typeof t=="string"&&Sl.test(t)?t:null}catch{return null}}async function Ga(e){let t=null;try{let n=e.contexts().flatMap(a=>a.pages())[0];return n||(t=await e.newContext(),n=t.pages()[0]??await t.newPage()),await _a(n)}catch{return null}finally{t&&await t.close().catch(()=>{})}}function Ys(e){let{headless:t,viewport:n,userAgent:a,user_agent:i,...s}=e;return s}async function Js(e,t={}){return t.blockServiceWorkers?e.newContext({viewport:null,serviceWorkers:"block"}):e.contexts()[0]??await e.newContext({viewport:null})}async function qs(e){return e.pages()[0]??await e.newPage()}function oe(e){return e.reason??new DOMException("The operation was aborted.","AbortError")}async function nt(e,t){if(!t)return e;if(t.aborted)throw oe(t);let n,a=new Promise((i,s)=>{n=()=>s(oe(t)),t.addEventListener("abort",n,{once:!0})});e.catch(()=>{});try{return await Promise.race([e,a])}finally{n&&t.removeEventListener("abort",n)}}function zs(e,t){let n=AbortSignal.timeout(e);return t?AbortSignal.any([t,n]):n}function En(e={}){let t=e.nowMs??Date.now(),n=Math.max(0,e.waitMs??3e4);return Math.min(e.deadlineMs??1/0,t+n)}var aw=En({nowMs:0});async function $s(e){let t=En(e),n=async()=>{if(e.signal?.aborted)throw oe(e.signal);let i=t-Date.now();if(i<=0)return!0;let s;try{return await nt(Promise.race([e.observeChallenge(),new Promise(o=>{s=setTimeout(()=>o(!0),i)})]),e.signal)}finally{s&&clearTimeout(s)}},a=await n();if(!e.solverEnabled)return a;for(;a&&Date.now()<t;){let i;try{await nt(new Promise(s=>{i=setTimeout(s,Math.min(500,t-Date.now()))}),e.signal)}finally{i&&clearTimeout(i)}if(e.signal?.aborted)throw oe(e.signal);if(Date.now()>t)break;a=await n()}return a}var Ul=`#search h3, #rso h3, #search .related-question-pair, #rso .related-question-pair, #search ${on.item}, #rso ${on.item}, #search .isv-r, #rso .isv-r`,cl=75e3,ul=3e3;async function Va(e,t){if(t.signal?.aborted)throw new ut;let n=Math.min(Date.now()+cl,t.deadlineMs===void 0?1/0:t.deadlineMs-ul);if(n<=Date.now())throw new ct("Google search navigation has no remaining time");let a=zs(Math.max(1,n-Date.now()),t.signal),i=!1,s,o=async()=>{if(!await nt(js(e),a))return!1;if(i=!0,s??=En({deadlineMs:n}),await $s({solverEnabled:t.solverEnabled,deadlineMs:s,signal:a,observeChallenge:()=>js(e)}))throw new et("Google challenge did not clear within the remaining browser time.");return!0};try{await wl(e,{params:hl(t),deadlineMs:n,signal:a},o,gl);let d=()=>nt(pl(e,{query:t.query,deadlineMs:n,signal:a,readySelector:Ul},o),a);if(await d(),t.purpose==="paa"){let S=Math.min(n,Date.now()+4e3);await nt(e.waitForSelector(dt.paaItem,{state:"visible",timeout:Math.max(1,S-Date.now())}).catch(()=>null),a);for(let U=1;U<=6&&Date.now()<n&&(await o(),!await nt(e.locator(dt.paaItem).count(),a));U+=1)await nt(e.evaluate(c=>{window.scrollTo(0,document.body.scrollHeight*c)},U/6),a),await nt(new Promise(c=>setTimeout(c,Math.min(400,n-Date.now()))),a)}for(;Date.now()<n;){await d();let S=await nt(e.locator(dt.paaItem).count(),a)>0;if(!await o())return{hasPaa:S,challengeObserved:i}}throw new ct("Google search results did not reach a readable state")}catch(d){throw t.signal?.aborted?new ut:d instanceof et||d instanceof ct?d:d instanceof Error&&d.message==="Google search results did not reach a readable state"?new ct(d.message):d instanceof Error&&/^Google search (?:homepage|consent inspection|consent|search box readiness|search box inspection|search box focus|search box clear|query typing|suggestion dismissal|search parameters|search button inspection|search submit) (?:failed|timed out)$/.test(d.message)?new ct(d.message):d instanceof Error&&["Google homepage did not expose a visible search box","Google search form did not expose a visible Search button"].includes(d.message)?new ct(d.message):new ct(a.aborted?"Google search navigation timed out before results were ready":"Google homepage search interaction failed")}}async function js(e){if(/google\.[^/]+\/sorry(?:\/|\?|$)/i.test(e.url())||await e.locator(dt.captchaMarker).count())return!0;let t=await e.locator("body").innerText({timeout:1e3}).catch(()=>"");return/recaptcha|unusual traffic|are you a robot|about this page|detected unusual traffic/i.test(t.slice(0,3e3))}function hl(e){let t={...e.extraParams,q:e.query,gl:e.gl,hl:e.hl,pws:"0"};return e.tbs&&(t.tbs=e.tbs),e.uule&&(t.uule=e.uule),t}async function gl(e,t={}){let n=t.deadlineMs??Date.now()+1e4,a=async(d,S,U=8e3)=>{let c=Math.min(U,n-Date.now());if(t.signal?.aborted){let h=new Error("Google search navigation aborted");throw h.name="AbortError",h}if(c<=0)throw new Error("Google search navigation deadline exhausted");let r,l,u=new Promise((h,w)=>{r=setTimeout(()=>w(new Error(`Google search ${d} timed out`)),c),t.signal&&(l=()=>{let g=new Error("Google search navigation aborted");g.name="AbortError",w(g)},t.signal.addEventListener("abort",l,{once:!0}))});try{return await Promise.race([S(c),u])}catch{if(t.signal?.aborted){let h=new Error("Google search navigation aborted");throw h.name="AbortError",h}throw new Error(`Google search ${d} failed`)}finally{r&&clearTimeout(r),l&&t.signal?.removeEventListener("abort",l)}},i=/^(reject all|reject optional|continue without accepting|only necessary|alle ablehnen|tout refuser|rechazar todo|rifiuta tutto|rejeitar tudo|alles afwijzen)$/i;if(!await a("consent inspection",()=>e.evaluate(d=>{let S=new RegExp(d,"i");return/^consent\.google\./i.test(window.location.hostname)||!!document.querySelector("#W0wltc")||Array.from(document.querySelectorAll('button, [role="button"]')).some(U=>S.test(U.textContent?.trim()??""))},i.source),2e3))return!1;let o=e.locator("#W0wltc").or(e.getByRole("button",{name:i}));for(let d=0,S=await a("consent inspection",()=>o.count(),2e3);d<S;d+=1){let U=o.nth(d);if(await a("consent inspection",()=>U.isVisible(),2e3))return await a("consent",c=>U.click({timeout:c})),!0}if(/consent\.google\./i.test(e.url()))throw new Error("Google consent did not expose a reject option");return!1}async function wl(e,t,n,a){let i=async(u,h,w=8e3)=>{let g=Math.min(w,t.deadlineMs-Date.now());if(t.signal?.aborted){let O=new Error("Google search navigation aborted");throw O.name="AbortError",O}if(g<=0)throw new Error("Google search navigation deadline exhausted");let C,y,m=new Promise((O,F)=>{C=setTimeout(()=>F(new Error(`Google search ${u} timed out`)),g),t.signal&&(y=()=>{let B=new Error("Google search navigation aborted");B.name="AbortError",F(B)},t.signal.addEventListener("abort",y,{once:!0}))});try{return await Promise.race([h(g),m])}catch{if(t.signal?.aborted){let F=new Error("Google search navigation aborted");throw F.name="AbortError",F}throw new Error(`Google search ${u} failed`)}finally{C&&clearTimeout(C),y&&t.signal?.removeEventListener("abort",y)}},s=()=>a(e,t);await i("homepage",u=>e.goto("https://www.google.com",{waitUntil:"domcontentloaded",timeout:u}),15e3),await n(),await s(),await n();let o='textarea[name="q"], input[name="q"]';await i("search box readiness",u=>e.waitForSelector(o,{state:"visible",timeout:u}));let d=e.locator(o),S;for(let u=0,h=await i("search box inspection",()=>d.count());u<h;u+=1)if(await i("search box inspection",()=>d.nth(u).isVisible())){S=d.nth(u);break}if(!S)throw new Error("Google homepage did not expose a visible search box");let U=S;await i("search box focus",u=>U.click({timeout:u})),await i("search box clear",u=>U.fill("",{timeout:u}));for(let u of t.params.q)await i("query typing",h=>U.pressSequentially(u,{delay:35+Math.floor(Math.random()*65),timeout:h}));let c=U.locator("xpath=ancestor::form[1]");await i("search parameters",()=>c.evaluate((u,h)=>{if(!(u instanceof HTMLFormElement))throw new Error("Google search form is unavailable");u.method="get";for(let[g,C]of Object.entries(h)){if(g==="q")continue;let y=Array.from(u.querySelectorAll("input")).filter(m=>m.name===g);for(let m of y)m.value=C,m.disabled=!1;if(y.length===0){let m=document.createElement("input");m.type="hidden",m.name=g,m.value=C,u.appendChild(m)}}let w=new URL(u.action,location.href);for(let g of Object.keys(h))w.searchParams.delete(g);u.action=w.toString()},t.params));let r=c.locator('input[name="btnK"], button[name="btnK"], button[type="submit"]'),l=!1;for(let u=0,h=await i("search button inspection",()=>r.count());u<h;u+=1){let w=r.nth(u);if(await i("search button inspection",()=>w.isVisible())){await i("search submit",g=>w.click({timeout:g,noWaitAfter:!0})),l=!0;break}}if(!l)throw new Error("Google search form did not expose a visible Search button");await n(),await s(),await n()}async function pl(e,t,n){let a=t.readySelector.split(",").map(s=>`${s.trim()}:visible`).join(", "),i;for(;Date.now()<t.deadlineMs;){if(t.signal?.aborted)throw new Error("Google search navigation aborted");let s=await n();if((i===void 0||s===!0)&&(i=Math.min(t.deadlineMs,Date.now()+15e3)),Date.now()>=i)break;let o=!1;try{let S=new URL(e.url());o=/(^|\.)google\.[a-z.]+$/i.test(S.hostname)&&S.pathname==="/search"&&S.searchParams.get("q")===t.query}catch{}if(o){let S=await e.waitForSelector(a,{state:"visible",timeout:Math.min(500,Math.max(1,i-Date.now()))}).catch(()=>null),U=S?!1:await e.locator("body").innerText({timeout:Math.min(1e3,Math.max(1,i-Date.now()))}).then(c=>/did not match any documents|no results found/i.test(c)).catch(()=>!1);if(S||U){if(await n()===!0)continue;return}}if(t.signal?.aborted)throw new Error("Google search navigation aborted");let d=Math.min(200,i-Date.now(),t.deadlineMs-Date.now());d>0&&await e.waitForTimeout(d)}throw new Error("Google search results did not reach a readable state")}Hn.chromium.use((0,Zs.default)());var yl=180,ml=3e3,Cl=5e3,fl='#search, #rso, a[href] h3, [data-snhf], [role="main"]';function Ka(e,t){return e?Math.max(1,Math.min(t,e-Date.now())):t}function kl(e,t){let n=process.env[e];if(!n)return t;let a=Number(n);return Number.isInteger(a)&&a>0?a:t}function Ya(e){return e?e.slice(-6):null}function Qs(e,t){let n=(t??process.env.SERP_REDIRECT_BASE)?.trim().replace(/\/+$/,"");return n?`${n}/g/${Buffer.from(e,"utf8").toString("base64url")}`:e}function Ml(e){return e?/united states|u\.?s\.?a?\.?|^us$/i.test(e.trim()):!1}function _e(e){return e instanceof Error?e.message:String(e)}function vl(e){return/\b409\b|conflict|already exists/i.test(_e(e))}function Tl(e){return/\b404\b|not[ _-]?found|already (?:gone|deleted|closed)|does not exist/i.test(_e(e))}async function bl(e,t){try{await e.profiles.create({name:t})}catch(n){if(!vl(n))throw n}}function Xs(e,t){return{viewport:e.viewport,locale:e.locale,...t?{userAgent:t}:{},...e.deviceScaleFactor?{deviceScaleFactor:e.deviceScaleFactor}:{},...e.isMobile!==void 0?{isMobile:e.isMobile}:{},...e.hasTouch!==void 0?{hasTouch:e.hasTouch}:{}}}async function re(e,t,n){let a;try{return await Promise.race([e,new Promise((i,s)=>{a=setTimeout(()=>s(new Error(`${n} timed out after ${t}ms`)),t)})])}finally{a&&clearTimeout(a)}}function Nl(e){let t=e.trim();if(!t)throw new Error("channelHandle is required");if(/^https?:\/\//i.test(t)||/^(www\.|m\.)?youtube\.com\//i.test(t)){let o=new URL(/^https?:\/\//i.test(t)?t:`https://${t}`);if(o.hostname.replace(/^www\./,"").replace(/^m\./,"").toLowerCase()!=="youtube.com")throw new Error("channel URL must be on youtube.com");let S=o.pathname.split("/").filter(Boolean),U=S[0]??"",c=S[1]??"";if(U.startsWith("@"))return`https://www.youtube.com/${U}/videos`;if(U==="channel"&&c)return`https://www.youtube.com/channel/${c}/videos`;if((U==="c"||U==="user")&&c)return`https://www.youtube.com/${U}/${c}/videos`;throw new Error("channel URL must be a YouTube handle, /channel/UC..., /c/..., or /user/... URL")}let i=t.replace(/^\/+/,"").replace(/\/+$/,"").replace(/\/videos$/i,"");if(/^UC[\w-]{20,}$/.test(i))return`https://www.youtube.com/channel/${i}/videos`;let s=i.startsWith("@")?i:`@${i}`;if(!/^@[\w.-]+$/.test(s))throw new Error("channelHandle must be an @handle, UC channel ID, or YouTube channel URL");return`https://www.youtube.com/${s}/videos`}var Fn=class{browser=null;context=null;page=null;\u006b\u0065\u0072\u006e\u0065\u006cClient=null;\u006b\u0065\u0072\u006e\u0065\u006cSessionId=null;\u006b\u0065\u0072\u006e\u0065\u006cOpenedAtMs=null;\u006b\u0065\u0072\u006e\u0065\u006cStealth=null;\u006b\u0065\u0072\u006e\u0065\u006cSolverEnabled=!1;operationDeadlineMs;\u006b\u0065\u0072\u006e\u0065\u006cProxyUsed=null;\u006b\u0065\u0072\u006e\u0065\u006cProxySource=null;\u006b\u0065\u0072\u006e\u0065\u006cProxyType=null;\u006b\u0065\u0072\u006e\u0065\u006cHeadlessSent=null;last\u004b\u0065\u0072\u006e\u0065\u006cBillingMode=null;last\u004b\u0065\u0072\u006e\u0065\u006cOpenedAtMs=null;last\u004b\u0065\u0072\u006e\u0065\u006cClosedAtMs=null;debugEnabled=!1;debugSnapshot={\u006b\u0065\u0072\u006e\u0065\u006c:null,context:null,networkLocation:null,serpNavigation:null};async launch(t){if(t.\u006b\u0065\u0072\u006e\u0065\u006cApiKey&&t.isMobile)throw new ct("\u004b\u0065\u0072\u006e\u0065\u006c acquisition requires a native desktop browser; mobile capture needs provider-native mobile support.");this.operationDeadlineMs=t.operationDeadlineMs,this.debugEnabled=t.debug===!0;let n=t.proxyMode??(t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId?"configured":"none"),a=t.isMobile?"mobile":"desktop";if(this.debugSnapshot={\u006b\u0065\u0072\u006e\u0065\u006c:null,context:{viewport:t.viewport,locale:t.locale,device:a,userAgent:null,deviceScaleFactor:t.deviceScaleFactor??null,isMobile:t.isMobile===!0,hasTouch:t.hasTouch===!0},networkLocation:null,serpNavigation:null},t.\u006b\u0065\u0072\u006e\u0065\u006cApiKey){this.\u006b\u0065\u0072\u006e\u0065\u006cClient=new V({apiKey:t.\u006b\u0065\u0072\u006e\u0065\u006cApiKey});let s=Number.isInteger(t.\u006b\u0065\u0072\u006e\u0065\u006cTimeoutSeconds)&&Number(t.\u006b\u0065\u0072\u006e\u0065\u006cTimeoutSeconds)>0?Number(t.\u006b\u0065\u0072\u006e\u0065\u006cTimeoutSeconds):kl("\u004b\u0045\u0052\u004e\u0045\u004c_BROWSER_TIMEOUT_SECONDS",yl),o=Math.min(s,600);t.\u006b\u0065\u0072\u006e\u0065\u006cProfileName&&t.\u006b\u0065\u0072\u006e\u0065\u006cProfileSaveChanges===!0&&await bl(this.\u006b\u0065\u0072\u006e\u0065\u006cClient,t.\u006b\u0065\u0072\u006e\u0065\u006cProfileName);let d=se();this.\u006b\u0065\u0072\u006e\u0065\u006cHeadlessSent=null,this.last\u004b\u0065\u0072\u006e\u0065\u006cBillingMode="headful",d?.headlessSentOut&&(d.headlessSentOut.value=this.\u006b\u0065\u0072\u006e\u0065\u006cHeadlessSent);let S=await this.\u006b\u0065\u0072\u006e\u0065\u006cClient.browsers.create(Ys({stealth:t.\u006b\u0065\u0072\u006e\u0065\u006cStealth===!0,timeout_seconds:o,...t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId?{proxy_id:t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId}:{},...t.\u006b\u0065\u0072\u006e\u0065\u006cProfileName?{profile:{name:t.\u006b\u0065\u0072\u006e\u0065\u006cProfileName,...typeof t.\u006b\u0065\u0072\u006e\u0065\u006cProfileSaveChanges=="boolean"?{save_changes:t.\u006b\u0065\u0072\u006e\u0065\u006cProfileSaveChanges}:{}}}:{}}));this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId=S.session_id,this.\u006b\u0065\u0072\u006e\u0065\u006cOpenedAtMs=Date.now(),this.last\u004b\u0065\u0072\u006e\u0065\u006cOpenedAtMs=this.\u006b\u0065\u0072\u006e\u0065\u006cOpenedAtMs,this.last\u004b\u0065\u0072\u006e\u0065\u006cClosedAtMs=null,this.\u006b\u0065\u0072\u006e\u0065\u006cStealth=typeof S.stealth=="boolean"?S.stealth:null,this.\u006b\u0065\u0072\u006e\u0065\u006cSolverEnabled=t.\u006b\u0065\u0072\u006e\u0065\u006cStealth===!0&&S.stealth!==!1,this.\u006b\u0065\u0072\u006e\u0065\u006cProxyUsed=typeof S.proxy_id=="string"?!!S.proxy_id:!!t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId,this.\u006b\u0065\u0072\u006e\u0065\u006cProxySource=t.\u006b\u0065\u0072\u006e\u0065\u006cProxyResolution?.source??null,this.\u006b\u0065\u0072\u006e\u0065\u006cProxyType=t.\u006b\u0065\u0072\u006e\u0065\u006cProxyResolution?.proxyType??null;let U=null,c=null;if(!t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId&&!t.keepDefaultProxy)try{await re(this.\u006b\u0065\u0072\u006e\u0065\u006cClient.browsers.update(this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId,{disable_default_proxy:!0}),5e3,`\u004b\u0065\u0072\u006e\u0065\u006c session ${this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId} disable default proxy`),U=!0}catch(l){U=!1,c=_e(l)}let r={sessionId:this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId,proxyMode:n,requestedProxyIdPresent:!!t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId,requestedProxyIdSuffix:Ya(t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId),createdProxyIdPresent:typeof S.proxy_id=="string"?!!S.proxy_id:null,createdProxyIdSuffix:Ya(S.proxy_id),retrievedProxyIdPresent:null,retrievedProxyIdSuffix:null,retrievedProxyIdMatchesRequested:null,defaultProxyDisabled:U,defaultProxyDisableError:c,proxyResolution:t.\u006b\u0065\u0072\u006e\u0065\u006cProxyResolution??null,timeoutSeconds:o,stealth:typeof S.stealth=="boolean"?S.stealth:null,profilePresent:null,poolPresent:null,retrieveError:null};if(this.debugSnapshot.\u006b\u0065\u0072\u006e\u0065\u006c=r,console.info(JSON.stringify({event:"\u006b\u0065\u0072\u006e\u0065\u006c_browser_created",\u006b\u0065\u0072\u006e\u0065\u006c_session_id:this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId,timeout_seconds:o,proxy_mode:n,proxy_id_present:!!t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId,profile_name_present:!!t.\u006b\u0065\u0072\u006e\u0065\u006cProfileName,proxy_resolution_source:t.\u006b\u0065\u0072\u006e\u0065\u006cProxyResolution?.source})),this.debugEnabled&&await this.populate\u004b\u0065\u0072\u006e\u0065\u006cRetrieveDebug(r,t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId),this.browser=await to.chromium.connectOverCDP(S.cdp_ws_url),this.context=await Js(this.browser),this.page=await qs(this.context),await this.capture\u004b\u0065\u0072\u006e\u0065\u006cContextDebug(),await this.installEsbuildHelperShims(this.context),(this.debugEnabled||t.requireUsEgress)&&(this.debugSnapshot.networkLocation=await this.captureBrowserNetworkLocation()),t.requireUsEgress){let l=this.debugSnapshot.networkLocation?.country??null;if(!Ml(l))throw new et(`Non-US egress (${l??"unknown"}) \u2014 retrying with a fresh session`)}return}let i={headless:t.headless,proxy:t.proxy?{server:t.proxy}:void 0,...t.browserExecutablePath?{executablePath:t.browserExecutablePath}:{},...t.ignoreDefaultArgs?{ignoreDefaultArgs:t.ignoreDefaultArgs}:{}};if(t.profileDir)this.context=await Hn.chromium.launchPersistentContext(t.profileDir,{...i,...Xs(t)}),await this.installEsbuildHelperShims(this.context),this.page=await this.context.newPage(),this.debugSnapshot.context.userAgent=await _a(this.page);else{this.browser=await Hn.chromium.launch(i);let s=await Ga(this.browser);this.debugSnapshot.context.userAgent=s,this.context=await this.browser.newContext(Xs(t,s)),await this.installEsbuildHelperShims(this.context),this.page=await this.context.newPage()}this.debugEnabled&&(this.debugSnapshot.networkLocation=await this.captureBrowserNetworkLocation())}async capture\u004b\u0065\u0072\u006e\u0065\u006cContextDebug(){if(this.debugSnapshot.context={viewport:null,locale:null,device:"desktop",requestedDevice:"desktop",userAgent:null,deviceScaleFactor:null,isMobile:!1,hasTouch:!1},!this.page)return;let t=await this.page.evaluate(()=>({viewport:{width:window.innerWidth,height:window.innerHeight},locale:navigator.language,userAgent:navigator.userAgent,deviceScaleFactor:window.devicePixelRatio,isMobile:!1,hasTouch:navigator.maxTouchPoints>0})).catch(()=>null);!t||typeof t!="object"||!t.viewport||typeof t.viewport.width!="number"||typeof t.viewport.height!="number"||typeof t.locale!="string"||typeof t.userAgent!="string"||(this.debugSnapshot.context={...t,device:"desktop",requestedDevice:"desktop"})}async populate\u004b\u0065\u0072\u006e\u0065\u006cRetrieveDebug(t,n){if(!(!this.\u006b\u0065\u0072\u006e\u0065\u006cClient||!this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId))try{let a=await re(this.\u006b\u0065\u0072\u006e\u0065\u006cClient.browsers.retrieve(this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId),5e3,`\u004b\u0065\u0072\u006e\u0065\u006c session ${this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId} retrieve`);t.retrievedProxyIdPresent=typeof a.proxy_id=="string"?!!a.proxy_id:!1,t.retrievedProxyIdSuffix=Ya(a.proxy_id),t.retrievedProxyIdMatchesRequested=n?a.proxy_id===n:!a.proxy_id,t.timeoutSeconds=typeof a.timeout_seconds=="number"?a.timeout_seconds:t.timeoutSeconds,t.stealth=typeof a.stealth=="boolean"?a.stealth:t.stealth,t.profilePresent=!!a.profile,t.poolPresent=!!a.pool}catch(a){t.retrieveError=_e(a)}}async captureBrowserNetworkLocation(){let t=(a,i="ipapi.co")=>({source:i,ip:null,city:null,region:null,country:null,org:null,timezone:null,error:a});if(!this.context)return t("browser context is not available");let n=null;try{n=await this.context.newPage();let a=await this.loadJsonInDebugPage(n,"https://ipwho.is/");if(a){let d=typeof a.connection=="object"&&a.connection!==null?a.connection:{};return{source:"ipwho.is",ip:typeof a.ip=="string"?a.ip:null,city:typeof a.city=="string"?a.city:null,region:typeof a.region=="string"?a.region:null,country:typeof a.country=="string"?a.country:null,org:typeof d.org=="string"?d.org:null,timezone:typeof a.timezone=="object"&&a.timezone!==null&&typeof a.timezone.id=="string"?a.timezone.id:null,error:null}}let i=await this.loadJsonInDebugPage(n,"https://api64.ipify.org?format=json");if(i)return{source:"api64.ipify.org",ip:typeof i.ip=="string"?i.ip:null,city:null,region:null,country:null,org:null,timezone:null,error:null};await re(n.goto("https://ipapi.co/json/",{waitUntil:"domcontentloaded",timeout:7e3}),8e3,"browser network location navigation");let s=await n.locator("body").innerText({timeout:2e3}),o=JSON.parse(s);return{source:"ipapi.co",ip:typeof o.ip=="string"?o.ip:null,city:typeof o.city=="string"?o.city:null,region:typeof o.region=="string"?o.region:null,country:typeof o.country_name=="string"?o.country_name:typeof o.country=="string"?o.country:null,org:typeof o.org=="string"?o.org:null,timezone:typeof o.timezone=="string"?o.timezone:null,error:null}}catch(a){return t(_e(a))}finally{await n?.close().catch(()=>{})}}async loadJsonInDebugPage(t,n){try{await re(t.goto(n,{waitUntil:"domcontentloaded",timeout:7e3}),8e3,`browser network location navigation ${n}`);let a=await t.locator("body").innerText({timeout:2e3});return JSON.parse(a)}catch{return null}}async installEsbuildHelperShims(t){await t.addInitScript(()=>{let n=globalThis;typeof n.__name!="function"&&(n.__name=a=>a),typeof n.__publicField!="function"&&(n.__publicField=(a,i,s)=>(a[i]=s,s))})}async withTemporaryPage(t,n){if(!this.context)throw new Error("Browser context is not available");return Bn(this.context,async()=>{},t,n)}async navigateToSERP(t,n,a,i,s){let o=new URLSearchParams({q:t,gl:a,hl:i,pws:"0"});s?.tbs&&o.set("tbs",s.tbs),n&&o.set("uule",n);let d="https://www.google.com/search?"+o.toString(),S=Qs(d),U=s?.debug?{requestedUrl:d,finalUrl:null,title:null,bodySnippet:null,hasPaa:null,captchaDetected:null,googleSorryUrl:null,redirected:null}:null;if(U&&(this.debugSnapshot.serpNavigation=U),this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId){let r={deadlineMs:s?.deadlineMs??this.operationDeadlineMs,signal:s?.signal};try{let l=await Va(this.page,{query:t,gl:a,hl:i,uule:n??void 0,tbs:s?.tbs,purpose:s?.purpose,deadlineMs:s?.deadlineMs??this.operationDeadlineMs,signal:s?.signal,solverEnabled:this.\u006b\u0065\u0072\u006e\u0065\u006cSolverEnabled});return await this.updateSerpNavigationDebug(U,d,{hasPaa:l.hasPaa,captchaDetected:l.challengeObserved===!0},r),{hasPaa:l.hasPaa}}catch(l){throw await this.updateSerpNavigationDebug(U,d,{hasPaa:null,captchaDetected:l instanceof et?!0:null},r),l}}try{await this.page.goto(S,{waitUntil:"domcontentloaded",timeout:Ka(s?.deadlineMs,s?.purpose==="serp"?8e3:45e3)})}catch(r){await this.updateSerpNavigationDebug(U,d,{hasPaa:null,captchaDetected:null});let l=await this.captureDiagnostics(d);throw new ct(`page.goto failed: ${r.message} | ${l}`)}if(await this.isSerpChallengeVisible())throw await this.updateSerpNavigationDebug(U,d,{hasPaa:!1,captchaDetected:!0}),new et(this.captchaMessage());if(s?.purpose==="serp"){await this.page.waitForSelector(fl,{timeout:Ka(s.deadlineMs,1500)}).catch(()=>null);let r=await this.page.locator(dt.paaItem).count().catch(()=>0)>0;return await this.updateSerpNavigationDebug(U,d,{hasPaa:r,captchaDetected:!1}),{hasPaa:r}}if(await this.page.waitForSelector(dt.paaItem,{timeout:Ka(s?.deadlineMs,4e3)}).catch(()=>null))return await this.updateSerpNavigationDebug(U,d,{hasPaa:!0,captchaDetected:!1}),{hasPaa:!0};if(await this.isSerpChallengeVisible())throw await this.updateSerpNavigationDebug(U,d,{hasPaa:!1,captchaDetected:!0}),new et(this.captchaMessage());for(let r=1;r<=6;r++)if(await this.page.evaluate(u=>{window.scrollTo(0,document.body.scrollHeight*u)},r/6),await this.page.waitForTimeout(600),await this.page.locator(dt.paaItem).count()>0)return await this.updateSerpNavigationDebug(U,d,{hasPaa:!0,captchaDetected:!1}),{hasPaa:!0};return await this.updateSerpNavigationDebug(U,d,{hasPaa:!1,captchaDetected:!1}),{hasPaa:!1}}async isSerpChallengeVisible(){if(!this.page)return!1;if(await this.page.locator(dt.captchaMarker).count().catch(()=>0)>0)return!0;let n=this.page.url();if(/google\.[^/]+\/sorry\//i.test(n))return!0;let a=await this.page.evaluate(()=>(document.body?.innerText??"").replace(/\s+/g," ").trim().slice(0,1e3)).catch(()=>"");return/recaptcha|unusual traffic|are you a robot|about this page|detected unusual traffic/i.test(a)}async updateSerpNavigationDebug(t,n,a,i){if(!(!t||!this.page))try{let s=this.page.url();t.finalUrl=s,t.hasPaa=a.hasPaa,t.captchaDetected=a.captchaDetected,t.googleSorryUrl=/google\.[^/]+\/sorry\//i.test(s),t.redirected=s!==n;let o=Math.min(1e3,i?.deadlineMs===void 0?1e3:i.deadlineMs-Date.now());if(i&&(i.signal?.aborted||o<=0))return;let d=Promise.all([this.page.title().catch(()=>""),this.page.evaluate(()=>(document.body?.innerText??"").replace(/\s+/g," ").trim().slice(0,500)).catch(()=>"")]),[S,U]=i?await nt(re(d,o,"\u004b\u0065\u0072\u006e\u0065\u006c navigation debug"),i.signal):await d;t.title=S,t.bodySnippet=U,t.captchaDetected=a.captchaDetected??/recaptcha|unusual traffic|are you a robot/i.test(U)}catch(s){t.bodySnippet=`debug capture failed: ${_e(s)}`}}async captureDiagnostics(t){try{let n=this.page.url(),a=await this.page.title().catch(()=>""),i=await this.page.evaluate(()=>(document.body?.innerText??"").replace(/\s+/g," ").trim().slice(0,400)).catch(()=>""),s=/consent\.google\./.test(n)||/before you continue/i.test(i),o=/recaptcha|unusual traffic|are you a robot/i.test(i),d=[s?"CONSENT_WALL":"",o?"BOT_CHALLENGE":"",n!==t?"REDIRECTED":""].filter(Boolean).join(",");return`intended=${t} | final=${n} | title="${a}" | flags=[${d}] | body="${i}"`}catch(n){return`diagnostics-failed: ${n.message}`}}captchaMessage(){return this.\u006b\u0065\u0072\u006e\u0065\u006cClient?"Google returned a CAPTCHA on this session \u2014 retrying with a fresh session.":Ti}async navigateTo(t){if(this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId){let i=new URL(t);if(/^(?:www\.)?google\.[a-z.]+$/i.test(i.hostname)&&i.pathname==="/search"&&i.searchParams.has("q")){await Va(this.page,{query:i.searchParams.get("q"),gl:i.searchParams.get("gl")??"us",hl:i.searchParams.get("hl")??"en",uule:i.searchParams.get("uule")??void 0,tbs:i.searchParams.get("tbs")??void 0,extraParams:Object.fromEntries([...i.searchParams].filter(([s])=>!["q","gl","hl","uule","tbs","pws"].includes(s))),purpose:"serp",deadlineMs:this.operationDeadlineMs,solverEnabled:this.\u006b\u0065\u0072\u006e\u0065\u006cSolverEnabled});return}}let n=process.env.ADS_ARRIVAL_REDIRECT_BASE?.trim(),a=n?Qs(t,n):t;try{if(await this.page.goto(a,{waitUntil:"domcontentloaded",timeout:45e3}),/google\.[^/]+\/search\?/i.test(t)&&await this.isSerpChallengeVisible())throw new et(this.captchaMessage())}catch(i){if(i instanceof et)throw i;let s=await this.captureDiagnostics(t);throw new ct(`page.goto failed: ${i.message} | ${s}`)}}async navigateToChannel(t){let n=Nl(t);try{await this.page.goto(n,{waitUntil:"networkidle",timeout:3e4})}catch(a){let i=await this.captureDiagnostics(n);throw new ct(`navigateToChannel failed: ${a.message} | ${i}`)}}async evaluate(t,n){return this.page.evaluate(t,n)}getPage(){return this.page}get\u004b\u0065\u0072\u006e\u0065\u006cSessionId(){return this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId}get\u004b\u0065\u0072\u006e\u0065\u006cMeteringEvidence(){return{sessionId:this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId??this.debugSnapshot.\u006b\u0065\u0072\u006e\u0065\u006c?.sessionId??null,billingMode:this.last\u004b\u0065\u0072\u006e\u0065\u006cBillingMode,openedAtMs:this.last\u004b\u0065\u0072\u006e\u0065\u006cOpenedAtMs,closedAtMs:this.last\u004b\u0065\u0072\u006e\u0065\u006cClosedAtMs}}getProviderSessionMetadata(){return{provider:this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId?"\u006b\u0065\u0072\u006e\u0065\u006c":"local",providerSessionId:this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId,disconnectObservation:null,billingMode:this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId?this.\u006b\u0065\u0072\u006e\u0065\u006cHeadlessSent?"headless":"headful":null}}getDebugSnapshot(){return this.debugSnapshot}async close(){if(this.browser){let t=this.browser,n=this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId,a=this.\u006b\u0065\u0072\u006e\u0065\u006cClient,i=this.\u006b\u0065\u0072\u006e\u0065\u006cOpenedAtMs,s=this.\u006b\u0065\u0072\u006e\u0065\u006cStealth,o=this.\u006b\u0065\u0072\u006e\u0065\u006cProxyUsed,d=this.\u006b\u0065\u0072\u006e\u0065\u006cProxySource,S=this.\u006b\u0065\u0072\u006e\u0065\u006cProxyType,U=this.\u006b\u0065\u0072\u006e\u0065\u006cHeadlessSent,c=this.getProviderSessionMetadata();if(this.browser=null,this.context=null,this.page=null,this.\u006b\u0065\u0072\u006e\u0065\u006cSessionId=null,this.\u006b\u0065\u0072\u006e\u0065\u006cClient=null,this.\u006b\u0065\u0072\u006e\u0065\u006cSolverEnabled=!1,this.\u006b\u0065\u0072\u006e\u0065\u006cOpenedAtMs=null,this.\u006b\u0065\u0072\u006e\u0065\u006cHeadlessSent=null,this.\u006b\u0065\u0072\u006e\u0065\u006cProxySource=null,this.\u006b\u0065\u0072\u006e\u0065\u006cProxyType=null,a&&n){console.info(JSON.stringify({event:"\u006b\u0065\u0072\u006e\u0065\u006c_browser_delete_started",\u006b\u0065\u0072\u006e\u0065\u006c_session_id:n}));let r=re(a.browsers.deleteByID(n),Cl,`\u004b\u0065\u0072\u006e\u0065\u006c session ${n} delete`),l=re(t.close(),ml,`\u004b\u0065\u0072\u006e\u0065\u006c browser ${n} close`),[u,h]=await Promise.allSettled([r,l]);this.last\u004b\u0065\u0072\u006e\u0065\u006cClosedAtMs=Date.now(),i!=null&&Ks({\u006b\u0065\u0072\u006e\u0065\u006cSessionId:n,source:"browser_driver",stealth:s,headlessSent:U,proxyUsed:o,proxySource:d,proxyType:S,openedAtMs:i,closedAtMs:this.last\u004b\u0065\u0072\u006e\u0065\u006cClosedAtMs});let w=u.status==="rejected"&&Tl(u.reason),g={\u006b\u0065\u0072\u006e\u0065\u006cSessionId:n,\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted:!0,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:u.status==="fulfilled"||w,\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:u.status==="rejected"&&!w?u.reason instanceof Error?u.reason.message:String(u.reason):null,browserCloseSucceeded:h.status==="fulfilled",browserCloseError:h.status==="rejected"?h.reason instanceof Error?h.reason.message:String(h.reason):null,provider:c.provider,providerSessionId:c.providerSessionId,providerDisconnectObserved:!1,providerDisconnectMessage:null};return u.status==="rejected"&&!w?(console.warn(JSON.stringify({event:"\u006b\u0065\u0072\u006e\u0065\u006c_browser_delete_failed",\u006b\u0065\u0072\u006e\u0065\u006c_session_id:n,message:g.\u006b\u0065\u0072\u006e\u0065\u006cDeleteError})),console.warn(`\u004b\u0065\u0072\u006e\u0065\u006c session cleanup failed for ${n}:`,u.reason)):console.info(JSON.stringify({event:"\u006b\u0065\u0072\u006e\u0065\u006c_browser_delete_succeeded",\u006b\u0065\u0072\u006e\u0065\u006c_session_id:n})),h.status==="rejected"&&(console.warn(JSON.stringify({event:"\u006b\u0065\u0072\u006e\u0065\u006c_browser_close_failed",\u006b\u0065\u0072\u006e\u0065\u006c_session_id:n,message:g.browserCloseError})),console.warn(`\u004b\u0065\u0072\u006e\u0065\u006c browser close failed for ${n}:`,h.reason)),g}return await t.close(),{\u006b\u0065\u0072\u006e\u0065\u006cSessionId:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted:!1,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:null,browserCloseSucceeded:!0,browserCloseError:null,provider:c.provider,providerSessionId:c.providerSessionId,providerDisconnectObserved:!1,providerDisconnectMessage:null}}else if(this.context){let t=this.context;return this.context=null,this.page=null,await t.close(),{\u006b\u0065\u0072\u006e\u0065\u006cSessionId:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted:!1,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:null,browserCloseSucceeded:!0,browserCloseError:null,provider:"local",providerSessionId:null,providerDisconnectObserved:!1,providerDisconnectMessage:null}}return{\u006b\u0065\u0072\u006e\u0065\u006cSessionId:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted:!1,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:null,browserCloseSucceeded:null,browserCloseError:null,provider:"local",providerSessionId:null,providerDisconnectObserved:!1,providerDisconnectMessage:null}}};var no=require("playwright");var Pl=new Set(["image","media","font","stylesheet","ping"]),Il=["doubleclick.net","googleadservices.com","googlesyndication.com","google-analytics.com"],Al='#search, #rso, a[href] h3, [data-snhf], [role="main"]',xl=3e4,eo=1500,Wl=3e3,Ol=new Set(["https://www.google.com","https://www.gstatic.com","https://www.recaptcha.net","https://recaptcha.net"]);function Dn(e){return e.origin==="https://www.google.com"&&/^\/sorry(?:\/|$)/.test(e.pathname)}function Ll(e,t){if(Dn(e)||Ol.has(e.origin)&&/^\/recaptcha(?:\/|$)/.test(e.pathname))return!0;try{return Dn(new URL(t))}catch{return!1}}function de(e,t){return e?Math.max(1,Math.min(t,e-Date.now())):t}async function Bl(e,t,n){let a=Math.min(Date.now()+Wl,n??1/0);if(Date.now()>=a)return!1;let i=e.request(),s=new AbortController;t.add(s);let o=new Promise((U,c)=>{s.signal.addEventListener("abort",()=>c(s.signal.reason),{once:!0})}),d=setTimeout(()=>{s.abort(new DOMException("Controller asset transfer timed out","TimeoutError"))},Math.max(0,a-Date.now())),S=!1;try{let U=i.headers();if(s.signal.aborted||Date.now()>=a)return!1;let c=await Promise.race([fetch(i.url(),{method:i.method(),signal:s.signal,redirect:"error",headers:{accept:U.accept??"*/*","accept-language":U["accept-language"]??"en-US,en;q=0.9","user-agent":U["user-agent"]??"Mozilla/5.0"},body:i.method()==="GET"||i.method()==="HEAD"?void 0:i.postData()}),o]);if(!c.ok||s.signal.aborted||Date.now()>=a)return!1;let r=Buffer.from(await Promise.race([c.arrayBuffer(),o]));if(s.signal.aborted||Date.now()>=a)return!1;let l={status:c.status,contentType:c.headers.get("content-type")??"application/octet-stream",headers:{"cache-control":"public, max-age=3600"},body:r};return clearTimeout(d),S=!0,await e.fulfill(l),!0}catch{return S}finally{clearTimeout(d),t.delete(s),s.abort()}}var _n=class{constructor(t={}){this.resourcePolicy=t}resourcePolicy;browser=null;context=null;page=null;cdpSession=null;providerSessionId=null;disconnectObservation=null;closing=!1;connectionStarted=!1;closeReceipt=null;controllerAssetTransfers=new Set;operationDeadlineMs;observeDisconnect(t,n){this.closing||this.disconnectObservation||(this.disconnectObservation=Qn(t,n))}async launch(t){if(this.page)return;this.operationDeadlineMs=t.operationDeadlineMs,this.closing=!1,this.providerSessionId=null,this.disconnectObservation=null;let n=Ra();if(!n)throw new Error("SERP browser service is not configured");if(this.connectionStarted)throw new Error("Previous browser connection outcome is unresolved");if(this.closeReceipt)throw new Error("Browser driver has already been closed");this.connectionStarted=!0;try{this.browser=await no.chromium.connectOverCDP(n,{timeout:de(t.operationDeadlineMs,xl)})}catch(s){let o=(s instanceof Error?s.message:String(s)).replaceAll(n,"[redacted endpoint]");throw new Error(xt(o)??"\u0042\u0072\u0069\u0067\u0068\u0074 \u0044\u0061\u0074\u0061 browser connection failed")}this.context=this.browser.contexts()[0]??await this.browser.newContext(),await this.context.addInitScript(()=>{let s=globalThis;typeof s.__name!="function"&&(s.__name=o=>o),typeof s.__publicField!="function"&&(s.__publicField=(o,d,S)=>(o[d]=S,S))}),this.page=this.context.pages()[0]??await this.context.newPage(),this.browser.on("disconnected",()=>this.observeDisconnect("browser_disconnected")),this.context.on("close",()=>this.observeDisconnect("context_closed")),this.page.on("close",()=>this.observeDisconnect("page_closed")),this.page.on("crash",()=>this.observeDisconnect("page_crashed")),this.cdpSession=await this.context.newCDPSession(this.page);let i=await this.cdpSession.send("Browser.getSessionId");this.providerSessionId=pi(i?.sessionId),await this.setupPage(this.page),this.resourcePolicy.startupSettleMs&&await this.page.waitForTimeout(this.resourcePolicy.startupSettleMs)}async setupPage(t){this.resourcePolicy.nativeGoogleAssets||await t.route("**/*",async n=>{if(this.closing)return;let a=n.request(),i=a.resourceType(),s;try{s=new URL(a.url())}catch{await n.continue();return}if(s.origin==="https://www.google.com"&&(s.pathname==="/sgasync"||/^\/async(?:\/|$)/.test(s.pathname))||Ll(s,t.url())){await n.continue();return}let d=s.hostname.toLowerCase();if(!((s.origin==="https://www.google.com"||s.origin==="https://www.gstatic.com")&&(s.pathname.includes("/shared_dict/")||i==="script")&&await Bl(n,this.controllerAssetTransfers,this.operationDeadlineMs))&&!this.closing){if(Pl.has(i)&&!(i==="image"&&this.resourcePolicy.allowImages)&&!(i==="stylesheet"&&this.resourcePolicy.allowStylesheets)){await n.abort("blockedbyclient");return}if(Il.some(U=>d===U||d.endsWith(`.${U}`))){await n.abort("blockedbyclient");return}await n.continue()}})}async withTemporaryPage(t,n){if(!this.context||this.closing)throw new Error("Browser context is not available");return Bn(this.context,a=>this.setupPage(a),t,n)}async navigateToSERP(t,n,a,i,s){if(!this.page)throw new Error("Browser page is not available");let o=()=>{if(s?.signal?.aborted)throw oe(s.signal);if(s?.deadlineMs!=null&&Date.now()>=s.deadlineMs)throw new DOMException("Google navigation exceeded the work deadline","TimeoutError")};o();let d=new URLSearchParams({q:t,gl:a,hl:i,pws:"0"});if(s?.tbs&&d.set("tbs",s.tbs),n&&d.set("uule",n),await nt(this.page.goto(`https://www.google.com/search?${d}`,{waitUntil:"domcontentloaded",timeout:de(s?.deadlineMs,s?.purpose==="serp"?12e4:45e3)}),s?.signal),o(),Dn(new URL(this.page.url()))&&this.cdpSession){let c=this.cdpSession,r,l=await nt(Promise.race([c.send("Captcha.solve",{detectTimeout:de(s?.deadlineMs,3e4)}).catch(()=>null),new Promise(u=>{r=setTimeout(()=>u(null),de(s?.deadlineMs,75e3))})]),s?.signal).finally(()=>{r&&clearTimeout(r)});o(),l?.status==="solve_finished"&&(await nt(this.page.waitForURL(u=>u.origin==="https://www.google.com"&&u.pathname==="/search",{timeout:de(s?.deadlineMs,25e3)}).catch(()=>{}),s?.signal),o())}if(s?.purpose==="serp")return await nt(this.page.waitForSelector(Al,{timeout:de(s.deadlineMs,8e3)}).catch(()=>null),s.signal),o(),{hasPaa:await nt(this.page.locator(dt.paaItem).count().catch(()=>0),s.signal)>0};if(Dn(new URL(this.page.url())))throw new et("Google SERP returned a CAPTCHA \u2014 retrying with a fresh session.");let S=await nt(this.page.evaluate(c=>!!document.querySelector(c),dt.paaItem).catch(()=>!1),s?.signal);if(o(),S)return{hasPaa:!0};let U=!!await nt(this.page.waitForSelector(dt.paaItem,{state:"attached",timeout:de(s?.deadlineMs,8e3)}).catch(()=>null),s?.signal);return o(),{hasPaa:U}}async navigateTo(t){if(!this.page)throw new Error("Browser page is not available");await this.page.goto(t,{waitUntil:"load",timeout:45e3})}async navigateToChannel(){throw new Error("YouTube navigation is not supported by the SERP browser driver")}async evaluate(t,n){if(!this.page)throw new Error("Browser page is not available");return this.page.evaluate(t,n)}getPage(){if(!this.page)throw new Error("Browser page is not available");return this.page}get\u004b\u0065\u0072\u006e\u0065\u006cSessionId(){return null}get\u0042\u0072\u0069\u0067\u0068\u0074\u0044\u0061\u0074\u0061SessionId(){return this.providerSessionId}getProviderSessionMetadata(){return{provider:"\u0062\u0072\u0069\u0067\u0068\u0074_\u0064\u0061\u0074\u0061_browser_api",providerSessionId:this.providerSessionId,disconnectObservation:this.disconnectObservation}}getDebugSnapshot(){return{\u006b\u0065\u0072\u006e\u0065\u006c:null,context:null,networkLocation:null,serpNavigation:null}}async close(){return this.closeReceipt??=this.closePhysicalSession()}async closePhysicalSession(){this.closing=!0;for(let d of this.controllerAssetTransfers)d.abort(new DOMException("Browser is closing","AbortError"));let t=yi(this.getProviderSessionMetadata()),n=!1,a=null,i=null,s=null,o=async(d,S)=>{let U;try{await Promise.race([d(),new Promise((c,r)=>{U=setTimeout(()=>r(new Error(`${S} acknowledgement exceeded ${eo}ms`)),eo)})])}finally{U&&clearTimeout(U)}};if(this.connectionStarted)if(!this.browser)a="Browser connection outcome is unknown; no remote termination receipt";else{try{await o(async()=>{let d=this.cdpSession??(this.context&&this.page?await this.context.newCDPSession(this.page):null);if(!d)throw new Error("Remote browser termination channel is unavailable");await d.send("Browser.close")},"Remote browser close"),n=!0}catch(d){a=xt(d instanceof Error?d.message:String(d))??"Remote browser termination is unconfirmed",this.disconnectObservation??=Qn("browser_close_error",a)}try{await o(()=>this.browser.close(),"Local browser disconnect"),i=!0}catch(d){i=!1,s=xt(d instanceof Error?d.message:String(d))??"Local browser disconnect failed"}}return this.browser=null,this.context=null,this.page=null,this.cdpSession=null,{\u006b\u0065\u0072\u006e\u0065\u006cSessionId:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted:!1,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:null,browserCloseSucceeded:this.connectionStarted?n:null,browserCloseError:a,localDisconnectSucceeded:i,localDisconnectError:s,physicalOutcome:this.connectionStarted?n?"terminated":"unknown":"not_started",...t}}};function ao(e,t){return e.plannedProvider==="\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061"?new _n({nativeGoogleAssets:t?.nativeGoogleAssets}):new Fn}var Z={container:".eJH8qe.adDDi",dataInitq:"[data-initq]",item:dt.paaItem,itemDataQ:"data-q",itemDataInitQ:"data-initq",itemQuestionEl:".JlqpRe",answerContainer:".bCOlv, .hgKElc, .wDYxhc, .LGOjhe, .fo7IQd, .fmW3u",aiAnswerBody:".pWvJNd",answerBody:".hgKElc, .LGOjhe, .fo7IQd, .fmW3u",answerControl:'button, [role="button"], a',answerEntity:".q224lc",citationBadge:".WBgIic",sourceCard:"[data-src-id]",sourceCardTitle:".vFyWT",sourceDescription:"[data-crb-snippet-text]",aiCitation:"a.PMDqCb[href]",aiSourceCard:"a.vIWmYe[href], a.Zbfntb[href]",sourceTitle:"h3",sourceSite:".VuuXrf",sourceCite:"cite",clickTarget:".JlqpRe",expandedClass:"aoRk1c",captchaMarker:dt.captchaMarker};var Ja={alabama:"AL",alaska:"AK",arizona:"AZ",arkansas:"AR",california:"CA",colorado:"CO",connecticut:"CT",delaware:"DE",florida:"FL",georgia:"GA",hawaii:"HI",idaho:"ID",illinois:"IL",indiana:"IN",iowa:"IA",kansas:"KS",kentucky:"KY",louisiana:"LA",maine:"ME",maryland:"MD",massachusetts:"MA",michigan:"MI",minnesota:"MN",mississippi:"MS",missouri:"MO",montana:"MT",nebraska:"NE",nevada:"NV","new hampshire":"NH","new jersey":"NJ","new mexico":"NM","new york":"NY","north carolina":"NC","north dakota":"ND",ohio:"OH",oklahoma:"OK",oregon:"OR",pennsylvania:"PA","rhode island":"RI","south carolina":"SC","south dakota":"SD",tennessee:"TN",texas:"TX",utah:"UT",vermont:"VT",virginia:"VA",washington:"WA","west virginia":"WV",wisconsin:"WI",wyoming:"WY","district of columbia":"DC"},Rl=[...Object.keys(Ja).map(e=>e.replace(/\s+/g,"\\s+")),...Object.values(Ja)].join("|"),El=new RegExp(`\\b([A-Z][A-Za-z]+(?:[\\s.-][A-Z][A-Za-z]+){0,4}),?\\s+(${Rl})\\b`,"gi");function so(e){if(!e)return null;let t=e.trim();return/^[A-Z]{2}$/i.test(t)?t.toUpperCase():Ja[t.toLowerCase()]??null}function oo(e){return e.replace(/\s+/g," ").trim().replace(/^.*\b(?:in|near|around|serving)\s+/i,"").toLowerCase().replace(/\b[a-z]/g,n=>n.toUpperCase())}function Hl(e){if(!e)return null;let[t="",n=""]=e.split(",").map(a=>a.trim());return{city:oo(t),regionCode:so(n),canonicalLocation:e}}function Fl(e,t,n,a){let i=oo(t),s=so(n);if(!i||!s)return;let o=`${i.toLowerCase()}|${s}`,d=e.get(o);if(d){d.count++,d.examples.length<3&&!d.examples.includes(a)&&d.examples.push(a);return}e.set(o,{city:i,regionCode:s,count:1,examples:[a]})}function Dl(e){try{return decodeURIComponent(e)}catch{}try{return decodeURIComponent(e.replace(/%(?![0-9a-fA-F]{2})/g,"%25"))}catch{return e}}function io(e,t){let n=Dl(t).replace(/[+/|_-]+/g," ");for(let a of n.matchAll(El))Fl(e,a[1]??"",a[2]??"",n.slice(0,180))}function ln(e,t,n){let a=Hl(e),i=new Map;for(let d of t)io(i,[d.title,d.snippet??"",d.cite??"",d.url].join(" "));for(let d of n)io(i,[d.name,...d.metadata,d.websiteUrl??"",d.directionsUrl??""].join(" "));let s=Array.from(i.values()).sort((d,S)=>S.count-d.count||d.city.localeCompare(S.city)).slice(0,8);return a?s.length===0?{status:"unknown",expected:a,candidates:[]}:{status:s.some(d=>d.city.toLowerCase()===a.city.toLowerCase()&&(a.regionCode==null||d.regionCode===a.regionCode))?"matched":"mismatch",expected:a,candidates:s}:{status:"not_requested",expected:null,candidates:s}}var _l=/^(?:an error has occurred(?:[.!…]\s*)?(?:please try again later[.!…]?)?|loading|please wait|try again|something went wrong|an AI overview is not available for this search|can't generate an AI overview right now\.?\s*try again later\.?)[.!…\s]*$/i,Gl=/^(?:AI Overview|View all|Show more|Show less|Related Links|Ask anything in AI Mode|AI can make mistakes)[.!…\s]*$/i;function qa(e){return e.replace(/\u00a0/g," ").replace(/\s+/g," ").trim()}function Sn(e,t){if(!e)return;let n=qa(e.split(/\r?\n/).filter(i=>!Gl.test(qa(i))).join(`
21776
+ `)),a=t?qa(t):"";return a&&n.toLowerCase().startsWith(a.toLowerCase())&&(n=n.slice(a.length).trim()),!n||_l.test(n)?void 0:n}function le({selectors:e,onlyQuestion:t}){let n=l=>(l??"").replace(/\u00a0/g," ").replace(/\s+/g," ").trim(),a=l=>n(l).replace(/\s*\(\+\d+\)\s*-\s*View related links.*$/i,"").replace(/\s*(?:[-.]\s*)?Opens in new tab[.!]?$/i,"").trim(),i=(l,u)=>{if(l.matches(e.clickTarget)||l.getAttribute("aria-expanded")==="true")return!1;let h=l.closest(".biJ8pb")?.closest(".hICk5e[data-collapsed]");if(h&&(h.getAttribute("data-collapsed")!=="1"||u?.closest(".hICk5e[data-collapsed]")===h))return!1;let w=l.getAttribute("href");return w&&!/^(?:#|javascript:void\(0\);?$)/i.test(w)||l.closest(e.aiSourceCard+","+e.sourceCard)?!1:[l.getAttribute("aria-label"),l.textContent].map(n).some(C=>/^(?:(?:show|read|see) more(?: (?:AI Overview|(?:of )?(?:this |the )?answer))?|continue reading|expand(?: (?:this |the )?answer)?)(?:[.!…]|\s*[▼⌄+])?$/i.test(C))},s=(l,u=!1)=>l.hasAttribute("hidden")||l.getAttribute("aria-hidden")==="true"&&!u||/(?:display\s*:\s*none|visibility\s*:\s*hidden)/i.test(l.getAttribute("style")??""),o=l=>{let u=l.ownerDocument.defaultView?.getComputedStyle(l);return u?.display==="none"||u?.visibility==="hidden"},d=(l,u)=>!u?.matches(e.aiAnswerBody)||!u.closest(".hICk5e[data-collapsed]")||!l?.matches("span.mTEjhd > span.dteT0b > div[data-xpm-copy-root][data-xpm-math-type]")||!l.querySelector(":scope > div > math > semantics")?"":n(l.querySelector(':scope > img[data-xpm-latex][role="presentation"][aria-hidden="true"]')?.getAttribute("data-xpm-latex")),S=(l,u)=>{let h=l?.closest('div.Q9iar.bliT4d.KfKEse.xRMEde[role="list"]');return!!(u?.matches(e.aiAnswerBody)&&u.closest(".hICk5e[data-collapsed]")&&h&&u.contains(h)&&l?.matches('div.Q9iar.BPUOre.bliT4d.KfKEse.xRMEde[role="listitem"]')&&l.querySelector(":scope > div.Q9iar.BPUOre.ua6Thd.bliT4d.KfKEse.xRMEde"))},U=(l,u)=>{if(!u?.matches(e.aiAnswerBody)||!u.closest(".hICk5e[data-collapsed]")||!l.matches('span.jAOkJc[role="button"]')||!l.parentElement?.matches("u.wfWfIf.fxyaSe")||!l.parentElement.parentElement?.matches("span.iNqyIf"))return!1;let h=l.firstElementChild;return!!(h?.matches("span.iNqyIf")&&l.children.length===1&&n(l.textContent)===n(h.textContent))},c=(l,u)=>{if(!u?.matches(e.aiAnswerBody)||!u.closest(".hICk5e[data-collapsed]"))return!1;if(l.matches("li.Z1qcYe, div.WYczDe, span.iNqyIf, ol.T9WCjf.qkgVBf")||S(l,u)||l.matches("strong.rQesXe.MPyX")&&l.closest("div.n6owBd.awi2gc")&&S(l.closest('[role="listitem"]'),u))return!0;if(l.closest("span.iNqyIf")){if(l.matches("strong.rQesXe.MPyX"))return!0;let w=l.matches("span")?l.querySelector(":scope > a.H23r4e[href]"):null;if(w&&/^(?:https?:\/\/|\/goto\?url=|\/url\?)/i.test(w.getAttribute("href")??"")&&l.children.length===1&&n(l.textContent)===n(w.textContent)&&l.parentElement?.matches("span")&&/display\s*:\s*contents/i.test(l.parentElement.getAttribute("style")??""))return!0}if(!l.matches("div.tYHU1b"))return!1;let h=l.querySelector(":scope > div.ID94bb[id]");return h?Array.from(l.querySelectorAll('[role="button"][aria-expanded="true"][aria-controls]')).some(w=>{if(w.closest(".tYHU1b")!==l||w.getAttribute("aria-controls")!==h.id||n(w.textContent)!=="Show less")return!1;for(let g=w;g&&g!==l;g=g.parentElement)if(s(g)||o(g))return!1;return!0}):!1},r=(l,u,h)=>{if(!l||l!==u&&(s(l,c(l,u))||l.matches('style,script,noscript,button,[data-artifact-type="map"]')||l.matches('[role="button"]')&&!l.matches(e.answerEntity)&&!U(l,u)||l.matches(e.aiSourceCard+","+e.sourceCard+","+e.citationBadge)||h&&(l.matches("cite,"+e.sourceSite)||l.matches("a[href]")&&l.querySelector("h3"))))return"";let w=d(l,u);if(w)return w;let g=[];for(let C of l.childNodes)C.nodeType===Node.TEXT_NODE?g.push(C.textContent??""):C.nodeType===Node.ELEMENT_NODE&&g.push(r(C,u,h));return n(g.join(" "))};return Array.from(document.querySelectorAll(e.item)).flatMap((l,u)=>{let h=n(l.getAttribute(e.itemDataQ)||l.getAttribute(e.itemDataInitQ)||l.querySelector(e.itemQuestionEl)?.innerText||l.querySelector(e.itemQuestionEl)?.textContent);if(!h||t&&h!==n(t))return[];let w=l.classList.contains(e.expandedClass)||l.querySelector(e.clickTarget)?.getAttribute("aria-expanded")==="true",g=l.querySelector(e.answerContainer),C=g?.querySelector(e.aiAnswerBody)||(g?.matches(e.aiAnswerBody)?g:null)||g?.querySelector(e.answerBody)||(g?.matches(e.answerBody)?g:null),y=C||g,m=r(y,y,!C),O=/^(?:an error has occurred(?:[.!…]\s*)?(?:please try again later[.!…]?)?|loading|please wait|try again|something went wrong)[.!…\s]*$/i.test(m),F=[...Array.from((y||l).querySelectorAll("a[href]")),...Array.from(g?.querySelectorAll("a[href]")||[]),...Array.from(l.querySelectorAll(e.aiCitation+","+e.aiSourceCard))],B=!O&&(w&&m.length>=10||m.length>30&&F.some(P=>/^https?:\/\//i.test(P.href))),I=y?.matches(e.aiAnswerBody)&&y.closest(".hICk5e[data-collapsed]")?y:null,K=I&&Array.from(I.querySelectorAll('[hidden], [aria-hidden="true"], [style]')).some(P=>{if(!s(P)||!n(P.textContent))return!1;let G=P.closest('button, [role="button"]');if(G&&!U(G,I)||P.closest('[data-artifact-type="map"], .AQisZb, '+e.aiSourceCard+","+e.sourceCard+","+e.citationBadge))return!1;let v=P.closest("[data-xpm-copy-root][data-xpm-math-type]");return d(v,I)&&(P.closest("svg")?.parentElement===v||P.closest("math")?.parentElement?.parentElement===v)?!1:!c(P,I)||s(P,!0)}),_=I&&!K?I:null,b=Array.from(g?.querySelectorAll(e.answerControl)||[]),k=B?b.flatMap((P,G)=>{if(!i(P,_))return[];for(let v=P;v&&v!==g;v=v.parentElement)if(s(v)||o(v))return[];return[G]}):[],A=new Map;if(B)for(let P of F){if(!/^https?:\/\//i.test(P.href)||P.closest('[data-artifact-type="map"]'))continue;let G=P.closest(e.sourceCard),v=G?n(G.querySelector(e.sourceDescription)?.textContent):"",R=(G?n(G.querySelector(e.sourceCardTitle)?.textContent):"")||a(P.getAttribute("aria-label"))||n(P.querySelector("h3")?.textContent)||n(P.textContent),f=A.get(P.href);A.set(P.href,{title:G&&R?R:f?.title||R,rawHref:P.href,...v||f?.description?{description:v||f?.description}:{}})}let T=[...A.values()],M=B&&n(l.querySelector(e.sourceTitle)?.textContent)||void 0,q=B&&n(l.querySelector(e.sourceSite)?.textContent)||void 0;return M||=T.find(P=>P.title.length>2)?.title||T[0]?.title||void 0,[{googleLinkId:l.getAttribute("data-lk")||l.querySelector("[data-lk]")?.getAttribute("data-lk")||null,googleEvidenceId:l.getAttribute("data-ved")||l.querySelector("[data-ved]")?.getAttribute("data-ved")||null,question:h,answer:B?m:void 0,sourceTitle:M,sourceSite:q,sources:T,...k.length||B&&K||l.getAttribute("data-mcp-answer-expansion")==="pending"?{answerExpansionIncomplete:!0}:{},itemIndex:u,expanded:w,answerControls:k,...k.some(P=>b[P]?.getAttribute("data-mcp-answer-expansion")==="pending")?{answerControlPending:!0}:{}}]})}async function za(e,t,n,a){let i=Math.min(n.deadlineMs??1/0,Date.now()+1e4),s=()=>Math.max(0,i-Date.now()),o=n.dispatchClick??(u=>u()),d=async()=>(await e.evaluate(a,{selectors:n.selectors,onlyQuestion:t}))[0],S=await d(),U=async(u,h)=>n.signal?.aborted||s()<=0?!1:e.evaluate(({selectors:w,question:g,operation:C,controlIndex:y})=>{let m=K=>(K??"").replace(/\u00a0/g," ").replace(/\s+/g," ").trim(),O=Array.from(document.querySelectorAll(w.item)).find(K=>m(K.getAttribute(w.itemDataQ)||K.getAttribute(w.itemDataInitQ)||K.querySelector(w.itemQuestionEl)?.textContent)===m(g));if(!O)return!1;if(C==="clear")return O.removeAttribute("data-mcp-answer-expansion"),!0;let F=Array.from(O.querySelector(w.answerContainer)?.querySelectorAll(w.answerControl)||[]),B=F.filter(K=>K.getAttribute("data-mcp-answer-expansion")==="pending");if(C==="confirmed")return B.length>1?!1:(B[0]?.setAttribute("data-mcp-answer-expansion","confirmed"),!0);let I=y===void 0?void 0:F[y];return!I||B.length||I.matches(":disabled")||I.closest('[aria-disabled="true"]')?!1:(I.setAttribute("data-mcp-answer-expansion","pending"),I.setAttribute("data-mcp-answer-expansion-for",encodeURIComponent(g)),O.setAttribute("data-mcp-answer-expansion","pending"),!0)},{selectors:n.selectors,question:t,operation:u,controlIndex:h}).catch(()=>!1);async function c(u,h){let w=Date.now()+u.budgetMs,g,C=null,y=u.beforeAnswer;for(;Date.now()<w;){if(await new Promise(m=>window.setTimeout(m,Math.min(150,w-Date.now()))),g=h({selectors:u.selectors,onlyQuestion:u.onlyQuestion})[0],!g)return{acknowledged:!1,clearMarker:!1};if(g.answer!==y&&(y=g.answer,C=Date.now()),!g.answerControls.length&&g.answer){C??=Date.now();let m=g.answer!==u.beforeAnswer?300:1e3;if(Date.now()-C>=m)return{state:g,acknowledged:!0,clearMarker:!0}}else if(g.answerControls.length&&(g.answer!==u.beforeAnswer||!g.answerControlPending)&&(C??=Date.now(),Date.now()-C>=300))return{state:g,acknowledged:!0,clearMarker:!1}}return{state:g,acknowledged:!1,clearMarker:!1}}let r=new Function("input",`return (${c.toString()})(input, (${a.toString()}));`),l=async u=>{if(n.signal?.aborted||s()<=0)return!1;let h,w=new Promise(g=>{h=()=>g(void 0),n.signal?.addEventListener("abort",h,{once:!0})});try{let g=e.evaluate(r,{selectors:n.selectors,onlyQuestion:t,beforeAnswer:u,budgetMs:Math.min(2500,s())}),C=await Promise.race([g,w]);return!C||n.signal?.aborted||s()<=0?!1:(S=C.state,C.acknowledged&&(C.clearMarker?await U("clear"):!0))}finally{h&&n.signal?.removeEventListener("abort",h)}};if(S?.answerExpansionIncomplete&&!S.answerControls.length){await l(S.answer);return}for(let u=0;S?.answerControls.length&&u<8;u+=1){if(n.signal?.aborted||s()<=0)return;let h=S.answer,w=!1;try{if(S=await d(),!S?.answerControls.length)return;h=S.answer;let C=e.locator(n.selectors.item).nth(S.itemIndex);if(!S.expanded){if(n.allowOuterReopen===!1||(await o(async()=>{n.signal?.aborted||s()<=0||await C.locator(n.selectors.clickTarget).first().click({force:!0,noWaitAfter:!0,timeout:Math.min(1200,s())})}),s()<=0||n.signal?.aborted)||(await e.waitForTimeout(Math.min(250,s())),S=await d(),!S?.answerControls.length))return;h=S.answer}if(n.signal?.aborted||s()<=0)return;let y=S;await o(async()=>{if(n.signal?.aborted||s()<=0)return;let m=await U("pending",y.answerControls[0]);w=!0,m&&!n.signal?.aborted&&s()>0&&await e.locator(`[data-mcp-answer-expansion="pending"][data-mcp-answer-expansion-for="${encodeURIComponent(t)}"]`).first().click({force:!0,noWaitAfter:!0,timeout:Math.min(1200,s())}).catch(()=>{})})}catch{}if(!w||n.signal?.aborted||s()<=0||!await l(h)||!S?.answerControls.length||!await U("confirmed"))return}}async function ro(e){let t=e??{aio:{root:"[data-lhcontainer][data-streaming-container][eid]",legacyRoot:'[data-hveid="CBMQAA"]',wrapper:".Fgyi2e",controller:'[jscontroller="AkrxPe"]',contentSubtree:'[data-subtree="mfc"]',heading:".Fzsovc.cwYVJe.RJPOee",header:".heWuVc",showMoreButton:'[aria-label="Show more AI Overview"]',sourcesPanel:".OZ9ddf.WAUd4",disclaimer:".DuQANe.MSJHRb"},aim:{root:'[data-hveid="CAUQAA"]',wrapper:".Fgyi2e"},expandWaitMs:1500},n=window.google?.sn??"unknown",a=n==="aim"?"aim":n==="web"?"web":"unknown";function i(b){return b?(b.innerText??b.textContent??"").trim():""}function s(b){if(!b)return!1;let k=b.replace(/\s+/g," ").trim();return k.length>=16&&k.split(" ").filter(Boolean).length>=2}function o(b){let k=b.querySelector(t.aio.heading);if(i(k)==="AI Overview")return!0;let A=b.querySelector(t.aio.header);return!!i(A).split(/\n|\s{2,}/).some(T=>T.trim()==="AI Overview")}function d(){let k=Array.from(document.querySelectorAll(t.aio.root)).find(o);if(k)return k;if(t.aio.legacyRoot){let T=document.querySelector(t.aio.legacyRoot);if(T&&o(T))return T}let A=document.querySelectorAll(`${t.aio.heading}, h1, h2, h3, [role="heading"]`);for(let T of A){if(i(T)!=="AI Overview")continue;let M=T.parentElement;for(let q=0;q<8&&M;q++){if(M.matches(t.aio.root)||M.querySelector(t.aio.controller)||M.querySelector(t.aio.contentSubtree))return M;M=M.parentElement}return T.parentElement}return null}function S(b){if(!b)return null;let k=b.cloneNode(!0);k.querySelectorAll(["script","style","noscript","img","picture","video",t.aio.header,t.aio.showMoreButton,t.aio.sourcesPanel,t.aio.disclaimer,'[data-subtree="dfa"]',"[data-src-id]",'[role="dialog"]',".HWMcu",".bTFeG",".CyMdWb",".MFrAxb",".F0OfWd.hfWAgb",".x2qcTc.fZavHb",".SvjEff",".sR2MY",".lKuDef",".GSPQcc","a[href]","button",'[role="button"]'].join(",")).forEach(G=>G.remove());let A=document.createElement("div");A.style.position="fixed",A.style.left="-10000px",A.style.top="0",A.style.width=`${Math.max(320,Math.round(b.getBoundingClientRect?.().width||960))}px`,A.style.opacity="0",A.style.pointerEvents="none",A.append(k),document.body.append(A);let T=k.innerText||k.textContent||"";A.remove();let M=T.replace(/\r/g,"").replace(/[ \t]+\n/g,`
21777
21777
  `).replace(/\n[ \t]+/g,`
21778
21778
  `).replace(/\n{3,}/g,`
21779
21779
 
@@ -21782,14 +21782,14 @@ Zwolle,Louisiana,United States`,ms={ad:"Andorra",ae:"United Arab Emirates",af:"A
21782
21782
  `).replace(/\n{3,}/g,`
21783
21783
 
21784
21784
  `).trim();return!P||/not available|try again|can't generate/i.test(P)?null:P}function U(b){if(!b||b.startsWith("javascript:"))return null;try{let k=new URL(b,window.location.href);return!["http:","https:"].includes(k.protocol)||k.username||k.password?null:{href:k.href,rawHref:k.href}}catch{return null}}function c(b){if(!b)return[];let k=new Set,A=[];for(let T of Array.from(b.querySelectorAll("a[href]"))){let M=U(T.getAttribute("href")??"");if(!M||k.has(M.rawHref))continue;k.add(M.rawHref);let q="";try{q=new URL(M.href).hostname.replace(/^www\./,"")}catch{}A.push({text:i(T)||q||M.href,href:M.href,rawHref:M.rawHref})}return A}async function r(b){let k=b.querySelector(t.aio.showMoreButton);if(!k||k.getAttribute("aria-expanded")!=="false")return!1;k.click();let A=t.expandWaitMs??1500;return A>0&&await new Promise(T=>setTimeout(T,A)),!0}let l=d(),u=null,h=[],w=!1,g=!1,C=[];if(l){w=await r(l);let b=l.querySelector(t.aio.controller),k=l.querySelector(t.aio.contentSubtree),A=l.querySelector(t.aio.showMoreButton);g=b?.getAttribute("data-trnct")==="false"||A?.getAttribute("aria-expanded")==="true"||!A,u=S(k??b??l),C=(u??"").split(`
21785
- `).map(T=>T.trim()).filter(T=>/^\d+\.\s+.+/.test(T)),h=c(l)}let y=document.querySelector(t.aim.root),m=a==="aim"&&!!y,O=y?.closest(t.aim.wrapper)??y,F=m?S(O):null,B=m&&s(F),I=B?F:null,K=B?c(O):[],D=!!l&&s(u);return{surface:a,aiOverview:{detected:D,text:D?u:null,citations:D?h:[],expanded:D?w:!1,fullyExpanded:D?g:!1,sections:D?C:[]},aiMode:{detected:B&&I!==null,text:I,citations:K}}}var So=require("crypto"),Uo=8e3,co=3e3,uo=1e4,Vl=8;function Gt(e){return/(^|\.)google\.(?:com|[a-z]{2,3}(?:\.[a-z]{2})?)$/i.test(e)}function cn(e){if(!e||e.length>Uo)return null;try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"||t.username||t.password?null:t}catch{return null}}function Kl(e,t){if(!e||e.length>Uo||/^javascript:/i.test(e))return null;try{let n=new URL(e,t);return cn(n.href)}catch{return null}}function Un(e){let t=cn(e);return!t||t.protocol!=="https:"||!Gt(t.hostname)||t.pathname!=="/goto"?null:t.searchParams.get("url")?t:null}function $a(e){if(e.linkType!=="google_goto_redirect"||e.resolutionStatus!=="resolved"||!Un(e.rawUrl)||!e.resolvedUrl)return!1;let t=cn(e.resolvedUrl);return!!(t&&!Gt(t.hostname)&&t.href===e.resolvedUrl&&e.url===t.href)}function Se(e){let t=e.normalize("NFKC").toLocaleLowerCase("en-US").replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return`paa_${(0,So.createHash)("sha256").update(t).digest("hex").slice(0,16)}`}function Ue(e,t){let n=Kl(e,t);if(!n)return null;let a=n.href;if(!Gt(n.hostname))return{url:a,rawUrl:a,resolvedUrl:a,linkType:"plain",resolutionStatus:"not_needed"};if(n.pathname==="/url"){let i=cn(n.searchParams.get("q")??n.searchParams.get("url")??"");return!i||Gt(i.hostname)?null:{url:i.href,rawUrl:a,resolvedUrl:i.href,linkType:"google_url_redirect",resolutionStatus:"resolved"}}return n.pathname==="/goto"&&n.searchParams.get("url")?{url:a,rawUrl:a,resolvedUrl:null,linkType:"google_goto_redirect",resolutionStatus:"unresolved"}:null}function ja(e){return Un(e)?.searchParams.get("url")??null}function ho(e,t){try{let n=new URL(e),a=cn(new URL(t,n).href);return!a||Gt(a.hostname)?null:(!a.hash&&n.hash&&(a.hash=n.hash),a.href)}catch{return null}}async function go(e,t={}){let n=[...new Set([...e].flatMap(r=>Un(r)?[r]:[]))],a=new Map(n.map(r=>[r,{rawUrl:r,resolvedUrl:null,resolutionStatus:"unresolved"}])),i=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):null,s=t.fetchImpl??i;if(n.length===0||!s)return{resolutions:[...a.values()],nonGoogleRequestsObserved:0};let o=Math.max(1,t.timeoutMs??co),d=Date.now()+Math.max(1,t.totalBudgetMs??uo),S=Math.max(1,Math.min(16,Math.floor(t.concurrency??Vl))),U=0,c=async()=>{for(;U<n.length;){let r=n[U++],l=Un(r),u=l?.searchParams.get("url");if(!l||!u){a.set(r,{rawUrl:r,resolvedUrl:null,resolutionStatus:"rejected"});continue}l.hash="";let h=l.href;for(let w=0;w<2;w++){let g=d-Date.now();if(g<=0)return;let C=new AbortController,y=setTimeout(()=>C.abort(),Math.min(o,g)),m;try{m=await s(h,{method:"GET",redirect:"manual",headers:{accept:"*/*","user-agent":"Mozilla/5.0"},signal:C.signal})}catch{break}finally{clearTimeout(y)}if(m.status<300||m.status>=400)break;let O=m.headers.get("location");if(!O)break;let F=ho(r,O);if(F){a.set(r,{rawUrl:r,resolvedUrl:F,resolutionStatus:"resolved"});break}let B;try{B=new URL(O,h)}catch{a.set(r,{rawUrl:r,resolvedUrl:null,resolutionStatus:"rejected"});break}if(!Gt(B.hostname)||ja(B.href)!==u){a.set(r,{rawUrl:r,resolvedUrl:null,resolutionStatus:"rejected"});break}h=B.href}}};return await Promise.all(Array.from({length:Math.min(S,n.length)},()=>c())),{resolutions:[...a.values()],nonGoogleRequestsObserved:0}}function lo(e,t){try{return new URL(e.resolvedUrl??e.url).hostname.replace(/^www\./,"")}catch{return t}}async function wo(e,t={}){let n=[],a=r=>{for(let l of r)n.push(l),a(l.children??[])};a(e.tree??[]);let i=[...e.flat.flatMap(r=>r.sources??[]),...n.flatMap(r=>r.sources),...e.organicResults??[],...(e.aiOverview?.citations??[]).map(({text:r,href:l,...u})=>({...u,url:l})),...(e.aiMode?.citations??[]).map(({text:r,href:l,...u})=>({...u,url:l}))],s=new Map(i.filter(r=>!!r?.rawUrl).map(r=>[r.rawUrl,r])),o=[...s.values()].filter(r=>r.linkType==="google_goto_redirect"&&r.resolutionStatus!=="resolved").map(r=>r.rawUrl);if(o.length>0){let r=await go(o,t);for(let l of r.resolutions){let u=s.get(l.rawUrl);u&&s.set(l.rawUrl,l.resolutionStatus==="resolved"&&l.resolvedUrl?{...u,url:l.resolvedUrl,resolvedUrl:l.resolvedUrl,resolutionStatus:"resolved"}:{...u,resolutionStatus:l.resolutionStatus})}}let d=r=>({...r,...s.get(r.rawUrl)??r}),S=r=>r.map(l=>{let u=d(l);return{...u,site:lo(u,l.site)}});for(let r of e.flat){r.sources=S(r.sources??[]);let l=r.sources[0];r.source_title=l?.title??r.source_title,r.source_site=l?.site??r.source_site,r.source_cite=l?.url??r.source_cite}for(let r of n){r.sources=S(r.sources??[]);let l=r.sources[0];r.sourceTitle=l?.title??r.sourceTitle,r.sourceSite=l?.site??r.sourceSite,r.sourceCite=l?.url??r.sourceCite}for(let r=0;r<(e.organicResults?.length??0);r++){let l=d(e.organicResults[r]);e.organicResults[r]={...l,domain:lo(l,e.organicResults[r].domain)??""}}let U=r=>{let l=d({url:r.href,rawUrl:r.rawUrl,resolvedUrl:r.resolvedUrl,linkType:r.linkType,resolutionStatus:r.resolutionStatus}),{url:u,...h}=l;return{...r,...h,href:u}};e.aiOverview&&(e.aiOverview.citations=(e.aiOverview.citations??[]).map(U)),e.aiMode&&(e.aiMode.citations=(e.aiMode.citations??[]).map(U));let c=[...s.values()];return e.diagnostics.links={linkCandidatesObserved:s.size,plainLinksObserved:c.filter(r=>r.linkType==="plain").length,googleUrlRedirectsObserved:c.filter(r=>r.linkType==="google_url_redirect").length,googleGotoRedirectsObserved:c.filter(r=>r.linkType==="google_goto_redirect").length,redirectsResolved:c.filter(r=>r.linkType!=="plain"&&r.resolutionStatus==="resolved").length,redirectsUnresolved:c.filter(r=>r.resolutionStatus==="unresolved").length,redirectsRejected:c.filter(r=>r.resolutionStatus==="rejected").length,resolverNonGoogleRequestsObserved:0,paaSourcesPreserved:e.flat.reduce((r,l)=>r+l.sources.length,0),aiOverviewLabelValidated:e.aiOverview?.detected??!1},e}async function po(e,t,n={}){let a=new Map;for(let l of t){let u=a.get(l.rawUrl);u&&$a(u)||a.set(l.rawUrl,l.linkType==="google_goto_redirect"&&!$a(l)?{...l,url:l.rawUrl,resolvedUrl:null,resolutionStatus:"unresolved"}:l)}let i=[...a.values()].filter(l=>l.linkType==="google_goto_redirect"&&!$a(l));if(i.length===0)return a;let s=Date.now()+(n.totalBudgetMs??uo),o=await go(i.map(l=>l.rawUrl),n);for(let l of o.resolutions){let u=a.get(l.rawUrl);u&&a.set(l.rawUrl,l.resolutionStatus==="resolved"&&l.resolvedUrl?{...u,url:l.resolvedUrl,resolvedUrl:l.resolvedUrl,resolutionStatus:"resolved"}:{...u,resolutionStatus:l.resolutionStatus})}let d=i.filter(l=>a.get(l.rawUrl)?.resolutionStatus==="unresolved");if(d.length===0||n.browserFallback===!1||Date.now()>=s)return n.onNetworkAudit?.({nonGoogleRequestsObserved:0}),a;let S=n.timeoutMs??co,U=await e.context().newPage().catch(()=>null);if(!U)return n.onNetworkAudit?.({nonGoogleRequestsObserved:0}),a;let c=null,r=0;try{await U.route("**/*",async l=>{let u=l.request().url();try{Gt(new URL(u).hostname)||(r+=1)}catch{}let h=ja(u);if(!c||h!==c.token){await l.abort("blockedbyclient").catch(()=>{});return}let w=c;try{let g=await l.fetch({maxRedirects:0,timeout:w.timeoutMs});w.location=g.headers().location??null}finally{await l.abort("blockedbyclient").catch(()=>{}),w.finish()}});for(let l of d){let u=s-Date.now();if(u<=0)break;let h=Un(l.rawUrl),w=h?.searchParams.get("url");if(!h||!w){a.set(l.rawUrl,{...l,resolutionStatus:"rejected"});continue}let g=Math.min(S,u);h.hash="";let C=h.href,y=!1;for(let m=0;m<2;m++){let O,F=new Promise(b=>{O=b}),B=`mcp-goto-${Math.random().toString(36).slice(2)}`;c={token:w,timeoutMs:g,location:null,finish:O},await U.evaluate(({url:b,id:k})=>{let A=document.createElement("iframe");A.id=k,A.hidden=!0,A.src=b,document.body.append(A)},{url:C,id:B}).catch(()=>null),await Promise.race([F,new Promise(b=>setTimeout(b,g))]);let I=c.location;if(c=null,await U.evaluate(b=>document.getElementById(b)?.remove(),B).catch(()=>null),!I)break;let K=ho(l.rawUrl,I);if(K){a.set(l.rawUrl,{...l,url:K,resolvedUrl:K,resolutionStatus:"resolved"});break}let D;try{D=new URL(I,C)}catch{y=!0;break}if(!Gt(D.hostname)||ja(D.href)!==w){y=!0;break}C=D.href}y&&a.get(l.rawUrl)?.resolutionStatus!=="resolved"&&a.set(l.rawUrl,{...l,resolutionStatus:"rejected"})}}finally{c=null,await U.close().catch(()=>{}),n.onNetworkAudit?.({nonGoogleRequestsObserved:r})}return a}async function yo(e){let t=on;return e.evaluate(n=>{let a=[],i=Array.from(document.querySelectorAll(n.container));for(let s of i){let S=(s.querySelector(n.sectionHeading)?.textContent?.trim()??"").toLowerCase().includes("short")?"short_video":"video",U=Array.from(s.querySelectorAll(n.item));for(let c of U){let r=c.href;if(!r||!r.includes("youtube")&&!r.includes("youtu.be"))continue;let l=c.textContent?.trim()??"",u=l.indexOf("YouTube");if(u===-1)continue;let h=l.slice(0,u).trim(),g=l.slice(u+7).replace(/^[·\s·]+/,"").match(/^([^·\n]+)/),C=g?g[1].trim():"";h&&a.push({type:S,title:h,channel:C,platform:"YouTube",duration:"",url:r})}}return a},t)}async function mo(e){let t=Bs;return e.evaluate(n=>{let a=[],s=Array.from(document.querySelectorAll(n.section)).find(d=>d.textContent?.includes("Discussions"));if(!s)return a;let o=Array.from(s.querySelectorAll(n.item));for(let d of o){let S=d.href;if(!S)continue;let U=d.querySelector(n.title),c=d.querySelector(n.source),r=U?.textContent?.trim()??"",l=c?.textContent?.trim()??"";r&&a.push({title:r,source:l,url:S})}return a},t)}async function Co(e,t,n){try{await e.goto(t,{waitUntil:"domcontentloaded"}),await e.waitForTimeout(1500)}catch{return[]}await n(e,"Google short video search");let a={item:rn.item,platforms:[...rn.platforms]};return(await e.evaluate(s=>{let o=new Set,d=[],S=Array.from(document.querySelectorAll(s.item)),U=["youtube.com","youtu.be","tiktok.com","instagram.com","facebook.com","fb.watch"],c=new Map;for(let r of S){let l=r.href;if(!l||!U.some(h=>l.includes(h)))continue;let u=r.textContent?.trim()??"";c.has(l)||c.set(l,[]),c.get(l).push(u)}for(let[r,l]of c.entries()){if(o.has(r))continue;o.add(r);let u=l.find(y=>/^\d+:\d+$/.test(y))??"",h=l.find(y=>!/^\d+:\d+$/.test(y)&&y.length>5)??"";if(!h)continue;let w=h,g="",C="";for(let y of s.platforms){let m=-1,O=0;for(;;){let D=h.indexOf(y,O);if(D===-1)break;m=D,O=D+1}if(m===-1)continue;let F=h.slice(m+y.length);if(!(/^[\s·]/.test(F)||F.trim()===""))continue;w=h.slice(0,m).trim(),g=y;let I=F.replace(/^[\s·]+/,""),K=I.indexOf("\xB7");C=(K===-1?I:I.slice(0,K)).trim();break}w&&d.push({title:w,channel:C,platform:g,duration:u,url:r})}return d},a)).map(s=>({type:"short_video",...s}))}async function fo(e){let t=Rs;return e.evaluate(n=>{let a=Array.from(document.querySelectorAll(n.sectionTag)).find(i=>i.textContent?.includes(n.sectionHeadingText))??document.querySelector(".yG4QQe.TBC9ub.NbhJ1c");return a?Array.from(a.querySelectorAll(n.card)).map(i=>{let o=i.querySelector(n.cardLink)?.href??"",d=i.querySelector(n.titleH1)?.textContent?.trim(),S=i.querySelector(n.titleDiv)?.textContent?.trim(),U=d??S??"",c=i.querySelector(n.source)?.textContent?.trim()??"",l=i.querySelector(n.platformBadge)?.textContent?.trim()??"",u=i.querySelector(n.ytChannel)?.textContent?.trim()??"",h=i.querySelector(n.ytDate)?.textContent?.trim()??"",w=i.querySelector(n.authorNote)?.textContent?.trim()??null,g=i.querySelector(n.popularCommentLabel),C=null;if(g){let M=g.nextSibling;for(;M;){let q=M.textContent?.trim();if(q){C=q;break}M=M.nextSibling}}let y=Array.from(i.querySelectorAll("span")),m=y.find(M=>/^\d+:\d+$/.test(M.textContent?.trim()??""))?.textContent?.trim()??null,F=y.map(M=>M.textContent?.trim()??"").filter(M=>/\d/.test(M)&&(M.includes("comment")||M.includes("reaction")||M.includes("view")||M.includes("like")||M.includes("share")))[0]??"",B=y.map(M=>M.textContent?.trim()??"").filter(M=>/\d+ (day|week|month|year|hour)s? ago|Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec/.test(M)),I=h||(B[0]??""),K=l||(u?"YouTube":""),D=u||c,b="unknown",k=K.toLowerCase(),A=D.toLowerCase(),T=c.toLowerCase();return k.includes("reddit")||A.startsWith("r/")?b="reddit":k.includes("facebook")||T.includes("facebook")?b="facebook":k.includes("instagram")||T.includes("instagram")?b="instagram":k.includes("tiktok")||T.includes("tiktok")?b="tiktok":k.includes("youtube")||u?b="youtube":b="news",{type:b,title:U,url:o,source:D,platform:K,popularComment:C,engagement:F,date:I,duration:m,authorNote:w}}):[]},t)}async function ko(e){let t=Fs,n=await e.evaluate(i=>{let s=[],o=0;return document.querySelectorAll(i.result).forEach(d=>{let S=d.querySelector(i.title);if(!S)return;let U=S.textContent?.trim()??"",r=S.closest("a")?.href??"";if(!U||!r)return;o++;let l=d.querySelector(i.cite)?.textContent?.trim()??null,u=d.querySelector(i.snippet)?.textContent?.trim()??null,h=!!d.querySelector(i.redditCite),w=d.querySelector(i.ratingWrap),g=w?{value:w.querySelector(i.ratingValue)?.textContent?.trim()??"",count:w.querySelector(i.reviewCount)?.textContent?.trim()??""}:null,C="";try{C=new URL(r).hostname.replace(/^www\./,"")}catch{C=d.querySelector(i.siteName)?.textContent?.trim()??""}s.push({position:o,title:U,url:r,domain:C,cite:l,snippet:u,isRedditStyle:h,inlineRating:g})}),s},t),a=typeof e.url=="function"?e.url():"https://www.google.com/";return n.flatMap(i=>{let s=Ue(i.url,a);if(!s)return[];let o=i.domain;try{o=new URL(s.resolvedUrl??s.rawUrl).hostname.replace(/^www\./,"")}catch{}return[{...i,...s,domain:o}]})}async function Mo(e){let t=_s;return e.evaluate(n=>{let a=[],i=null;return document.querySelectorAll('[role="heading"]').forEach(s=>{!i&&s.textContent?.includes(n.headingText)&&(i=s.closest("[data-hveid]"))}),i&&i.querySelectorAll(n.card).forEach((s,o)=>{let d=s.querySelector(n.name)?.textContent?.trim()??"";if(!d)return;let S=s.querySelector(n.ratingValue)?.textContent?.trim()??null,U=s.querySelector(n.reviewCount)?.textContent?.trim()??null,c=U?U.replace(/[()]/g,"").trim():null,r=s.querySelector("a[data-cid]")?.getAttribute("data-cid")??null;if(!r)for(let g of Array.from(s.querySelectorAll("a[href]"))){let C=g.href.match(/[?&]cid=(\d+)/);if(C){r=C[1];break}let y=g.href.match(/!1s0x[0-9a-f]+:0x([0-9a-f]+)/i);if(y){try{r=BigInt("0x"+y[1]).toString()}catch{}if(r)break}}let l=[];s.querySelectorAll("div, span").forEach(g=>{let C=Array.from(g.childNodes).filter(y=>y.nodeType===3).map(y=>y.textContent?.trim()??"").filter(y=>y.length>1&&y.length<120).join(" ");C&&!l.includes(C)&&l.push(C)});let u=Array.from(s.querySelectorAll("a[href]")),h=u.find(g=>g.href.includes("google.com/maps"))?.href??null,w=u.find(g=>!g.href.includes("google.com")&&g.href.startsWith("http"))?.href??null;a.push({position:o+1,name:d,cid:r,rating:S,reviewCount:c,metadata:l,websiteUrl:w,directionsUrl:h})}),a},t)}async function vo(e){return e.evaluate(()=>{let t=new Set,n=new Set,a=new Set,i=new Map;function s(d){let S=[".OSrXXb",".dbg0pd",".tzt0oe",'[role="heading"]',"h3"];for(let U of S){let c=d.querySelector(U);if(c?.textContent?.trim())return c.textContent.trim()}return""}document.querySelectorAll('[id^="pv-/g/"]').forEach(d=>{let S=d.getAttribute("id");if(!S)return;let U=S.replace("pv-","");t.add(U);let c=s(d),l=d.querySelector("a[data-cid]")?.getAttribute("data-cid")??null;l&&n.add(l),c&&i.set(U,{name:c,kgId:U,cid:l,gcid:null})}),document.querySelectorAll("[data-mid]").forEach(d=>{let S=d.getAttribute("data-mid");if(S?.startsWith("/g/")&&(t.add(S),!i.has(S))){let U=s(d);U&&i.set(S,{name:U,kgId:S,cid:null,gcid:null})}}),document.querySelectorAll(".w7Dbne").forEach(d=>{let U=d.querySelector("a[data-cid]")?.getAttribute("data-cid")??null;if(!U)return;n.add(U);let c=d.querySelector(".OSrXXb")?.textContent?.trim()??"";if(!c)return;let r=d.querySelector('[id^="pv-/g/"]'),l=r?r.getAttribute("id").replace("pv-",""):null,u=l??`cid:${U}`;if(i.has(u)){let h=i.get(u);h.cid||i.set(u,{...h,cid:U})}else i.set(u,{name:c,kgId:l,cid:U,gcid:null})}),document.querySelectorAll("a[data-cid]").forEach(d=>{let S=d.getAttribute("data-cid");if(!S)return;if(n.add(S),![...i.values()].some(c=>c.cid===S)){let c=d.parentElement,r="";for(let l=0;l<8&&c;l++){let u=c.querySelector('.OSrXXb, .dbg0pd, [role="heading"], h3');if(u?.textContent?.trim()){r=u.textContent.trim();break}c=c.parentElement}r&&i.set(`cid:${S}`,{name:r,kgId:null,cid:S,gcid:null})}});let o=Array.from(document.querySelectorAll("script:not([src])")).map(d=>d.textContent??"").filter(d=>d.length>1e4).join(`
21786
- `);for(let d of o.matchAll(/\/g\/[a-zA-Z0-9_-]{5,20}/g))t.add(d[0]);for(let d of o.matchAll(/gcid:[a-zA-Z0-9_]+/g))a.add(d[0]);for(let d of o.matchAll(/0x[0-9a-f]+:0x([0-9a-f]+)/gi))try{n.add(BigInt("0x"+d[1]).toString())}catch{}return{entities:[...i.values()],kgIds:[...t],cids:[...n],gcids:[...a]}})}function To(e,t){let n=new Set(e.cids),a=e.entities.map(i=>({...i}));for(let i of t){if(!i.cid)continue;n.add(i.cid);let s=i.name.toLowerCase().trim(),o=a.find(d=>d.name.toLowerCase().trim()===s);o?o.cid||(o.cid=i.cid):a.find(d=>d.cid===i.cid)||a.push({name:i.name,kgId:null,cid:i.cid,gcid:null})}return{...e,entities:a,cids:[...n]}}var bo=String.raw`^(?:an error has occurred(?:[.!…]\s*)?(?:please try again later[.!…]?)?|loading|please wait|try again|something went wrong)[.!…\s]*$`,Jl=700,ql=1e3,No=1400,Po=2e3,zl=4,Io=250,Gn=class{constructor(t,n,a,i){this.driver=t;this.reporter=n;this.onPaaProgress=a;this.onProviderSession=i}driver;reporter;onPaaProgress;onProviderSession;completeness={paaWithoutAnswer:0,paaWithoutSource:0,paaAnswersRecovered:0,aioShareCaptured:null};aioShareUrlEarly=null;linkDiagnostics=this.emptyLinkDiagnostics();collectedRows=[];partialContext=null;progressSequence=0;clickedQuestions=new Set;paaLifecycle=this.emptyPaaLifecycle(0);checkpointMaterial=null;interactionObservations=[];phaseTimings={};currentPhaseTimings(t){return{...this.phaseTimings,totalServerMs:Math.max(0,Date.now()-t)}}emptyPaaLifecycle(t){return{requestedQuestions:t,questionsFound:0,targetStatus:"not_met",discoveryStatus:"in_progress",materialStatus:"partial",completionReason:"PAA expansion is still running.",automaticRetries:0,retryBreakdown:{controlRetries:0,browserRetries:0,providerFallbacks:0,runtimeRecoveries:0,idempotentReplays:0},knownQuestions:0,processedQuestions:0,failedInteractions:0,noGrowthConfirmations:0,visibleControls:0,eligibleControls:0,dispatchedInteractions:0,confirmedInteractions:0,unconfirmedInteractions:0}}emptyLinkDiagnostics(){return{linkCandidatesObserved:0,plainLinksObserved:0,googleUrlRedirectsObserved:0,googleGotoRedirectsObserved:0,redirectsResolved:0,redirectsUnresolved:0,redirectsRejected:0,resolverNonGoogleRequestsObserved:0,paaSourcesPreserved:0,aiOverviewLabelValidated:!1}}mergePaaSources(t=[],n=[]){let a=new Map;for(let i of[...t,...n]){let s=a.get(i.rawUrl);if(!s){a.set(i.rawUrl,i);continue}let o=i.resolutionStatus==="resolved"&&s.resolutionStatus!=="resolved"?i:s,d=i.description?.trim()&&!s.description?.trim()?i:s.description?.trim()?s:o;a.set(i.rawUrl,{...o,title:d.title??o.title??s.title??i.title,site:o.site??s.site??i.site,...(d.description??s.description??i.description)!==void 0?{description:d.description??s.description??i.description}:{}})}return[...a.values()]}normalizeAICitations(t,n){let a=new Set;return n.flatMap(i=>{let s=Ue(i.rawHref??i.href,t);if(!s||a.has(s.rawUrl))return[];a.add(s.rawUrl);let{url:o,...d}=s;return[{...d,text:i.text,href:o}]})}async resolveMaterialLinks(t,n,a,i,s){let o=Date.now(),d=[...n.flatMap(h=>h.sources??[]),...a,...i.citations.map(({text:h,href:w,...g})=>({...g,url:w})),...s.citations.map(({text:h,href:w,...g})=>({...g,url:w}))],S=new Map(d.map(h=>[h.rawUrl,h])),U=0,c=await po(t,d,{onNetworkAudit:h=>{U=h.nonGoogleRequestsObserved}}),r=h=>({...h,...c.get(h.rawUrl)??h});for(let h of n){h.sources=(h.sources??[]).map(r);let w=h.sources[0];h.source_title=w?.title??h.source_title,h.source_site=w?.site??h.source_site,h.source_cite=w?.url??h.source_cite}for(let h=0;h<a.length;h++){let w=r(a[h]);if(w.resolvedUrl)try{w.domain=new URL(w.resolvedUrl).hostname.replace(/^www\./,"")}catch{}a[h]=w}let l=h=>{let w=r({url:h.href,rawUrl:h.rawUrl,resolvedUrl:h.resolvedUrl,linkType:h.linkType,resolutionStatus:h.resolutionStatus}),{url:g,...C}=w;return{...C,text:h.text,href:g}};i.citations=i.citations.map(l),s.citations=s.citations.map(l);let u=[...c.values()];this.linkDiagnostics={linkCandidatesObserved:S.size,plainLinksObserved:u.filter(h=>h.linkType==="plain").length,googleUrlRedirectsObserved:u.filter(h=>h.linkType==="google_url_redirect").length,googleGotoRedirectsObserved:u.filter(h=>h.linkType==="google_goto_redirect").length,redirectsResolved:u.filter(h=>h.linkType!=="plain"&&h.resolutionStatus==="resolved").length,redirectsUnresolved:u.filter(h=>h.resolutionStatus==="unresolved").length,redirectsRejected:u.filter(h=>h.resolutionStatus==="rejected").length,resolverNonGoogleRequestsObserved:U,paaSourcesPreserved:n.reduce((h,w)=>h+(w.sources??[]).length,0),aiOverviewLabelValidated:i.detected},this.phaseTimings.linkResolutionMs=(this.phaseTimings.linkResolutionMs??0)+(Date.now()-o)}normalizeQuestion(t){return t.toLowerCase().replace(/[^\w\s]/g,"").replace(/\s+/g," ").trim()}throwIfAborted(t){if(t?.aborted)throw t.reason instanceof DOMException&&t.reason.name==="TimeoutError"?t.reason:new ut}async throwIfCaptcha(t,n){if(await t.locator(Z.captchaMarker).count().catch(()=>0)>0)throw new et(`${n} returned a CAPTCHA \u2014 retrying with a fresh session.`)}async extractVisibleItems(t,n){let a=await t.evaluate(le,{selectors:Z,onlyQuestion:n}),i=typeof t.url=="function"?t.url():"https://www.google.com/";return this.mapPaaDomRecords(a,i)}mapPaaDomRecords(t,n){return t.flatMap(a=>{let i=[],s=new Set;for(let U of a.sources){let c=Ue(U.rawHref,n);if(!c||s.has(c.rawUrl))continue;s.add(c.rawUrl);let r=a.sourceSite??null;try{r||=new URL(c.resolvedUrl??c.rawUrl).hostname.replace(/^www\./,"")}catch{}i.push({...c,title:U.title||a.sourceTitle||null,site:r,...U.description?{description:U.description}:{}})}let o=i[0],d={questionId:Se(a.question),googleLinkId:a.googleLinkId,googleEvidenceId:a.googleEvidenceId,question:a.question,answer:Sn(a.answer,a.question),sourceTitle:o?.title??a.sourceTitle,sourceSite:o?.site??a.sourceSite,sourceCite:o?.url,sources:i,...a.answerExpansionIncomplete?{answerExpansionIncomplete:!0}:{}},S=ki.safeParse(d);return S.success?[S.data]:(console.warn("[PAAExtractor] item parse failed:",a.question,S.error.issues[0]?.message),[])})}jitteredDelayMs(t,n){return t+Math.floor(Math.random()*(n-t+1))}async clickItem(t,n){try{await t.locator(`${Z.item}[data-q="${n}"], ${Z.item}[data-initq="${n}"]`).first().click()}catch{}}toFlatRow(t,n,a,i){return{seed_query:i,question_id:t.questionId??Se(t.question),google_link_id:t.googleLinkId??"",google_evidence_id:t.googleEvidenceId??"",question:t.question,answer:t.answer??"",...t.answerExpansionIncomplete?{answerExpansionIncomplete:!0}:{},source_title:t.sourceTitle??"",source_site:t.sourceSite??"",source_cite:t.sourceCite??"",sources:t.sources??[],depth:n,parent_question:a??"",extracted_at:new Date().toISOString()}}upsertCollectedRow(t){let n=this.normalizeQuestion(t.question),a=this.collectedRows.findIndex(d=>this.normalizeQuestion(d.question)===n);if(a<0)return this.collectedRows.push({...t}),!0;let i=this.collectedRows[a],s={...i,...t,answer:t.answer||i.answer,answerExpansionIncomplete:t.answer?t.answerExpansionIncomplete:i.answerExpansionIncomplete,source_title:t.source_title||i.source_title,source_site:t.source_site||i.source_site,source_cite:t.source_cite||i.source_cite,sources:this.mergePaaSources(i.sources,t.sources),extracted_at:t.extracted_at||i.extracted_at},o=s.answerExpansionIncomplete!==i.answerExpansionIncomplete||s.answer!==i.answer||s.source_title!==i.source_title||s.source_site!==i.source_site||s.source_cite!==i.source_cite||JSON.stringify(s.sources)!==JSON.stringify(i.sources);return o&&(this.collectedRows[a]=s),o}async emitProgress(t){if(!this.onPaaProgress||this.collectedRows.length===0&&!this.checkpointMaterial)return;let n={sequence:++this.progressSequence,observedAt:new Date().toISOString(),clickedQuestions:[...this.clickedQuestions],phase:t,records:this.collectedRows.map(a=>({...a})),lifecycle:{...this.paaLifecycle},...this.checkpointMaterial?{material:structuredClone(this.checkpointMaterial)}:{},interactions:this.interactionObservations.map(a=>({...a,confirmationSignals:[...a.confirmationSignals]}))};try{await this.onPaaProgress(n)}catch(a){console.warn(JSON.stringify({event:"paa_progress_sink_failed",sequence:n.sequence,phase:n.phase,message:a instanceof Error?a.message:String(a)}))}}getPartialResult(){let t=this.partialContext;if(!t||this.collectedRows.length===0&&!this.checkpointMaterial)return null;let n=this.collectedRows.map(S=>({...S})),a=this.checkpointMaterial,i=t.questionsOnly?0:n.filter(S=>!S.answer?.trim()).length,s=t.questionsOnly?0:n.filter(S=>(S.sources??[]).length===0).length,o=t.questionsOnly?0:n.filter(S=>S.answerExpansionIncomplete).length,d={seed:t.seed,totalQuestions:n.length,maxDepthReached:n.reduce((S,U)=>Math.max(S,U.depth),0),durationMs:Date.now()-t.startMs,errorCount:0};return{seed:t.seed,location:t.location,extractedAt:new Date().toISOString(),diagnostics:{phaseTimings:this.currentPhaseTimings(t.startMs),completionStatus:"paa_found",problem:null,...a?.pagination?{pagination:{...a.pagination}}:{},resultQuality:"partial",degradedResult:!1,retryRecommended:!0,paaLifecycle:{...this.paaLifecycle,questionsFound:n.length,targetStatus:n.length>=(t.maxQuestions??0)?"met":"not_met",discoveryStatus:"interrupted",materialStatus:i>0||s>0||o>0?"partial":"complete",completionReason:"The browser attempt ended before frontier exhaustion could be proven."},completeness:{...this.completeness,paaWithoutAnswer:i,paaWithoutSource:s,paaIncompleteAnswers:o,paaRequested:t.maxQuestions,paaReturned:n.length,paaUnique:n.length},warnings:[{code:"paa_partial",surface:"paa",message:`Harvest stopped before finishing; returning the ${n.length} question(s) collected up to that point.`,retryable:!0}]},totalQuestions:n.length,surface:a?.surface??"web",aiOverview:a?.aiOverview??{detected:!1,text:null,citations:[]},aiMode:a?.aiMode??{detected:!1,text:null,citations:[]},whatPeopleSaying:a?.whatPeopleSaying??[],tree:this.buildTree(n,t.seed),flat:n,videos:a?.videos??[],forums:a?.forums??[],organicResults:a?.organicResults??[],localPack:a?.localPack??[],entityIds:a?.entityIds??{entities:[],kgIds:[],cids:[],gcids:[]},stats:d}}async runBFS(t,n,a){await t.waitForTimeout(700);let i=new Set,s=new Set,o=[];this.clickedQuestions=new Set,this.interactionObservations=[];let d=new Set,S=new Map,U=new Set,c=new Set,r=new Map,l=new Set,u=2,h=3,w=0,g=Promise.resolve(),C=k=>{let A=g.then(()=>{if(this.throwIfAborted(a),n.softDeadlineMs&&Date.now()>=n.softDeadlineMs)throw new Ot("The execution deadline arrived before the next PAA interaction.");return k()});return g=A.then(()=>{},()=>{}),A},y={sel:Z.item,dataQ:Z.itemDataQ,dataInitQ:Z.itemDataInitQ,questionEl:Z.itemQuestionEl,answerSel:Z.answerContainer,expandedClass:Z.expandedClass,clickTarget:Z.clickTarget,answerPlaceholderPattern:bo,questionsOnly:n.questionsOnly},m=()=>t.evaluate(({sel:k,dataQ:A,dataInitQ:T,questionEl:M,expandedClass:q,clickTarget:P,answerSel:G,answerPlaceholderPattern:v,questionsOnly:R})=>{let f=x=>{if(!x)return"";let _=[];for(let H of x.childNodes){if(H.nodeType===Node.TEXT_NODE){let tt=H.textContent?.trim();tt&&_.push(tt);continue}if(H.nodeType!==Node.ELEMENT_NODE)continue;let X=H;if(X.tagName==="STYLE"||X.tagName==="SCRIPT"||X.getAttribute("aria-hidden")==="true")continue;let E=f(X);E&&_.push(E)}return _.join(" ").replace(/\s+/g," ").trim()};return Array.from(document.querySelectorAll(k)).map((x,_)=>{let H=f(x.querySelector(G)).replace(/An AI Overview is not available for this search/gi," ").replace(/Can't generate an AI overview right now\.?\s*Try again later\.?/gi," ").replace(/\bAI Overview\b/gi," ").replace(/\s+/g," ").trim(),X=x.classList.contains(q)||x.querySelector(P)?.getAttribute("aria-expanded")==="true",E=H.length>=10&&!new RegExp(v,"i").test(H);return{q:(x.getAttribute(A)||x.getAttribute(T)||x.querySelector(M)?.innerText?.trim()||"").replace(/\s+/g," ").trim(),done:X&&(R||E),expanded:X,index:_,answerReady:E,sourceCount:E?x.querySelector(G)?.querySelectorAll("a[href]").length??0:0}}).filter(x=>x.q)},y),O=async(k,A,T,M,q,P,G)=>{let v=Date.now(),R={id:`${G}:${Se(k)}:${P}`,questionId:Se(k),question:k,batchNumber:G,controlAttempt:P,observedAt:new Date(v).toISOString(),beforeQuestionCount:A,expandedBefore:M},f=T>=0?t.locator(y.sel).nth(T).locator(y.clickTarget):null,x=null,_=await C(async()=>(v=Date.now(),R.observedAt=new Date(v).toISOString(),f?(M&&(await f.click({timeout:Po,force:!0,noWaitAfter:!0}),await t.waitForTimeout(120)),await f.click({timeout:Po,force:!0,noWaitAfter:!0}),!0):!1)).catch(E=>(x=E instanceof Error&&(E.name==="TimeoutError"||/timeout/i.test(E.message))?"click_ack_timeout":"click_failed",!1)),H=Date.now()-v,X={...R,dispatched:_,outcome:_?"unconfirmed":"dispatch_failed",confirmationSignals:[],confirmationCheckpointMs:null,confirmedAtMs:null,dispatchDurationMs:H,totalDurationMs:H,afterQuestionCount:A,newQuestionCount:0,expandedAfter:M,answerObserved:!1,sourceCount:0,errorCode:T<0?"control_missing":x};return{clickStartedMs:v,dispatched:_,confirmed:!1,hadMaterialBefore:q,observation:X}},F=async k=>{let A=null,T=k.filter(M=>M.dispatched||M.observation.errorCode==="click_ack_timeout");for(let M of[Jl,ql,No]){if(!T.length)break;let q=Math.min(...T.map(v=>v.clickStartedMs+M-Date.now()));q>0&&await t.waitForTimeout(q);let P=n.questionsOnly?await m().catch(()=>null):await t.evaluate(le,{selectors:Z}).catch(()=>null);P&&!n.questionsOnly&&(A=P);let G=P?.length;for(let v of T){let R=v.observation;if(P){let f=n.questionsOnly?P.find(E=>E.q===R.question):P.find(E=>E.question===R.question),x=!1,_=0;if(f)if("q"in f)x=f.answerReady,_=f.sourceCount;else{let E=Sn(f.answer,f.question);x=!!(E&&E.length>=10&&!new RegExp(bo,"i").test(E)),_=x?f.sources.length:0}R.afterQuestionCount=G??R.beforeQuestionCount,R.newQuestionCount=Math.max(0,R.afterQuestionCount-R.beforeQuestionCount),R.expandedAfter=f?.expanded??!1,R.answerObserved=x,R.sourceCount=x?_:0,R.confirmationSignals=[...R.expandedAfter?["expanded"]:[],...x?["answer"]:[],...R.sourceCount>0?["source"]:[],...R.newQuestionCount>0?["question_growth"]:[]];let H=!!(f?.expanded&&!R.expandedBefore);((x||R.sourceCount>0)&&(!v.hadMaterialBefore||v.dispatched||H)||R.newQuestionCount>0&&(v.dispatched||H))&&(v.confirmed=!0,R.outcome="confirmed",R.confirmationCheckpointMs=M,R.confirmedAtMs=Date.now()-v.clickStartedMs),v.dispatched&&(R.errorCode=v.confirmed?null:f?"confirmation_timeout":"control_missing")}R.totalDurationMs=Date.now()-v.clickStartedMs}T=T.filter(v=>!v.confirmed&&Date.now()-v.clickStartedMs<No)}for(let M of k)M.dispatched&&!M.confirmed&&M.observation.errorCode===null&&(M.observation.errorCode="confirmation_timeout");return A},B=null,I=0;t:for(;;){if(n.softDeadlineMs&&Date.now()>=n.softDeadlineMs)throw this.paaLifecycle={...this.paaLifecycle,discoveryStatus:"interrupted",completionReason:"The execution deadline arrived before frontier exhaustion could be proven."},new Ot(this.paaLifecycle.completionReason);this.throwIfAborted(a);let k=n.questionsOnly?null:B??await t.evaluate(le,{selectors:Z});B=null;let A=typeof t.url=="function"?t.url():"https://www.google.com/",T=k?k.map(f=>{let x=!!Sn(f.answer,f.question),_=x&&!f.answerExpansionIncomplete&&f.sources.some(H=>!!Ue(H.rawHref,A));return{q:f.question,done:_||f.expanded&&x,answerReady:x,expanded:f.expanded,index:f.itemIndex}}):await m(),M=!1;for(let f of T)s.has(f.q)||(s.add(f.q),o.push(f.q),o.length<=n.maxQuestions&&(M=this.upsertCollectedRow(this.toFlatRow({questionId:Se(f.q),googleLinkId:null,googleEvidenceId:null,question:f.q,sources:[]},1,null,n.query))||M)),f.done&&(U.has(f.q)||c.delete(f.q),U.add(f.q));if(this.paaLifecycle={...this.paaLifecycle,questionsFound:Math.min(o.length,n.maxQuestions),targetStatus:o.length>=n.maxQuestions?"met":"not_met",knownQuestions:o.length,processedQuestions:U.size,failedInteractions:c.size,visibleControls:T.length},M&&await this.emitProgress("discovered"),n.questionsOnly&&s.size>=n.maxQuestions){this.paaLifecycle={...this.paaLifecycle,discoveryStatus:"target_reached",targetStatus:"met",completionReason:"The requested unique-question count was observed."};break}if(!n.questionsOnly&&s.size>=n.maxQuestions){let f=!1,x=new Set(o.slice(0,n.maxQuestions)),_=this.mapPaaDomRecords(k??[],A),H=_.filter(E=>x.has(E.question)&&E.answerExpansionIncomplete&&!l.has(E.question)),X;await Promise.allSettled(H.map(async E=>{l.add(E.question);try{await za(t,E.question,{selectors:Z,deadlineMs:n.softDeadlineMs,signal:a,allowOuterReopen:!d.has(E.question),dispatchClick:C},le)}catch(tt){X??={reason:tt}}})),H.length&&(_=await this.extractVisibleItems(t).catch(E=>{if(X)return _;throw E}));for(let E of _){if(!x.has(E.question))continue;let tt=r.get(E.question),$={...E,answer:E.answer||tt?.answer,answerExpansionIncomplete:E.answer?E.answerExpansionIncomplete:tt?.answerExpansionIncomplete,sourceTitle:E.sourceTitle??tt?.sourceTitle,sourceSite:E.sourceSite??tt?.sourceSite,sourceCite:E.sourceCite??tt?.sourceCite,sources:this.mergePaaSources(tt?.sources,E.sources)};r.set(E.question,$),f=this.upsertCollectedRow(this.toFlatRow($,1,null,n.query))||f}if(f&&await this.emitProgress("answer_captured"),X)throw X.reason;if([...x].every(E=>{let tt=r.get(E);return!!(tt?.answer?.trim()&&tt.sources.length>0&&!tt.answerExpansionIncomplete)})){c.clear(),this.paaLifecycle={...this.paaLifecycle,discoveryStatus:"target_reached",targetStatus:"met",failedInteractions:0,completionReason:"The requested unique-question count and its answer/source material were observed."};break}}let q=new Set(o.slice(0,n.maxQuestions)),P=T.filter(f=>q.has(f.q)&&(!f.done||s.size<n.maxQuestions&&!this.clickedQuestions.has(f.q))&&(S.get(f.q)??0)<u&&!d.has(f.q)),G=P.slice(-zl);if(this.paaLifecycle={...this.paaLifecycle,eligibleControls:P.length},G.length===0){if(s.size>=n.maxQuestions){this.paaLifecycle={...this.paaLifecycle,discoveryStatus:"target_reached",targetStatus:"met",completionReason:"The requested unique-question count was observed."};break}let f=new Set(T.map(_=>_.q)),x=o.slice(0,n.maxQuestions).filter(_=>c.has(_)||!U.has(_)&&!f.has(_));if(x.length>0)throw this.paaLifecycle={...this.paaLifecycle,discoveryStatus:"interrupted",failedInteractions:new Set([...c,...x]).size,completionReason:"At least one known PAA control failed or disappeared before it could be confirmed."},await this.emitProgress("expansion_finished"),new Ot(this.paaLifecycle.completionReason);for(let _=1;_<=h;_++){this.throwIfAborted(a),await this.throwIfCaptcha(t,"Google PAA exhaustion confirmation"),await t.mouse.wheel(0,320);let H=await t.waitForFunction(({sel:E,min:tt})=>document.querySelectorAll(E).length>tt,{sel:Z.item,min:T.length},{timeout:1500,polling:100}).catch(()=>null);if(this.paaLifecycle={...this.paaLifecycle,noGrowthConfirmations:_},H||(await m()).some(E=>!s.has(E.q)))continue t}this.paaLifecycle={...this.paaLifecycle,discoveryStatus:"frontier_exhausted",targetStatus:"not_met",failedInteractions:0,noGrowthConfirmations:h,completionReason:"Every known eligible PAA control was processed and three healthy no-growth confirmations found no additional questions."};break}await this.throwIfCaptcha(t,"Google PAA expansion"),w+=1;for(let f of G){if(this.reporter.onDepth(++I),(S.get(f.q)??0)>0){let x=this.paaLifecycle.retryBreakdown.controlRetries+1;this.paaLifecycle={...this.paaLifecycle,automaticRetries:x+this.paaLifecycle.retryBreakdown.browserRetries+this.paaLifecycle.retryBreakdown.runtimeRecoveries,retryBreakdown:{...this.paaLifecycle.retryBreakdown,controlRetries:x}}}S.set(f.q,(S.get(f.q)??0)+1)}let v=[];for(let f of G)v.push({target:f,result:await O(f.q,T.length,f.index,f.expanded,f.answerReady,S.get(f.q)??1,w)});let R=await F(v.map(({result:f})=>f));for(let{target:f,result:x}of v)(x.dispatched||x.confirmed)&&this.clickedQuestions.add(f.q),this.interactionObservations.push(x.observation);if(this.interactionObservations.length>Io&&this.interactionObservations.splice(0,this.interactionObservations.length-Io),!n.questionsOnly){let f=new Set(G.map(_=>_.q)),x=R??await t.evaluate(le,{selectors:Z});for(let _ of this.mapPaaDomRecords(x,typeof t.url=="function"?t.url():"https://www.google.com/"))f.has(_.question)&&(r.set(_.question,_),this.upsertCollectedRow(this.toFlatRow(_,1,null,n.query))&&await this.emitProgress("answer_captured"));o.length>=n.maxQuestions&&o.slice(0,n.maxQuestions).every(_=>{let H=x.find(X=>X.question===_);return!!(H&&Sn(H.answer,H.question)&&!H.answerExpansionIncomplete&&H.sources.some(X=>Ue(X.rawHref,A)))})&&(B=x)}for(let{target:f,result:x}of v){x.observation.errorCode==="click_ack_timeout"&&d.add(f.q);let _=r.get(f.q);x.confirmed||_?.answer?.trim()&&(!x.hadMaterialBefore||x.dispatched)?(U.add(f.q),c.delete(f.q)):(x.observation.errorCode==="click_ack_timeout"||(S.get(f.q)??0)>=u)&&(c.add(f.q),d.add(f.q))}this.paaLifecycle={...this.paaLifecycle,processedQuestions:U.size,failedInteractions:c.size,noGrowthConfirmations:0,dispatchedInteractions:this.interactionObservations.filter(f=>f.dispatched).length,confirmedInteractions:this.interactionObservations.filter(f=>f.outcome==="confirmed").length,unconfirmedInteractions:this.interactionObservations.filter(f=>f.outcome!=="confirmed").length},await this.emitProgress("click_observed")}let K=n.questionsOnly?new Map:new Map(r);n.questionsOnly||await this.fillIncompleteItems(t,o,K,n,d,a);let D=[];for(let k of o){if(D.length>=n.maxQuestions)break;let A=this.normalizeQuestion(k);if(i.has(A))continue;i.add(A);let T=K.get(k);if(T){let M=this.toFlatRow(T,1,null,n.query);this.upsertCollectedRow(M),D.push(M),this.reporter.onQuestion({questionId:T.questionId,googleLinkId:T.googleLinkId,googleEvidenceId:T.googleEvidenceId,question:T.question,answer:T.answer??null,sourceTitle:T.sourceTitle??null,sourceSite:T.sourceSite??null,sourceCite:T.sourceCite??null,sources:T.sources,...T.answerExpansionIncomplete?{answerExpansionIncomplete:!0}:{},depth:1,parentQuestion:null,children:[]})}else{let M=this.toFlatRow({questionId:Se(k),googleLinkId:null,googleEvidenceId:null,question:k,answer:void 0,sourceTitle:void 0,sourceSite:void 0,sourceCite:void 0,sources:[]},1,null,n.query);this.upsertCollectedRow(M),D.push(M)}}this.completeness.paaWithoutAnswer=n.questionsOnly?0:D.filter(k=>!k.answer).length,this.completeness.paaWithoutSource=n.questionsOnly?0:D.filter(k=>(k.sources??[]).length===0).length,this.completeness.paaIncompleteAnswers=n.questionsOnly?0:D.filter(k=>k.answerExpansionIncomplete).length,this.completeness.paaRequested=n.maxQuestions,this.completeness.paaReturned=D.length,this.completeness.paaUnique=i.size;let b=!n.questionsOnly&&(this.completeness.paaWithoutAnswer>0||this.completeness.paaWithoutSource>0||this.completeness.paaIncompleteAnswers>0);return this.paaLifecycle={...this.paaLifecycle,questionsFound:D.length,targetStatus:D.length>=n.maxQuestions?"met":"not_met",materialStatus:b?"partial":"complete",processedQuestions:U.size,failedInteractions:c.size},await this.emitProgress("fill_incomplete"),await this.emitProgress("expansion_finished"),D}async fillIncompleteItems(t,n,a,i,s,o){let d=new Set(n.slice(0,i.maxQuestions)),S=r=>!r?.answer||(r.sources??[]).length===0||!!r.answerExpansionIncomplete,U=new Set([...d].filter(r=>S(a.get(r)))),c=new Set([...U].filter(r=>!a.get(r)?.answer));if(U.size!==0){for(let r of U){if(i.softDeadlineMs&&Date.now()>=i.softDeadlineMs)break;let l=(await this.extractVisibleItems(t,r))[0];if(l?.answerExpansionIncomplete&&(await za(t,r,{selectors:Z,deadlineMs:i.softDeadlineMs,signal:o,allowOuterReopen:!s?.has(r)},le),l=(await this.extractVisibleItems(t,r))[0]),!l)continue;let u=a.get(r);a.set(r,{...l,answer:l.answer||u?.answer,answerExpansionIncomplete:l.answer?l.answerExpansionIncomplete:u?.answerExpansionIncomplete,sourceTitle:l.sourceTitle??u?.sourceTitle,sourceSite:l.sourceSite??u?.sourceSite,sourceCite:l.sourceCite??u?.sourceCite,sources:this.mergePaaSources(u?.sources,l.sources)});let h=a.get(r);h&&this.upsertCollectedRow(this.toFlatRow(h,1,null,i.query))&&await this.emitProgress("fill_incomplete")}this.completeness.paaAnswersRecovered=[...c].filter(r=>a.get(r)?.answer).length}}async reExpandCollapsedItems(t){let n=`${Z.item}:not(.${Z.expandedClass}) ${Z.clickTarget}`,a=await t.locator(n).count().catch(()=>0);if(a===0)return!1;for(let i=0;i<a;i++)try{let s=t.locator(n).first();await s.scrollIntoViewIfNeeded(),await s.click({force:!0}),await t.waitForTimeout(this.jitteredDelayMs(300,500))}catch{}return!0}extractVideos(t){return yo(t)}extractForums(t){return mo(t)}extractShortVideos(t,n){return Co(t,n,(a,i)=>this.throwIfCaptcha(a,i))}extractWhatPeopleSaying(t){return fo(t)}extractOrganicResults(t){return ko(t)}extractLocalPack(t){return Mo(t)}extractEntityIds(t){return vo(t)}mergeLocalPackIntoEntities(t,n){return To(t,n)}async extractAISurfaces(t,n){let a=await t.evaluate(ro,{aio:Es,aim:Hs,expandWaitMs:1500}),i=typeof t.url=="function"?t.url():"https://www.google.com/",s={surface:a.surface,aiOverview:{...a.aiOverview,citations:this.normalizeAICitations(i,a.aiOverview.citations)},aiMode:{...a.aiMode,citations:this.normalizeAICitations(i,a.aiMode.citations)}};if(!s.aiOverview.detected)return this.completeness.aioShareCaptured=null,s;let o=this.aioShareUrlEarly??await this.captureAIOverviewShareUrl(t,n).catch(()=>null);return this.completeness.aioShareCaptured=o!==null,{...s,aiOverview:{...s.aiOverview,shareUrl:o}}}async captureAIOverviewShareUrl(t,n){if(n?.softDeadlineMs&&Date.now()>=n.softDeadlineMs||!await t.evaluate(()=>{let s=Array.from(document.querySelectorAll('h1,h2,h3,[role="heading"],div')).filter(o=>(o.textContent||"").trim()==="AI Overview");for(let o of s){let d=o;for(let S=0;S<8&&d;S++){let U=d.querySelector('[aria-label="Share"]');if(U)return U.scrollIntoView({block:"center"}),U.click(),!0;d=d.parentElement}}return!1}).catch(()=>!1))return null;let i=null;try{i=await(await t.waitForFunction(()=>{let o=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);for(;o.nextNode();){let d=(o.currentNode.textContent||"").match(/https:\/\/share\.google\/aimode\/\S+/);if(d)return d[0]}return!1},void 0,{timeout:4500,polling:250})).jsonValue()}catch{i=null}return await t.keyboard.press("Escape").catch(()=>{}),i}buildTree(t,n){let a=[],i=new Map;for(let s of t){let o={questionId:s.question_id,googleLinkId:s.google_link_id||null,googleEvidenceId:s.google_evidence_id||null,question:s.question,answer:s.answer||null,...s.answerExpansionIncomplete?{answerExpansionIncomplete:!0}:{},sourceTitle:s.source_title||null,sourceSite:s.source_site||null,sourceCite:s.source_cite||null,sources:s.sources??[],depth:s.depth,parentQuestion:s.parent_question||null,children:[]};i.set(s.question,o)}for(let s of i.values())s.parentQuestion&&i.has(s.parentQuestion)?i.get(s.parentQuestion).children.push(s):a.push(s);return a}getBrowserDebugSnapshot(){return this.driver.getDebugSnapshot()}buildHarvestDebugSnapshot(t,n,a,i,s){if(t.debug)return{enabled:!0,request:{query:t.query,locationInput:t.location??null,canonicalLocation:n,locationResolved:s?s.matched:null,locationMatchSource:s?s.source:null,locationAmbiguousCandidates:s?s.ambiguousCandidates:null,uule:a,gl:t.gl,hl:t.hl,device:t.device,proxyMode:t.proxyMode,proxyZip:t.proxyZip??null,serpIdentity:t.serpIdentity??null,serpOnly:t.serpOnly,pages:t.pages??1},browser:this.getBrowserDebugSnapshot(),...i?{locationEvidence:i}:{}}}async captureSecondOrganicPage(t,n,a){if(this.throwIfAborted(a),!n.serpOnly&&!this.driver.withTemporaryPage)return{organic:[],status:"failed",failureCode:"unsupported_driver"};let i;try{let s=new URL(t.url()),o=U=>{try{let c=new URL(U,s);return s.origin==="https://www.google.com"&&c.origin===s.origin&&!c.username&&!c.password&&c.pathname==="/search"&&c.searchParams.getAll("q").length===1&&c.searchParams.get("q")===n.query&&c.searchParams.getAll("start").length===1&&c.searchParams.get("start")==="10"&&(!c.searchParams.has("num")||c.searchParams.get("num")==="10")&&["gl","hl"].every(r=>!c.searchParams.has(r)||c.searchParams.getAll(r).length===1&&c.searchParams.get(r)===n[r])&&["uule","tbs","udm","tbm","pws"].every(r=>c.searchParams.getAll(r).length<=1&&c.searchParams.get(r)===s.searchParams.get(r))}catch{return!1}},d=await t.evaluate(U=>document.querySelector(U?'a[aria-label="Page 2"], a#pnnext, a[rel="next"]':'a#pnnext, a[rel="next"]')?.getAttribute("href")??null,n.serpOnly);if(!d)return{organic:[],status:"unavailable",failureCode:"missing_next"};if(!o(d))return{organic:[],status:"unavailable",failureCode:"invalid_next"};if(n.serpOnly){let U=t.locator('a[aria-label="Page 2"], a#pnnext, a[rel="next"]').first();if(await U.scrollIntoViewIfNeeded({timeout:1e4}),await U.click({timeout:2e4}),this.throwIfAborted(a),await this.throwIfCaptcha(t,"Google SERP page 2"),!o(t.url()))throw i="invalid_next",new Error("Invalid pagination landing");let c=await this.extractOrganicResults(t);return c.length>0?{organic:c.map(r=>({...r,position:r.position+10})),status:"captured"}:{organic:[],status:"unavailable",failureCode:"empty_page"}}let S=await this.driver.withTemporaryPage(async U=>{if(await U.route("**/*",async c=>{let r=c.request();r.isNavigationRequest()&&r.frame()===U.mainFrame()&&!o(r.url())?(i=/^https:\/\/www\.google\.com\/sorry(?:\/|\?)/.test(r.url())?"captcha":"invalid_next",await c.abort("blockedbyclient")):await c.fallback()}),await U.goto(new URL(d,s).href,{waitUntil:"domcontentloaded",timeout:2e4}),this.throwIfAborted(a),await this.throwIfCaptcha(U,"Google SERP page 2"),!o(U.url()))throw i="invalid_next",new Error("Invalid pagination landing");return this.extractOrganicResults(U)},a);return this.throwIfAborted(a),S.length>0?{organic:S.map(U=>({...U,position:U.position+10})),status:"captured"}:{organic:[],status:"unavailable",failureCode:"empty_page"}}catch(s){if(this.throwIfAborted(a),s instanceof ut)throw s;return{organic:[],status:"failed",failureCode:i??(s instanceof et?"captcha":s instanceof Error&&(s.name==="TimeoutError"||/timed? ?out/i.test(s.message))?"timeout":"navigation_error")}}}async extract(t,n){let a=Date.now();this.phaseTimings={},this.completeness={paaWithoutAnswer:0,paaWithoutSource:0,paaAnswersRecovered:0,aioShareCaptured:null},this.linkDiagnostics=this.emptyLinkDiagnostics(),this.aioShareUrlEarly=null,this.collectedRows=[],this.progressSequence=0,this.checkpointMaterial=null,this.clickedQuestions=new Set,this.paaLifecycle=this.emptyPaaLifecycle(t.maxQuestions),this.partialContext={seed:t.query,location:t.location??null,startMs:a,maxQuestions:t.maxQuestions,questionsOnly:t.questionsOnly};let i=t.device==="mobile",s={headless:t.headless,profileDir:t.profileDir,proxy:t.proxy,\u006b\u0065\u0072\u006e\u0065\u006cApiKey:t.\u006b\u0065\u0072\u006e\u0065\u006cApiKey,\u006b\u0065\u0072\u006e\u0065\u006cProxyId:t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId,\u006b\u0065\u0072\u006e\u0065\u006cProfileName:t.\u006b\u0065\u0072\u006e\u0065\u006cProfileName,\u006b\u0065\u0072\u006e\u0065\u006cProfileSaveChanges:t.\u006b\u0065\u0072\u006e\u0065\u006cProfileSaveChanges,\u006b\u0065\u0072\u006e\u0065\u006cStealth:t.\u006b\u0065\u0072\u006e\u0065\u006cStealth,\u006b\u0065\u0072\u006e\u0065\u006cProxyResolution:t.\u006b\u0065\u0072\u006e\u0065\u006cProxyResolution,proxyMode:t.proxyMode,keepDefaultProxy:t.keepDefaultProxy,requireUsEgress:t.requireUsEgress,viewport:i?{width:390,height:844}:{width:1280,height:800},locale:`${t.hl}-${t.gl.toUpperCase()}`,deviceScaleFactor:i?3:1,isMobile:i,hasTouch:i,debug:t.debug,operationDeadlineMs:t.softDeadlineMs},o=0,d=[];try{this.throwIfAborted(n);let S=Date.now();await this.driver.launch(s),this.phaseTimings.providerConnectMs=Date.now()-S;let U=this.driver.getProviderSessionMetadata();if(U?.providerSessionId&&this.onProviderSession)try{await this.onProviderSession(U)}catch($){console.warn(JSON.stringify({event:"paa_provider_session_sink_failed",provider:U.provider,message:$ instanceof Error?$.message:String($)}))}this.throwIfAborted(n);let c=t.location?Wa(t.location):null,r=t.location?c?.canonical??t.location:null,l=r?ks(r):null,u=t,h=t.includeAllSerpFeatures,w=h||t.includeLocalPack,g=h||t.includeForums,C=h||t.includeVideos,y=h||t.includeAiOverview,m=h||t.includeWhatPeopleSaying,O={surface:"web",aiOverview:{detected:!1,text:null,citations:[]},aiMode:{detected:!1,text:null,citations:[]}},F=Date.now(),{hasPaa:B}=await this.driver.navigateToSERP(u.query,l,t.gl,t.hl,{...ea(t.recency)?{tbs:ea(t.recency)}:{},debug:t.debug,purpose:t.serpOnly?"serp":"paa",pages:t.pages===2?2:1,...t.softDeadlineMs?{deadlineMs:t.softDeadlineMs}:{},...n?{signal:n}:{}});this.phaseTimings.navigationMs=Date.now()-F,this.throwIfAborted(n);let I=this.driver.getPage();if(await this.throwIfCaptcha(I,"Google SERP"),B||(this.paaLifecycle={...this.paaLifecycle,discoveryStatus:"no_paa_observed",materialStatus:"complete",completionReason:"A readable Google SERP was observed without a People Also Ask block."}),t.questionsOnly){let $=Date.now(),J=B?await this.runBFS(I,u,n):[];this.phaseTimings.paaExpansionMs=Date.now()-$,await this.resolveMaterialLinks(I,J,[],O.aiOverview,O.aiMode);let ft={seed:u.query,totalQuestions:J.length,maxDepthReached:J.reduce((Mt,Ye)=>Math.max(Mt,Ye.depth),0),durationMs:Date.now()-a,errorCount:o};return this.reporter.onComplete(ft),{seed:u.query,location:t.location??null,extractedAt:new Date().toISOString(),diagnostics:{phaseTimings:this.currentPhaseTimings(a),completionStatus:B?"paa_found":"no_paa",...B?{}:{noPaaObserved:!0},problem:null,paaLifecycle:{...this.paaLifecycle},completeness:{...this.completeness},links:{...this.linkDiagnostics},...t.debug?{debug:this.buildHarvestDebugSnapshot(u,r,l,void 0,c)}:{}},totalQuestions:J.length,surface:"web",aiOverview:{detected:!1,text:null,citations:[]},aiMode:{detected:!1,text:null,citations:[]},whatPeopleSaying:[],tree:this.buildTree(J,u.query),flat:J,videos:[],forums:[],organicResults:[],localPack:[],entityIds:{entities:[],kgIds:[],cids:[],gcids:[]},stats:ft}}if(y&&(this.aioShareUrlEarly=await this.captureAIOverviewShareUrl(I,t).catch(()=>null)),t.serpOnly){let $=Date.now(),[J,ft,Mt]=await Promise.all([this.extractOrganicResults(I),w?this.extractLocalPack(I):Promise.resolve([]),this.extractEntityIds(I)]),Ye=this.mergeLocalPackIntoEntities(Mt,ft),z=y?await this.extractAISurfaces(I,t):O;this.phaseTimings.serpParseMs=Date.now()-$;let he=t.debug?ln(r,J,ft):void 0,It=J,Je={requestedPages:(t.pages??1)>=2?2:1,capturedPages:1,page2Status:(t.pages??1)>=2?"not_attempted":"not_requested",page1OrganicCount:J.length,page2OrganicCount:0};if((t.pages??1)>=2){let it=await this.captureSecondOrganicPage(I,u,n);It=[...J,...it.organic],Je={...Je,capturedPages:it.status==="captured"?2:1,page2Status:it.status,page2OrganicCount:it.organic.length,...it.failureCode?{failureCode:it.failureCode}:{}},t.debug&&(he=ln(r,It,ft))}await this.resolveMaterialLinks(I,[],It,z.aiOverview,z.aiMode);let at={seed:u.query,totalQuestions:0,maxDepthReached:0,durationMs:Date.now()-a,errorCount:o};return this.reporter.onComplete(at),{seed:u.query,location:t.location??null,extractedAt:new Date().toISOString(),diagnostics:{phaseTimings:this.currentPhaseTimings(a),completionStatus:"serp_only",problem:null,pagination:Je,completeness:{...this.completeness},links:{...this.linkDiagnostics},...t.debug?{debug:this.buildHarvestDebugSnapshot(u,r,l,he,c)}:{}},totalQuestions:0,surface:z.surface,aiOverview:z.aiOverview,aiMode:z.aiMode,whatPeopleSaying:[],tree:[],flat:[],videos:[],forums:[],organicResults:It,localPack:ft,entityIds:Ye,stats:at}}let[K,D,b,k,A,T]=await Promise.all([C?this.extractVideos(I):Promise.resolve([]),g?this.extractForums(I):Promise.resolve([]),m?this.extractWhatPeopleSaying(I):Promise.resolve([]),this.extractEntityIds(I),this.extractOrganicResults(I),w?this.extractLocalPack(I):Promise.resolve([])]),M=this.mergeLocalPackIntoEntities(k,T),q=t.debug?ln(r,A,T):void 0;this.reporter.onVideos(K),this.reporter.onForums(D);let P=y?await this.extractAISurfaces(I,t):O,G={requestedPages:(t.pages??1)>=2?2:1,capturedPages:1,page2Status:(t.pages??1)>=2?"not_attempted":"not_requested",page1OrganicCount:A.length,page2OrganicCount:0},v=A;if(this.checkpointMaterial={surface:P.surface,aiOverview:P.aiOverview,aiMode:P.aiMode,whatPeopleSaying:b,videos:K,forums:D,organicResults:v,localPack:T,entityIds:M,pagination:G},await this.emitProgress("serp_captured"),G.requestedPages===2){let $=await this.captureSecondOrganicPage(I,u,n);v=[...A,...$.organic],G={...G,capturedPages:$.status==="captured"?2:1,page2Status:$.status,page2OrganicCount:$.organic.length,...$.failureCode?{failureCode:$.failureCode}:{}},this.checkpointMaterial={...this.checkpointMaterial,organicResults:v,pagination:G},await this.emitProgress("serp_captured"),await this.resolveMaterialLinks(I,[],v,P.aiOverview,P.aiMode),this.checkpointMaterial={...this.checkpointMaterial,organicResults:v},await this.emitProgress("serp_captured")}let R=t.debug?ln(r,v,T):q;if(!B){await this.resolveMaterialLinks(I,[],v,P.aiOverview,P.aiMode),this.checkpointMaterial={...this.checkpointMaterial,organicResults:v},await this.emitProgress("serp_captured");let $={seed:u.query,totalQuestions:0,maxDepthReached:0,durationMs:Date.now()-a,errorCount:o};return this.reporter.onComplete($),{seed:u.query,location:t.location??null,extractedAt:new Date().toISOString(),diagnostics:{phaseTimings:this.currentPhaseTimings(a),completionStatus:"no_paa",noPaaObserved:!0,problem:null,pagination:G,paaLifecycle:{...this.paaLifecycle},completeness:{...this.completeness},links:{...this.linkDiagnostics},...t.debug?{debug:this.buildHarvestDebugSnapshot(u,r,l,R,c)}:{}},totalQuestions:0,surface:P.surface,aiOverview:P.aiOverview,aiMode:P.aiMode,whatPeopleSaying:b,tree:[],flat:[],videos:K,forums:D,organicResults:v,localPack:T,entityIds:M,stats:$}}let f=Date.now(),x=await this.runBFS(I,u,n);this.phaseTimings.paaExpansionMs=Date.now()-f,this.throwIfAborted(n);let _=new URLSearchParams({q:u.query,gl:t.gl,hl:t.hl,pws:"0",udm:rn.udm});l&&_.set("uule",l);let H=[];if(t.includeShortVideos===!0||t.includeShortVideos!==!1&&(C||h))try{H=await this.extractShortVideos(I,"https://www.google.com/search?"+_.toString())}catch($){if(!($ instanceof et))throw $;o++,d.push({code:"short_videos_captcha_skipped",surface:"short_videos",message:$.message,retryable:!0})}this.reporter.onVideos(H),await this.resolveMaterialLinks(I,x,v,P.aiOverview,P.aiMode),this.checkpointMaterial={...this.checkpointMaterial,surface:P.surface,aiOverview:P.aiOverview,aiMode:P.aiMode,videos:[...K,...H],organicResults:v},await this.emitProgress("expansion_finished");let X=[...K,...H],E=this.buildTree(x,u.query),tt={seed:u.query,totalQuestions:x.length,maxDepthReached:x.reduce(($,J)=>Math.max($,J.depth),0),durationMs:Date.now()-a,errorCount:o};return this.reporter.onComplete(tt),{seed:u.query,location:t.location??null,extractedAt:new Date().toISOString(),diagnostics:{phaseTimings:this.currentPhaseTimings(a),completionStatus:"paa_found",problem:null,pagination:G,paaLifecycle:{...this.paaLifecycle},completeness:{...this.completeness},links:{...this.linkDiagnostics},...d.length>0?{warnings:d}:{},...t.debug?{debug:this.buildHarvestDebugSnapshot(u,r,l,R,c)}:{}},totalQuestions:x.length,surface:P.surface,aiOverview:P.aiOverview,aiMode:P.aiMode,whatPeopleSaying:b,tree:E,flat:x,videos:X,forums:D,organicResults:v,localPack:T,entityIds:M,stats:tt}}catch(S){throw o++,this.paaLifecycle.discoveryStatus==="in_progress"&&(this.paaLifecycle={...this.paaLifecycle,discoveryStatus:"interrupted",completionReason:"The browser attempt ended before frontier exhaustion could be proven."}),await this.emitProgress("attempt_ending").catch(()=>{}),this.reporter.onError(S instanceof Error?S:new Error(String(S))),S}}};var Vn=class{onQuestion(t){process.stdout.write(JSON.stringify({event:"question",depth:t.depth,question:t.question})+`
21785
+ `).map(T=>T.trim()).filter(T=>/^\d+\.\s+.+/.test(T)),h=c(l)}let y=document.querySelector(t.aim.root),m=a==="aim"&&!!y,O=y?.closest(t.aim.wrapper)??y,F=m?S(O):null,B=m&&s(F),I=B?F:null,K=B?c(O):[],_=!!l&&s(u);return{surface:a,aiOverview:{detected:_,text:_?u:null,citations:_?h:[],expanded:_?w:!1,fullyExpanded:_?g:!1,sections:_?C:[]},aiMode:{detected:B&&I!==null,text:I,citations:K}}}var So=require("crypto"),Uo=8e3,co=3e3,uo=1e4,Vl=8;function Gt(e){return/(^|\.)google\.(?:com|[a-z]{2,3}(?:\.[a-z]{2})?)$/i.test(e)}function cn(e){if(!e||e.length>Uo)return null;try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"||t.username||t.password?null:t}catch{return null}}function Kl(e,t){if(!e||e.length>Uo||/^javascript:/i.test(e))return null;try{let n=new URL(e,t);return cn(n.href)}catch{return null}}function Un(e){let t=cn(e);return!t||t.protocol!=="https:"||!Gt(t.hostname)||t.pathname!=="/goto"?null:t.searchParams.get("url")?t:null}function $a(e){if(e.linkType!=="google_goto_redirect"||e.resolutionStatus!=="resolved"||!Un(e.rawUrl)||!e.resolvedUrl)return!1;let t=cn(e.resolvedUrl);return!!(t&&!Gt(t.hostname)&&t.href===e.resolvedUrl&&e.url===t.href)}function Se(e){let t=e.normalize("NFKC").toLocaleLowerCase("en-US").replace(/[^\p{L}\p{N}\s]/gu,"").replace(/\s+/g," ").trim();return`paa_${(0,So.createHash)("sha256").update(t).digest("hex").slice(0,16)}`}function Ue(e,t){let n=Kl(e,t);if(!n)return null;let a=n.href;if(!Gt(n.hostname))return{url:a,rawUrl:a,resolvedUrl:a,linkType:"plain",resolutionStatus:"not_needed"};if(n.pathname==="/url"){let i=cn(n.searchParams.get("q")??n.searchParams.get("url")??"");return!i||Gt(i.hostname)?null:{url:i.href,rawUrl:a,resolvedUrl:i.href,linkType:"google_url_redirect",resolutionStatus:"resolved"}}return n.pathname==="/goto"&&n.searchParams.get("url")?{url:a,rawUrl:a,resolvedUrl:null,linkType:"google_goto_redirect",resolutionStatus:"unresolved"}:null}function ja(e){return Un(e)?.searchParams.get("url")??null}function ho(e,t){try{let n=new URL(e),a=cn(new URL(t,n).href);return!a||Gt(a.hostname)?null:(!a.hash&&n.hash&&(a.hash=n.hash),a.href)}catch{return null}}async function go(e,t={}){let n=[...new Set([...e].flatMap(r=>Un(r)?[r]:[]))],a=new Map(n.map(r=>[r,{rawUrl:r,resolvedUrl:null,resolutionStatus:"unresolved"}])),i=typeof globalThis.fetch=="function"?globalThis.fetch.bind(globalThis):null,s=t.fetchImpl??i;if(n.length===0||!s)return{resolutions:[...a.values()],nonGoogleRequestsObserved:0};let o=Math.max(1,t.timeoutMs??co),d=Date.now()+Math.max(1,t.totalBudgetMs??uo),S=Math.max(1,Math.min(16,Math.floor(t.concurrency??Vl))),U=0,c=async()=>{for(;U<n.length;){let r=n[U++],l=Un(r),u=l?.searchParams.get("url");if(!l||!u){a.set(r,{rawUrl:r,resolvedUrl:null,resolutionStatus:"rejected"});continue}l.hash="";let h=l.href;for(let w=0;w<2;w++){let g=d-Date.now();if(g<=0)return;let C=new AbortController,y=setTimeout(()=>C.abort(),Math.min(o,g)),m;try{m=await s(h,{method:"GET",redirect:"manual",headers:{accept:"*/*","user-agent":"Mozilla/5.0"},signal:C.signal})}catch{break}finally{clearTimeout(y)}if(m.status<300||m.status>=400)break;let O=m.headers.get("location");if(!O)break;let F=ho(r,O);if(F){a.set(r,{rawUrl:r,resolvedUrl:F,resolutionStatus:"resolved"});break}let B;try{B=new URL(O,h)}catch{a.set(r,{rawUrl:r,resolvedUrl:null,resolutionStatus:"rejected"});break}if(!Gt(B.hostname)||ja(B.href)!==u){a.set(r,{rawUrl:r,resolvedUrl:null,resolutionStatus:"rejected"});break}h=B.href}}};return await Promise.all(Array.from({length:Math.min(S,n.length)},()=>c())),{resolutions:[...a.values()],nonGoogleRequestsObserved:0}}function lo(e,t){try{return new URL(e.resolvedUrl??e.url).hostname.replace(/^www\./,"")}catch{return t}}async function wo(e,t={}){let n=[],a=r=>{for(let l of r)n.push(l),a(l.children??[])};a(e.tree??[]);let i=[...e.flat.flatMap(r=>r.sources??[]),...n.flatMap(r=>r.sources),...e.organicResults??[],...(e.aiOverview?.citations??[]).map(({text:r,href:l,...u})=>({...u,url:l})),...(e.aiMode?.citations??[]).map(({text:r,href:l,...u})=>({...u,url:l}))],s=new Map(i.filter(r=>!!r?.rawUrl).map(r=>[r.rawUrl,r])),o=[...s.values()].filter(r=>r.linkType==="google_goto_redirect"&&r.resolutionStatus!=="resolved").map(r=>r.rawUrl);if(o.length>0){let r=await go(o,t);for(let l of r.resolutions){let u=s.get(l.rawUrl);u&&s.set(l.rawUrl,l.resolutionStatus==="resolved"&&l.resolvedUrl?{...u,url:l.resolvedUrl,resolvedUrl:l.resolvedUrl,resolutionStatus:"resolved"}:{...u,resolutionStatus:l.resolutionStatus})}}let d=r=>({...r,...s.get(r.rawUrl)??r}),S=r=>r.map(l=>{let u=d(l);return{...u,site:lo(u,l.site)}});for(let r of e.flat){r.sources=S(r.sources??[]);let l=r.sources[0];r.source_title=l?.title??r.source_title,r.source_site=l?.site??r.source_site,r.source_cite=l?.url??r.source_cite}for(let r of n){r.sources=S(r.sources??[]);let l=r.sources[0];r.sourceTitle=l?.title??r.sourceTitle,r.sourceSite=l?.site??r.sourceSite,r.sourceCite=l?.url??r.sourceCite}for(let r=0;r<(e.organicResults?.length??0);r++){let l=d(e.organicResults[r]);e.organicResults[r]={...l,domain:lo(l,e.organicResults[r].domain)??""}}let U=r=>{let l=d({url:r.href,rawUrl:r.rawUrl,resolvedUrl:r.resolvedUrl,linkType:r.linkType,resolutionStatus:r.resolutionStatus}),{url:u,...h}=l;return{...r,...h,href:u}};e.aiOverview&&(e.aiOverview.citations=(e.aiOverview.citations??[]).map(U)),e.aiMode&&(e.aiMode.citations=(e.aiMode.citations??[]).map(U));let c=[...s.values()];return e.diagnostics.links={linkCandidatesObserved:s.size,plainLinksObserved:c.filter(r=>r.linkType==="plain").length,googleUrlRedirectsObserved:c.filter(r=>r.linkType==="google_url_redirect").length,googleGotoRedirectsObserved:c.filter(r=>r.linkType==="google_goto_redirect").length,redirectsResolved:c.filter(r=>r.linkType!=="plain"&&r.resolutionStatus==="resolved").length,redirectsUnresolved:c.filter(r=>r.resolutionStatus==="unresolved").length,redirectsRejected:c.filter(r=>r.resolutionStatus==="rejected").length,resolverNonGoogleRequestsObserved:0,paaSourcesPreserved:e.flat.reduce((r,l)=>r+l.sources.length,0),aiOverviewLabelValidated:e.aiOverview?.detected??!1},e}async function po(e,t,n={}){let a=new Map;for(let l of t){let u=a.get(l.rawUrl);u&&$a(u)||a.set(l.rawUrl,l.linkType==="google_goto_redirect"&&!$a(l)?{...l,url:l.rawUrl,resolvedUrl:null,resolutionStatus:"unresolved"}:l)}let i=[...a.values()].filter(l=>l.linkType==="google_goto_redirect"&&!$a(l));if(i.length===0)return a;let s=Date.now()+(n.totalBudgetMs??uo),o=await go(i.map(l=>l.rawUrl),n);for(let l of o.resolutions){let u=a.get(l.rawUrl);u&&a.set(l.rawUrl,l.resolutionStatus==="resolved"&&l.resolvedUrl?{...u,url:l.resolvedUrl,resolvedUrl:l.resolvedUrl,resolutionStatus:"resolved"}:{...u,resolutionStatus:l.resolutionStatus})}let d=i.filter(l=>a.get(l.rawUrl)?.resolutionStatus==="unresolved");if(d.length===0||n.browserFallback===!1||Date.now()>=s)return n.onNetworkAudit?.({nonGoogleRequestsObserved:0}),a;let S=n.timeoutMs??co,U=await e.context().newPage().catch(()=>null);if(!U)return n.onNetworkAudit?.({nonGoogleRequestsObserved:0}),a;let c=null,r=0;try{await U.route("**/*",async l=>{let u=l.request().url();try{Gt(new URL(u).hostname)||(r+=1)}catch{}let h=ja(u);if(!c||h!==c.token){await l.abort("blockedbyclient").catch(()=>{});return}let w=c;try{let g=await l.fetch({maxRedirects:0,timeout:w.timeoutMs});w.location=g.headers().location??null}finally{await l.abort("blockedbyclient").catch(()=>{}),w.finish()}});for(let l of d){let u=s-Date.now();if(u<=0)break;let h=Un(l.rawUrl),w=h?.searchParams.get("url");if(!h||!w){a.set(l.rawUrl,{...l,resolutionStatus:"rejected"});continue}let g=Math.min(S,u);h.hash="";let C=h.href,y=!1;for(let m=0;m<2;m++){let O,F=new Promise(b=>{O=b}),B=`mcp-goto-${Math.random().toString(36).slice(2)}`;c={token:w,timeoutMs:g,location:null,finish:O},await U.evaluate(({url:b,id:k})=>{let A=document.createElement("iframe");A.id=k,A.hidden=!0,A.src=b,document.body.append(A)},{url:C,id:B}).catch(()=>null),await Promise.race([F,new Promise(b=>setTimeout(b,g))]);let I=c.location;if(c=null,await U.evaluate(b=>document.getElementById(b)?.remove(),B).catch(()=>null),!I)break;let K=ho(l.rawUrl,I);if(K){a.set(l.rawUrl,{...l,url:K,resolvedUrl:K,resolutionStatus:"resolved"});break}let _;try{_=new URL(I,C)}catch{y=!0;break}if(!Gt(_.hostname)||ja(_.href)!==w){y=!0;break}C=_.href}y&&a.get(l.rawUrl)?.resolutionStatus!=="resolved"&&a.set(l.rawUrl,{...l,resolutionStatus:"rejected"})}}finally{c=null,await U.close().catch(()=>{}),n.onNetworkAudit?.({nonGoogleRequestsObserved:r})}return a}async function yo(e){let t=on;return e.evaluate(n=>{let a=[],i=Array.from(document.querySelectorAll(n.container));for(let s of i){let S=(s.querySelector(n.sectionHeading)?.textContent?.trim()??"").toLowerCase().includes("short")?"short_video":"video",U=Array.from(s.querySelectorAll(n.item));for(let c of U){let r=c.href;if(!r||!r.includes("youtube")&&!r.includes("youtu.be"))continue;let l=c.textContent?.trim()??"",u=l.indexOf("YouTube");if(u===-1)continue;let h=l.slice(0,u).trim(),g=l.slice(u+7).replace(/^[·\s·]+/,"").match(/^([^·\n]+)/),C=g?g[1].trim():"";h&&a.push({type:S,title:h,channel:C,platform:"YouTube",duration:"",url:r})}}return a},t)}async function mo(e){let t=Bs;return e.evaluate(n=>{let a=[],s=Array.from(document.querySelectorAll(n.section)).find(d=>d.textContent?.includes("Discussions"));if(!s)return a;let o=Array.from(s.querySelectorAll(n.item));for(let d of o){let S=d.href;if(!S)continue;let U=d.querySelector(n.title),c=d.querySelector(n.source),r=U?.textContent?.trim()??"",l=c?.textContent?.trim()??"";r&&a.push({title:r,source:l,url:S})}return a},t)}async function Co(e,t,n){try{await e.goto(t,{waitUntil:"domcontentloaded"}),await e.waitForTimeout(1500)}catch{return[]}await n(e,"Google short video search");let a={item:rn.item,platforms:[...rn.platforms]};return(await e.evaluate(s=>{let o=new Set,d=[],S=Array.from(document.querySelectorAll(s.item)),U=["youtube.com","youtu.be","tiktok.com","instagram.com","facebook.com","fb.watch"],c=new Map;for(let r of S){let l=r.href;if(!l||!U.some(h=>l.includes(h)))continue;let u=r.textContent?.trim()??"";c.has(l)||c.set(l,[]),c.get(l).push(u)}for(let[r,l]of c.entries()){if(o.has(r))continue;o.add(r);let u=l.find(y=>/^\d+:\d+$/.test(y))??"",h=l.find(y=>!/^\d+:\d+$/.test(y)&&y.length>5)??"";if(!h)continue;let w=h,g="",C="";for(let y of s.platforms){let m=-1,O=0;for(;;){let _=h.indexOf(y,O);if(_===-1)break;m=_,O=_+1}if(m===-1)continue;let F=h.slice(m+y.length);if(!(/^[\s·]/.test(F)||F.trim()===""))continue;w=h.slice(0,m).trim(),g=y;let I=F.replace(/^[\s·]+/,""),K=I.indexOf("\xB7");C=(K===-1?I:I.slice(0,K)).trim();break}w&&d.push({title:w,channel:C,platform:g,duration:u,url:r})}return d},a)).map(s=>({type:"short_video",...s}))}async function fo(e){let t=Rs;return e.evaluate(n=>{let a=Array.from(document.querySelectorAll(n.sectionTag)).find(i=>i.textContent?.includes(n.sectionHeadingText))??document.querySelector(".yG4QQe.TBC9ub.NbhJ1c");return a?Array.from(a.querySelectorAll(n.card)).map(i=>{let o=i.querySelector(n.cardLink)?.href??"",d=i.querySelector(n.titleH1)?.textContent?.trim(),S=i.querySelector(n.titleDiv)?.textContent?.trim(),U=d??S??"",c=i.querySelector(n.source)?.textContent?.trim()??"",l=i.querySelector(n.platformBadge)?.textContent?.trim()??"",u=i.querySelector(n.ytChannel)?.textContent?.trim()??"",h=i.querySelector(n.ytDate)?.textContent?.trim()??"",w=i.querySelector(n.authorNote)?.textContent?.trim()??null,g=i.querySelector(n.popularCommentLabel),C=null;if(g){let M=g.nextSibling;for(;M;){let q=M.textContent?.trim();if(q){C=q;break}M=M.nextSibling}}let y=Array.from(i.querySelectorAll("span")),m=y.find(M=>/^\d+:\d+$/.test(M.textContent?.trim()??""))?.textContent?.trim()??null,F=y.map(M=>M.textContent?.trim()??"").filter(M=>/\d/.test(M)&&(M.includes("comment")||M.includes("reaction")||M.includes("view")||M.includes("like")||M.includes("share")))[0]??"",B=y.map(M=>M.textContent?.trim()??"").filter(M=>/\d+ (day|week|month|year|hour)s? ago|Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec/.test(M)),I=h||(B[0]??""),K=l||(u?"YouTube":""),_=u||c,b="unknown",k=K.toLowerCase(),A=_.toLowerCase(),T=c.toLowerCase();return k.includes("reddit")||A.startsWith("r/")?b="reddit":k.includes("facebook")||T.includes("facebook")?b="facebook":k.includes("instagram")||T.includes("instagram")?b="instagram":k.includes("tiktok")||T.includes("tiktok")?b="tiktok":k.includes("youtube")||u?b="youtube":b="news",{type:b,title:U,url:o,source:_,platform:K,popularComment:C,engagement:F,date:I,duration:m,authorNote:w}}):[]},t)}async function ko(e){let t=Fs,n=await e.evaluate(i=>{let s=[],o=0;return document.querySelectorAll(i.result).forEach(d=>{let S=d.querySelector(i.title);if(!S)return;let U=S.textContent?.trim()??"",r=S.closest("a")?.href??"";if(!U||!r)return;o++;let l=d.querySelector(i.cite)?.textContent?.trim()??null,u=d.querySelector(i.snippet)?.textContent?.trim()??null,h=!!d.querySelector(i.redditCite),w=d.querySelector(i.ratingWrap),g=w?{value:w.querySelector(i.ratingValue)?.textContent?.trim()??"",count:w.querySelector(i.reviewCount)?.textContent?.trim()??""}:null,C="";try{C=new URL(r).hostname.replace(/^www\./,"")}catch{C=d.querySelector(i.siteName)?.textContent?.trim()??""}s.push({position:o,title:U,url:r,domain:C,cite:l,snippet:u,isRedditStyle:h,inlineRating:g})}),s},t),a=typeof e.url=="function"?e.url():"https://www.google.com/";return n.flatMap(i=>{let s=Ue(i.url,a);if(!s)return[];let o=i.domain;try{o=new URL(s.resolvedUrl??s.rawUrl).hostname.replace(/^www\./,"")}catch{}return[{...i,...s,domain:o}]})}async function Mo(e){let t=Ds;return e.evaluate(n=>{let a=[],i=null;return document.querySelectorAll('[role="heading"]').forEach(s=>{!i&&s.textContent?.includes(n.headingText)&&(i=s.closest("[data-hveid]"))}),i&&i.querySelectorAll(n.card).forEach((s,o)=>{let d=s.querySelector(n.name)?.textContent?.trim()??"";if(!d)return;let S=s.querySelector(n.ratingValue)?.textContent?.trim()??null,U=s.querySelector(n.reviewCount)?.textContent?.trim()??null,c=U?U.replace(/[()]/g,"").trim():null,r=s.querySelector("a[data-cid]")?.getAttribute("data-cid")??null;if(!r)for(let g of Array.from(s.querySelectorAll("a[href]"))){let C=g.href.match(/[?&]cid=(\d+)/);if(C){r=C[1];break}let y=g.href.match(/!1s0x[0-9a-f]+:0x([0-9a-f]+)/i);if(y){try{r=BigInt("0x"+y[1]).toString()}catch{}if(r)break}}let l=[];s.querySelectorAll("div, span").forEach(g=>{let C=Array.from(g.childNodes).filter(y=>y.nodeType===3).map(y=>y.textContent?.trim()??"").filter(y=>y.length>1&&y.length<120).join(" ");C&&!l.includes(C)&&l.push(C)});let u=Array.from(s.querySelectorAll("a[href]")),h=u.find(g=>g.href.includes("google.com/maps"))?.href??null,w=u.find(g=>!g.href.includes("google.com")&&g.href.startsWith("http"))?.href??null;a.push({position:o+1,name:d,cid:r,rating:S,reviewCount:c,metadata:l,websiteUrl:w,directionsUrl:h})}),a},t)}async function vo(e){return e.evaluate(()=>{let t=new Set,n=new Set,a=new Set,i=new Map;function s(d){let S=[".OSrXXb",".dbg0pd",".tzt0oe",'[role="heading"]',"h3"];for(let U of S){let c=d.querySelector(U);if(c?.textContent?.trim())return c.textContent.trim()}return""}document.querySelectorAll('[id^="pv-/g/"]').forEach(d=>{let S=d.getAttribute("id");if(!S)return;let U=S.replace("pv-","");t.add(U);let c=s(d),l=d.querySelector("a[data-cid]")?.getAttribute("data-cid")??null;l&&n.add(l),c&&i.set(U,{name:c,kgId:U,cid:l,gcid:null})}),document.querySelectorAll("[data-mid]").forEach(d=>{let S=d.getAttribute("data-mid");if(S?.startsWith("/g/")&&(t.add(S),!i.has(S))){let U=s(d);U&&i.set(S,{name:U,kgId:S,cid:null,gcid:null})}}),document.querySelectorAll(".w7Dbne").forEach(d=>{let U=d.querySelector("a[data-cid]")?.getAttribute("data-cid")??null;if(!U)return;n.add(U);let c=d.querySelector(".OSrXXb")?.textContent?.trim()??"";if(!c)return;let r=d.querySelector('[id^="pv-/g/"]'),l=r?r.getAttribute("id").replace("pv-",""):null,u=l??`cid:${U}`;if(i.has(u)){let h=i.get(u);h.cid||i.set(u,{...h,cid:U})}else i.set(u,{name:c,kgId:l,cid:U,gcid:null})}),document.querySelectorAll("a[data-cid]").forEach(d=>{let S=d.getAttribute("data-cid");if(!S)return;if(n.add(S),![...i.values()].some(c=>c.cid===S)){let c=d.parentElement,r="";for(let l=0;l<8&&c;l++){let u=c.querySelector('.OSrXXb, .dbg0pd, [role="heading"], h3');if(u?.textContent?.trim()){r=u.textContent.trim();break}c=c.parentElement}r&&i.set(`cid:${S}`,{name:r,kgId:null,cid:S,gcid:null})}});let o=Array.from(document.querySelectorAll("script:not([src])")).map(d=>d.textContent??"").filter(d=>d.length>1e4).join(`
21786
+ `);for(let d of o.matchAll(/\/g\/[a-zA-Z0-9_-]{5,20}/g))t.add(d[0]);for(let d of o.matchAll(/gcid:[a-zA-Z0-9_]+/g))a.add(d[0]);for(let d of o.matchAll(/0x[0-9a-f]+:0x([0-9a-f]+)/gi))try{n.add(BigInt("0x"+d[1]).toString())}catch{}return{entities:[...i.values()],kgIds:[...t],cids:[...n],gcids:[...a]}})}function To(e,t){let n=new Set(e.cids),a=e.entities.map(i=>({...i}));for(let i of t){if(!i.cid)continue;n.add(i.cid);let s=i.name.toLowerCase().trim(),o=a.find(d=>d.name.toLowerCase().trim()===s);o?o.cid||(o.cid=i.cid):a.find(d=>d.cid===i.cid)||a.push({name:i.name,kgId:null,cid:i.cid,gcid:null})}return{...e,entities:a,cids:[...n]}}var bo=String.raw`^(?:an error has occurred(?:[.!…]\s*)?(?:please try again later[.!…]?)?|loading|please wait|try again|something went wrong)[.!…\s]*$`,Jl=700,ql=1e3,No=1400,Po=2e3,zl=4,Io=250,Gn=class{constructor(t,n,a,i){this.driver=t;this.reporter=n;this.onPaaProgress=a;this.onProviderSession=i}driver;reporter;onPaaProgress;onProviderSession;completeness={paaWithoutAnswer:0,paaWithoutSource:0,paaAnswersRecovered:0,aioShareCaptured:null};aioShareUrlEarly=null;linkDiagnostics=this.emptyLinkDiagnostics();collectedRows=[];partialContext=null;progressSequence=0;clickedQuestions=new Set;paaLifecycle=this.emptyPaaLifecycle(0);checkpointMaterial=null;interactionObservations=[];phaseTimings={};currentPhaseTimings(t){return{...this.phaseTimings,totalServerMs:Math.max(0,Date.now()-t)}}emptyPaaLifecycle(t){return{requestedQuestions:t,questionsFound:0,targetStatus:"not_met",discoveryStatus:"in_progress",materialStatus:"partial",completionReason:"PAA expansion is still running.",automaticRetries:0,retryBreakdown:{controlRetries:0,browserRetries:0,providerFallbacks:0,runtimeRecoveries:0,idempotentReplays:0},knownQuestions:0,processedQuestions:0,failedInteractions:0,noGrowthConfirmations:0,visibleControls:0,eligibleControls:0,dispatchedInteractions:0,confirmedInteractions:0,unconfirmedInteractions:0}}emptyLinkDiagnostics(){return{linkCandidatesObserved:0,plainLinksObserved:0,googleUrlRedirectsObserved:0,googleGotoRedirectsObserved:0,redirectsResolved:0,redirectsUnresolved:0,redirectsRejected:0,resolverNonGoogleRequestsObserved:0,paaSourcesPreserved:0,aiOverviewLabelValidated:!1}}mergePaaSources(t=[],n=[]){let a=new Map;for(let i of[...t,...n]){let s=a.get(i.rawUrl);if(!s){a.set(i.rawUrl,i);continue}let o=i.resolutionStatus==="resolved"&&s.resolutionStatus!=="resolved"?i:s,d=i.description?.trim()&&!s.description?.trim()?i:s.description?.trim()?s:o;a.set(i.rawUrl,{...o,title:d.title??o.title??s.title??i.title,site:o.site??s.site??i.site,...(d.description??s.description??i.description)!==void 0?{description:d.description??s.description??i.description}:{}})}return[...a.values()]}normalizeAICitations(t,n){let a=new Set;return n.flatMap(i=>{let s=Ue(i.rawHref??i.href,t);if(!s||a.has(s.rawUrl))return[];a.add(s.rawUrl);let{url:o,...d}=s;return[{...d,text:i.text,href:o}]})}async resolveMaterialLinks(t,n,a,i,s){let o=Date.now(),d=[...n.flatMap(h=>h.sources??[]),...a,...i.citations.map(({text:h,href:w,...g})=>({...g,url:w})),...s.citations.map(({text:h,href:w,...g})=>({...g,url:w}))],S=new Map(d.map(h=>[h.rawUrl,h])),U=0,c=await po(t,d,{onNetworkAudit:h=>{U=h.nonGoogleRequestsObserved}}),r=h=>({...h,...c.get(h.rawUrl)??h});for(let h of n){h.sources=(h.sources??[]).map(r);let w=h.sources[0];h.source_title=w?.title??h.source_title,h.source_site=w?.site??h.source_site,h.source_cite=w?.url??h.source_cite}for(let h=0;h<a.length;h++){let w=r(a[h]);if(w.resolvedUrl)try{w.domain=new URL(w.resolvedUrl).hostname.replace(/^www\./,"")}catch{}a[h]=w}let l=h=>{let w=r({url:h.href,rawUrl:h.rawUrl,resolvedUrl:h.resolvedUrl,linkType:h.linkType,resolutionStatus:h.resolutionStatus}),{url:g,...C}=w;return{...C,text:h.text,href:g}};i.citations=i.citations.map(l),s.citations=s.citations.map(l);let u=[...c.values()];this.linkDiagnostics={linkCandidatesObserved:S.size,plainLinksObserved:u.filter(h=>h.linkType==="plain").length,googleUrlRedirectsObserved:u.filter(h=>h.linkType==="google_url_redirect").length,googleGotoRedirectsObserved:u.filter(h=>h.linkType==="google_goto_redirect").length,redirectsResolved:u.filter(h=>h.linkType!=="plain"&&h.resolutionStatus==="resolved").length,redirectsUnresolved:u.filter(h=>h.resolutionStatus==="unresolved").length,redirectsRejected:u.filter(h=>h.resolutionStatus==="rejected").length,resolverNonGoogleRequestsObserved:U,paaSourcesPreserved:n.reduce((h,w)=>h+(w.sources??[]).length,0),aiOverviewLabelValidated:i.detected},this.phaseTimings.linkResolutionMs=(this.phaseTimings.linkResolutionMs??0)+(Date.now()-o)}normalizeQuestion(t){return t.toLowerCase().replace(/[^\w\s]/g,"").replace(/\s+/g," ").trim()}throwIfAborted(t){if(t?.aborted)throw t.reason instanceof DOMException&&t.reason.name==="TimeoutError"?t.reason:new ut}async throwIfCaptcha(t,n){if(await t.locator(Z.captchaMarker).count().catch(()=>0)>0)throw new et(`${n} returned a CAPTCHA \u2014 retrying with a fresh session.`)}async extractVisibleItems(t,n){let a=await t.evaluate(le,{selectors:Z,onlyQuestion:n}),i=typeof t.url=="function"?t.url():"https://www.google.com/";return this.mapPaaDomRecords(a,i)}mapPaaDomRecords(t,n){return t.flatMap(a=>{let i=[],s=new Set;for(let U of a.sources){let c=Ue(U.rawHref,n);if(!c||s.has(c.rawUrl))continue;s.add(c.rawUrl);let r=a.sourceSite??null;try{r||=new URL(c.resolvedUrl??c.rawUrl).hostname.replace(/^www\./,"")}catch{}i.push({...c,title:U.title||a.sourceTitle||null,site:r,...U.description?{description:U.description}:{}})}let o=i[0],d={questionId:Se(a.question),googleLinkId:a.googleLinkId,googleEvidenceId:a.googleEvidenceId,question:a.question,answer:Sn(a.answer,a.question),sourceTitle:o?.title??a.sourceTitle,sourceSite:o?.site??a.sourceSite,sourceCite:o?.url,sources:i,...a.answerExpansionIncomplete?{answerExpansionIncomplete:!0}:{}},S=ki.safeParse(d);return S.success?[S.data]:(console.warn("[PAAExtractor] item parse failed:",a.question,S.error.issues[0]?.message),[])})}jitteredDelayMs(t,n){return t+Math.floor(Math.random()*(n-t+1))}async clickItem(t,n){try{await t.locator(`${Z.item}[data-q="${n}"], ${Z.item}[data-initq="${n}"]`).first().click()}catch{}}toFlatRow(t,n,a,i){return{seed_query:i,question_id:t.questionId??Se(t.question),google_link_id:t.googleLinkId??"",google_evidence_id:t.googleEvidenceId??"",question:t.question,answer:t.answer??"",...t.answerExpansionIncomplete?{answerExpansionIncomplete:!0}:{},source_title:t.sourceTitle??"",source_site:t.sourceSite??"",source_cite:t.sourceCite??"",sources:t.sources??[],depth:n,parent_question:a??"",extracted_at:new Date().toISOString()}}upsertCollectedRow(t){let n=this.normalizeQuestion(t.question),a=this.collectedRows.findIndex(d=>this.normalizeQuestion(d.question)===n);if(a<0)return this.collectedRows.push({...t}),!0;let i=this.collectedRows[a],s={...i,...t,answer:t.answer||i.answer,answerExpansionIncomplete:t.answer?t.answerExpansionIncomplete:i.answerExpansionIncomplete,source_title:t.source_title||i.source_title,source_site:t.source_site||i.source_site,source_cite:t.source_cite||i.source_cite,sources:this.mergePaaSources(i.sources,t.sources),extracted_at:t.extracted_at||i.extracted_at},o=s.answerExpansionIncomplete!==i.answerExpansionIncomplete||s.answer!==i.answer||s.source_title!==i.source_title||s.source_site!==i.source_site||s.source_cite!==i.source_cite||JSON.stringify(s.sources)!==JSON.stringify(i.sources);return o&&(this.collectedRows[a]=s),o}async emitProgress(t){if(!this.onPaaProgress||this.collectedRows.length===0&&!this.checkpointMaterial)return;let n={sequence:++this.progressSequence,observedAt:new Date().toISOString(),clickedQuestions:[...this.clickedQuestions],phase:t,records:this.collectedRows.map(a=>({...a})),lifecycle:{...this.paaLifecycle},...this.checkpointMaterial?{material:structuredClone(this.checkpointMaterial)}:{},interactions:this.interactionObservations.map(a=>({...a,confirmationSignals:[...a.confirmationSignals]}))};try{await this.onPaaProgress(n)}catch(a){console.warn(JSON.stringify({event:"paa_progress_sink_failed",sequence:n.sequence,phase:n.phase,message:a instanceof Error?a.message:String(a)}))}}getPartialResult(){let t=this.partialContext;if(!t||this.collectedRows.length===0&&!this.checkpointMaterial)return null;let n=this.collectedRows.map(S=>({...S})),a=this.checkpointMaterial,i=t.questionsOnly?0:n.filter(S=>!S.answer?.trim()).length,s=t.questionsOnly?0:n.filter(S=>(S.sources??[]).length===0).length,o=t.questionsOnly?0:n.filter(S=>S.answerExpansionIncomplete).length,d={seed:t.seed,totalQuestions:n.length,maxDepthReached:n.reduce((S,U)=>Math.max(S,U.depth),0),durationMs:Date.now()-t.startMs,errorCount:0};return{seed:t.seed,location:t.location,extractedAt:new Date().toISOString(),diagnostics:{phaseTimings:this.currentPhaseTimings(t.startMs),completionStatus:"paa_found",problem:null,...a?.pagination?{pagination:{...a.pagination}}:{},resultQuality:"partial",degradedResult:!1,retryRecommended:!0,paaLifecycle:{...this.paaLifecycle,questionsFound:n.length,targetStatus:n.length>=(t.maxQuestions??0)?"met":"not_met",discoveryStatus:"interrupted",materialStatus:i>0||s>0||o>0?"partial":"complete",completionReason:"The browser attempt ended before frontier exhaustion could be proven."},completeness:{...this.completeness,paaWithoutAnswer:i,paaWithoutSource:s,paaIncompleteAnswers:o,paaRequested:t.maxQuestions,paaReturned:n.length,paaUnique:n.length},warnings:[{code:"paa_partial",surface:"paa",message:`Harvest stopped before finishing; returning the ${n.length} question(s) collected up to that point.`,retryable:!0}]},totalQuestions:n.length,surface:a?.surface??"web",aiOverview:a?.aiOverview??{detected:!1,text:null,citations:[]},aiMode:a?.aiMode??{detected:!1,text:null,citations:[]},whatPeopleSaying:a?.whatPeopleSaying??[],tree:this.buildTree(n,t.seed),flat:n,videos:a?.videos??[],forums:a?.forums??[],organicResults:a?.organicResults??[],localPack:a?.localPack??[],entityIds:a?.entityIds??{entities:[],kgIds:[],cids:[],gcids:[]},stats:d}}async runBFS(t,n,a){await t.waitForTimeout(700);let i=new Set,s=new Set,o=[];this.clickedQuestions=new Set,this.interactionObservations=[];let d=new Set,S=new Map,U=new Set,c=new Set,r=new Map,l=new Set,u=2,h=3,w=0,g=Promise.resolve(),C=k=>{let A=g.then(()=>{if(this.throwIfAborted(a),n.softDeadlineMs&&Date.now()>=n.softDeadlineMs)throw new Ot("The execution deadline arrived before the next PAA interaction.");return k()});return g=A.then(()=>{},()=>{}),A},y={sel:Z.item,dataQ:Z.itemDataQ,dataInitQ:Z.itemDataInitQ,questionEl:Z.itemQuestionEl,answerSel:Z.answerContainer,expandedClass:Z.expandedClass,clickTarget:Z.clickTarget,answerPlaceholderPattern:bo,questionsOnly:n.questionsOnly},m=()=>t.evaluate(({sel:k,dataQ:A,dataInitQ:T,questionEl:M,expandedClass:q,clickTarget:P,answerSel:G,answerPlaceholderPattern:v,questionsOnly:R})=>{let f=x=>{if(!x)return"";let D=[];for(let H of x.childNodes){if(H.nodeType===Node.TEXT_NODE){let tt=H.textContent?.trim();tt&&D.push(tt);continue}if(H.nodeType!==Node.ELEMENT_NODE)continue;let X=H;if(X.tagName==="STYLE"||X.tagName==="SCRIPT"||X.getAttribute("aria-hidden")==="true")continue;let E=f(X);E&&D.push(E)}return D.join(" ").replace(/\s+/g," ").trim()};return Array.from(document.querySelectorAll(k)).map((x,D)=>{let H=f(x.querySelector(G)).replace(/An AI Overview is not available for this search/gi," ").replace(/Can't generate an AI overview right now\.?\s*Try again later\.?/gi," ").replace(/\bAI Overview\b/gi," ").replace(/\s+/g," ").trim(),X=x.classList.contains(q)||x.querySelector(P)?.getAttribute("aria-expanded")==="true",E=H.length>=10&&!new RegExp(v,"i").test(H);return{q:(x.getAttribute(A)||x.getAttribute(T)||x.querySelector(M)?.innerText?.trim()||"").replace(/\s+/g," ").trim(),done:X&&(R||E),expanded:X,index:D,answerReady:E,sourceCount:E?x.querySelector(G)?.querySelectorAll("a[href]").length??0:0}}).filter(x=>x.q)},y),O=async(k,A,T,M,q,P,G)=>{let v=Date.now(),R={id:`${G}:${Se(k)}:${P}`,questionId:Se(k),question:k,batchNumber:G,controlAttempt:P,observedAt:new Date(v).toISOString(),beforeQuestionCount:A,expandedBefore:M},f=T>=0?t.locator(y.sel).nth(T).locator(y.clickTarget):null,x=null,D=await C(async()=>(v=Date.now(),R.observedAt=new Date(v).toISOString(),f?(M&&(await f.click({timeout:Po,force:!0,noWaitAfter:!0}),await t.waitForTimeout(120)),await f.click({timeout:Po,force:!0,noWaitAfter:!0}),!0):!1)).catch(E=>(x=E instanceof Error&&(E.name==="TimeoutError"||/timeout/i.test(E.message))?"click_ack_timeout":"click_failed",!1)),H=Date.now()-v,X={...R,dispatched:D,outcome:D?"unconfirmed":"dispatch_failed",confirmationSignals:[],confirmationCheckpointMs:null,confirmedAtMs:null,dispatchDurationMs:H,totalDurationMs:H,afterQuestionCount:A,newQuestionCount:0,expandedAfter:M,answerObserved:!1,sourceCount:0,errorCode:T<0?"control_missing":x};return{clickStartedMs:v,dispatched:D,confirmed:!1,hadMaterialBefore:q,observation:X}},F=async k=>{let A=null,T=k.filter(M=>M.dispatched||M.observation.errorCode==="click_ack_timeout");for(let M of[Jl,ql,No]){if(!T.length)break;let q=Math.min(...T.map(v=>v.clickStartedMs+M-Date.now()));q>0&&await t.waitForTimeout(q);let P=n.questionsOnly?await m().catch(()=>null):await t.evaluate(le,{selectors:Z}).catch(()=>null);P&&!n.questionsOnly&&(A=P);let G=P?.length;for(let v of T){let R=v.observation;if(P){let f=n.questionsOnly?P.find(E=>E.q===R.question):P.find(E=>E.question===R.question),x=!1,D=0;if(f)if("q"in f)x=f.answerReady,D=f.sourceCount;else{let E=Sn(f.answer,f.question);x=!!(E&&E.length>=10&&!new RegExp(bo,"i").test(E)),D=x?f.sources.length:0}R.afterQuestionCount=G??R.beforeQuestionCount,R.newQuestionCount=Math.max(0,R.afterQuestionCount-R.beforeQuestionCount),R.expandedAfter=f?.expanded??!1,R.answerObserved=x,R.sourceCount=x?D:0,R.confirmationSignals=[...R.expandedAfter?["expanded"]:[],...x?["answer"]:[],...R.sourceCount>0?["source"]:[],...R.newQuestionCount>0?["question_growth"]:[]];let H=!!(f?.expanded&&!R.expandedBefore);((x||R.sourceCount>0)&&(!v.hadMaterialBefore||v.dispatched||H)||R.newQuestionCount>0&&(v.dispatched||H))&&(v.confirmed=!0,R.outcome="confirmed",R.confirmationCheckpointMs=M,R.confirmedAtMs=Date.now()-v.clickStartedMs),v.dispatched&&(R.errorCode=v.confirmed?null:f?"confirmation_timeout":"control_missing")}R.totalDurationMs=Date.now()-v.clickStartedMs}T=T.filter(v=>!v.confirmed&&Date.now()-v.clickStartedMs<No)}for(let M of k)M.dispatched&&!M.confirmed&&M.observation.errorCode===null&&(M.observation.errorCode="confirmation_timeout");return A},B=null,I=0;t:for(;;){if(n.softDeadlineMs&&Date.now()>=n.softDeadlineMs)throw this.paaLifecycle={...this.paaLifecycle,discoveryStatus:"interrupted",completionReason:"The execution deadline arrived before frontier exhaustion could be proven."},new Ot(this.paaLifecycle.completionReason);this.throwIfAborted(a);let k=n.questionsOnly?null:B??await t.evaluate(le,{selectors:Z});B=null;let A=typeof t.url=="function"?t.url():"https://www.google.com/",T=k?k.map(f=>{let x=!!Sn(f.answer,f.question),D=x&&!f.answerExpansionIncomplete&&f.sources.some(H=>!!Ue(H.rawHref,A));return{q:f.question,done:D||f.expanded&&x,answerReady:x,expanded:f.expanded,index:f.itemIndex}}):await m(),M=!1;for(let f of T)s.has(f.q)||(s.add(f.q),o.push(f.q),o.length<=n.maxQuestions&&(M=this.upsertCollectedRow(this.toFlatRow({questionId:Se(f.q),googleLinkId:null,googleEvidenceId:null,question:f.q,sources:[]},1,null,n.query))||M)),f.done&&(U.has(f.q)||c.delete(f.q),U.add(f.q));if(this.paaLifecycle={...this.paaLifecycle,questionsFound:Math.min(o.length,n.maxQuestions),targetStatus:o.length>=n.maxQuestions?"met":"not_met",knownQuestions:o.length,processedQuestions:U.size,failedInteractions:c.size,visibleControls:T.length},M&&await this.emitProgress("discovered"),n.questionsOnly&&s.size>=n.maxQuestions){this.paaLifecycle={...this.paaLifecycle,discoveryStatus:"target_reached",targetStatus:"met",completionReason:"The requested unique-question count was observed."};break}if(!n.questionsOnly&&s.size>=n.maxQuestions){let f=!1,x=new Set(o.slice(0,n.maxQuestions)),D=this.mapPaaDomRecords(k??[],A),H=D.filter(E=>x.has(E.question)&&E.answerExpansionIncomplete&&!l.has(E.question)),X;await Promise.allSettled(H.map(async E=>{l.add(E.question);try{await za(t,E.question,{selectors:Z,deadlineMs:n.softDeadlineMs,signal:a,allowOuterReopen:!d.has(E.question),dispatchClick:C},le)}catch(tt){X??={reason:tt}}})),H.length&&(D=await this.extractVisibleItems(t).catch(E=>{if(X)return D;throw E}));for(let E of D){if(!x.has(E.question))continue;let tt=r.get(E.question),$={...E,answer:E.answer||tt?.answer,answerExpansionIncomplete:E.answer?E.answerExpansionIncomplete:tt?.answerExpansionIncomplete,sourceTitle:E.sourceTitle??tt?.sourceTitle,sourceSite:E.sourceSite??tt?.sourceSite,sourceCite:E.sourceCite??tt?.sourceCite,sources:this.mergePaaSources(tt?.sources,E.sources)};r.set(E.question,$),f=this.upsertCollectedRow(this.toFlatRow($,1,null,n.query))||f}if(f&&await this.emitProgress("answer_captured"),X)throw X.reason;if([...x].every(E=>{let tt=r.get(E);return!!(tt?.answer?.trim()&&tt.sources.length>0&&!tt.answerExpansionIncomplete)})){c.clear(),this.paaLifecycle={...this.paaLifecycle,discoveryStatus:"target_reached",targetStatus:"met",failedInteractions:0,completionReason:"The requested unique-question count and its answer/source material were observed."};break}}let q=new Set(o.slice(0,n.maxQuestions)),P=T.filter(f=>q.has(f.q)&&(!f.done||s.size<n.maxQuestions&&!this.clickedQuestions.has(f.q))&&(S.get(f.q)??0)<u&&!d.has(f.q)),G=P.slice(-zl);if(this.paaLifecycle={...this.paaLifecycle,eligibleControls:P.length},G.length===0){if(s.size>=n.maxQuestions){this.paaLifecycle={...this.paaLifecycle,discoveryStatus:"target_reached",targetStatus:"met",completionReason:"The requested unique-question count was observed."};break}let f=new Set(T.map(D=>D.q)),x=o.slice(0,n.maxQuestions).filter(D=>c.has(D)||!U.has(D)&&!f.has(D));if(x.length>0)throw this.paaLifecycle={...this.paaLifecycle,discoveryStatus:"interrupted",failedInteractions:new Set([...c,...x]).size,completionReason:"At least one known PAA control failed or disappeared before it could be confirmed."},await this.emitProgress("expansion_finished"),new Ot(this.paaLifecycle.completionReason);for(let D=1;D<=h;D++){this.throwIfAborted(a),await this.throwIfCaptcha(t,"Google PAA exhaustion confirmation"),await t.mouse.wheel(0,320);let H=await t.waitForFunction(({sel:E,min:tt})=>document.querySelectorAll(E).length>tt,{sel:Z.item,min:T.length},{timeout:1500,polling:100}).catch(()=>null);if(this.paaLifecycle={...this.paaLifecycle,noGrowthConfirmations:D},H||(await m()).some(E=>!s.has(E.q)))continue t}this.paaLifecycle={...this.paaLifecycle,discoveryStatus:"frontier_exhausted",targetStatus:"not_met",failedInteractions:0,noGrowthConfirmations:h,completionReason:"Every known eligible PAA control was processed and three healthy no-growth confirmations found no additional questions."};break}await this.throwIfCaptcha(t,"Google PAA expansion"),w+=1;for(let f of G){if(this.reporter.onDepth(++I),(S.get(f.q)??0)>0){let x=this.paaLifecycle.retryBreakdown.controlRetries+1;this.paaLifecycle={...this.paaLifecycle,automaticRetries:x+this.paaLifecycle.retryBreakdown.browserRetries+this.paaLifecycle.retryBreakdown.runtimeRecoveries,retryBreakdown:{...this.paaLifecycle.retryBreakdown,controlRetries:x}}}S.set(f.q,(S.get(f.q)??0)+1)}let v=[];for(let f of G)v.push({target:f,result:await O(f.q,T.length,f.index,f.expanded,f.answerReady,S.get(f.q)??1,w)});let R=await F(v.map(({result:f})=>f));for(let{target:f,result:x}of v)(x.dispatched||x.confirmed)&&this.clickedQuestions.add(f.q),this.interactionObservations.push(x.observation);if(this.interactionObservations.length>Io&&this.interactionObservations.splice(0,this.interactionObservations.length-Io),!n.questionsOnly){let f=new Set(G.map(D=>D.q)),x=R??await t.evaluate(le,{selectors:Z});for(let D of this.mapPaaDomRecords(x,typeof t.url=="function"?t.url():"https://www.google.com/"))f.has(D.question)&&(r.set(D.question,D),this.upsertCollectedRow(this.toFlatRow(D,1,null,n.query))&&await this.emitProgress("answer_captured"));o.length>=n.maxQuestions&&o.slice(0,n.maxQuestions).every(D=>{let H=x.find(X=>X.question===D);return!!(H&&Sn(H.answer,H.question)&&!H.answerExpansionIncomplete&&H.sources.some(X=>Ue(X.rawHref,A)))})&&(B=x)}for(let{target:f,result:x}of v){x.observation.errorCode==="click_ack_timeout"&&d.add(f.q);let D=r.get(f.q);x.confirmed||D?.answer?.trim()&&(!x.hadMaterialBefore||x.dispatched)?(U.add(f.q),c.delete(f.q)):(x.observation.errorCode==="click_ack_timeout"||(S.get(f.q)??0)>=u)&&(c.add(f.q),d.add(f.q))}this.paaLifecycle={...this.paaLifecycle,processedQuestions:U.size,failedInteractions:c.size,noGrowthConfirmations:0,dispatchedInteractions:this.interactionObservations.filter(f=>f.dispatched).length,confirmedInteractions:this.interactionObservations.filter(f=>f.outcome==="confirmed").length,unconfirmedInteractions:this.interactionObservations.filter(f=>f.outcome!=="confirmed").length},await this.emitProgress("click_observed")}let K=n.questionsOnly?new Map:new Map(r);n.questionsOnly||await this.fillIncompleteItems(t,o,K,n,d,a);let _=[];for(let k of o){if(_.length>=n.maxQuestions)break;let A=this.normalizeQuestion(k);if(i.has(A))continue;i.add(A);let T=K.get(k);if(T){let M=this.toFlatRow(T,1,null,n.query);this.upsertCollectedRow(M),_.push(M),this.reporter.onQuestion({questionId:T.questionId,googleLinkId:T.googleLinkId,googleEvidenceId:T.googleEvidenceId,question:T.question,answer:T.answer??null,sourceTitle:T.sourceTitle??null,sourceSite:T.sourceSite??null,sourceCite:T.sourceCite??null,sources:T.sources,...T.answerExpansionIncomplete?{answerExpansionIncomplete:!0}:{},depth:1,parentQuestion:null,children:[]})}else{let M=this.toFlatRow({questionId:Se(k),googleLinkId:null,googleEvidenceId:null,question:k,answer:void 0,sourceTitle:void 0,sourceSite:void 0,sourceCite:void 0,sources:[]},1,null,n.query);this.upsertCollectedRow(M),_.push(M)}}this.completeness.paaWithoutAnswer=n.questionsOnly?0:_.filter(k=>!k.answer).length,this.completeness.paaWithoutSource=n.questionsOnly?0:_.filter(k=>(k.sources??[]).length===0).length,this.completeness.paaIncompleteAnswers=n.questionsOnly?0:_.filter(k=>k.answerExpansionIncomplete).length,this.completeness.paaRequested=n.maxQuestions,this.completeness.paaReturned=_.length,this.completeness.paaUnique=i.size;let b=!n.questionsOnly&&(this.completeness.paaWithoutAnswer>0||this.completeness.paaWithoutSource>0||this.completeness.paaIncompleteAnswers>0);return this.paaLifecycle={...this.paaLifecycle,questionsFound:_.length,targetStatus:_.length>=n.maxQuestions?"met":"not_met",materialStatus:b?"partial":"complete",processedQuestions:U.size,failedInteractions:c.size},await this.emitProgress("fill_incomplete"),await this.emitProgress("expansion_finished"),_}async fillIncompleteItems(t,n,a,i,s,o){let d=new Set(n.slice(0,i.maxQuestions)),S=r=>!r?.answer||(r.sources??[]).length===0||!!r.answerExpansionIncomplete,U=new Set([...d].filter(r=>S(a.get(r)))),c=new Set([...U].filter(r=>!a.get(r)?.answer));if(U.size!==0){for(let r of U){if(i.softDeadlineMs&&Date.now()>=i.softDeadlineMs)break;let l=(await this.extractVisibleItems(t,r))[0];if(l?.answerExpansionIncomplete&&(await za(t,r,{selectors:Z,deadlineMs:i.softDeadlineMs,signal:o,allowOuterReopen:!s?.has(r)},le),l=(await this.extractVisibleItems(t,r))[0]),!l)continue;let u=a.get(r);a.set(r,{...l,answer:l.answer||u?.answer,answerExpansionIncomplete:l.answer?l.answerExpansionIncomplete:u?.answerExpansionIncomplete,sourceTitle:l.sourceTitle??u?.sourceTitle,sourceSite:l.sourceSite??u?.sourceSite,sourceCite:l.sourceCite??u?.sourceCite,sources:this.mergePaaSources(u?.sources,l.sources)});let h=a.get(r);h&&this.upsertCollectedRow(this.toFlatRow(h,1,null,i.query))&&await this.emitProgress("fill_incomplete")}this.completeness.paaAnswersRecovered=[...c].filter(r=>a.get(r)?.answer).length}}async reExpandCollapsedItems(t){let n=`${Z.item}:not(.${Z.expandedClass}) ${Z.clickTarget}`,a=await t.locator(n).count().catch(()=>0);if(a===0)return!1;for(let i=0;i<a;i++)try{let s=t.locator(n).first();await s.scrollIntoViewIfNeeded(),await s.click({force:!0}),await t.waitForTimeout(this.jitteredDelayMs(300,500))}catch{}return!0}extractVideos(t){return yo(t)}extractForums(t){return mo(t)}extractShortVideos(t,n){return Co(t,n,(a,i)=>this.throwIfCaptcha(a,i))}extractWhatPeopleSaying(t){return fo(t)}extractOrganicResults(t){return ko(t)}extractLocalPack(t){return Mo(t)}extractEntityIds(t){return vo(t)}mergeLocalPackIntoEntities(t,n){return To(t,n)}async extractAISurfaces(t,n){let a=await t.evaluate(ro,{aio:Es,aim:Hs,expandWaitMs:1500}),i=typeof t.url=="function"?t.url():"https://www.google.com/",s={surface:a.surface,aiOverview:{...a.aiOverview,citations:this.normalizeAICitations(i,a.aiOverview.citations)},aiMode:{...a.aiMode,citations:this.normalizeAICitations(i,a.aiMode.citations)}};if(!s.aiOverview.detected)return this.completeness.aioShareCaptured=null,s;let o=this.aioShareUrlEarly??await this.captureAIOverviewShareUrl(t,n).catch(()=>null);return this.completeness.aioShareCaptured=o!==null,{...s,aiOverview:{...s.aiOverview,shareUrl:o}}}async captureAIOverviewShareUrl(t,n){if(n?.softDeadlineMs&&Date.now()>=n.softDeadlineMs||!await t.evaluate(()=>{let s=Array.from(document.querySelectorAll('h1,h2,h3,[role="heading"],div')).filter(o=>(o.textContent||"").trim()==="AI Overview");for(let o of s){let d=o;for(let S=0;S<8&&d;S++){let U=d.querySelector('[aria-label="Share"]');if(U)return U.scrollIntoView({block:"center"}),U.click(),!0;d=d.parentElement}}return!1}).catch(()=>!1))return null;let i=null;try{i=await(await t.waitForFunction(()=>{let o=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);for(;o.nextNode();){let d=(o.currentNode.textContent||"").match(/https:\/\/share\.google\/aimode\/\S+/);if(d)return d[0]}return!1},void 0,{timeout:4500,polling:250})).jsonValue()}catch{i=null}return await t.keyboard.press("Escape").catch(()=>{}),i}buildTree(t,n){let a=[],i=new Map;for(let s of t){let o={questionId:s.question_id,googleLinkId:s.google_link_id||null,googleEvidenceId:s.google_evidence_id||null,question:s.question,answer:s.answer||null,...s.answerExpansionIncomplete?{answerExpansionIncomplete:!0}:{},sourceTitle:s.source_title||null,sourceSite:s.source_site||null,sourceCite:s.source_cite||null,sources:s.sources??[],depth:s.depth,parentQuestion:s.parent_question||null,children:[]};i.set(s.question,o)}for(let s of i.values())s.parentQuestion&&i.has(s.parentQuestion)?i.get(s.parentQuestion).children.push(s):a.push(s);return a}getBrowserDebugSnapshot(){return this.driver.getDebugSnapshot()}buildHarvestDebugSnapshot(t,n,a,i,s){if(t.debug)return{enabled:!0,request:{query:t.query,locationInput:t.location??null,canonicalLocation:n,locationResolved:s?s.matched:null,locationMatchSource:s?s.source:null,locationAmbiguousCandidates:s?s.ambiguousCandidates:null,uule:a,gl:t.gl,hl:t.hl,device:t.device,proxyMode:t.proxyMode,proxyZip:t.proxyZip??null,serpIdentity:t.serpIdentity??null,serpOnly:t.serpOnly,pages:t.pages??1},browser:this.getBrowserDebugSnapshot(),...i?{locationEvidence:i}:{}}}async captureSecondOrganicPage(t,n,a){if(this.throwIfAborted(a),!n.serpOnly&&!this.driver.withTemporaryPage)return{organic:[],status:"failed",failureCode:"unsupported_driver"};let i;try{let s=new URL(t.url()),o=U=>{try{let c=new URL(U,s);return s.origin==="https://www.google.com"&&c.origin===s.origin&&!c.username&&!c.password&&c.pathname==="/search"&&c.searchParams.getAll("q").length===1&&c.searchParams.get("q")===n.query&&c.searchParams.getAll("start").length===1&&c.searchParams.get("start")==="10"&&(!c.searchParams.has("num")||c.searchParams.get("num")==="10")&&["gl","hl"].every(r=>!c.searchParams.has(r)||c.searchParams.getAll(r).length===1&&c.searchParams.get(r)===n[r])&&["uule","tbs","udm","tbm","pws"].every(r=>c.searchParams.getAll(r).length<=1&&c.searchParams.get(r)===s.searchParams.get(r))}catch{return!1}},d=await t.evaluate(U=>document.querySelector(U?'a[aria-label="Page 2"], a#pnnext, a[rel="next"]':'a#pnnext, a[rel="next"]')?.getAttribute("href")??null,n.serpOnly);if(!d)return{organic:[],status:"unavailable",failureCode:"missing_next"};if(!o(d))return{organic:[],status:"unavailable",failureCode:"invalid_next"};if(n.serpOnly){let U=t.locator('a[aria-label="Page 2"], a#pnnext, a[rel="next"]').first();if(await U.scrollIntoViewIfNeeded({timeout:1e4}),await U.click({timeout:2e4}),this.throwIfAborted(a),await this.throwIfCaptcha(t,"Google SERP page 2"),!o(t.url()))throw i="invalid_next",new Error("Invalid pagination landing");let c=await this.extractOrganicResults(t);return c.length>0?{organic:c.map(r=>({...r,position:r.position+10})),status:"captured"}:{organic:[],status:"unavailable",failureCode:"empty_page"}}let S=await this.driver.withTemporaryPage(async U=>{if(await U.route("**/*",async c=>{let r=c.request();r.isNavigationRequest()&&r.frame()===U.mainFrame()&&!o(r.url())?(i=/^https:\/\/www\.google\.com\/sorry(?:\/|\?)/.test(r.url())?"captcha":"invalid_next",await c.abort("blockedbyclient")):await c.fallback()}),await U.goto(new URL(d,s).href,{waitUntil:"domcontentloaded",timeout:2e4}),this.throwIfAborted(a),await this.throwIfCaptcha(U,"Google SERP page 2"),!o(U.url()))throw i="invalid_next",new Error("Invalid pagination landing");return this.extractOrganicResults(U)},a);return this.throwIfAborted(a),S.length>0?{organic:S.map(U=>({...U,position:U.position+10})),status:"captured"}:{organic:[],status:"unavailable",failureCode:"empty_page"}}catch(s){if(this.throwIfAborted(a),s instanceof ut)throw s;return{organic:[],status:"failed",failureCode:i??(s instanceof et?"captcha":s instanceof Error&&(s.name==="TimeoutError"||/timed? ?out/i.test(s.message))?"timeout":"navigation_error")}}}async extract(t,n){let a=Date.now();this.phaseTimings={},this.completeness={paaWithoutAnswer:0,paaWithoutSource:0,paaAnswersRecovered:0,aioShareCaptured:null},this.linkDiagnostics=this.emptyLinkDiagnostics(),this.aioShareUrlEarly=null,this.collectedRows=[],this.progressSequence=0,this.checkpointMaterial=null,this.clickedQuestions=new Set,this.paaLifecycle=this.emptyPaaLifecycle(t.maxQuestions),this.partialContext={seed:t.query,location:t.location??null,startMs:a,maxQuestions:t.maxQuestions,questionsOnly:t.questionsOnly};let i=t.device==="mobile",s={headless:t.headless,profileDir:t.profileDir,proxy:t.proxy,\u006b\u0065\u0072\u006e\u0065\u006cApiKey:t.\u006b\u0065\u0072\u006e\u0065\u006cApiKey,\u006b\u0065\u0072\u006e\u0065\u006cProxyId:t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId,\u006b\u0065\u0072\u006e\u0065\u006cProfileName:t.\u006b\u0065\u0072\u006e\u0065\u006cProfileName,\u006b\u0065\u0072\u006e\u0065\u006cProfileSaveChanges:t.\u006b\u0065\u0072\u006e\u0065\u006cProfileSaveChanges,\u006b\u0065\u0072\u006e\u0065\u006cStealth:t.\u006b\u0065\u0072\u006e\u0065\u006cStealth,\u006b\u0065\u0072\u006e\u0065\u006cProxyResolution:t.\u006b\u0065\u0072\u006e\u0065\u006cProxyResolution,proxyMode:t.proxyMode,keepDefaultProxy:t.keepDefaultProxy,requireUsEgress:t.requireUsEgress,viewport:i?{width:390,height:844}:{width:1280,height:800},locale:`${t.hl}-${t.gl.toUpperCase()}`,deviceScaleFactor:i?3:1,isMobile:i,hasTouch:i,debug:t.debug,operationDeadlineMs:t.softDeadlineMs},o=0,d=[];try{this.throwIfAborted(n);let S=Date.now();await this.driver.launch(s),this.phaseTimings.providerConnectMs=Date.now()-S;let U=this.driver.getProviderSessionMetadata();if(U?.providerSessionId&&this.onProviderSession)try{await this.onProviderSession(U)}catch($){console.warn(JSON.stringify({event:"paa_provider_session_sink_failed",provider:U.provider,message:$ instanceof Error?$.message:String($)}))}this.throwIfAborted(n);let c=t.location?Wa(t.location):null,r=t.location?c?.canonical??t.location:null,l=r?ks(r):null,u=t,h=t.includeAllSerpFeatures,w=h||t.includeLocalPack,g=h||t.includeForums,C=h||t.includeVideos,y=h||t.includeAiOverview,m=h||t.includeWhatPeopleSaying,O={surface:"web",aiOverview:{detected:!1,text:null,citations:[]},aiMode:{detected:!1,text:null,citations:[]}},F=Date.now(),{hasPaa:B}=await this.driver.navigateToSERP(u.query,l,t.gl,t.hl,{...ea(t.recency)?{tbs:ea(t.recency)}:{},debug:t.debug,purpose:t.serpOnly?"serp":"paa",pages:t.pages===2?2:1,...t.softDeadlineMs?{deadlineMs:t.softDeadlineMs}:{},...n?{signal:n}:{}});this.phaseTimings.navigationMs=Date.now()-F,this.throwIfAborted(n);let I=this.driver.getPage();if(await this.throwIfCaptcha(I,"Google SERP"),B||(this.paaLifecycle={...this.paaLifecycle,discoveryStatus:"no_paa_observed",materialStatus:"complete",completionReason:"A readable Google SERP was observed without a People Also Ask block."}),t.questionsOnly){let $=Date.now(),J=B?await this.runBFS(I,u,n):[];this.phaseTimings.paaExpansionMs=Date.now()-$,await this.resolveMaterialLinks(I,J,[],O.aiOverview,O.aiMode);let ft={seed:u.query,totalQuestions:J.length,maxDepthReached:J.reduce((Mt,Ye)=>Math.max(Mt,Ye.depth),0),durationMs:Date.now()-a,errorCount:o};return this.reporter.onComplete(ft),{seed:u.query,location:t.location??null,extractedAt:new Date().toISOString(),diagnostics:{phaseTimings:this.currentPhaseTimings(a),completionStatus:B?"paa_found":"no_paa",...B?{}:{noPaaObserved:!0},problem:null,paaLifecycle:{...this.paaLifecycle},completeness:{...this.completeness},links:{...this.linkDiagnostics},...t.debug?{debug:this.buildHarvestDebugSnapshot(u,r,l,void 0,c)}:{}},totalQuestions:J.length,surface:"web",aiOverview:{detected:!1,text:null,citations:[]},aiMode:{detected:!1,text:null,citations:[]},whatPeopleSaying:[],tree:this.buildTree(J,u.query),flat:J,videos:[],forums:[],organicResults:[],localPack:[],entityIds:{entities:[],kgIds:[],cids:[],gcids:[]},stats:ft}}if(y&&(this.aioShareUrlEarly=await this.captureAIOverviewShareUrl(I,t).catch(()=>null)),t.serpOnly){let $=Date.now(),[J,ft,Mt]=await Promise.all([this.extractOrganicResults(I),w?this.extractLocalPack(I):Promise.resolve([]),this.extractEntityIds(I)]),Ye=this.mergeLocalPackIntoEntities(Mt,ft),z=y?await this.extractAISurfaces(I,t):O;this.phaseTimings.serpParseMs=Date.now()-$;let he=t.debug?ln(r,J,ft):void 0,It=J,Je={requestedPages:(t.pages??1)>=2?2:1,capturedPages:1,page2Status:(t.pages??1)>=2?"not_attempted":"not_requested",page1OrganicCount:J.length,page2OrganicCount:0};if((t.pages??1)>=2){let it=await this.captureSecondOrganicPage(I,u,n);It=[...J,...it.organic],Je={...Je,capturedPages:it.status==="captured"?2:1,page2Status:it.status,page2OrganicCount:it.organic.length,...it.failureCode?{failureCode:it.failureCode}:{}},t.debug&&(he=ln(r,It,ft))}await this.resolveMaterialLinks(I,[],It,z.aiOverview,z.aiMode);let at={seed:u.query,totalQuestions:0,maxDepthReached:0,durationMs:Date.now()-a,errorCount:o};return this.reporter.onComplete(at),{seed:u.query,location:t.location??null,extractedAt:new Date().toISOString(),diagnostics:{phaseTimings:this.currentPhaseTimings(a),completionStatus:"serp_only",problem:null,pagination:Je,completeness:{...this.completeness},links:{...this.linkDiagnostics},...t.debug?{debug:this.buildHarvestDebugSnapshot(u,r,l,he,c)}:{}},totalQuestions:0,surface:z.surface,aiOverview:z.aiOverview,aiMode:z.aiMode,whatPeopleSaying:[],tree:[],flat:[],videos:[],forums:[],organicResults:It,localPack:ft,entityIds:Ye,stats:at}}let[K,_,b,k,A,T]=await Promise.all([C?this.extractVideos(I):Promise.resolve([]),g?this.extractForums(I):Promise.resolve([]),m?this.extractWhatPeopleSaying(I):Promise.resolve([]),this.extractEntityIds(I),this.extractOrganicResults(I),w?this.extractLocalPack(I):Promise.resolve([])]),M=this.mergeLocalPackIntoEntities(k,T),q=t.debug?ln(r,A,T):void 0;this.reporter.onVideos(K),this.reporter.onForums(_);let P=y?await this.extractAISurfaces(I,t):O,G={requestedPages:(t.pages??1)>=2?2:1,capturedPages:1,page2Status:(t.pages??1)>=2?"not_attempted":"not_requested",page1OrganicCount:A.length,page2OrganicCount:0},v=A;if(this.checkpointMaterial={surface:P.surface,aiOverview:P.aiOverview,aiMode:P.aiMode,whatPeopleSaying:b,videos:K,forums:_,organicResults:v,localPack:T,entityIds:M,pagination:G},await this.emitProgress("serp_captured"),G.requestedPages===2){let $=await this.captureSecondOrganicPage(I,u,n);v=[...A,...$.organic],G={...G,capturedPages:$.status==="captured"?2:1,page2Status:$.status,page2OrganicCount:$.organic.length,...$.failureCode?{failureCode:$.failureCode}:{}},this.checkpointMaterial={...this.checkpointMaterial,organicResults:v,pagination:G},await this.emitProgress("serp_captured"),await this.resolveMaterialLinks(I,[],v,P.aiOverview,P.aiMode),this.checkpointMaterial={...this.checkpointMaterial,organicResults:v},await this.emitProgress("serp_captured")}let R=t.debug?ln(r,v,T):q;if(!B){await this.resolveMaterialLinks(I,[],v,P.aiOverview,P.aiMode),this.checkpointMaterial={...this.checkpointMaterial,organicResults:v},await this.emitProgress("serp_captured");let $={seed:u.query,totalQuestions:0,maxDepthReached:0,durationMs:Date.now()-a,errorCount:o};return this.reporter.onComplete($),{seed:u.query,location:t.location??null,extractedAt:new Date().toISOString(),diagnostics:{phaseTimings:this.currentPhaseTimings(a),completionStatus:"no_paa",noPaaObserved:!0,problem:null,pagination:G,paaLifecycle:{...this.paaLifecycle},completeness:{...this.completeness},links:{...this.linkDiagnostics},...t.debug?{debug:this.buildHarvestDebugSnapshot(u,r,l,R,c)}:{}},totalQuestions:0,surface:P.surface,aiOverview:P.aiOverview,aiMode:P.aiMode,whatPeopleSaying:b,tree:[],flat:[],videos:K,forums:_,organicResults:v,localPack:T,entityIds:M,stats:$}}let f=Date.now(),x=await this.runBFS(I,u,n);this.phaseTimings.paaExpansionMs=Date.now()-f,this.throwIfAborted(n);let D=new URLSearchParams({q:u.query,gl:t.gl,hl:t.hl,pws:"0",udm:rn.udm});l&&D.set("uule",l);let H=[];if(t.includeShortVideos===!0||t.includeShortVideos!==!1&&(C||h))try{H=await this.extractShortVideos(I,"https://www.google.com/search?"+D.toString())}catch($){if(!($ instanceof et))throw $;o++,d.push({code:"short_videos_captcha_skipped",surface:"short_videos",message:$.message,retryable:!0})}this.reporter.onVideos(H),await this.resolveMaterialLinks(I,x,v,P.aiOverview,P.aiMode),this.checkpointMaterial={...this.checkpointMaterial,surface:P.surface,aiOverview:P.aiOverview,aiMode:P.aiMode,videos:[...K,...H],organicResults:v},await this.emitProgress("expansion_finished");let X=[...K,...H],E=this.buildTree(x,u.query),tt={seed:u.query,totalQuestions:x.length,maxDepthReached:x.reduce(($,J)=>Math.max($,J.depth),0),durationMs:Date.now()-a,errorCount:o};return this.reporter.onComplete(tt),{seed:u.query,location:t.location??null,extractedAt:new Date().toISOString(),diagnostics:{phaseTimings:this.currentPhaseTimings(a),completionStatus:"paa_found",problem:null,pagination:G,paaLifecycle:{...this.paaLifecycle},completeness:{...this.completeness},links:{...this.linkDiagnostics},...d.length>0?{warnings:d}:{},...t.debug?{debug:this.buildHarvestDebugSnapshot(u,r,l,R,c)}:{}},totalQuestions:x.length,surface:P.surface,aiOverview:P.aiOverview,aiMode:P.aiMode,whatPeopleSaying:b,tree:E,flat:x,videos:X,forums:_,organicResults:v,localPack:T,entityIds:M,stats:tt}}catch(S){throw o++,this.paaLifecycle.discoveryStatus==="in_progress"&&(this.paaLifecycle={...this.paaLifecycle,discoveryStatus:"interrupted",completionReason:"The browser attempt ended before frontier exhaustion could be proven."}),await this.emitProgress("attempt_ending").catch(()=>{}),this.reporter.onError(S instanceof Error?S:new Error(String(S))),S}}};var Vn=class{onQuestion(t){process.stdout.write(JSON.stringify({event:"question",depth:t.depth,question:t.question})+`
21787
21787
  `)}onDepth(t){process.stdout.write(JSON.stringify({event:"depth",depth:t})+`
21788
21788
  `)}onVideos(t){for(let n of t)process.stdout.write(JSON.stringify({event:"video",type:n.type,platform:n.platform,duration:n.duration,title:n.title,channel:n.channel,url:n.url})+`
21789
21789
  `)}onForums(t){for(let n of t)process.stdout.write(JSON.stringify({event:"forum",title:n.title,source:n.source,url:n.url})+`
21790
21790
  `)}onComplete(t){process.stdout.write(JSON.stringify({event:"complete",...t})+`
21791
21791
  `)}onError(t){process.stderr.write(JSON.stringify({event:"error",type:t.constructor.name,message:t.message})+`
21792
- `)}};function Kn(e){return e.reason instanceof DOMException&&e.reason.name==="TimeoutError"?e.reason:new ut}async function $l(e){let t=await e.evaluate(n=>{let a=n,i=Array.from(document.querySelectorAll(a.item)),s=i.map(S=>S.querySelector(a.clickTarget)).filter(S=>S!=null),o=S=>{let U=S.getBoundingClientRect();if(U.width<=0||U.height<=0)return!1;let c=U.left+U.width/2,r=U.top+U.height/2;if(c<0||r<0||c>=window.innerWidth||r>=window.innerHeight)return!1;let l=document.elementFromPoint(c,r);return l!=null&&l!==S&&!S.contains(l)&&!l.contains(S)},d=Array.from(document.querySelectorAll("body *")).filter(S=>{let U=window.getComputedStyle(S);if(U.position!=="fixed"&&U.position!=="sticky")return!1;let c=S.getBoundingClientRect();return c.width*c.height>=window.innerWidth*window.innerHeight*.15&&U.visibility!=="hidden"&&U.display!=="none"});return{itemCount:i.length,expandedItemCount:i.filter(S=>S.classList.contains(a.expandedClass)||S.querySelector(a.clickTarget)?.getAttribute("aria-expanded")==="true").length,answeredItemCount:i.filter(S=>(S.querySelector(a.answerContainer)?.textContent?.trim().length??0)>=10).length,sourcedItemCount:i.filter(S=>S.querySelector(`${a.answerContainer} a[href]`)!=null).length,clickTargetCount:s.length,clickTargetsWithButtonRole:s.filter(S=>S.getAttribute("role")==="button"||S.tagName==="BUTTON").length,clickTargetsWithExpandedState:s.filter(S=>S.hasAttribute("aria-expanded")).length,clickTargetsOffscreen:s.filter(S=>{let U=S.getBoundingClientRect(),c=U.left+U.width/2,r=U.top+U.height/2;return c<0||r<0||c>=window.innerWidth||r>=window.innerHeight}).length,clickTargetsBlockedAtCenter:s.filter(o).length,fixedOrStickyOverlayCount:d.length}},{item:Z.item,answerContainer:Z.answerContainer,clickTarget:Z.clickTarget,expandedClass:Z.expandedClass});return{capturedAt:new Date().toISOString(),...t,selectorVersion:Ds}}function Ge(e){if(e instanceof At)return"error";if(e instanceof et)return"captcha";if(e instanceof ge)return"location_mismatch";if(e instanceof ut)return"request_aborted";if(e instanceof Ot)return"browser_session_interrupted";if(e instanceof DOMException&&(e.name==="TimeoutError"||e.name==="AbortError"))return"timeout";let t=e instanceof Error?e.message:String(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(t)?"browser_session_interrupted":jl(t)?"proxy_tunnel_failed":Ql(t)?"proxy_unavailable":/timeout|timed out|Timeout \d+ms exceeded|deadline/i.test(t)?"timeout":"error"}function jl(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 Ql(e){return/proxy unavailable|proxy_unavailable|connection_test_failed|did not return a proxy id|configured fallback/i.test(e)}async function Qa(e,t,n,a,i,s,o){let d=ao(t,{nativeGoogleAssets:e.serpOnly}),S=o?mi(d,o.execution,o.permit,t.plannedProvider):d,U=new Vn,c=new Gn(S,U,a,i);if(n?.aborted)return{result:null,error:Kn(n),cleanup:await S.close(),debug:null};let r,l=n?new Promise((m,O)=>{r=()=>O(Kn(n)),n.addEventListener("abort",r,{once:!0})}):null,u=null,h=null,w,g=null,C=!1,y;try{y=c.extract(e,n),y.then(()=>{C=!0},()=>{C=!0}),u=await(l?Promise.race([y,l]):y)}catch(m){h=m}finally{if(n&&r&&n.removeEventListener("abort",r),s){let m;try{let O=$l(S);O.catch(()=>{});let F=await Promise.race([O,new Promise((B,I)=>{m=setTimeout(()=>I(new DOMException("PAA DOM evidence timed out","TimeoutError")),2e3)})]);await s(F)}catch(O){console.warn(JSON.stringify({event:"paa_dom_evidence_failed",message:O instanceof Error?O.message:String(O)}))}finally{m&&clearTimeout(m)}}g=u?.diagnostics.debug??(e.debug?{enabled:!0,request:{query:e.query,locationInput:e.location??null,canonicalLocation:null,locationResolved:null,locationMatchSource:null,locationAmbiguousCandidates:null,uule:null,gl:e.gl,hl:e.hl,device:e.device,proxyMode:e.proxyMode,proxyZip:e.proxyZip??null,serpIdentity:e.serpIdentity??null,serpOnly:e.serpOnly,pages:e.pages??1},browser:S.getDebugSnapshot()}:null);try{w=await S.close()}catch(m){w={\u006b\u0065\u0072\u006e\u0065\u006cSessionId:S.get\u004b\u0065\u0072\u006e\u0065\u006cSessionId?.()??null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted:!1,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:null,browserCloseSucceeded:!1,browserCloseError:m instanceof Error?m.message:String(m),physicalOutcome:"unknown"}}if(y&&!C){let m;try{await Promise.race([y.then(()=>{},()=>{}),new Promise(O=>{m=setTimeout(O,2e3)})])}finally{m&&clearTimeout(m)}}w.extractionDrained=C,C||(w.physicalOutcome="unknown")}if(h){let m=Ge(h),O=m==="timeout"||m==="request_aborted"||m==="browser_session_interrupted"?m:null,F=null;if(O)try{F=typeof c.getPartialResult=="function"?c.getPartialResult():null}catch{F=null}return F&&O?(F.diagnostics={...F.diagnostics,interruption:{code:O,reasonSource:"client_runtime",message:h instanceof Error?h.message:String(h)}},{result:F,error:h,cleanup:w,debug:g,salvagedFrom:h}):{result:null,error:h,cleanup:w,debug:g}}return{result:u,error:null,cleanup:w,debug:g}}function Ao(e){return e.diagnostics.degradedResult?"degraded_result":e.diagnostics?.completionStatus??(e.totalQuestions>0?"paa_found":"no_paa")}function Xl(e){return e.flat.length>0||e.organicResults.length>0||e.localPack.length>0||e.videos.length>0||e.forums.length>0||e.whatPeopleSaying.length>0||e.aiOverview.detected||e.aiMode.detected}function Xa(e,t,n){let a=Xl(e),i=(e.diagnostics.warnings?.length??0)>0,s=new Set(e.flat.map(g=>g.question.toLowerCase().replace(/[^\w\s]/g,"").replace(/\s+/g," ").trim())).size,o=n?0:e.flat.filter(g=>!g.answer?.trim()).length,d=n?0:e.flat.filter(g=>!g.source_cite?.trim()).length,S=n?0:e.flat.filter(g=>g.answerExpansionIncomplete===!0).length,U=e.diagnostics.completionStatus==="no_paa"&&(e.diagnostics.noPaaObserved===!0||a),c=e.diagnostics.completionStatus==="paa_found",r=e.diagnostics.paaLifecycle?.discoveryStatus,l=r==="interrupted"||r==="recovery_exhausted",u=c&&(s<t&&r!=="frontier_exhausted"||o>0||d>0||S>0||!!e.diagnostics.interruption||l),h=U?"complete":c&&s>0?u||i?"partial":"complete":a?i?"partial":"complete":"degraded",w=h==="degraded";return e.diagnostics={...e.diagnostics,resultQuality:h,degradedResult:w,degradationReasons:w?["empty_primary_serp"]:[],retryRecommended:w||h==="partial"&&(u||e.diagnostics.warnings?.some(g=>g.retryable)===!0),completeness:{paaWithoutAnswer:o,paaWithoutSource:d,paaIncompleteAnswers:S,paaAnswersRecovered:e.diagnostics.completeness?.paaAnswersRecovered??0,aioShareCaptured:e.diagnostics.completeness?.aioShareCaptured??null,paaRequested:t,paaReturned:e.flat.length,paaUnique:s},...e.diagnostics.paaLifecycle?{paaLifecycle:{...e.diagnostics.paaLifecycle,questionsFound:s,targetStatus:s>=t?"met":"not_met",materialStatus:o>0||d>0||S>0?"partial":"complete"}}:{}},e}function Za(e,t,n){let a=e.diagnostics.paaLifecycle;if(!a)return e;let i={...a.retryBreakdown,browserRetries:t,providerFallbacks:n};return{...e,diagnostics:{...e.diagnostics,paaLifecycle:{...a,retryBreakdown:i,automaticRetries:i.controlRetries+i.browserRetries+i.runtimeRecoveries}}}}function xo(e){return(e.diagnostics.degradationReasons??[]).includes("empty_primary_serp")?"No usable primary SERP surface was captured; the result may be incomplete.":"The harvest result was marked degraded."}function ti(e,t){if(t||!e.diagnostics.debug)return e;let n={...e.diagnostics};return delete n.debug,{...e,diagnostics:n}}async function ei(e,t){let n=t==null?3e3:t-Date.now();if(n<=0)return e;try{return await wo(e,{totalBudgetMs:Math.min(3e3,n)})}catch(a){return console.warn(JSON.stringify({event:"harvest_goto_resolution_failed",message:a instanceof Error?a.message:String(a)})),e}}var ni=2,Zl=2,tS=3e3;function eS(e){if(!e||typeof e!="object")return;let t=e.signal;if(t instanceof AbortSignal)return t}function nS(e){if(!e||typeof e!="object")return;let t=e.onAttemptEvent;return typeof t=="function"?t:void 0}function aS(e){if(!e||typeof e!="object")return;let t=e.onPaaProgress;return typeof t=="function"?t:void 0}function iS(e){if(!e||typeof e!="object")return;let t=e.onPaaDomEvidence;return typeof t=="function"?t:void 0}async function Ve(e,t){if(e)try{await e(t)}catch(n){console.warn(JSON.stringify({event:"harvest_attempt_log_failed",attempt_number:t.attemptNumber,message:n instanceof Error?n.message:String(n)}))}}function Vt(e){return e instanceof Error?e.message:String(e)}function sS(e){return e==="location"?Zl:ni}function Wo(e){return e==="captcha"||e==="proxy_tunnel_failed"||e==="proxy_unavailable"}function Oo(e){return e==="browser_session_interrupted"}function oS(e){let t=e.diagnostics.debug?.locationEvidence,n=t?.expected?.canonicalLocation??e.location??"requested location",a=t?.candidates.slice(0,3).map(i=>`${i.city}, ${i.regionCode}`).join("; ");return a?`Google returned results for ${a}, not ${n}`:`Google returned results for a different location than ${n}`}function rS(e,t){return t==="location"&&e.diagnostics.debug?.locationEvidence?.status==="mismatch"}function Lo(e){return e.extractionDrained===!0&&e.browserCloseSucceeded===!0&&e.localDisconnectSucceeded!==!1&&(e.\u006b\u0065\u0072\u006e\u0065\u006cSessionId==null||e.\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded===!0)&&e.physicalOutcome!=="unknown"}async function dS(e,t){if(!t)return!0;if(!e)return!1;try{return await Ps(e,t),console.info(JSON.stringify({event:"\u006b\u0065\u0072\u006e\u0065\u006c_proxy_deleted",proxy_id_suffix:t.slice(-6)})),!0}catch(n){return console.warn(JSON.stringify({event:"\u006b\u0065\u0072\u006e\u0065\u006c_proxy_delete_failed",proxy_id_suffix:t.slice(-6),message:Vt(n)})),!1}}async function Bo(e){let t=typeof e=="object"&&e!==null?e:{},n=eS(e),a=fi(e),i=nS(e),s=aS(e),o=iS(e),d=t.forceManagedSerp===!0,S=t.force\u004b\u0065\u0072\u006e\u0065\u006cSerp===!0,U=gi({forceManagedSerp:d,force\u004b\u0065\u0072\u006e\u0065\u006cSerp:S}),c=t.proxyMode,r=c==="location"||c==="none"||c==="configured"?c:yn,l=typeof t.\u006b\u0065\u0072\u006e\u0065\u006cApiKey=="string"?t.\u006b\u0065\u0072\u006e\u0065\u006cApiKey.trim():Mi(),u=typeof t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId=="string"?t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId.trim():void 0,h={\u006b\u0065\u0072\u006e\u0065\u006cApiKey:l,proxyMode:r,configured\u004b\u0065\u0072\u006e\u0065\u006cProxyId:u,location:typeof t.location=="string"?t.location:void 0,proxyZip:typeof t.proxyZip=="string"?t.proxyZip:void 0,gl:typeof t.gl=="string"?t.gl:"us"},w=typeof t.debug=="boolean"?t.debug:!1,g=r==="location"&&!!h.location,C=t.maxAttempts,y=typeof C=="number"&&Number.isInteger(C)&&C>=1?Math.min(ni,C):sS(r),m=Math.min(ni,y),O=typeof t.softDeadlineMs=="number"?t.softDeadlineMs:null,F=new mn,B=null,I=r,K=0,D=()=>O==null||O-Date.now()>=tS;for(let b=0;b<m;b++){let k=b+1,A=Date.now(),T=!0,M,q=!1,P=n,G;try{if(P?.aborted)throw Kn(P);let v=hi({intent:U,\u0062\u0072\u0069\u0067\u0068\u0074\u0044\u0061\u0074\u0061Available:Ls(),\u006b\u0065\u0072\u006e\u0065\u006cFallbackAvailable:!!l,persistent\u004b\u0065\u0072\u006e\u0065\u006cIdentityRequested:!!(t.serpIdentity||t.\u006b\u0065\u0072\u006e\u0065\u006cProfileName),retryIndex:b,priorTerminalReason:B==null?null:Ge(B),softDeadlineMs:O}),R=na.parse({...t,\u006b\u0065\u0072\u006e\u0065\u006cApiKey:l,proxyMode:I,debug:w||g});a&&(M=await a.prepare(v.plannedProvider,k),G=a.watch(M,n),P=G.signal);let f=v.plannedProvider==="\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061"?"\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061_browser":R.serpIdentity?"\u006b\u0065\u0072\u006e\u0065\u006c_persistent_identity":"\u006b\u0065\u0072\u006e\u0065\u006c_browser";await Ve(i,{type:"started",attemptNumber:k,maxAttempts:m,method:f,provider:f==="\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061_browser"?"\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061":"\u006b\u0065\u0072\u006e\u0065\u006c",planReason:v.reasonCode,planTimeoutMs:v.timeoutMs,retryKind:k===1?null:v.attemptKind==="provider_fallback"?"provider_fallback":"same_method",retryReason:k===1||B==null?null:Ge(B),query:R.query,location:R.location??null,maxQuestions:R.maxQuestions,startedAt:new Date(A).toISOString()}),v.plannedProvider==="\u006b\u0065\u0072\u006e\u0065\u006c"&&(T=!1,a&&M&&await a.start(M,"proxy"));let x=v.plannedProvider==="\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061"?null:await Is({...h,proxyMode:I,attemptIndex:b,fresh:I==="location"});if(v.plannedProvider==="\u006b\u0065\u0072\u006e\u0065\u006c"&&!x)throw new Error("\u004b\u0065\u0072\u006e\u0065\u006c proxy resolution did not produce an execution plan");a&&M&&v.plannedProvider==="\u006b\u0065\u0072\u006e\u0065\u006c"&&await a.resource(M,"proxy",x?.disposableProxyId??null);let _={...t,\u006b\u0065\u0072\u006e\u0065\u006cApiKey:l,...x?{\u006b\u0065\u0072\u006e\u0065\u006cProxyId:x.\u006b\u0065\u0072\u006e\u0065\u006cProxyId,\u006b\u0065\u0072\u006e\u0065\u006cProxyResolution:x.resolution}:{},proxyMode:I,keepDefaultProxy:b>0,softDeadlineMs:O==null?void 0:A+v.timeoutMs,debug:w||g};I==="none"&&(_.\u006b\u0065\u0072\u006e\u0065\u006cProxyId=void 0);let H=na.parse(_);console.info(JSON.stringify({event:"harvest_attempt_started",attempt_number:k,max_attempts:m,query:H.query,location:H.location??null,max_questions:H.maxQuestions}));let X=se(),E=null,tt=async at=>{pn(at.provider)!==v.plannedProvider&&(E=new At(v.plannedProvider,at.provider)),await Ve(i,{type:"provider_session_started",attemptNumber:k,maxAttempts:m,provider:at.provider,providerSessionId:at.providerSessionId,billingMode:at.billingMode,observedAt:new Date().toISOString()})},$=X?.harvestBrowserMode==="headless-test"&&process.env[xs]==="true";T=!1;let J=X?await Os({...X,forceHeadless:$,forceHeadful:!$},()=>Qa(H,v,P,s,tt,o,a&&M?{execution:a,permit:M}:void 0)):await Qa(H,v,P,s,tt,o,a&&M?{execution:a,permit:M}:void 0),ft=await dS(l,x?.disposableProxyId);if(J.cleanup.disposableProxyDeleted=ft,a&&M){let at=await Xn(a,M,J.cleanup,x?.disposableProxyId??null);q=!0,G?.stop(),T=at.state!=="unknown"&&Lo(J.cleanup)&&ft}else T=Lo(J.cleanup)&&ft;if(J.error||E){let at=E??J.error,it=Ge(at);(it==="captcha"||it==="proxy_tunnel_failed")&&I==="location"&&(K++,K>=2&&(I="none"));let qe=!J.result&&T&&!P?.aborted&&b<m-1&&D()&&(it==="captcha"||Oo(it)||r==="location"&&Wo(it));if(it==="captcha"?console.warn(JSON.stringify({event:"harvest_attempt_captcha",attempt_number:k,max_attempts:m,message:Vt(at),will_retry:qe})):qe&&console.warn(JSON.stringify({event:"harvest_attempt_proxy_retry",attempt_number:k,max_attempts:m,outcome:it,message:Vt(at),will_retry:qe})),await Ve(i,{type:"finished",attemptNumber:k,maxAttempts:m,outcome:it,\u006b\u0065\u0072\u006e\u0065\u006cSessionId:J.cleanup.\u006b\u0065\u0072\u006e\u0065\u006cSessionId,questionCount:J.result?.totalQuestions??0,durationMs:Date.now()-A,error:Vt(at),willRetry:qe,cleanup:J.cleanup,debug:J.debug,completedAt:new Date().toISOString()}),B=at,qe)continue;if(J.result&&!E){let Jo=await ei(J.result,O);return Za(Xa(ti(Jo,w),H.maxQuestions,H.questionsOnly),b,v.attemptKind==="provider_fallback"?1:0)}break}let Mt=J.result;if(!Mt)throw new Error("Harvest attempt completed without a result");if(rS(Mt,r)){let at=new ge(oS(Mt)),it=T&&!P?.aborted&&b<m-1&&D();if(console.warn(JSON.stringify({event:"harvest_attempt_location_mismatch",attempt_number:k,max_attempts:m,message:at.message,will_retry:it})),await Ve(i,{type:"finished",attemptNumber:k,maxAttempts:m,outcome:"location_mismatch",\u006b\u0065\u0072\u006e\u0065\u006cSessionId:J.cleanup.\u006b\u0065\u0072\u006e\u0065\u006cSessionId,questionCount:Mt.totalQuestions,durationMs:Date.now()-A,error:at.message,willRetry:it,cleanup:J.cleanup,debug:J.debug,completedAt:new Date().toISOString()}),B=at,it)continue;break}let Ye=await ei(Mt,O),z=Za(Xa(ti(Ye,w),H.maxQuestions,H.questionsOnly),b,v.attemptKind==="provider_fallback"?1:0),he=Ao(z),It=he==="degraded_result"&&T&&!P?.aborted&&b<m-1&&D(),Je=he==="degraded_result"?xo(z):null;if(It&&console.warn(JSON.stringify({event:"harvest_attempt_degraded_result",attempt_number:k,max_attempts:m,degradation_reasons:z.diagnostics.degradationReasons,will_retry:!0})),await Ve(i,{type:"finished",attemptNumber:k,maxAttempts:m,outcome:he,\u006b\u0065\u0072\u006e\u0065\u006cSessionId:J.cleanup.\u006b\u0065\u0072\u006e\u0065\u006cSessionId,questionCount:z.totalQuestions,durationMs:Date.now()-A,error:Je,willRetry:It,cleanup:J.cleanup,debug:J.debug,completedAt:new Date().toISOString()}),It)continue;return(H.format==="json"||H.format==="both")&&await F.writeJSON(z,H.outputDir),(H.format==="csv"||H.format==="both")&&await Promise.all([F.writeCSV(z.flat,H.outputDir),z.videos.length>0?F.writeVideoCSV(z.videos,z.seed,H.outputDir):Promise.resolve(""),z.forums.length>0?F.writeForumCSV(z.forums,z.seed,H.outputDir):Promise.resolve(""),z.aiOverview.detected?F.writeAIOverviewCSV(z.aiOverview.citations,z.aiOverview.text,z.seed,H.outputDir):Promise.resolve(""),z.aiMode.detected?F.writeAIModeCSV(z.aiMode.citations,z.aiMode.text,z.seed,H.outputDir):Promise.resolve(""),z.whatPeopleSaying.length>0?F.writeWhatPeopleSayingCSV(z.whatPeopleSaying,z.seed,H.outputDir):Promise.resolve("")]),z}catch(v){a&&M&&!q&&(T=!1,await Xn(a,M,{\u006b\u0065\u0072\u006e\u0065\u006cSessionId:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted:!1,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:null,browserCloseSucceeded:null,browserCloseError:Vt(v),physicalOutcome:"unknown",extractionDrained:!0,disposableProxyDeleted:!1}).catch(()=>{}));let R=Ge(v);(R==="captcha"||R==="proxy_tunnel_failed")&&I==="location"&&(K++,K>=2&&(I="none"));let f=T&&!P?.aborted&&b<m-1&&D()&&(R==="captcha"||Oo(R)||r==="location"&&Wo(R));if(R==="captcha"?console.warn(JSON.stringify({event:"harvest_attempt_captcha",attempt_number:k,max_attempts:m,message:Vt(v),will_retry:f})):f&&console.warn(JSON.stringify({event:"harvest_attempt_proxy_retry",attempt_number:k,max_attempts:m,outcome:R,message:Vt(v),will_retry:f})),await Ve(i,{type:"finished",attemptNumber:k,maxAttempts:m,outcome:R,\u006b\u0065\u0072\u006e\u0065\u006cSessionId:null,questionCount:0,durationMs:Date.now()-A,error:Vt(v),willRetry:f,cleanup:{\u006b\u0065\u0072\u006e\u0065\u006cSessionId:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted:!1,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:null,browserCloseSucceeded:null,browserCloseError:null},debug:null,completedAt:new Date().toISOString()}),B=v,f)continue;if(R==="captcha")break;throw v}finally{G?.stop()}}throw B&&!(B instanceof et)?B:(console.warn(JSON.stringify({event:"harvest_captcha_exhausted",max_attempts:m,session_kind:l?"\u006b\u0065\u0072\u006e\u0065\u006c":"local"})),new et(bi(`CAPTCHA on all ${m} fresh sessions. Try again in a few minutes.`)))}var Yo=require("child_process"),pt=require("fs"),ci=require("os"),ce=require("path"),ue=require("@fal-ai/client");var lS="https://api.deepinfra.com/v1/openai/chat/completions",Eo="https://openrouter.ai/api/v1/chat/completions",ai="Qwen/Qwen3.6-35B-A3B",SS=`You are a video prompt engineer for Seedance 2.0 text-to-video AI.
21792
+ `)}};function Kn(e){return e.reason instanceof DOMException&&e.reason.name==="TimeoutError"?e.reason:new ut}async function $l(e){let t=await e.evaluate(n=>{let a=n,i=Array.from(document.querySelectorAll(a.item)),s=i.map(S=>S.querySelector(a.clickTarget)).filter(S=>S!=null),o=S=>{let U=S.getBoundingClientRect();if(U.width<=0||U.height<=0)return!1;let c=U.left+U.width/2,r=U.top+U.height/2;if(c<0||r<0||c>=window.innerWidth||r>=window.innerHeight)return!1;let l=document.elementFromPoint(c,r);return l!=null&&l!==S&&!S.contains(l)&&!l.contains(S)},d=Array.from(document.querySelectorAll("body *")).filter(S=>{let U=window.getComputedStyle(S);if(U.position!=="fixed"&&U.position!=="sticky")return!1;let c=S.getBoundingClientRect();return c.width*c.height>=window.innerWidth*window.innerHeight*.15&&U.visibility!=="hidden"&&U.display!=="none"});return{itemCount:i.length,expandedItemCount:i.filter(S=>S.classList.contains(a.expandedClass)||S.querySelector(a.clickTarget)?.getAttribute("aria-expanded")==="true").length,answeredItemCount:i.filter(S=>(S.querySelector(a.answerContainer)?.textContent?.trim().length??0)>=10).length,sourcedItemCount:i.filter(S=>S.querySelector(`${a.answerContainer} a[href]`)!=null).length,clickTargetCount:s.length,clickTargetsWithButtonRole:s.filter(S=>S.getAttribute("role")==="button"||S.tagName==="BUTTON").length,clickTargetsWithExpandedState:s.filter(S=>S.hasAttribute("aria-expanded")).length,clickTargetsOffscreen:s.filter(S=>{let U=S.getBoundingClientRect(),c=U.left+U.width/2,r=U.top+U.height/2;return c<0||r<0||c>=window.innerWidth||r>=window.innerHeight}).length,clickTargetsBlockedAtCenter:s.filter(o).length,fixedOrStickyOverlayCount:d.length}},{item:Z.item,answerContainer:Z.answerContainer,clickTarget:Z.clickTarget,expandedClass:Z.expandedClass});return{capturedAt:new Date().toISOString(),...t,selectorVersion:_s}}function Ge(e){if(e instanceof At)return"error";if(e instanceof et)return"captcha";if(e instanceof ge)return"location_mismatch";if(e instanceof ut)return"request_aborted";if(e instanceof Ot)return"browser_session_interrupted";if(e instanceof DOMException&&(e.name==="TimeoutError"||e.name==="AbortError"))return"timeout";let t=e instanceof Error?e.message:String(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(t)?"browser_session_interrupted":jl(t)?"proxy_tunnel_failed":Ql(t)?"proxy_unavailable":/timeout|timed out|Timeout \d+ms exceeded|deadline/i.test(t)?"timeout":"error"}function jl(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 Ql(e){return/proxy unavailable|proxy_unavailable|connection_test_failed|did not return a proxy id|configured fallback/i.test(e)}async function Qa(e,t,n,a,i,s,o){let d=ao(t,{nativeGoogleAssets:e.serpOnly}),S=o?mi(d,o.execution,o.permit,t.plannedProvider):d,U=new Vn,c=new Gn(S,U,a,i);if(n?.aborted)return{result:null,error:Kn(n),cleanup:await S.close(),debug:null};let r,l=n?new Promise((m,O)=>{r=()=>O(Kn(n)),n.addEventListener("abort",r,{once:!0})}):null,u=null,h=null,w,g=null,C=!1,y;try{y=c.extract(e,n),y.then(()=>{C=!0},()=>{C=!0}),u=await(l?Promise.race([y,l]):y)}catch(m){h=m}finally{if(n&&r&&n.removeEventListener("abort",r),s){let m;try{let O=$l(S);O.catch(()=>{});let F=await Promise.race([O,new Promise((B,I)=>{m=setTimeout(()=>I(new DOMException("PAA DOM evidence timed out","TimeoutError")),2e3)})]);await s(F)}catch(O){console.warn(JSON.stringify({event:"paa_dom_evidence_failed",message:O instanceof Error?O.message:String(O)}))}finally{m&&clearTimeout(m)}}g=u?.diagnostics.debug??(e.debug?{enabled:!0,request:{query:e.query,locationInput:e.location??null,canonicalLocation:null,locationResolved:null,locationMatchSource:null,locationAmbiguousCandidates:null,uule:null,gl:e.gl,hl:e.hl,device:e.device,proxyMode:e.proxyMode,proxyZip:e.proxyZip??null,serpIdentity:e.serpIdentity??null,serpOnly:e.serpOnly,pages:e.pages??1},browser:S.getDebugSnapshot()}:null);try{w=await S.close()}catch(m){w={\u006b\u0065\u0072\u006e\u0065\u006cSessionId:S.get\u004b\u0065\u0072\u006e\u0065\u006cSessionId?.()??null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted:!1,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:null,browserCloseSucceeded:!1,browserCloseError:m instanceof Error?m.message:String(m),physicalOutcome:"unknown"}}if(y&&!C){let m;try{await Promise.race([y.then(()=>{},()=>{}),new Promise(O=>{m=setTimeout(O,2e3)})])}finally{m&&clearTimeout(m)}}w.extractionDrained=C,C||(w.physicalOutcome="unknown")}if(h){let m=Ge(h),O=m==="timeout"||m==="request_aborted"||m==="browser_session_interrupted"?m:null,F=null;if(O)try{F=typeof c.getPartialResult=="function"?c.getPartialResult():null}catch{F=null}return F&&O?(F.diagnostics={...F.diagnostics,interruption:{code:O,reasonSource:"client_runtime",message:h instanceof Error?h.message:String(h)}},{result:F,error:h,cleanup:w,debug:g,salvagedFrom:h}):{result:null,error:h,cleanup:w,debug:g}}return{result:u,error:null,cleanup:w,debug:g}}function Ao(e){return e.diagnostics.degradedResult?"degraded_result":e.diagnostics?.completionStatus??(e.totalQuestions>0?"paa_found":"no_paa")}function Xl(e){return e.flat.length>0||e.organicResults.length>0||e.localPack.length>0||e.videos.length>0||e.forums.length>0||e.whatPeopleSaying.length>0||e.aiOverview.detected||e.aiMode.detected}function Xa(e,t,n){let a=Xl(e),i=(e.diagnostics.warnings?.length??0)>0,s=new Set(e.flat.map(g=>g.question.toLowerCase().replace(/[^\w\s]/g,"").replace(/\s+/g," ").trim())).size,o=n?0:e.flat.filter(g=>!g.answer?.trim()).length,d=n?0:e.flat.filter(g=>!g.source_cite?.trim()).length,S=n?0:e.flat.filter(g=>g.answerExpansionIncomplete===!0).length,U=e.diagnostics.completionStatus==="no_paa"&&(e.diagnostics.noPaaObserved===!0||a),c=e.diagnostics.completionStatus==="paa_found",r=e.diagnostics.paaLifecycle?.discoveryStatus,l=r==="interrupted"||r==="recovery_exhausted",u=c&&(s<t&&r!=="frontier_exhausted"||o>0||d>0||S>0||!!e.diagnostics.interruption||l),h=U?"complete":c&&s>0?u||i?"partial":"complete":a?i?"partial":"complete":"degraded",w=h==="degraded";return e.diagnostics={...e.diagnostics,resultQuality:h,degradedResult:w,degradationReasons:w?["empty_primary_serp"]:[],retryRecommended:w||h==="partial"&&(u||e.diagnostics.warnings?.some(g=>g.retryable)===!0),completeness:{paaWithoutAnswer:o,paaWithoutSource:d,paaIncompleteAnswers:S,paaAnswersRecovered:e.diagnostics.completeness?.paaAnswersRecovered??0,aioShareCaptured:e.diagnostics.completeness?.aioShareCaptured??null,paaRequested:t,paaReturned:e.flat.length,paaUnique:s},...e.diagnostics.paaLifecycle?{paaLifecycle:{...e.diagnostics.paaLifecycle,questionsFound:s,targetStatus:s>=t?"met":"not_met",materialStatus:o>0||d>0||S>0?"partial":"complete"}}:{}},e}function Za(e,t,n){let a=e.diagnostics.paaLifecycle;if(!a)return e;let i={...a.retryBreakdown,browserRetries:t,providerFallbacks:n};return{...e,diagnostics:{...e.diagnostics,paaLifecycle:{...a,retryBreakdown:i,automaticRetries:i.controlRetries+i.browserRetries+i.runtimeRecoveries}}}}function xo(e){return(e.diagnostics.degradationReasons??[]).includes("empty_primary_serp")?"No usable primary SERP surface was captured; the result may be incomplete.":"The harvest result was marked degraded."}function ti(e,t){if(t||!e.diagnostics.debug)return e;let n={...e.diagnostics};return delete n.debug,{...e,diagnostics:n}}async function ei(e,t){let n=t==null?3e3:t-Date.now();if(n<=0)return e;try{return await wo(e,{totalBudgetMs:Math.min(3e3,n)})}catch(a){return console.warn(JSON.stringify({event:"harvest_goto_resolution_failed",message:a instanceof Error?a.message:String(a)})),e}}var ni=2,Zl=2,tS=3e3;function eS(e){if(!e||typeof e!="object")return;let t=e.signal;if(t instanceof AbortSignal)return t}function nS(e){if(!e||typeof e!="object")return;let t=e.onAttemptEvent;return typeof t=="function"?t:void 0}function aS(e){if(!e||typeof e!="object")return;let t=e.onPaaProgress;return typeof t=="function"?t:void 0}function iS(e){if(!e||typeof e!="object")return;let t=e.onPaaDomEvidence;return typeof t=="function"?t:void 0}async function Ve(e,t){if(e)try{await e(t)}catch(n){console.warn(JSON.stringify({event:"harvest_attempt_log_failed",attempt_number:t.attemptNumber,message:n instanceof Error?n.message:String(n)}))}}function Vt(e){return e instanceof Error?e.message:String(e)}function sS(e){return e==="location"?Zl:ni}function Wo(e){return e==="captcha"||e==="proxy_tunnel_failed"||e==="proxy_unavailable"}function Oo(e){return e==="browser_session_interrupted"}function oS(e){let t=e.diagnostics.debug?.locationEvidence,n=t?.expected?.canonicalLocation??e.location??"requested location",a=t?.candidates.slice(0,3).map(i=>`${i.city}, ${i.regionCode}`).join("; ");return a?`Google returned results for ${a}, not ${n}`:`Google returned results for a different location than ${n}`}function rS(e,t){return t==="location"&&e.diagnostics.debug?.locationEvidence?.status==="mismatch"}function Lo(e){return e.extractionDrained===!0&&e.browserCloseSucceeded===!0&&e.localDisconnectSucceeded!==!1&&(e.\u006b\u0065\u0072\u006e\u0065\u006cSessionId==null||e.\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded===!0)&&e.physicalOutcome!=="unknown"}async function dS(e,t){if(!t)return!0;if(!e)return!1;try{return await Ps(e,t),console.info(JSON.stringify({event:"\u006b\u0065\u0072\u006e\u0065\u006c_proxy_deleted",proxy_id_suffix:t.slice(-6)})),!0}catch(n){return console.warn(JSON.stringify({event:"\u006b\u0065\u0072\u006e\u0065\u006c_proxy_delete_failed",proxy_id_suffix:t.slice(-6),message:Vt(n)})),!1}}async function Bo(e){let t=typeof e=="object"&&e!==null?e:{},n=eS(e),a=fi(e),i=nS(e),s=aS(e),o=iS(e),d=t.forceManagedSerp===!0,S=t.force\u004b\u0065\u0072\u006e\u0065\u006cSerp===!0,U=gi({forceManagedSerp:d,force\u004b\u0065\u0072\u006e\u0065\u006cSerp:S}),c=t.proxyMode,r=c==="location"||c==="none"||c==="configured"?c:yn,l=typeof t.\u006b\u0065\u0072\u006e\u0065\u006cApiKey=="string"?t.\u006b\u0065\u0072\u006e\u0065\u006cApiKey.trim():Mi(),u=typeof t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId=="string"?t.\u006b\u0065\u0072\u006e\u0065\u006cProxyId.trim():void 0,h={\u006b\u0065\u0072\u006e\u0065\u006cApiKey:l,proxyMode:r,configured\u004b\u0065\u0072\u006e\u0065\u006cProxyId:u,location:typeof t.location=="string"?t.location:void 0,proxyZip:typeof t.proxyZip=="string"?t.proxyZip:void 0,gl:typeof t.gl=="string"?t.gl:"us"},w=typeof t.debug=="boolean"?t.debug:!1,g=r==="location"&&!!h.location,C=t.maxAttempts,y=typeof C=="number"&&Number.isInteger(C)&&C>=1?Math.min(ni,C):sS(r),m=Math.min(ni,y),O=typeof t.softDeadlineMs=="number"?t.softDeadlineMs:null,F=new mn,B=null,I=r,K=0,_=()=>O==null||O-Date.now()>=tS;for(let b=0;b<m;b++){let k=b+1,A=Date.now(),T=!0,M,q=!1,P=n,G;try{if(P?.aborted)throw Kn(P);let v=hi({intent:U,\u0062\u0072\u0069\u0067\u0068\u0074\u0044\u0061\u0074\u0061Available:Ls(),\u006b\u0065\u0072\u006e\u0065\u006cFallbackAvailable:!!l,persistent\u004b\u0065\u0072\u006e\u0065\u006cIdentityRequested:!!(t.serpIdentity||t.\u006b\u0065\u0072\u006e\u0065\u006cProfileName),retryIndex:b,priorTerminalReason:B==null?null:Ge(B),softDeadlineMs:O}),R=na.parse({...t,\u006b\u0065\u0072\u006e\u0065\u006cApiKey:l,proxyMode:I,debug:w||g});a&&(M=await a.prepare(v.plannedProvider,k),G=a.watch(M,n),P=G.signal);let f=v.plannedProvider==="\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061"?"\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061_browser":R.serpIdentity?"\u006b\u0065\u0072\u006e\u0065\u006c_persistent_identity":"\u006b\u0065\u0072\u006e\u0065\u006c_browser";await Ve(i,{type:"started",attemptNumber:k,maxAttempts:m,method:f,provider:f==="\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061_browser"?"\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061":"\u006b\u0065\u0072\u006e\u0065\u006c",planReason:v.reasonCode,planTimeoutMs:v.timeoutMs,retryKind:k===1?null:v.attemptKind==="provider_fallback"?"provider_fallback":"same_method",retryReason:k===1||B==null?null:Ge(B),query:R.query,location:R.location??null,maxQuestions:R.maxQuestions,startedAt:new Date(A).toISOString()}),v.plannedProvider==="\u006b\u0065\u0072\u006e\u0065\u006c"&&(T=!1,a&&M&&await a.start(M,"proxy"));let x=v.plannedProvider==="\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061"?null:await Is({...h,proxyMode:I,attemptIndex:b,fresh:I==="location"});if(v.plannedProvider==="\u006b\u0065\u0072\u006e\u0065\u006c"&&!x)throw new Error("\u004b\u0065\u0072\u006e\u0065\u006c proxy resolution did not produce an execution plan");a&&M&&v.plannedProvider==="\u006b\u0065\u0072\u006e\u0065\u006c"&&await a.resource(M,"proxy",x?.disposableProxyId??null);let D={...t,\u006b\u0065\u0072\u006e\u0065\u006cApiKey:l,...x?{\u006b\u0065\u0072\u006e\u0065\u006cProxyId:x.\u006b\u0065\u0072\u006e\u0065\u006cProxyId,\u006b\u0065\u0072\u006e\u0065\u006cProxyResolution:x.resolution}:{},proxyMode:I,keepDefaultProxy:b>0,softDeadlineMs:O==null?void 0:A+v.timeoutMs,debug:w||g};I==="none"&&(D.\u006b\u0065\u0072\u006e\u0065\u006cProxyId=void 0);let H=na.parse(D);console.info(JSON.stringify({event:"harvest_attempt_started",attempt_number:k,max_attempts:m,query:H.query,location:H.location??null,max_questions:H.maxQuestions}));let X=se(),E=null,tt=async at=>{pn(at.provider)!==v.plannedProvider&&(E=new At(v.plannedProvider,at.provider)),await Ve(i,{type:"provider_session_started",attemptNumber:k,maxAttempts:m,provider:at.provider,providerSessionId:at.providerSessionId,billingMode:at.billingMode,observedAt:new Date().toISOString()})},$=X?.harvestBrowserMode==="headless-test"&&process.env[xs]==="true";T=!1;let J=X?await Os({...X,forceHeadless:$,forceHeadful:!$},()=>Qa(H,v,P,s,tt,o,a&&M?{execution:a,permit:M}:void 0)):await Qa(H,v,P,s,tt,o,a&&M?{execution:a,permit:M}:void 0),ft=await dS(l,x?.disposableProxyId);if(J.cleanup.disposableProxyDeleted=ft,a&&M){let at=await Xn(a,M,J.cleanup,x?.disposableProxyId??null);q=!0,G?.stop(),T=at.state!=="unknown"&&Lo(J.cleanup)&&ft}else T=Lo(J.cleanup)&&ft;if(J.error||E){let at=E??J.error,it=Ge(at);(it==="captcha"||it==="proxy_tunnel_failed")&&I==="location"&&(K++,K>=2&&(I="none"));let qe=!J.result&&T&&!P?.aborted&&b<m-1&&_()&&(it==="captcha"||Oo(it)||r==="location"&&Wo(it));if(it==="captcha"?console.warn(JSON.stringify({event:"harvest_attempt_captcha",attempt_number:k,max_attempts:m,message:Vt(at),will_retry:qe})):qe&&console.warn(JSON.stringify({event:"harvest_attempt_proxy_retry",attempt_number:k,max_attempts:m,outcome:it,message:Vt(at),will_retry:qe})),await Ve(i,{type:"finished",attemptNumber:k,maxAttempts:m,outcome:it,\u006b\u0065\u0072\u006e\u0065\u006cSessionId:J.cleanup.\u006b\u0065\u0072\u006e\u0065\u006cSessionId,questionCount:J.result?.totalQuestions??0,durationMs:Date.now()-A,error:Vt(at),willRetry:qe,cleanup:J.cleanup,debug:J.debug,completedAt:new Date().toISOString()}),B=at,qe)continue;if(J.result&&!E){let Jo=await ei(J.result,O);return Za(Xa(ti(Jo,w),H.maxQuestions,H.questionsOnly),b,v.attemptKind==="provider_fallback"?1:0)}break}let Mt=J.result;if(!Mt)throw new Error("Harvest attempt completed without a result");if(rS(Mt,r)){let at=new ge(oS(Mt)),it=T&&!P?.aborted&&b<m-1&&_();if(console.warn(JSON.stringify({event:"harvest_attempt_location_mismatch",attempt_number:k,max_attempts:m,message:at.message,will_retry:it})),await Ve(i,{type:"finished",attemptNumber:k,maxAttempts:m,outcome:"location_mismatch",\u006b\u0065\u0072\u006e\u0065\u006cSessionId:J.cleanup.\u006b\u0065\u0072\u006e\u0065\u006cSessionId,questionCount:Mt.totalQuestions,durationMs:Date.now()-A,error:at.message,willRetry:it,cleanup:J.cleanup,debug:J.debug,completedAt:new Date().toISOString()}),B=at,it)continue;break}let Ye=await ei(Mt,O),z=Za(Xa(ti(Ye,w),H.maxQuestions,H.questionsOnly),b,v.attemptKind==="provider_fallback"?1:0),he=Ao(z),It=he==="degraded_result"&&T&&!P?.aborted&&b<m-1&&_(),Je=he==="degraded_result"?xo(z):null;if(It&&console.warn(JSON.stringify({event:"harvest_attempt_degraded_result",attempt_number:k,max_attempts:m,degradation_reasons:z.diagnostics.degradationReasons,will_retry:!0})),await Ve(i,{type:"finished",attemptNumber:k,maxAttempts:m,outcome:he,\u006b\u0065\u0072\u006e\u0065\u006cSessionId:J.cleanup.\u006b\u0065\u0072\u006e\u0065\u006cSessionId,questionCount:z.totalQuestions,durationMs:Date.now()-A,error:Je,willRetry:It,cleanup:J.cleanup,debug:J.debug,completedAt:new Date().toISOString()}),It)continue;return(H.format==="json"||H.format==="both")&&await F.writeJSON(z,H.outputDir),(H.format==="csv"||H.format==="both")&&await Promise.all([F.writeCSV(z.flat,H.outputDir),z.videos.length>0?F.writeVideoCSV(z.videos,z.seed,H.outputDir):Promise.resolve(""),z.forums.length>0?F.writeForumCSV(z.forums,z.seed,H.outputDir):Promise.resolve(""),z.aiOverview.detected?F.writeAIOverviewCSV(z.aiOverview.citations,z.aiOverview.text,z.seed,H.outputDir):Promise.resolve(""),z.aiMode.detected?F.writeAIModeCSV(z.aiMode.citations,z.aiMode.text,z.seed,H.outputDir):Promise.resolve(""),z.whatPeopleSaying.length>0?F.writeWhatPeopleSayingCSV(z.whatPeopleSaying,z.seed,H.outputDir):Promise.resolve("")]),z}catch(v){a&&M&&!q&&(T=!1,await Xn(a,M,{\u006b\u0065\u0072\u006e\u0065\u006cSessionId:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted:!1,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:null,browserCloseSucceeded:null,browserCloseError:Vt(v),physicalOutcome:"unknown",extractionDrained:!0,disposableProxyDeleted:!1}).catch(()=>{}));let R=Ge(v);(R==="captcha"||R==="proxy_tunnel_failed")&&I==="location"&&(K++,K>=2&&(I="none"));let f=T&&!P?.aborted&&b<m-1&&_()&&(R==="captcha"||Oo(R)||r==="location"&&Wo(R));if(R==="captcha"?console.warn(JSON.stringify({event:"harvest_attempt_captcha",attempt_number:k,max_attempts:m,message:Vt(v),will_retry:f})):f&&console.warn(JSON.stringify({event:"harvest_attempt_proxy_retry",attempt_number:k,max_attempts:m,outcome:R,message:Vt(v),will_retry:f})),await Ve(i,{type:"finished",attemptNumber:k,maxAttempts:m,outcome:R,\u006b\u0065\u0072\u006e\u0065\u006cSessionId:null,questionCount:0,durationMs:Date.now()-A,error:Vt(v),willRetry:f,cleanup:{\u006b\u0065\u0072\u006e\u0065\u006cSessionId:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted:!1,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:null,\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:null,browserCloseSucceeded:null,browserCloseError:null},debug:null,completedAt:new Date().toISOString()}),B=v,f)continue;if(R==="captcha")break;throw v}finally{G?.stop()}}throw B&&!(B instanceof et)?B:(console.warn(JSON.stringify({event:"harvest_captcha_exhausted",max_attempts:m,session_kind:l?"\u006b\u0065\u0072\u006e\u0065\u006c":"local"})),new et(bi(`CAPTCHA on all ${m} fresh sessions. Try again in a few minutes.`)))}var Yo=require("child_process"),pt=require("fs"),ci=require("os"),ce=require("path"),ue=require("@fal-ai/client");var lS="https://api.deepinfra.com/v1/openai/chat/completions",Eo="https://openrouter.ai/api/v1/chat/completions",ai="Qwen/Qwen3.6-35B-A3B",SS=`You are a video prompt engineer for Seedance 2.0 text-to-video AI.
21793
21793
 
21794
21794
  IMPORTANT TECHNICAL CONTEXT: Clip 2 will be generated using image-to-video, meaning it will start from the exact last frame of Clip 1. The two clips will be visually seamless \u2014 same location, same characters, continuous motion. You must write prompts that make this feel like one uninterrupted 16-second video.
21795
21795
 
@@ -21813,7 +21813,7 @@ Rules for visuals:
21813
21813
  Respond with JSON only:
21814
21814
  {"clip1": "...", "clip2": "...", "voiceover": "...", "audioMood": "..."}`;async function Ro(e,t,n,a){let i=await fetch(t,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({model:ai,temperature:.7,messages:[{role:"system",content:SS},{role:"user",content:`Question: ${n}
21815
21815
 
21816
- Answer: ${a.slice(0,500)}`}]})});if(!i.ok)throw new Error(`LLM call failed (${i.status}): ${await i.text()}`);let s=await i.json();t===Eo?_a({vendor:"openrouter",model:ai,units:s.usage?.cost??0,unitType:"usd"}):_a({vendor:"deepinfra_qwen",model:ai,units:s.usage?.completion_tokens??0,unitType:"tokens"});let o=s.choices[0]?.message?.content?.trim()??"",d=o.match(/\{[\s\S]*\}/);if(!d)throw new Error(`No JSON in QWEN response: ${o.slice(0,200)}`);let S=JSON.parse(d[0]);if(!S.clip1||!S.clip2||!S.voiceover||!S.audioMood)throw new Error(`QWEN response missing fields: ${o.slice(0,200)}`);return S}async function Yn(e,t){let n=process.env.DEEPINFRA_API_KEY,a=process.env.OPENROUTER_API_KEY;if(n)try{return await Ro(n,lS,e,t)}catch(i){console.warn("[promptBuilder] DeepInfra failed, trying OpenRouter:",i.message)}if(a)return await Ro(a,Eo,e,t);throw new Error("No LLM key \u2014 set DEEPINFRA_API_KEY or OPENROUTER_API_KEY")}function Ho(e){if(!e.clip1||!e.clip2||!e.voiceover||!e.audioMood)throw new Error("Episode brief is missing prompt fields \u2014 run blog-to-video skill to regenerate");return{clip1:e.clip1,clip2:e.clip2,voiceover:e.voiceover,audioMood:e.audioMood}}var un=require("fs"),ii=require("path"),_o=require("os"),Jn=require("@fal-ai/client"),US="fal-ai/mmaudio-v2",cS="fal-ai/elevenlabs/tts",uS="fal-ai/google/gemini-2.5-flash-preview-tts";async function Fo(e){let t=await fetch(e);if(!t.ok)throw new Error(`Failed to download TTS audio (${t.status})`);return Buffer.from(await t.arrayBuffer())}async function si(e){console.log("[AudioGenerator] Generating voiceover...");let t=(0,ii.join)((0,_o.tmpdir)(),`tts-${Date.now()}`);(0,un.mkdirSync)(t,{recursive:!0});let n=(0,ii.join)(t,"voiceover.mp3");try{let s=process.env.ELEVENLABS_VOICE_ID??"pNInz6obpgDQGcFmaJgB",o=await Jn.fal.run(cS,{input:{text:e,voice_id:s,model_id:"eleven_v3"}});return(0,un.writeFileSync)(n,await Fo(o.audio.url)),console.log("[AudioGenerator] TTS: ElevenLabs via fal"),n}catch(s){console.warn("[AudioGenerator] ElevenLabs via fal failed, trying Gemini:",s.message)}let a=process.env.GEMINI_TTS_VOICE??"Kore",i=await Jn.fal.run(uS,{input:{text:e,voice:a}});return(0,un.writeFileSync)(n,await Fo(i.audio.url)),console.log("[AudioGenerator] TTS: Gemini via fal"),n}async function oi(e,t,n){return console.log("[AudioGenerator] Adding background audio via MMAudio V2..."),(await Jn.fal.run(US,{input:{video_url:e,prompt:t,negative_prompt:"speech, voice, talking, dialogue, narration, vocals, singing, human voice, conversation, words, lyrics, announcer, commentary",duration:n,cfg_strength:4.5}})).video.url}var di=require("child_process"),qn=require("fs"),Ke=require("path"),Do=require("@fal-ai/client");async function ri(e,t){let n=await fetch(e);if(!n.ok)throw new Error(`Download failed (${n.status}): ${e}`);(0,qn.writeFileSync)(t,Buffer.from(await n.arrayBuffer()))}async function li(e,t,n){(0,qn.mkdirSync)(n,{recursive:!0});let a=Date.now(),i=(0,Ke.join)(n,`clip1-${a}.mp4`),s=(0,Ke.join)(n,`clip2-${a}.mp4`),o=(0,Ke.join)(n,`combined-${a}.mp4`);return console.log("[VideoMixer] Downloading clips..."),await Promise.all([ri(e,i),ri(t,s)]),console.log("[VideoMixer] Concatenating..."),(0,di.execSync)(`ffmpeg -i "${i}" -i "${s}" -filter_complex "[0:v][1:v]concat=n=2:v=1:a=0[v]" -map "[v]" -y "${o}" -loglevel error`),o}async function Si(e){let{readFileSync:t}=await import("fs"),n=new Blob([t(e)],{type:"video/mp4"}),a=await Do.fal.storage.upload(n);return console.log("[VideoMixer] Uploaded to fal:",a),a}async function Ui(e,t,n){let a=Date.now(),i=(0,Ke.join)(n,`voiceover-${a}.wav`),s=(0,Ke.join)(n,`final-${a}.mp4`);return console.log("[VideoMixer] Downloading voiceover..."),await ri(t,i),console.log("[VideoMixer] Mixing voiceover over background audio..."),(0,di.execSync)(`ffmpeg -i "${e}" -i "${i}" -filter_complex "[0:a]volume=0.2[bg];[1:a]volume=1.0[vo];[bg][vo]amix=inputs=2:duration=first[a]" -map 0:v -map "[a]" -c:v copy -y "${s}" -loglevel error`),s}var Go="bytedance/seedance-2.0/text-to-video",Vo="bytedance/seedance-2.0/image-to-video";function zn(e,t,n,a){return{prompt:e,resolution:t.resolution??"720p",duration:t.clipDurationSeconds??8,aspect_ratio:t.aspectRatio??"16:9",generate_audio:!1,...n!==void 0?{seed:n}:{},...a!==void 0?{image_url:a}:{}}}async function $n(e,t){let{request_id:n}=await ue.fal.queue.submit(e,{input:t});for(console.log(`[fal] submitted ${e} \u2192 ${n}`);;){await new Promise(s=>setTimeout(s,5e3));let a=await ue.fal.queue.status(e,{requestId:n,logs:!1});if(console.log(`[fal] ${n} \u2192 ${a.status}`),a.status==="FAILED")throw new Error(`Request ${n} failed`);if(a.status!=="COMPLETED")continue;return(await ue.fal.queue.result(e,{requestId:n})).data}}async function Ko(e,t){let n=Date.now(),a=(0,ce.join)(t,`clip1-raw-${n}.mp4`),i=(0,ce.join)(t,`last-frame-${n}.jpg`),s=await fetch(e);if(!s.ok)throw new Error(`Failed to download clip 1 (${s.status})`);(0,pt.writeFileSync)(a,Buffer.from(await s.arrayBuffer()));try{(0,Yo.execSync)(`ffmpeg -sseof -0.1 -i "${a}" -vframes 1 -y "${i}" -loglevel error`)}finally{try{(0,pt.unlinkSync)(a)}catch{}}return i}var jn=class{constructor(t){let n=t??process.env.FAL_KEY;if(!n)throw new Error("FAL_KEY is required");ue.fal.config({credentials:n})}async generateClipPair(t,n,a={}){let i=a.outputDir??(0,ce.join)((0,ci.tmpdir)(),`paa-video-${Date.now()}`);(0,pt.mkdirSync)(i,{recursive:!0}),console.log(`
21816
+ Answer: ${a.slice(0,500)}`}]})});if(!i.ok)throw new Error(`LLM call failed (${i.status}): ${await i.text()}`);let s=await i.json();t===Eo?Da({vendor:"openrouter",model:ai,units:s.usage?.cost??0,unitType:"usd"}):Da({vendor:"deepinfra_qwen",model:ai,units:s.usage?.completion_tokens??0,unitType:"tokens"});let o=s.choices[0]?.message?.content?.trim()??"",d=o.match(/\{[\s\S]*\}/);if(!d)throw new Error(`No JSON in QWEN response: ${o.slice(0,200)}`);let S=JSON.parse(d[0]);if(!S.clip1||!S.clip2||!S.voiceover||!S.audioMood)throw new Error(`QWEN response missing fields: ${o.slice(0,200)}`);return S}async function Yn(e,t){let n=process.env.DEEPINFRA_API_KEY,a=process.env.OPENROUTER_API_KEY;if(n)try{return await Ro(n,lS,e,t)}catch(i){console.warn("[promptBuilder] DeepInfra failed, trying OpenRouter:",i.message)}if(a)return await Ro(a,Eo,e,t);throw new Error("No LLM key \u2014 set DEEPINFRA_API_KEY or OPENROUTER_API_KEY")}function Ho(e){if(!e.clip1||!e.clip2||!e.voiceover||!e.audioMood)throw new Error("Episode brief is missing prompt fields \u2014 run blog-to-video skill to regenerate");return{clip1:e.clip1,clip2:e.clip2,voiceover:e.voiceover,audioMood:e.audioMood}}var un=require("fs"),ii=require("path"),Do=require("os"),Jn=require("@fal-ai/client"),US="fal-ai/mmaudio-v2",cS="fal-ai/elevenlabs/tts",uS="fal-ai/google/gemini-2.5-flash-preview-tts";async function Fo(e){let t=await fetch(e);if(!t.ok)throw new Error(`Failed to download TTS audio (${t.status})`);return Buffer.from(await t.arrayBuffer())}async function si(e){console.log("[AudioGenerator] Generating voiceover...");let t=(0,ii.join)((0,Do.tmpdir)(),`tts-${Date.now()}`);(0,un.mkdirSync)(t,{recursive:!0});let n=(0,ii.join)(t,"voiceover.mp3");try{let s=process.env.ELEVENLABS_VOICE_ID??"pNInz6obpgDQGcFmaJgB",o=await Jn.fal.run(cS,{input:{text:e,voice_id:s,model_id:"eleven_v3"}});return(0,un.writeFileSync)(n,await Fo(o.audio.url)),console.log("[AudioGenerator] TTS: ElevenLabs via fal"),n}catch(s){console.warn("[AudioGenerator] ElevenLabs via fal failed, trying Gemini:",s.message)}let a=process.env.GEMINI_TTS_VOICE??"Kore",i=await Jn.fal.run(uS,{input:{text:e,voice:a}});return(0,un.writeFileSync)(n,await Fo(i.audio.url)),console.log("[AudioGenerator] TTS: Gemini via fal"),n}async function oi(e,t,n){return console.log("[AudioGenerator] Adding background audio via MMAudio V2..."),(await Jn.fal.run(US,{input:{video_url:e,prompt:t,negative_prompt:"speech, voice, talking, dialogue, narration, vocals, singing, human voice, conversation, words, lyrics, announcer, commentary",duration:n,cfg_strength:4.5}})).video.url}var di=require("child_process"),qn=require("fs"),Ke=require("path"),_o=require("@fal-ai/client");async function ri(e,t){let n=await fetch(e);if(!n.ok)throw new Error(`Download failed (${n.status}): ${e}`);(0,qn.writeFileSync)(t,Buffer.from(await n.arrayBuffer()))}async function li(e,t,n){(0,qn.mkdirSync)(n,{recursive:!0});let a=Date.now(),i=(0,Ke.join)(n,`clip1-${a}.mp4`),s=(0,Ke.join)(n,`clip2-${a}.mp4`),o=(0,Ke.join)(n,`combined-${a}.mp4`);return console.log("[VideoMixer] Downloading clips..."),await Promise.all([ri(e,i),ri(t,s)]),console.log("[VideoMixer] Concatenating..."),(0,di.execSync)(`ffmpeg -i "${i}" -i "${s}" -filter_complex "[0:v][1:v]concat=n=2:v=1:a=0[v]" -map "[v]" -y "${o}" -loglevel error`),o}async function Si(e){let{readFileSync:t}=await import("fs"),n=new Blob([t(e)],{type:"video/mp4"}),a=await _o.fal.storage.upload(n);return console.log("[VideoMixer] Uploaded to fal:",a),a}async function Ui(e,t,n){let a=Date.now(),i=(0,Ke.join)(n,`voiceover-${a}.wav`),s=(0,Ke.join)(n,`final-${a}.mp4`);return console.log("[VideoMixer] Downloading voiceover..."),await ri(t,i),console.log("[VideoMixer] Mixing voiceover over background audio..."),(0,di.execSync)(`ffmpeg -i "${e}" -i "${i}" -filter_complex "[0:a]volume=0.2[bg];[1:a]volume=1.0[vo];[bg][vo]amix=inputs=2:duration=first[a]" -map 0:v -map "[a]" -c:v copy -y "${s}" -loglevel error`),s}var Go="bytedance/seedance-2.0/text-to-video",Vo="bytedance/seedance-2.0/image-to-video";function zn(e,t,n,a){return{prompt:e,resolution:t.resolution??"720p",duration:t.clipDurationSeconds??8,aspect_ratio:t.aspectRatio??"16:9",generate_audio:!1,...n!==void 0?{seed:n}:{},...a!==void 0?{image_url:a}:{}}}async function $n(e,t){let{request_id:n}=await ue.fal.queue.submit(e,{input:t});for(console.log(`[fal] submitted ${e} \u2192 ${n}`);;){await new Promise(s=>setTimeout(s,5e3));let a=await ue.fal.queue.status(e,{requestId:n,logs:!1});if(console.log(`[fal] ${n} \u2192 ${a.status}`),a.status==="FAILED")throw new Error(`Request ${n} failed`);if(a.status!=="COMPLETED")continue;return(await ue.fal.queue.result(e,{requestId:n})).data}}async function Ko(e,t){let n=Date.now(),a=(0,ce.join)(t,`clip1-raw-${n}.mp4`),i=(0,ce.join)(t,`last-frame-${n}.jpg`),s=await fetch(e);if(!s.ok)throw new Error(`Failed to download clip 1 (${s.status})`);(0,pt.writeFileSync)(a,Buffer.from(await s.arrayBuffer()));try{(0,Yo.execSync)(`ffmpeg -sseof -0.1 -i "${a}" -vframes 1 -y "${i}" -loglevel error`)}finally{try{(0,pt.unlinkSync)(a)}catch{}}return i}var jn=class{constructor(t){let n=t??process.env.FAL_KEY;if(!n)throw new Error("FAL_KEY is required");ue.fal.config({credentials:n})}async generateClipPair(t,n,a={}){let i=a.outputDir??(0,ce.join)((0,ci.tmpdir)(),`paa-video-${Date.now()}`);(0,pt.mkdirSync)(i,{recursive:!0}),console.log(`
21817
21817
  [1/7] Generating prompts via QWEN 3.6...`);let s=await Yn(t,n);console.log(" Voiceover:",s.voiceover),console.log(" Audio mood:",s.audioMood),console.log(`
21818
21818
  [2/7] Generating clip 1 (text-to-video)...`);let o=await $n(Go,zn(s.clip1,a,a.seed));console.log(`
21819
21819
  [3/7] Extracting last frame \u2192 clip 2 start...`);let d=await Ko(o.video.url,i),S=new Blob([(0,pt.readFileSync)(d)],{type:"image/jpeg"}),U=await ue.fal.storage.upload(S);try{(0,pt.unlinkSync)(d)}catch{}console.log(`