mcp-scraper 0.88.2 → 0.89.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CHANGELOG.md +36 -15
  2. package/README.md +6 -5
  3. package/THIRD_PARTY_NOTICES.html +203 -0
  4. package/dist/analytics-repository-2BMT5JNE.js +1 -0
  5. package/dist/bin/api-server.js +2 -41
  6. package/dist/bin/mcp-scraper-cli.js +39 -756
  7. package/dist/bin/mcp-scraper-core.js +1 -60
  8. package/dist/bin/mcp-scraper-install.js +2 -25
  9. package/dist/bin/mcp-stdio-server.js +1 -19
  10. package/dist/bin/paa-harvest.js +1 -41
  11. package/dist/chunk-3GP5CYZX.js +1 -0
  12. package/dist/chunk-4AI7DOS7.js +59 -0
  13. package/dist/chunk-4FROKQJN.js +1 -0
  14. package/dist/chunk-7YGVI5J4.js +21710 -0
  15. package/dist/chunk-CCYWSJNG.js +16 -0
  16. package/dist/chunk-CFI6CXIV.js +182 -0
  17. package/dist/chunk-E2WRWV3A.js +1 -0
  18. package/dist/chunk-GMWKPIYX.js +1172 -0
  19. package/dist/chunk-HDPYG3XV.js +102 -0
  20. package/dist/chunk-HE45FFBU.js +1 -0
  21. package/dist/chunk-HUV2WTRW.js +1 -0
  22. package/dist/chunk-KJQXUZ4Y.js +4 -0
  23. package/dist/chunk-L4CGLFPU.js +4 -0
  24. package/dist/chunk-M22MM4N4.js +84 -0
  25. package/dist/chunk-MASR22K4.js +73 -0
  26. package/dist/chunk-MZN4U5BL.js +1 -0
  27. package/dist/chunk-PUHFVA7P.js +1280 -0
  28. package/dist/chunk-QPWPR5XG.js +10 -0
  29. package/dist/chunk-TMB56NCA.js +1 -0
  30. package/dist/chunk-TXENITMS.js +20 -0
  31. package/dist/chunk-W2BVJ7S2.js +13 -0
  32. package/dist/chunk-WO3N5FH2.js +5 -0
  33. package/dist/chunk-WSCGYRWA.js +2595 -0
  34. package/dist/chunk-X54CQLK2.js +1 -0
  35. package/dist/chunk-XLWNEVUZ.js +27 -0
  36. package/dist/chunk-XPZVJIZ2.js +100 -0
  37. package/dist/chunk-YQZGZBB4.js +1 -0
  38. package/dist/chunk-Z2QGQJS2.js +1 -0
  39. package/dist/db-F2MX63GI.js +1 -0
  40. package/dist/extract-bundle-SNUIHM3J.js +26 -0
  41. package/dist/gmail-service-BZ3H75XC.js +1 -0
  42. package/dist/index.cjs +21750 -6045
  43. package/dist/index.d.cts +14 -14
  44. package/dist/index.d.ts +14 -14
  45. package/dist/index.js +18 -315
  46. package/dist/lead-list-enrichment-repository-S2H3U7T7.js +1 -0
  47. package/dist/location-data-repository-OTWHWMV6.js +1 -0
  48. package/dist/server-RFR2A5UJ.js +7303 -0
  49. package/dist/site-extract-repository-SE776XDC.js +1 -0
  50. package/dist/worker-XUDSM3AL.js +1 -0
  51. package/package.json +17 -124
  52. package/dist/analytics-repository-GGJJCVVP.js +0 -194
  53. package/dist/chunk-4QMUF6XM.js +0 -1013
  54. package/dist/chunk-6HAV7LCE.js +0 -265
  55. package/dist/chunk-ABF2CGOZ.js +0 -113
  56. package/dist/chunk-C5Z4OFKW.js +0 -404
  57. package/dist/chunk-DNM65UCK.js +0 -299
  58. package/dist/chunk-EQGTEHLZ.js +0 -592
  59. package/dist/chunk-F5GQJWZU.js +0 -732
  60. package/dist/chunk-GGZEC22A.js +0 -215
  61. package/dist/chunk-GXBZXWXB.js +0 -184
  62. package/dist/chunk-IHXAXYIS.js +0 -843
  63. package/dist/chunk-K3Z5AQYE.js +0 -683
  64. package/dist/chunk-K45K75OF.js +0 -6
  65. package/dist/chunk-LFW2FRPJ.js +0 -224
  66. package/dist/chunk-MZDNZQWT.js +0 -2078
  67. package/dist/chunk-NVUKO5NN.js +0 -256
  68. package/dist/chunk-OM7HVEJ3.js +0 -26
  69. package/dist/chunk-OPQIGAFB.js +0 -286
  70. package/dist/chunk-OZJMVCDK.js +0 -16
  71. package/dist/chunk-P7FWOMU7.js +0 -505
  72. package/dist/chunk-PGJQDMC2.js +0 -383
  73. package/dist/chunk-PKZS6SHW.js +0 -33139
  74. package/dist/chunk-RJ7JVYKU.js +0 -68
  75. package/dist/chunk-S24LFPL7.js +0 -5262
  76. package/dist/chunk-T3MZISOF.js +0 -240
  77. package/dist/chunk-UZPTGUDV.js +0 -1915
  78. package/dist/chunk-X623GTBV.js +0 -8290
  79. package/dist/chunk-YXNDOQXN.js +0 -4018
  80. package/dist/db-Z34LPZNR.js +0 -284
  81. package/dist/extract-bundle-565SBZCR.js +0 -1003
  82. package/dist/gmail-service-E6ALS7JG.js +0 -25
  83. package/dist/lead-list-enrichment-repository-36RPVV6N.js +0 -67
  84. package/dist/location-data-repository-WPRG62GE.js +0 -34
  85. package/dist/server-SQZ3A7SY.js +0 -86606
  86. package/dist/site-extract-repository-VYFZASPU.js +0 -69
  87. package/dist/worker-LDCAULWL.js +0 -146
@@ -0,0 +1,10 @@
1
+ function S(r,e,t,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!o:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(r,t):o?o.value=t:e.set(r,t),t}function _(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}var ct=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return ct=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};function Ue(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var ve=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};var x=class extends Error{},I=class r extends x{constructor(e,t,n,o){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=o,this.error=t}static makeMessage(e,t,n){let o=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,t,n,o){if(!e||!o)return new K({message:n,cause:ve(t)});let s=t;return e===400?new fe(e,s,n,o):e===401?new de(e,s,n,o):e===403?new pe(e,s,n,o):e===404?new he(e,s,n,o):e===409?new me(e,s,n,o):e===422?new ye(e,s,n,o):e===429?new ge(e,s,n,o):e>=500?new we(e,s,n,o):new r(e,s,n,o)}},T=class extends I{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},K=class extends I{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},D=class extends K{constructor({message:e}={}){super({message:e??"Request timed out."})}},fe=class extends I{},de=class extends I{},pe=class extends I{},he=class extends I{},me=class extends I{},ye=class extends I{},ge=class extends I{},we=class extends I{};var Er=/^[a-z][a-z0-9+.-]*:/i,vt=r=>Er.test(r),$=r=>($=Array.isArray,$(r)),lt=$;function ut(r){return typeof r!="object"?{}:r??{}}function ft(r){if(!r)return!0;for(let e in r)return!1;return!0}function Dt(r,e){return Object.prototype.hasOwnProperty.call(r,e)}var Nt=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new x(`${r} must be an integer`);if(e<0)throw new x(`${r} must be a positive integer`);return e},Sr=r=>{if(typeof r=="number")return Math.round(r);if(typeof r=="string")return parseInt(r,10);throw new x(`Could not coerce ${r} (type: ${typeof r}) into a number`)};var Ir=r=>typeof r=="boolean"?r:typeof r=="string"?r==="true":!!r,Ht=r=>{if(r!=null)return Sr(r)};var dt=r=>{if(r!=null)return Ir(r)},Bt=r=>{try{return JSON.parse(r)}catch{return}};var Mt=r=>new Promise(e=>setTimeout(e,r));var W="0.93.0";function $r(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var Lr=()=>{let r=$r();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":Kt(Deno.build.os),"X-Stainless-Arch":qt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":Kt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":qt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Tr();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Tr(){if(typeof navigator>"u"||!navigator)return null;let r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${s}.${a}`}}}return null}var qt=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Kt=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),Wt,Xt=()=>Wt??(Wt=Lr());function zt(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new \u004b\u0065\u0072\u006e\u0065\u006c({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function pt(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function ze(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return pt({start(){},async pull(t){let{done:n,value:o}=await e.next();n?t.close():t.enqueue(o)},async cancel(){await e.return?.()}})}function ht(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Vt(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}var Jt=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var mt="RFC3986",yt=r=>String(r),gt={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:yt},Gt="RFC1738";var Ve=(r,e)=>(Ve=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ve(r,e)),v=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var wt=1024,Qt=(r,e,t,n,o)=>{if(r.length===0)return r;let s=r;if(typeof r=="symbol"?s=Symbol.prototype.toString.call(r):typeof r!="string"&&(s=String(r)),t==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let a="";for(let c=0;c<s.length;c+=wt){let f=s.length>=wt?s.slice(c,c+wt):s,d=[];for(let m=0;m<f.length;++m){let l=f.charCodeAt(m);if(l===45||l===46||l===95||l===126||l>=48&&l<=57||l>=65&&l<=90||l>=97&&l<=122||o===Gt&&(l===40||l===41)){d[d.length]=f.charAt(m);continue}if(l<128){d[d.length]=v[l];continue}if(l<2048){d[d.length]=v[192|l>>6]+v[128|l&63];continue}if(l<55296||l>=57344){d[d.length]=v[224|l>>12]+v[128|l>>6&63]+v[128|l&63];continue}m+=1,l=65536+((l&1023)<<10|f.charCodeAt(m)&1023),d[d.length]=v[240|l>>18]+v[128|l>>12&63]+v[128|l>>6&63]+v[128|l&63]}a+=d.join("")}return a};function Yt(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function bt(r,e){if($(r)){let t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}var er={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},tr=function(r,e){Array.prototype.push.apply(r,$(e)?e:[e])},Zt,R={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Qt,encodeValuesOnly:!1,format:mt,formatter:yt,indices:!1,serializeDate(r){return(Zt??(Zt=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function Cr(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var xt={};function rr(r,e,t,n,o,s,a,c,f,d,m,l,g,h,A,E,U,k){let b=r,J=k,G=0,it=!1;for(;(J=J.get(xt))!==void 0&&!it;){let L=J.get(r);if(G+=1,typeof L<"u"){if(L===G)throw new RangeError("Cyclic object value");it=!0}typeof J.get(xt)>"u"&&(G=0)}if(typeof d=="function"?b=d(e,b):b instanceof Date?b=g?.(b):t==="comma"&&$(b)&&(b=bt(b,function(L){return L instanceof Date?g?.(L):L})),b===null){if(s)return f&&!E?f(e,R.encoder,U,"key",h):e;b=""}if(Cr(b)||Yt(b)){if(f){let L=E?e:f(e,R.encoder,U,"key",h);return[A?.(L)+"="+A?.(f(b,R.encoder,U,"value",h))]}return[A?.(e)+"="+A?.(String(b))]}let q=[];if(typeof b>"u")return q;let Fe;if(t==="comma"&&$(b))E&&f&&(b=bt(b,f)),Fe=[{value:b.length>0?b.join(",")||null:void 0}];else if($(d))Fe=d;else{let L=Object.keys(b);Fe=m?L.sort(m):L}let kt=c?String(e).replace(/\./g,"%2E"):String(e),Xe=n&&$(b)&&b.length===1?kt+"[]":kt;if(o&&$(b)&&b.length===0)return Xe+"[]";for(let L=0;L<Fe.length;++L){let ue=Fe[L],Ft=typeof ue=="object"&&typeof ue.value<"u"?ue.value:b[ue];if(a&&Ft===null)continue;let at=l&&c?ue.replace(/\./g,"%2E"):ue,Rr=$(b)?typeof t=="function"?t(Xe,at):Xe:Xe+(l?"."+at:"["+at+"]");k.set(r,G);let Ut=new WeakMap;Ut.set(xt,k),tr(q,rr(Ft,Rr,t,n,o,s,a,c,t==="comma"&&E&&$(b)?null:f,d,m,l,g,h,A,E,U,Ut))}return q}function kr(r=R){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||R.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=mt;if(typeof r.format<"u"){if(!Ve(gt,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=gt[t],o=R.filter;(typeof r.filter=="function"||$(r.filter))&&(o=r.filter);let s;if(r.arrayFormat&&r.arrayFormat in er?s=r.arrayFormat:"indices"in r?s=r.indices?"indices":"repeat":s=R.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:R.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:R.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:R.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:R.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?R.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:R.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:R.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:R.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:R.encodeValuesOnly,filter:o,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:R.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:R.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:R.strictNullHandling}}function nr(r,e={}){let t=r,n=kr(e),o,s;typeof n.filter=="function"?(s=n.filter,t=s("",t)):$(n.filter)&&(s=n.filter,o=s);let a=[];if(typeof t!="object"||t===null)return"";let c=er[n.arrayFormat],f=c==="comma"&&n.commaRoundTrip;o||(o=Object.keys(t)),n.sort&&o.sort(n.sort);let d=new WeakMap;for(let g=0;g<o.length;++g){let h=o[g];n.skipNulls&&t[h]===null||tr(a,rr(t[h],h,c,f,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,d))}let m=a.join(n.delimiter),l=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?l+="utf8=%26%2310003%3B&":l+="utf8=%E2%9C%93&"),m.length>0?l+m:""}function or(r){return nr(r,{arrayFormat:"comma"})}function ar(r){let e=0;for(let o of r)e+=o.length;let t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var sr;function De(r){let e;return(sr??(e=new globalThis.TextEncoder,sr=e.encode.bind(e)))(r)}var ir;function _t(r){let e;return(ir??(e=new globalThis.TextDecoder,ir=e.decode.bind(e)))(r)}var j,C,Q=class{constructor(){j.set(this,void 0),C.set(this,void 0),S(this,j,new Uint8Array,"f"),S(this,C,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?De(e):e;S(this,j,ar([_(this,j,"f"),t]),"f");let n=[],o;for(;(o=Ur(_(this,j,"f"),_(this,C,"f")))!=null;){if(o.carriage&&_(this,C,"f")==null){S(this,C,o.index,"f");continue}if(_(this,C,"f")!=null&&(o.index!==_(this,C,"f")+1||o.carriage)){n.push(_t(_(this,j,"f").subarray(0,_(this,C,"f")-1))),S(this,j,_(this,j,"f").subarray(_(this,C,"f")),"f"),S(this,C,null,"f");continue}let s=_(this,C,"f")!==null?o.preceding-1:o.preceding,a=_t(_(this,j,"f").subarray(0,s));n.push(a),S(this,j,_(this,j,"f").subarray(o.index),"f"),S(this,C,null,"f")}return n}flush(){return _(this,j,"f").length?this.decode(`
2
+ `):[]}};j=new WeakMap,C=new WeakMap;Q.NEWLINE_CHARS=new Set([`
3
+ `,"\r"]);Q.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ur(r,e){for(let o=e??0;o<r.length;o++){if(r[o]===10)return{preceding:o,index:o+1,carriage:!1};if(r[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function cr(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}var Ge={off:0,error:200,warn:300,info:400,debug:500},At=(r,e,t)=>{if(r){if(Dt(Ge,r))return r;P(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(Ge))}`)}};function Ne(){}function Je(r,e,t){return!e||Ge[r]>Ge[t]?Ne:e[r].bind(e)}var vr={error:Ne,warn:Ne,info:Ne,debug:Ne},lr=new WeakMap;function P(r){let e=r.logger,t=r.logLevel??"off";if(!e)return vr;let n=lr.get(e);if(n&&n[0]===t)return n[1];let o={error:Je("error",e,t),warn:Je("warn",e,t),info:Je("info",e,t),debug:Je("debug",e,t)};return lr.set(e,[t,o]),o}var N=r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r);var He,Qe=class r{constructor(e,t,n){this.iterator=e,He.set(this,void 0),this.controller=t,S(this,He,n,"f")}static fromSSEResponse(e,t,n){let o=!1,s=n?P(n):console;async function*a(){if(o)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let c=!1;try{for await(let f of Dr(e,t))try{yield JSON.parse(f.data)}catch(d){throw s.error("Could not parse message into JSON:",f.data),s.error("From chunk:",f.raw),d}c=!0}catch(f){if(Ue(f))return;throw f}finally{c||t.abort()}}return new r(a,t,n)}static fromReadableStream(e,t,n){let o=!1;async function*s(){let c=new Q,f=ht(e);for await(let d of f)for(let m of c.decode(d))yield m;for(let d of c.flush())yield d}async function*a(){if(o)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let c=!1;try{for await(let f of s())c||f&&(yield JSON.parse(f));c=!0}catch(f){if(Ue(f))return;throw f}finally{c||t.abort()}}return new r(a,t,n)}[(He=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),o=s=>({next:()=>{if(s.length===0){let a=n.next();e.push(a),t.push(a)}return s.shift()}});return[new r(()=>o(e),this.controller,_(this,He,"f")),new r(()=>o(t),this.controller,_(this,He,"f"))]}toReadableStream(){let e=this,t;return pt({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:s}=await t.next();if(s)return n.close();let a=De(JSON.stringify(o)+`
4
+ `);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await t.return?.()}})}};async function*Dr(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new x("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new x("Attempted to iterate over a response with no body");let t=new Rt,n=new Q,o=ht(r.body);for await(let s of Nr(o))for(let a of n.decode(s)){let c=t.decode(a);c&&(yield c)}for(let s of n.flush()){let a=t.decode(s);a&&(yield a)}}async function*Nr(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?De(t):t,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=cr(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var Rt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
5
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,o]=Hr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),t==="event"?this.event=o:t==="data"&&this.data.push(o),null}};function Hr(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}async function Ye(r,e){let{response:t,requestLogID:n,retryOfRequestLogID:o,startTime:s}=e,a=await(async()=>{if(e.options.stream)return P(r).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,r):Qe.fromSSEResponse(t,e.controller,r);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let f=t.headers.get("content-type")?.split(";")[0]?.trim();return f?.includes("application/json")||f?.endsWith("+json")?t.headers.get("content-length")==="0"?void 0:await t.json():await t.text()})();return P(r).debug(`[${n}] response parsed`,N({retryOfRequestLogID:o,url:t.url,status:t.status,body:a,durationMs:Date.now()-s})),a}var Be,Y=class r extends Promise{constructor(e,t,n=Ye){super(o=>{o(null)}),this.responsePromise=t,this.parseResponse=n,Be.set(this,void 0),S(this,Be,e,"f")}_thenUnwrap(e){return new r(_(this,Be,"f"),this.responsePromise,async(t,n)=>e(await this.parseResponse(t,n),n))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(_(this,Be,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Be=new WeakMap;var Ze,et=class{constructor(e,t,n,o){Ze.set(this,void 0),S(this,Ze,e,"f"),this.options=o,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new x("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await _(this,Ze,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ze=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Me=class extends Y{constructor(e,t,n){super(e,t,async(o,s)=>new n(o,s.response,await Ye(o,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},tt=class extends et{constructor(e,t,n,o){super(e,t,n,o),this.items=n||[],this.next_page_token=this.response.headers.get("x-next-page-token")??null,this.has_more=dt(this.response.headers.get("x-has-more"))??null}getPaginatedItems(){return this.items??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next_page_token;return e?{...this.options,query:{...ut(this.options.query),page_token:e}}:null}},w=class extends et{constructor(e,t,n,o){super(e,t,n,o),this.items=n||[],this.has_more=dt(this.response.headers.get("x-has-more"))??null,this.next_offset=Ht(this.response.headers.get("x-next-offset"))??null}getPaginatedItems(){return this.items??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next_offset;if(e==null){if(this.has_more)throw new x("Server reported X-Has-More: true without an X-Next-Offset header; refusing to silently truncate pagination");return null}return e===0?null:{...this.options,query:{...ut(this.options.query),offset:e}}}};var St=()=>{if(typeof File>"u"){let{process:r}=globalThis,e=typeof r?.versions?.node=="string"&&parseInt(r.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function be(r,e,t){return St(),new File(r,e??"unknown_file",t)}function qe(r){return(typeof r=="object"&&r!==null&&("name"in r&&r.name&&String(r.name)||"url"in r&&r.url&&String(r.url)||"filename"in r&&r.filename&&String(r.filename)||"path"in r&&r.path&&String(r.path))||"").split(/[\\/]/).pop()||void 0}var rt=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function";var H=async(r,e)=>({...r,body:await qr(r.body,e)}),ur=new WeakMap;function Mr(r){let e=typeof r=="function"?r:r.fetch,t=ur.get(e);if(t)return t;let n=(async()=>{try{let o="Response"in e?e.Response:(await e("data:,")).constructor,s=new FormData;return s.toString()!==await new o(s).text()}catch{return!0}})();return ur.set(e,n),n}var qr=async(r,e)=>{if(!await Mr(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let t=new FormData;return await Promise.all(Object.entries(r||{}).map(([n,o])=>Et(t,n,o))),t},fr=r=>r instanceof Blob&&"name"in r,Kr=r=>typeof r=="object"&&r!==null&&(r instanceof Response||rt(r)||fr(r)),Pt=r=>{if(Kr(r))return!0;if(Array.isArray(r))return r.some(Pt);if(r&&typeof r=="object"){for(let e in r)if(Pt(r[e]))return!0}return!1},Et=async(r,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")r.append(e,String(t));else if(t instanceof Response)r.append(e,be([await t.blob()],qe(t)));else if(rt(t))r.append(e,be([await new Response(ze(t)).blob()],qe(t)));else if(fr(t))r.append(e,t,qe(t));else if(Array.isArray(t))await Promise.all(t.map((n,o)=>Et(r,`${e}[${o}]`,n)));else if(typeof t=="object")!(e==="env_vars")&&!Pt(t)?Object.entries(t).filter(([s,a])=>a!==void 0).length>0&&r.append(e,JSON.stringify(t)):await Promise.all(Object.entries(t).map(([o,s])=>Et(r,`${e}[${o}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var dr=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function",Wr=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&dr(r),Xr=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function";async function nt(r,e,t){if(St(),r=await r,Wr(r))return r instanceof File?r:be([await r.arrayBuffer()],r.name);if(Xr(r)){let o=await r.blob();return e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()),be(await It(o),e,t)}let n=await It(r);if(e||(e=qe(r)),!t?.type){let o=n.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof o=="string"&&(t={...t,type:o})}return be(n,e,t)}async function It(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(dr(r))e.push(r instanceof Blob?r:await r.arrayBuffer());else if(rt(r))for await(let t of r)e.push(...await It(t));else{let t=r?.constructor?.name;throw new Error(`Unexpected data type: ${typeof r}${t?`; constructor: ${t}`:""}${zr(r)}`)}return e}function zr(r){return typeof r!="object"||r===null?"":`; props: [${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}var p=class{constructor(e){this._client=e}};var pr=Symbol("brand.privateNullableHeaders");function*Jr(r){if(!r)return;if(pr in r){let{values:n,nulls:o}=r;yield*n.entries();for(let s of o)yield[s,null];return}let e=!1,t;r instanceof Headers?t=r.entries():lt(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let n of t){let o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let s=lt(n[1])?n[1]:[n[1]],a=!1;for(let c of s)c!==void 0&&(e&&!a&&(a=!0,yield[o,null]),yield[o,c])}}var u=r=>{let e=new Headers,t=new Set;for(let n of r){let o=new Set;for(let[s,a]of Jr(n)){let c=s.toLowerCase();o.has(c)||(e.delete(s),o.add(c)),a===null?(e.delete(s),t.add(c)):(e.append(s,a),t.delete(c))}}return{[pr]:!0,values:e,nulls:t}};function mr(r){return r.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var hr=Object.freeze(Object.create(null)),Gr=(r=mr)=>function(t,...n){if(t.length===1)return t[0];let o=!1,s=[],a=t.reduce((m,l,g)=>{/[?#]/.test(l)&&(o=!0);let h=n[g],A=(o?encodeURIComponent:r)(""+h);return g!==n.length&&(h==null||typeof h=="object"&&h.toString===Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??hr)??hr)?.toString)&&(A=h+"",s.push({start:m.length+l.length,length:A.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),m+l+(g===n.length?"":A)},""),c=a.split(/[?#]/,1)[0],f=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,d;for(;(d=f.exec(c))!==null;)s.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(s.sort((m,l)=>m.start-l.start),s.length>0){let m=0,l=s.reduce((g,h)=>{let A=" ".repeat(h.start-m),E="^".repeat(h.length);return m=h.start+h.length,g+A+E},"");throw new x(`Path parameters result in path with invalid segments:
6
+ ${s.map(g=>g.error).join(`
7
+ `)}
8
+ ${a}
9
+ ${l}`)}return a},i=Gr(mr);var Z=class extends p{create(e,t){return this._client.post("/org/api_keys",{body:e,...t})}retrieve(e,t={},n){return this._client.get(i`/org/api_keys/${e}`,{query:t,...n})}update(e,t,n){return this._client.patch(i`/org/api_keys/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/org/api_keys",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/org/api_keys/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}rotate(e,t={},n){return this._client.post(i`/org/api_keys/${e}/rotate`,{body:t,...n})}};var ee=class extends p{list(e={},t){return this._client.getAPIList("/apps",w,{query:e,...t})}};var xe=class extends p{create(e,t){return this._client.post("/audit-logs/export/destinations",{body:e,...t})}retrieve(e,t){return this._client.get(i`/audit-logs/export/destinations/${e}`,t)}update(e,t,n){return this._client.patch(i`/audit-logs/export/destinations/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/audit-logs/export/destinations",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/audit-logs/export/destinations/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}test(e,t){return this._client.post(i`/audit-logs/export/destinations/${e}/test`,t)}};var Yr=6,Zr=5e4,en=8e3,F=class extends x{};async function gr(r,e,t,n,o={}){if(!t||typeof t.write!="function")throw new TypeError("audit log download destination must provide write()");let{onProgress:s,maxTransferRetries:a=Yr,...c}=o;if(!Number.isInteger(a)||a<0)throw new TypeError("maxTransferRetries must be a non-negative integer");let f=c.timeout??n,d,m={bytesWritten:0,chunks:0,rows:0},l=new Set;for(;;){let g=await tn(r,d?{...e,cursor:d}:e,c,a,f),{nextCursor:h,hasMore:A,rows:E}=rn(g.headers,d);if(A&&h){if(l.has(h))throw new F("response repeated X-Next-Cursor header");l.add(h)}if(await sn(t,g.body),d=h,m.bytesWritten+=g.body.byteLength,m.chunks+=1,m.rows+=E,s&&await s({...m,chunkRows:E}),!A)return m}}async function tn(r,e,t,n,o){for(let s=0;;s+=1){let a=new AbortController,c=()=>a.abort();t.signal?.aborted?a.abort():t.signal?.addEventListener("abort",c,{once:!0});let f;try{f=await r(e,{...t,signal:a.signal})}catch(l){throw t.signal?.removeEventListener("abort",c),l}let d=!1,m=setTimeout(()=>{d=!0,a.abort()},o);try{let l=new Uint8Array(await f.arrayBuffer());if(clearTimeout(m),t.signal?.aborted)throw new T;if(d)throw new D;let g=f.headers.get("x-content-sha256");if(!g)throw new F("response missing X-Content-Sha256 header");let h=await nn(l);if(t.signal?.aborted)throw new T;if(h!==g)throw new F(`audit log chunk checksum mismatch (got ${h}, want ${g})`);return{body:l,headers:f.headers}}catch(l){if(t.signal?.aborted&&!(l instanceof T)?l=new T:d&&(l=new D),s===n||l instanceof T)throw l;await on(s+1,t.signal)}finally{clearTimeout(m),t.signal?.removeEventListener("abort",c)}}}function rn(r,e){let t=r.get("x-has-more");if(t!=="true"&&t!=="false")throw new F("response missing or invalid X-Has-More header");let n=t==="true",o=r.get("x-row-count");if(o===null||!/^[0-9]+$/.test(o))throw new F("response missing or invalid X-Row-Count header");let s=Number(o);if(!Number.isSafeInteger(s)||s>Zr)throw new F("response missing or invalid X-Row-Count header");let a=r.get("x-next-cursor")||void 0;if(n&&(!a||a===e))throw new F("response has invalid X-Next-Cursor header");if(!n&&a)throw new F("response returned a cursor after the final chunk");return{rows:s,nextCursor:a,hasMore:n}}async function nn(r){let e=await globalThis.crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(e),t=>t.toString(16).padStart(2,"0")).join("")}async function on(r,e){let t=Math.min(1e3*2**(r-1),en);await new Promise((n,o)=>{if(e?.aborted){o(new T);return}let s=()=>{clearTimeout(a),o(new T)},a=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t);e?.addEventListener("abort",s,{once:!0})})}async function sn(r,e){let t=0;for(;t<e.byteLength;){let n=await r.write(t===0?e:e.subarray(t));if(typeof n=="number"){t+=yr(n,e.byteLength-t);continue}if(n&&typeof n=="object"&&"bytesWritten"in n){let o=n.bytesWritten;t+=yr(o,e.byteLength-t);continue}return}}function yr(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new F("audit log download destination performed a short write");return r}var X=class extends p{constructor(){super(...arguments),this.exportDestinations=new xe(this._client)}list(e,t){return this._client.getAPIList("/audit-logs",tt,{query:e,...t})}exportChunk(e,t){return this._client.get("/audit-logs/export/chunk",{query:e,...t,headers:u([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}download(e,t,n){return gr((o,s)=>this.exportChunk(o,s),e,t,this._client.timeout,n)}};X.ExportDestinations=xe;var _e=class extends p{create(e,t){return this._client.post("/auth/connections",{body:e,...t})}retrieve(e,t){return this._client.get(i`/auth/connections/${e}`,t)}update(e,t,n){return this._client.patch(i`/auth/connections/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/auth/connections",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/auth/connections/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}follow(e,t){return this._client.get(i`/auth/connections/${e}/events`,{...t,headers:u([{Accept:"text/event-stream"},t?.headers]),stream:!0})}login(e,t={},n){return this._client.post(i`/auth/connections/${e}/login`,{body:t,...n})}submit(e,t,n){return this._client.post(i`/auth/connections/${e}/submit`,{body:t,...n})}timeline(e,t={},n){return this._client.getAPIList(i`/auth/connections/${e}/timeline`,w,{query:t,...n})}};var Ae=class extends p{retrieve(e){return this._client.get("/auth/context",e)}};var B=class extends p{constructor(){super(...arguments),this.context=new Ae(this._client),this.connections=new _e(this._client)}};B.Context=Ae;B.Connections=_e;var te=class extends p{create(e,t){return this._client.post("/browser_pools",{body:e,...t})}retrieve(e,t){return this._client.get(i`/browser_pools/${e}`,t)}update(e,t,n){return this._client.patch(i`/browser_pools/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/browser_pools",w,{query:e,...t})}delete(e,t={},n){return this._client.delete(i`/browser_pools/${e}`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}acquire(e,t,n){return this._client.post(i`/browser_pools/${e}/acquire`,{body:t,...n})}flush(e,t){return this._client.post(i`/browser_pools/${e}/flush`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}release(e,t,n){return this._client.post(i`/browser_pools/${e}/release`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}};var Re=class extends p{batch(e,t,n){return this._client.post(i`/browsers/${e}/computer/batch`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}captureScreenshot(e,t={},n){return this._client.post(i`/browsers/${e}/computer/screenshot`,{body:t,...n,headers:u([{Accept:"image/png"},n?.headers]),__binaryResponse:!0})}clickMouse(e,t,n){return this._client.post(i`/browsers/${e}/computer/click_mouse`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}dragMouse(e,t,n){return this._client.post(i`/browsers/${e}/computer/drag_mouse`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}getMousePosition(e,t){return this._client.post(i`/browsers/${e}/computer/get_mouse_position`,t)}moveMouse(e,t,n){return this._client.post(i`/browsers/${e}/computer/move_mouse`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}pressKey(e,t,n){return this._client.post(i`/browsers/${e}/computer/press_key`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}readClipboard(e,t){return this._client.post(i`/browsers/${e}/computer/clipboard/read`,t)}scroll(e,t,n){return this._client.post(i`/browsers/${e}/computer/scroll`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}setCursorVisibility(e,t,n){return this._client.post(i`/browsers/${e}/computer/cursor`,{body:t,...n})}typeText(e,t,n){return this._client.post(i`/browsers/${e}/computer/type`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}writeClipboard(e,t,n){return this._client.post(i`/browsers/${e}/computer/clipboard/write`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}};var Pe=class extends p{stream(e,t,n){return this._client.get(i`/browsers/${e}/logs/stream`,{query:t,...n,headers:u([{Accept:"text/event-stream"},n?.headers]),stream:!0})}};var Ee=class extends p{execute(e,t,n){return this._client.post(i`/browsers/${e}/playwright/execute`,{body:t,...n})}};var Se=class extends p{exec(e,t,n){return this._client.post(i`/browsers/${e}/process/exec`,{body:t,...n})}kill(e,t,n){let{id:o,...s}=t;return this._client.post(i`/browsers/${o}/process/${e}/kill`,{body:s,...n})}resize(e,t,n){let{id:o,...s}=t;return this._client.post(i`/browsers/${o}/process/${e}/resize`,{body:s,...n})}spawn(e,t,n){return this._client.post(i`/browsers/${e}/process/spawn`,{body:t,...n})}status(e,t,n){let{id:o}=t;return this._client.get(i`/browsers/${o}/process/${e}/status`,n)}stdin(e,t,n){let{id:o,...s}=t;return this._client.post(i`/browsers/${o}/process/${e}/stdin`,{body:s,...n})}stdoutStream(e,t,n){let{id:o}=t;return this._client.get(i`/browsers/${o}/process/${e}/stdout/stream`,{...n,headers:u([{Accept:"text/event-stream"},n?.headers]),stream:!0})}};var Ie=class extends p{list(e,t){return this._client.get(i`/browsers/${e}/replays`,t)}download(e,t,n){let{id:o}=t;return this._client.get(i`/browsers/${o}/replays/${e}`,{...n,headers:u([{Accept:"video/mp4"},n?.headers]),__binaryResponse:!0})}start(e,t={},n){return this._client.post(i`/browsers/${e}/replays`,{body:t,...n})}stop(e,t,n){let{id:o}=t;return this._client.post(i`/browsers/${o}/replays/${e}/stop`,{...n,headers:u([{Accept:"*/*"},n?.headers])})}};var $e=class extends p{events(e,t={},n){return this._client.getAPIList(i`/browsers/${e}/telemetry/events`,w,{query:t,...n})}stream(e,t={},n){let{"Last-Event-ID":o,...s}=t??{};return this._client.get(i`/browsers/${e}/telemetry/stream`,{query:s,...n,headers:u([{Accept:"text/event-stream",...o!=null?{"Last-Event-ID":o}:void 0},n?.headers]),stream:!0})}};var Le=class extends p{events(e,t,n){let{id:o}=t;return this._client.get(i`/browsers/${o}/fs/watch/${e}/events`,{...n,headers:u([{Accept:"text/event-stream"},n?.headers]),stream:!0})}start(e,t,n){return this._client.post(i`/browsers/${e}/fs/watch`,{body:t,...n})}stop(e,t,n){let{id:o}=t;return this._client.delete(i`/browsers/${o}/fs/watch/${e}`,{...n,headers:u([{Accept:"*/*"},n?.headers])})}};var re=class extends p{constructor(){super(...arguments),this.watch=new Le(this._client)}createDirectory(e,t,n){return this._client.put(i`/browsers/${e}/fs/create_directory`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}deleteDirectory(e,t,n){return this._client.put(i`/browsers/${e}/fs/delete_directory`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}deleteFile(e,t,n){return this._client.put(i`/browsers/${e}/fs/delete_file`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}downloadDirZip(e,t,n){return this._client.get(i`/browsers/${e}/fs/download_dir_zip`,{query:t,...n,headers:u([{Accept:"application/zip"},n?.headers]),__binaryResponse:!0})}fileInfo(e,t,n){return this._client.get(i`/browsers/${e}/fs/file_info`,{query:t,...n})}listFiles(e,t,n){return this._client.get(i`/browsers/${e}/fs/list_files`,{query:t,...n})}move(e,t,n){return this._client.put(i`/browsers/${e}/fs/move`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}readFile(e,t,n){return this._client.get(i`/browsers/${e}/fs/read_file`,{query:t,...n,headers:u([{Accept:"application/octet-stream"},n?.headers]),__binaryResponse:!0})}setFilePermissions(e,t,n){return this._client.put(i`/browsers/${e}/fs/set_file_permissions`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}upload(e,t,n){return this._client.post(i`/browsers/${e}/fs/upload`,H({body:t,...n,headers:u([{Accept:"*/*"},n?.headers])},this._client))}uploadZip(e,t,n){return this._client.post(i`/browsers/${e}/fs/upload_zip`,H({body:t,...n,headers:u([{Accept:"*/*"},n?.headers])},this._client))}writeFile(e,t,n,o){let{path:s,mode:a}=n;return this._client.put(i`/browsers/${e}/fs/write_file`,{body:t,query:{path:s,mode:a},...o,headers:u([{"Content-Type":"application/octet-stream",Accept:"*/*"},o?.headers])})}};re.Watch=Le;function ot(r,e){return`${r.replace(/\/+$/,"")}${e.startsWith("/")?e:`/${e}`}`}async function wr(r,e,t,n){let o=r.browserRouteCache.get(e);if(!o)throw new x(`browser route cache does not contain session ${e}; create, retrieve, or list the browser before calling browser.fetch`);let{url:s,method:a,headers:c,body:f,signal:d,duplex:m,timeout_ms:l}=wn(t,n);bn(s);let g={url:s,jwt:o.jwt};l!==void 0&&(g.timeout_ms=l);let h=c.get("accept"),A={method:gn(a),path:ot(o.baseURL,"/curl/raw"),query:g,body:f,headers:u([{Authorization:null},h?{Accept:h}:{Accept:"*/*"},xn(c)]),signal:d??null,__binaryResponse:!0};return m&&(A.fetchOptions={duplex:m}),r.request(A).asResponse()}function gn(r){let e=r.toLowerCase();if(!new Set(["get","post","put","patch","delete"]).has(e))throw new x(`browser.fetch unsupported HTTP method: ${r}`);return e}function wn(r,e){let t=e&&"timeout_ms"in e?e.timeout_ms:void 0;if(r instanceof Request){let o=new Headers(r.headers);e?.headers&&new Headers(e.headers).forEach((d,m)=>{o.set(m,d)});let s={url:r.url,method:(e?.method??r.method)?.toUpperCase()||"GET",headers:o},a=e?.body??r.body;a!=null&&(s.body=a);let c=e?.signal??r.signal;return c!==void 0&&(s.signal=c),e?.duplex!==void 0&&(s.duplex=e.duplex),t!==void 0&&(s.timeout_ms=t),s}let n={url:r instanceof URL?r.href:String(r),method:(e?.method??"GET").toUpperCase(),headers:new Headers(e?.headers)};return e?.body!==void 0&&(n.body=e.body),e?.signal!==void 0&&(n.signal=e.signal),e?.duplex!==void 0&&(n.duplex=e.duplex),t!==void 0&&(n.timeout_ms=t),n}function bn(r){let e;try{e=new URL(r)}catch{throw new x(`browser.fetch target must be an absolute URL; received: ${r}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new x(`browser.fetch only supports http(s) URLs; received: ${e.protocol}`)}function xn(r){let e={};return r.forEach((t,n)=>{switch(n.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:e[n]=t}}),e}var O=class extends p{constructor(){super(...arguments),this.telemetry=new $e(this._client),this.replays=new Ie(this._client),this.fs=new re(this._client),this.process=new Se(this._client),this.logs=new Pe(this._client),this.computer=new Re(this._client),this.playwright=new Ee(this._client)}create(e={},t){return this._client.post("/browsers",{body:e,...t})}retrieve(e,t={},n){return this._client.get(i`/browsers/${e}`,{query:t,...n})}update(e,t,n){return this._client.patch(i`/browsers/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/browsers",w,{query:e,...t})}curl(e,t,n){return this._client.post(i`/browsers/${e}/curl`,{body:t,...n})}fetch(e,t,n){return wr(this._client,e,t,n)}deleteByID(e,t){return this._client.delete(i`/browsers/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}loadExtensions(e,t,n){return this._client.post(i`/browsers/${e}/extensions`,H({body:t,...n,headers:u([{Accept:"*/*"},n?.headers])},this._client))}};O.Telemetry=$e;O.Replays=Ie;O.Fs=re;O.Process=Se;O.Logs=Pe;O.Computer=Re;O.Playwright=Ee;var ne=class extends p{create(e,t){return this._client.post("/org/credential_providers",{body:e,...t})}retrieve(e,t){return this._client.get(i`/org/credential_providers/${e}`,t)}update(e,t,n){return this._client.patch(i`/org/credential_providers/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/org/credential_providers",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/org/credential_providers/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}listItems(e,t){return this._client.get(i`/org/credential_providers/${e}/items`,t)}test(e,t){return this._client.post(i`/org/credential_providers/${e}/test`,t)}};var oe=class extends p{create(e,t){return this._client.post("/credentials",{body:e,...t})}retrieve(e,t){return this._client.get(i`/credentials/${e}`,t)}update(e,t,n){return this._client.patch(i`/credentials/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/credentials",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/credentials/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}totpCode(e,t){return this._client.get(i`/credentials/${e}/totp-code`,t)}};var se=class extends p{create(e,t){return this._client.post("/deployments",H({body:e,...t},this._client))}retrieve(e,t){return this._client.get(i`/deployments/${e}`,t)}list(e={},t){return this._client.getAPIList("/deployments",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/deployments/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}follow(e,t={},n){return this._client.get(i`/deployments/${e}/events`,{query:t,...n,headers:u([{Accept:"text/event-stream"},n?.headers]),stream:!0})}};var ie=class extends p{list(e={},t){return this._client.getAPIList("/extensions",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/extensions/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}download(e,t){return this._client.get(i`/extensions/${e}`,{...t,headers:u([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}downloadFromChromeStore(e,t){return this._client.get("/extensions/from_chrome_store",{query:e,...t,headers:u([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}get(e,t){return this._client.get(i`/extensions/${e}/metadata`,t)}upload(e,t){return this._client.post("/extensions",H({body:e,...t},this._client))}};var ae=class extends p{create(e,t){return this._client.post("/invocations",{body:e,...t})}retrieve(e,t){return this._client.get(i`/invocations/${e}`,t)}update(e,t,n){return this._client.patch(i`/invocations/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/invocations",w,{query:e,...t})}deleteBrowsers(e,t){return this._client.delete(i`/invocations/${e}/browsers`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}follow(e,t={},n){return this._client.get(i`/invocations/${e}/events`,{query:t,...n,headers:u([{Accept:"text/event-stream"},n?.headers]),stream:!0})}listBrowsers(e,t){return this._client.get(i`/invocations/${e}/browsers`,t)}};var Te=class extends p{retrieve(e){return this._client.get("/org/entitlements",e)}};var Oe=class extends p{retrieve(e){return this._client.get("/org/limits",e)}update(e,t){return this._client.patch("/org/limits",{body:e,...t})}};var M=class extends p{constructor(){super(...arguments),this.entitlements=new Te(this._client),this.limits=new Oe(this._client)}};M.Entitlements=Te;M.Limits=Oe;var ce=class extends p{create(e,t){return this._client.post("/profiles",{body:e,...t})}retrieve(e,t){return this._client.get(i`/profiles/${e}`,t)}update(e,t,n){return this._client.patch(i`/profiles/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/profiles",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/profiles/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}download(e,t={},n){return this._client.get(i`/profiles/${e}/download`,{query:t,...n,headers:u([{Accept:"application/octet-stream"},n?.headers]),__binaryResponse:!0})}};var je=class extends p{retrieve(e,t){return this._client.get(i`/org/projects/${e}/limits`,t)}update(e,t,n){return this._client.patch(i`/org/projects/${e}/limits`,{body:t,...n})}};var z=class extends p{constructor(){super(...arguments),this.limits=new je(this._client)}create(e,t){return this._client.post("/org/projects",{body:e,...t})}retrieve(e,t){return this._client.get(i`/org/projects/${e}`,t)}update(e,t,n){return this._client.patch(i`/org/projects/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/org/projects",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/org/projects/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}};z.Limits=je;var le=class extends p{create(e,t){return this._client.post("/proxies",{body:e,...t})}retrieve(e,t){return this._client.get(i`/proxies/${e}`,t)}update(e,t,n){return this._client.patch(i`/proxies/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/proxies",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/proxies/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}check(e,t={},n){return this._client.post(i`/proxies/${e}/check`,{body:t,...n})}};var Ce=class extends p{create(e,t){return this._client.post("/telemetry/destinations",{body:e,...t})}retrieve(e,t){return this._client.get(i`/telemetry/destinations/${e}`,t)}update(e,t,n){return this._client.patch(i`/telemetry/destinations/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/telemetry/destinations",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/telemetry/destinations/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}};var V=class extends p{constructor(){super(...arguments),this.destinations=new Ce(this._client)}};V.Destinations=Ce;var Ke=class{constructor(){this.entries=new Map}get(e){return this.entries.get(e)}set(e){this.entries.set(e.sessionId,e)}delete(e){this.entries.delete(e)}clear(){this.entries.clear()}},br="\u004b\u0045\u0052\u004e\u0045\u004c_BROWSER_ROUTING_SUBRESOURCES",Sn=["curl","telemetry/stream"],In=/^\/(?:v\d+\/)?browsers(?:\/[^/]+)?\/?$/,$n=/^\/(?:v\d+\/)?browser_pools\/[^/]+\/acquire\/?$/,Ln=/^\/(?:v\d+\/)?browsers\/([^/]+)\/?$/,Tn=/^\/(?:v\d+\/)?browser_pools\/[^/]+\/release\/?$/;function Lt(){let r=qn();return r===void 0?[...Sn]:r.trim()===""?[]:r.split(",").map(e=>e.trim()).filter(Boolean)}function Tt(r,{apiBaseURL:e,subresources:t,cache:n}){let o=[...t].map(a=>a.trim().replace(/^\/+|\/+$/g,"")).filter(Boolean),s=new URL(e).origin;return async(a,c)=>{let f=new Request(a,c),d=On(f,s),m=await Dn(r,{input:a,init:c,request:f},s,o,n);return d&&await Un(m,n),await jn(f,m,s,n),m}}function On(r,e){let t=new URL(r.url);return t.origin===e&&(In.test(t.pathname)||$n.test(t.pathname))}async function jn(r,e,t,n){if(!e.ok)return;let o=new URL(r.url);if(o.origin!==t)return;let s=Cn(r,o.pathname)??await kn(r,o.pathname);s&&n.delete(s)}function Cn(r,e){if(r.method.toUpperCase()!=="DELETE")return;let t=e.match(Ln);return t&&decodeURIComponent(t[1]??"")||void 0}async function kn(r,e){if(!(r.method.toUpperCase()!=="POST"||!Tn.test(e)))try{let t=await r.clone().json();if(!t||typeof t!="object")return;let n=t.session_id;return typeof n=="string"&&n.trim()?n.trim():void 0}catch{return}}function Fn(r){if(!r||typeof r!="object")return;let e=r,t=typeof e.session_id=="string"?e.session_id.trim():"",n=typeof e.base_url=="string"?e.base_url.trim():"";if(!t||!n)return;let o=typeof e.jwt=="string"?e.jwt.trim():"",s=typeof e.cdp_ws_url=="string"?e.cdp_ws_url:void 0,a=o||Mn(s)||"";if(a)return{sessionId:t,baseURL:n,jwt:a}}async function Un(r,e){if((r.headers.get("content-type")?.toLowerCase()??"").includes("application/json"))try{$t(await r.clone().json(),e)}catch{}}function $t(r,e){let t=Fn(r);if(t&&e.set(t),Array.isArray(r)){for(let n of r)$t(n,e);return}if(!(!r||typeof r!="object"))for(let n of Object.values(r))typeof n=="object"&&n!==null&&$t(n,e)}function vn(r,e){let t=r.replace(/^\/+|\/+$/g,"");return e.some(n=>t===n||t.startsWith(n+"/"))}async function Dn(r,{input:e,init:t,request:n},o,s,a){let c=new URL(n.url);if(c.origin!==o)return r(e,t);let f=c.pathname.match(/^\/(?:v\d+\/)?browsers\/([^/]+)\/([^/]+)(\/.*)?$/);if(!f)return r(e,t);let d=decodeURIComponent(f[1]??""),m=f[2]??"";if(!d||!vn(m+(f[3]??""),s))return r(e,t);let l=a.get(d);if(l===void 0)return r(e,t);let g=new URL(ot(l.baseURL,`/${m}${f[3]??""}`));c.searchParams.forEach((A,E)=>{E!=="jwt"&&g.searchParams.append(E,A)}),g.searchParams.get("jwt")||g.searchParams.set("jwt",l.jwt);let h=new Headers(n.headers);return h.delete("authorization"),r(g.toString(),Nn(e,n,t,h))}function Nn(r,e,t,n){let o=e.method.toUpperCase(),s={...t??{},method:o,headers:n,redirect:e.redirect,signal:t?.signal??(r instanceof Request?r.signal:void 0)};if(delete s.body,delete s.duplex,o!=="GET"&&o!=="HEAD"){let a=Hn(e,t);a!==void 0&&(s.body=a),t?.duplex!==void 0?s.duplex=t.duplex:Bn(a)&&(s.duplex="half")}return s}function Hn(r,e){return e?.body!==void 0&&e.body!==null?e.body:r.body??void 0}function Bn(r){return globalThis.ReadableStream&&r instanceof globalThis.ReadableStream||typeof r=="object"&&r!==null&&Symbol.asyncIterator in r}function Mn(r){if(r)try{return new URL(r).searchParams.get("jwt")??void 0}catch{return}}function qn(){if(typeof globalThis.process<"u"){let r=globalThis.process.env?.[br];return typeof r=="string"?r:void 0}if(typeof globalThis.Deno<"u"){let r=globalThis.Deno.env?.get?.(br);return typeof r=="string"?r:void 0}}var st=class{constructor(e){this.actions=new Map,this.name=e,xr.registerApp(this)}action(e,t){let n;if(t.length===0)throw new Error("Action handlers must accept at least the context parameter");if(t.length===1){let o=t;n=async(s,a)=>o(s)}else n=t;return this.actions.set(e,{name:e,handler:n}),n}getActions(){return Array.from(this.actions.values())}getAction(e){return this.actions.get(e)}toJSON(){return{name:this.name,actions:this.getActions().map(e=>({name:e.name}))}}},Ot=class{constructor(){this.apps=new Map}registerApp(e){this.apps.set(e.name,e)}getApps(){return Array.from(this.apps.values())}getAppByName(e){return this.apps.get(e)}export(){return{apps:this.getApps().map(e=>e.toJSON())}}exportJSON(){return JSON.stringify(this.export(),null,2)}},xr=new Ot;var ke=r=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()||void 0};var jt,Ct,We,_r,Ar={production:"https://api.on\u006b\u0065\u0072\u006e\u0065\u006c.com/",development:"https://localhost:3001/"},y=class{constructor({baseURL:e=ke("\u004b\u0045\u0052\u004e\u0045\u004c_BASE_URL"),apiKey:t=ke("\u004b\u0045\u0052\u004e\u0045\u004c_API_KEY"),projectID:n=null,project:o=null,...s}={}){if(jt.add(this),We.set(this,void 0),this.deployments=new se(this),this.apps=new ee(this),this.invocations=new ae(this),this.browsers=new O(this),this.profiles=new ce(this),this.auth=new B(this),this.telemetry=new V(this),this.proxies=new le(this),this.extensions=new ie(this),this.browserPools=new te(this),this.credentials=new oe(this),this.projects=new z(this),this.organization=new M(this),this.auditLogs=new X(this),this.apiKeys=new Z(this),this.credentialProviders=new ne(this),typeof globalThis<"u"&&typeof globalThis.Bun<"u"&&globalThis.Bun.version&&!ke("\u004b\u0045\u0052\u004e\u0045\u004c_SUPPRESS_BUN_WARNING")&&P(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"),t===void 0)throw new x("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 a={apiKey:t,projectID:n,project:o,...s,baseURL:e,environment:s.environment??"production"};if(e&&s.environment)throw new x("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=a.baseURL||Ar[a.environment||"production"],this.timeout=a.timeout??Ct.DEFAULT_TIMEOUT,this.logger=a.logger??console;let c="warn";this.logLevel=c,this.logLevel=At(a.logLevel,"ClientOptions.logLevel",this)??At(ke("\u004b\u0045\u0052\u004e\u0045\u004c_LOG"),"process.env['\u004b\u0045\u0052\u004e\u0045\u004c_LOG']",this)??c,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.rawFetch=a.fetch??zt(),this.browserRouteCache=new Ke,this.fetch=Tt(this.rawFetch,{apiBaseURL:this.baseURL,subresources:Lt(),cache:this.browserRouteCache}),S(this,We,Jt,"f");let f=ke("\u004b\u0045\u0052\u004e\u0045\u004c_CUSTOM_HEADERS");if(f){let d={};for(let m of f.split(`
10
+ `)){let l=m.indexOf(":");l>=0&&(d[m.substring(0,l).trim()]=m.substring(l+1).trim())}a.defaultHeaders={...d,...a.defaultHeaders}}this._options=a,this.apiKey=t,this.projectID=n,this.project=o}withOptions(e){let t=new this.constructor({...this._options,environment:e.environment?e.environment:void 0,baseURL:e.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,...e});return t.browserRouteCache=this.browserRouteCache,t.fetch=Tt(t.rawFetch,{apiBaseURL:t.baseURL,subresources:Lt(),cache:t.browserRouteCache}),t}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return u([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return or(e)}getUserAgent(){return`${this.constructor.name}/JS ${W}`}defaultIdempotencyKey(){return`stainless-node-retry-${ct()}`}makeStatusError(e,t,n,o){return I.generate(e,t,n,o)}buildURL(e,t,n){let o=!_(this,jt,"m",_r).call(this)&&n||this.baseURL,s=vt(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),c=Object.fromEntries(s.searchParams);return(!ft(a)||!ft(c))&&(t={...c,...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(s.search=this.stringifyQuery(t)),s.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(o=>({method:e,path:t,...o})))}request(e,t=null){return new Y(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let o=await e,s=o.maxRetries??this.maxRetries;t==null&&(t=s),await this.prepareOptions(o);let{req:a,url:c,timeout:f}=await this.buildRequest(o,{retryCount:s-t});await this.prepareRequest(a,{url:c,options:o});let d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=n===void 0?"":`, retryOf: ${n}`,l=Date.now();if(P(this).debug(`[${d}] sending request`,N({retryOfRequestLogID:n,method:o.method,url:c,options:o,headers:a.headers})),o.signal?.aborted)throw new T;let g=new AbortController,h=await this.fetchWithTimeout(c,a,f,g).catch(ve),A=Date.now();if(h instanceof globalThis.Error){let U=`retrying, ${t} attempts remaining`;if(o.signal?.aborted)throw new T;let k=Ue(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return P(this).info(`[${d}] connection ${k?"timed out":"failed"} - ${U}`),P(this).debug(`[${d}] connection ${k?"timed out":"failed"} (${U})`,N({retryOfRequestLogID:n,url:c,durationMs:A-l,message:h.message})),this.retryRequest(o,t,n??d);throw P(this).info(`[${d}] connection ${k?"timed out":"failed"} - error; no more retries left`),P(this).debug(`[${d}] connection ${k?"timed out":"failed"} (error; no more retries left)`,N({retryOfRequestLogID:n,url:c,durationMs:A-l,message:h.message})),k?new D:new K({cause:h})}let E=`[${d}${m}] ${a.method} ${c} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${A-l}ms`;if(!h.ok){let U=await this.shouldRetry(h);if(t&&U){let q=`retrying, ${t} attempts remaining`;return await Vt(h.body),P(this).info(`${E} - ${q}`),P(this).debug(`[${d}] response error (${q})`,N({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:A-l})),this.retryRequest(o,t,n??d,h.headers)}let k=U?"error; no more retries left":"error; not retryable";P(this).info(`${E} - ${k}`);let b=await h.text().catch(q=>ve(q).message),J=Bt(b),G=J?void 0:b;throw P(this).debug(`[${d}] response error (${k})`,N({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,message:G,durationMs:Date.now()-l})),this.makeStatusError(h.status,J,G,h.headers)}return P(this).info(E),P(this).debug(`[${d}] response start`,N({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:A-l})),{response:h,options:o,controller:g,requestLogID:d,retryOfRequestLogID:n,startTime:l}}getAPIList(e,t,n){return this.requestAPIList(t,n&&"then"in n?n.then(o=>({method:"get",path:e,...o})):{method:"get",path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new Me(this,n,e)}async fetchWithTimeout(e,t,n,o){let{signal:s,method:a,...c}=t||{},f=this._makeAbort(o);s&&s.addEventListener("abort",f,{once:!0});let d=setTimeout(f,n),m=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,l={signal:o.signal,...m?{duplex:"half"}:{},method:"GET",...c};a&&(l.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,l)}finally{clearTimeout(d)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,o){let s,a=o?.get("retry-after-ms");if(a){let f=parseFloat(a);Number.isNaN(f)||(s=f)}let c=o?.get("retry-after");if(c&&!s){let f=parseFloat(c);Number.isNaN(f)?s=Date.parse(c)-Date.now():s=f*1e3}if(s===void 0){let f=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,f)}return await Mt(s),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let s=t-e,a=Math.min(.5*Math.pow(2,s),8),c=1-Math.random()*.25;return a*c*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:o,path:s,query:a,defaultBaseURL:c}=n,f=this.buildURL(s,a,c);"timeout"in n&&Nt("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:d,body:m}=this.buildBody({options:n}),l=await this.buildHeaders({options:e,method:o,bodyHeaders:d,retryCount:t});return{req:{method:o,headers:l,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"},...m&&{body:m},...this.fetchOptions??{},...n.fetchOptions??{}},url:f,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:o}){let s={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let a=u([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Xt(),"X-\u004b\u0065\u0072\u006e\u0065\u006c-Project-Id":this.projectID,"X-\u004b\u0065\u0072\u006e\u0065\u006c-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:n}=e;if(!t)return t==null&&"body"in e?_(this,We,"f").call(this,{body:t,headers:u([n])}):{bodyHeaders:void 0,body:void 0};let o=u([n]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&o.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:ze(t)}:typeof t=="object"&&o.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(t)}:_(this,We,"f").call(this,{body:t,headers:o})}app(e){return new st(e)}};Ct=y,We=new WeakMap,jt=new WeakSet,_r=function(){return this.baseURL!==Ar[this._options.environment||"production"]};y.\u004b\u0065\u0072\u006e\u0065\u006c=Ct;y.DEFAULT_TIMEOUT=6e4;y.\u004b\u0065\u0072\u006e\u0065\u006cError=x;y.APIError=I;y.APIConnectionError=K;y.APIConnectionTimeoutError=D;y.APIUserAbortError=T;y.NotFoundError=he;y.ConflictError=me;y.RateLimitError=ge;y.BadRequestError=fe;y.AuthenticationError=de;y.InternalServerError=we;y.PermissionDeniedError=pe;y.UnprocessableEntityError=ye;y.toFile=nt;y.Deployments=se;y.Apps=ee;y.Invocations=ae;y.Browsers=O;y.Profiles=ce;y.Auth=B;y.Telemetry=V;y.Proxies=le;y.Extensions=ie;y.BrowserPools=te;y.Credentials=oe;y.Projects=z;y.Organization=M;y.AuditLogs=X;y.APIKeys=Z;y.CredentialProviders=ne;export{K as a,D as b,de as c,pe as d,we as e,y as f};
@@ -0,0 +1 @@
1
+ import{createHash as M}from"crypto";import{mkdir as D,readFile as $,writeFile as O}from"fs/promises";import{createWriteStream as C}from"fs";import{homedir as N}from"os";import{dirname as _,join as x}from"path";import{Transform as K}from"stream";import{pipeline as E}from"stream/promises";var b="9999-12-31T23:59:59.999Z";function L(){return process.env.VERCEL==="1"||process.env.NODE_ENV==="production"}function T(t){return t.hosted??L()}function v(t){return t.localBaseDir?.trim()||process.env.MCP_SCRAPER_OUTPUT_DIR?.trim()||x(N(),"Downloads","mcp-scraper")}function P(t){let e=t.replace(/^\/+/,"").replace(/\/+$/,"");if(!e||e.includes("..")||!/^[a-zA-Z0-9/_-]+$/.test(e))throw new Error("private artifact prefix is invalid");return`${e}/`}function y(t,e){let r=t.trim();if(!/^[a-zA-Z0-9_-]{1,160}$/.test(r))throw new Error(`${e} must contain only letters, numbers, underscores, or hyphens`);return r}function U(t){let e=t.trim();if(!/^[a-zA-Z0-9_.-]{1,200}$/.test(e)||e==="."||e==="..")throw new Error("private artifact key is invalid");return e}function k(t){return(t.trim().replace(/[^a-zA-Z0-9_.-]+/g,"-").replace(/^-+|-+$/g,"")||"artifact").slice(0,160)}function R(t){let e=typeof t=="string"&&/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(t)?`${t.replace(" ","T")}Z`:t,r=e instanceof Date?e.getTime():typeof e=="number"?e:new Date(e).getTime();if(!Number.isSafeInteger(r)||r<=0)throw new Error("private artifact createdAt is invalid");return r}function I(t){if(t.artifactTtlMs!==null&&(!Number.isSafeInteger(t.artifactTtlMs)||t.artifactTtlMs<=0))throw new Error("private artifact TTL must be a positive integer");if(!Number.isSafeInteger(t.downloadTtlMs)||t.downloadTtlMs<=0)throw new Error("private artifact download TTL must be a positive integer");return{prefix:P(t.prefix),artifactTtlMs:t.artifactTtlMs,downloadTtlMs:t.downloadTtlMs}}function W(t,e){let r=P(e);if(!t.startsWith(r))return null;let n=(t.split("/").at(-1)??"").match(/^(\d{13})-/);if(!n)return null;let o=Number(n[1]);return Number.isSafeInteger(o)&&o>0?o:null}function g(t,e){let r=P(e);if(!t.startsWith(r)||t.includes(".."))return null;let n=t.slice(r.length).split("/");if(n.length<2)return null;try{return y(n[0]??"","ownerId")}catch{return null}}function S(t,e){let r=I(e);if(g(t,r.prefix)===null||r.artifactTtlMs===null)return null;let i=W(t,r.prefix);return i===null?null:new Date(i+r.artifactTtlMs)}async function B(t,e,r){let i=r.token?.trim();if(!i)return null;let n=e?Math.min(Date.now()+r.downloadTtlMs,e.getTime()):Date.now()+r.downloadTtlMs;if(n<=Date.now())return null;let{issueSignedToken:o,presignUrl:c}=await import("@vercel/blob"),a=await o({token:i,pathname:t,operations:["get"],validUntil:n}),{presignedUrl:u}=await c(a,{access:"private",operation:"get",pathname:t,validUntil:n});return{url:u,expiresAt:new Date(n).toISOString()}}async function J(t){let e={...t.policy,...I(t.policy)},r=y(t.ownerId,"ownerId"),i=U(t.artifactKey),n=(t.scopeSegments??[]).map((f,l)=>y(f,`scopeSegments[${l}]`)),o=R(t.createdAt),c=`${e.prefix}${r}/${n.length?`${n.join("/")}/`:""}${o}-${i}`,a=Buffer.isBuffer(t.content)?t.content:Buffer.from(t.content),u=a.length,A=M("sha256").update(a).digest("hex"),m=e.artifactTtlMs===null?null:new Date(o+e.artifactTtlMs),d=e.token?.trim()||null,p=c;if(d){let{put:f}=await import("@vercel/blob");p=(await f(c,a,{access:"private",token:d,contentType:t.contentType,addRandomSuffix:!1,allowOverwrite:!0,cacheControlMaxAge:60,multipart:u>100*1024*1024})).pathname}else{if(T(e))throw new Error("private_artifact_blob_not_configured");let f=x(v(e),"blobs",c);await D(_(f),{recursive:!0}),await O(f,a)}let h=await B(p,m,e);return{artifactId:p,filename:k(t.filename),contentType:t.contentType,bytes:u,sha256:A,expiresAt:m?.toISOString()??b,downloadUrl:h?.url??null,downloadUrlExpiresAt:h?.expiresAt??null}}async function Q(t){let e={...t.policy,...I(t.policy)},r=y(t.ownerId,"ownerId"),i=U(t.artifactKey),n=(t.scopeSegments??[]).map((l,w)=>y(l,`scopeSegments[${w}]`)),o=R(t.createdAt),c=`${e.prefix}${r}/${n.length?`${n.join("/")}/`:""}${o}-${i}`,a=e.artifactTtlMs===null?null:new Date(o+e.artifactTtlMs),u=e.token?.trim()||null,A=M("sha256"),m=0,d=new K({transform(l,w,s){m+=l.length,A.update(l),s(null,l)}}),p=c;if(u){let{put:l}=await import("@vercel/blob"),w=E(t.content,d);try{let s=await l(c,d,{access:"private",token:u,contentType:t.contentType,addRandomSuffix:!1,allowOverwrite:!0,cacheControlMaxAge:60,multipart:!0});await w,p=s.pathname}catch(s){throw t.content.destroy(s instanceof Error?s:new Error(String(s))),d.destroy(s instanceof Error?s:new Error(String(s))),await w.catch(()=>{}),s}}else{if(T(e))throw new Error("private_artifact_blob_not_configured");let l=x(v(e),"blobs",c);await D(_(l),{recursive:!0}),await E(t.content,d,C(l))}let h=A.digest("hex"),f=await B(p,a,e);return{artifactId:p,filename:k(t.filename),contentType:t.contentType,bytes:m,sha256:h,expiresAt:a?.toISOString()??b,downloadUrl:f?.url??null,downloadUrlExpiresAt:f?.expiresAt??null}}async function Y(t){if(g(t.artifactId,t.policy.prefix)!==t.ownerId)return null;let e=S(t.artifactId,t.policy);if(t.policy.artifactTtlMs!==null&&(!e||e.getTime()<=Date.now()))return null;let r=await B(t.artifactId,e,t.policy);return r?{downloadUrl:r.url,downloadUrlExpiresAt:r.expiresAt,expiresAt:e?.toISOString()??b}:null}async function z(t){let e=t.getReader(),r=[];try{for(;;){let{done:i,value:n}=await e.read();if(i)break;n&&r.push(Buffer.from(n))}}finally{e.releaseLock()}return Buffer.concat(r)}async function tt(t){if(g(t.artifactId,t.policy.prefix)===null)return null;let e=S(t.artifactId,t.policy);if(t.policy.artifactTtlMs!==null&&(!e||e.getTime()<=Date.now()))return null;if(!Number.isSafeInteger(t.offset)||t.offset<0)throw new Error("private artifact offset is invalid");if(!Number.isSafeInteger(t.maxBytes)||t.maxBytes<=0)throw new Error("private artifact maxBytes is invalid");let r=t.policy.token?.trim()||null,i;if(r){let{get:c}=await import("@vercel/blob"),a=await c(t.artifactId,{access:"private",token:r,useCache:!1});if(!a||a.statusCode!==200)return null;i=await z(a.stream)}else{if(T(t.policy))return null;try{i=await $(x(v(t.policy),"blobs",t.artifactId))}catch{return null}}let n=i.length,o=Math.min(n,t.offset+t.maxBytes);return{text:i.subarray(t.offset,o).toString("utf8"),totalBytes:n,nextOffset:o<n?o:null}}async function et(t){if(g(t.artifactId,t.policy.prefix)===null)return null;let e=S(t.artifactId,t.policy);if(t.policy.artifactTtlMs!==null&&(!e||e.getTime()<=Date.now()))return null;if(!Number.isSafeInteger(t.maxBytes)||t.maxBytes<=0)throw new Error("private artifact maxBytes is invalid");let r=t.policy.token?.trim()||null,i;if(r){let{get:n}=await import("@vercel/blob"),o=await n(t.artifactId,{access:"private",token:r,useCache:!1});if(!o||o.statusCode!==200)return null;i=await z(o.stream)}else{if(T(t.policy))return null;try{i=await $(x(v(t.policy),"blobs",t.artifactId))}catch{return null}}if(i.length>t.maxBytes)throw new Error("private artifact exceeds read limit");return i}export{g as a,J as b,Q as c,Y as d,tt as e,et as f};
@@ -0,0 +1,20 @@
1
+ import{a as N}from"./chunk-YQZGZBB4.js";import{b as L,c as P}from"./chunk-HE45FFBU.js";import{h as $,s as x}from"./chunk-GMWKPIYX.js";import{createWriteStream as Z,mkdirSync as ee,rmSync as te}from"fs";import{homedir as re}from"os";import{join as I,extname as k,basename as B}from"path";import{pipeline as ne}from"stream/promises";import{Readable as oe,Transform as ie}from"stream";var se=["doubleclick.net","googlesyndication.com","googletagmanager.com","google-analytics.com","googletagservices.com","adservice.google","googletag.","pagead2.googlesyndication","facebook.net/tr","connect.facebook.net","fbcdn.net/rsrc","analytics.twitter.com","static.ads-twitter.com","ads.twitter.com","t.co/i/adsct","pixel.advertising.com","hotjar.com","clarity.ms","quantserve.com","scorecardresearch.com","newrelic.com","nr-data.net","segment.io","segment.com","amplitude.com","mixpanel.com","heap.io","fullstory.com","moatads.com","criteo.com","adsrvr.org","rubiconproject.com","pubmatic.com","openx.net","appnexus.com","amazon-adsystem.com","media.net","yieldmo.com","triplelift.com","sharethrough.com","prebid.","smaato.net","indexworm.com","casalemedia.com","outbrain.com","taboola.com","revcontent.com","mgid.com","tawk.to","intercom.io","drift.com","hs-scripts.com","zopim.com","livechatinc.com","userlike.com","onetrust.com","cookielaw.org","cookieinformation.com","trustarc.com","/ads/","/ad/","/banner/","/banners/","/pixel/","/beacon/","/tracking/","/tracker/","/remarketing/","/conversion/","1x1.gif","spacer.gif","blank.gif","transparent.gif"],ae=new Set([".jpg",".jpeg",".png",".webp",".gif",".avif",".svg",".tiff"]),de=new Set([".mp4",".webm",".mov",".avi",".m4v",".ogv",".mkv"]),ce=new Set([".mp3",".wav",".ogg",".aac",".m4a",".flac",".opus"]);function le(e){let t=e.toLowerCase();return se.some(r=>t.includes(r))}function ue(e){return e.startsWith("data:")}function F(e){try{let t=k(new URL(e).pathname).toLowerCase();if(ae.has(t))return"image";if(de.has(t))return"video";if(ce.has(t))return"audio"}catch{}return null}function q(e){let t=e.toLowerCase();return t.startsWith("image/")?"image":t.startsWith("video/")?"video":t.startsWith("audio/")?"audio":null}function me(e,t){if(!e||ue(e))return null;try{return new URL(e,t).href}catch{return null}}function U(e,t){try{let r=new URL(e);return B(r.pathname).replace(/[^a-zA-Z0-9._-]/g,"_").slice(0,80)||`asset-${t}`}catch{return`asset-${t}`}}function O(e,t){let r=e?.replace(/&(?:amp|#0?38|#x26);/gi,"&").replace(/\s+/g," ").trim();return r?r.slice(0,t):null}function ge(e){let t=e.match(/[-_/](\d{2,5})x(\d{2,5})(?=[._/?#-]|$)/i);return t?{width:Number(t[1]),height:Number(t[2])}:null}function pe(e){try{let t=new URL(e);t.hash="",t.pathname=t.pathname.replace(/-(?:\d{2,5}x\d{2,5}|scaled|e\d{6,})(?=\.[a-z0-9]{2,6}$)/i,"");for(let r of["w","width","h","height","resize"])t.searchParams.delete(r);return t.searchParams.sort(),t.href}catch{return e}}function S(e){let t=(e.width??0)*(e.height??0),r=e.discoveryMethods.some(g=>g.includes("lightbox"))?1e12:0,n=/-(?:\d{2,5}x\d{2,5}|scaled|e\d{6,})(?=\.[a-z0-9]{2,6}(?:[?#]|$))/i.test(e.url)?0:1e11;return r+n+t}function A(e,t){let r=e.get(t.url);if(!r){e.set(t.url,t);return}r.discoveryMethods=[...new Set([...r.discoveryMethods,...t.discoveryMethods])],r.altTexts=[...new Set([...r.altTexts,...t.altTexts])],r.contexts=[...new Set([...r.contexts,...t.contexts])],!r.type&&t.type&&(r.type=t.type),(t.width??0)*(t.height??0)>(r.width??0)*(r.height??0)&&(r.width=t.width,r.height=t.height)}function he(e,t){let r=new Map,n=(d,i,o=null,h,l,u)=>{let s=d?me(d.trim().replace(/&amp;/g,"&"),t):null;if(!s||le(s))return;let m=u??ge(s);A(r,{url:s,type:o??F(s),discoveryMethods:[i],altTexts:h?[h]:[],contexts:l?[l]:[],width:m?.width??null,height:m?.height??null})},g=(d,i,o,h)=>{for(let l of(d??"").split(",")){let[u,s]=l.trim().split(/\s+/);if(!u)continue;let m=s?.match(/^(\d+)w$/)?.[1];n(u,i,o,h,null,m?{width:Number(m),height:0}:null)}},a=(d,i="")=>{let o=d.$;for(let l of d.images){let u=l.attributes,s=O(l.alt,500),m=l.width&&l.height?{width:l.width,height:l.height}:null;for(let p of["src","data-src","data-lazy-src","data-original","data-bg","data-background","data-bg-url","data-lazy-bg","data-echo"]){let y=u[p];n(y,`static-${p}${i}`,"image",s,null,m)}g(u.srcset,`static-srcset${i}`,"image",s),g(u["data-srcset"],`static-data-srcset${i}`,"image",s)}o("source").each((l,u)=>{let s=o(u),m=s.attr("type")??"",p=m.startsWith("video/")?"video":m.startsWith("audio/")?"audio":"image";n(s.attr("src"),`static-source${i}`,p),g(s.attr("srcset"),`static-source-srcset${i}`,p)}),o("video,audio").each((l,u)=>{let s=o(u),m=u.tagName.toLowerCase();n(s.attr("src"),`static-${m}${i}`,m),m==="video"&&n(s.attr("poster"),`static-video-poster${i}`,"image")}),o("meta").each((l,u)=>{let s=o(u),m=(s.attr("property")??s.attr("name")??"").toLowerCase();(m==="og:image"||m==="og:image:url"||m==="twitter:image"||m==="twitter:image:src")&&n(s.attr("content"),`static-${m}${i}`,"image")}),o("link[href]").each((l,u)=>{let s=o(u);(s.attr("rel")??"").toLowerCase().split(/\s+/).some(p=>p==="icon"||p==="apple-touch-icon")&&n(s.attr("href"),`static-icon${i}`,"image")}),o("svg image").each((l,u)=>{let s=o(u);n(s.attr("href")??s.attr("xlink:href"),`static-svg-image${i}`,"image")}),o("a[href]").has("img").each((l,u)=>{let s=o(u),m=s.attr("href");if(m&&(/lightbox|gallery|fancybox|glightbox|swipebox|elementor-open-lightbox/i.test(`${s.attr("class")??""} ${s.attr("data-elementor-open-lightbox")??""}`)||/\.(?:avif|gif|jpe?g|png|svg|webp)(?:[?#]|$)/i.test(m))){let p=O(s.find("img").first().attr("alt"),500);n(m,`static-lightbox-target${i}`,"image",p)}});let h=o("style").toArray().map(l=>o(l).text());o("[style]").each((l,u)=>{h.push(o(u).attr("style")??"")});for(let l of h.join(`
2
+ `).matchAll(/(?:background(?:-image)?\s*:\s*)?url\(\s*(?:["']|&quot;|&#0?34;|&apos;|&#0?39;)?([^"')&]+)(?:["']|&quot;|&#0?34;|&apos;|&#0?39;)?\s*\)/gi))n(l[1],`static-css-url${i}`,"image");for(let l of d.sourceHtml.matchAll(/["'](https?:\/\/[^"'\s<>]+\.(?:avif|gif|jpe?g|png|svg|webp|mp4|webm|mp3|ogg)(?:\?[^"'\s<>]*)?)["']/gi))n(l[1],`static-bare-url${i}`)},c=typeof e=="string"?P(e):e;return a(c),c.$("script").each((d,i)=>{let o=c.$(i).text(),h=o.replace(/\\u003[cC]/g,"<").replace(/\\u003[eE]/g,">").replace(/\\u0026/gi,"&").replace(/\\["']/g,l=>l.slice(1)).replace(/\\\//g,"/");h!==o&&/<(?:img|source|video|audio)\b/i.test(h)&&a(P(h),"-json-unescaped")}),[...r.values()]}function fe(e,t,r=100){let n=new Map;for(let a of e)A(n,a);for(let a of t?.assets??[])A(n,{...a,type:a.type});let g=new Map;for(let a of n.values()){let c=pe(a.url),d=g.get(c)??[];d.push(a),g.set(c,d)}return[...g.values()].map(a=>{let c=[...a].sort((i,o)=>S(o)-S(i)||i.url.localeCompare(o.url)),d={...c[0]};return d.discoveryMethods=[...new Set(a.flatMap(i=>i.discoveryMethods))],d.altTexts=[...new Set(a.flatMap(i=>i.altTexts))],d.contexts=[...new Set(a.flatMap(i=>i.contexts))],{...d,variants:c.slice(1).map(i=>i.url)}}).sort((a,c)=>S(c)-S(a)||a.url.localeCompare(c.url)).slice(0,Math.max(1,r))}async function ye(e,t,r,n={}){let g=Math.max(1,Math.min(n.maxBytes??52428800,104857600)),a=e,c=null;for(let p=0;p<=5;p++){let y=await L(a,{field:"media URL"});if(y.error||!y.parsed)throw new Error(y.error??"Media URL was rejected");if(c=await fetch(y.parsed.href,{signal:AbortSignal.timeout(15e3),redirect:"manual"}),c.status>=300&&c.status<400){let w=c.headers.get("location");if(!w)throw new Error(`HTTP ${c.status} redirect did not include Location`);a=new URL(w,y.parsed.href).href,c=null;continue}break}if(!c)throw new Error("Media download exceeded five redirects");if(!c.ok)throw new Error(`HTTP ${c.status}`);if(!c.body)throw new Error("Empty response body");let d=c.headers.get("content-type")?.split(";")[0].trim()??null;if(n.expectedType&&(!d||q(d)!==n.expectedType))throw new Error(`Expected ${n.expectedType} content but received ${d??"no content-type"}`);let i=Number(c.headers.get("content-length")??0);if(Number.isFinite(i)&&i>g)throw new Error(`Media asset exceeds ${g} byte limit`);let o=I(t,r);if(d&&!k(r)){let y={"image/jpeg":".jpg","image/png":".png","image/webp":".webp","image/gif":".gif","image/svg+xml":".svg","image/avif":".avif","video/mp4":".mp4","video/webm":".webm","audio/mpeg":".mp3","audio/ogg":".ogg","audio/wav":".wav"}[d];y&&(o=o+y)}let h=Z(o);await new Promise((p,y)=>{h.once("open",()=>p()),h.once("error",y)});let l=0,u=new ie({transform(p,y,w){let _=p.length;if(l+_>g){w(new Error(`Media asset exceeds ${g} byte limit`));return}if(n.consumeBytes&&!n.consumeBytes(_)){w(new Error("Media export total byte limit exceeded"));return}l+=_,w(null,p)}});try{await ne(oe.fromWeb(c.body),u,h)}catch(p){throw h.destroy(),te(o,{force:!0}),p}let{statSync:s}=await import("fs"),m=s(o).size;return{savedPath:o,sizeBytes:m,mimeType:d}}async function Le(e,t,r={}){let n=r.types??["image","video","audio"],g=new Set(n),a=he(e,t),c=Math.max(1,Math.min(r.maxAssets??100,250)),d=fe(a,r.rendered,2e3),i=d.slice(0,c),o=new Set([...a.map(f=>f.url),...(r.rendered?.assets??[]).map(f=>f.url)]).size,h=i.flatMap(f=>{let b=f.type??F(f.url);return b&&g.has(b)?[{...f,type:b}]:[]}),l=o-h.length,u=d.length>c,s=r.rendered?.exhausted===!0&&!u,m=u?"asset_limit":r.rendered?.stopReason??"render_unavailable",p=u?[`Media discovery found ${d.length} responsive families; only the requested ${c} records were retained.`]:r.rendered?r.rendered.exhausted?[]:[`Rendered media discovery stopped with ${r.rendered.stopReason}; the inventory may be incomplete.`]:["Rendered media discovery was unavailable; this manifest contains static-source evidence only."],y={pageUrl:t,staticFound:a.length,renderedFound:r.rendered?.assets.length??0,filteredCount:l,totalFound:o,completeness:s?"complete":"partial",exhausted:s,stopReason:m,scrollRounds:r.rendered?.scrollRounds??0,warnings:p,artifact:null};if(r.outputDir===null)return{...y,outputDir:null,assets:h.map((f,b)=>({...f,mimeType:null,filename:U(f.url,b),savedPath:null,sizeBytes:null,sha256:null,downloadStatus:"not_attempted",downloadError:null,inlinePreview:null}))};let w=(()=>{try{return new URL(t).hostname.replace(/^www\./,"")}catch{return"unknown"}})(),_=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),C=r.outputDir??I(re(),"Downloads","mcp-scraper","media",`${_}-${w}`);ee(C,{recursive:!0});let T=[];return await Promise.allSettled(h.map(async(f,b)=>{let R=U(f.url,b);try{let{savedPath:v,sizeBytes:Q,mimeType:D}=await ye(f.url,C,R),G=D?q(D)??f.type:f.type;T.push({...f,type:G,mimeType:D,filename:B(v),savedPath:v,sizeBytes:Q,sha256:null,downloadStatus:"downloaded",downloadError:null,inlinePreview:null})}catch(v){T.push({...f,mimeType:null,filename:R,savedPath:null,sizeBytes:null,sha256:null,downloadStatus:"failed",downloadError:v instanceof Error?v.message:"media_download_failed",inlinePreview:null})}})),T.sort((f,b)=>f.savedPath&&!b.savedPath?-1:!f.savedPath&&b.savedPath?1:f.url.localeCompare(b.url)),{...y,outputDir:C,assets:T}}var be=new Set(["browser_navigation_blocked","browser_navigation_failed","browser_timeout","browser_session_failed","browser_result_missing"]);function we(e){return e instanceof Error?e.code:void 0}function _e(e){return e instanceof Error?e.message:String(e)}function H(e){let t=e?.match(/^browser_http_(\d+)$/);return t?Number(t[1]):null}function ve(e){return e===404?"page_not_found":e===403?"page_forbidden":e===429?"page_rate_limited":e>=500&&e<=599?"page_server_error":"page_http_error"}function xe(e){let t=_e(e),r=we(e);if(N(e,t))return{errorCode:"vendor_unavailable",httpStatus:null,retryable:!0};let n=H(r)??H(t.match(/^(browser_http_\d+)/)?.[1]);return n!=null?{errorCode:ve(n),httpStatus:n,retryable:n===429||n>=500}:r==="browser_challenge_unresolved"||/^browser_challenge_unresolved/.test(t)?{errorCode:"bot_check_unresolved",httpStatus:null,retryable:!0}:r==="browser_response_too_large"||/exceeds \d+ byte limit/i.test(t)?{errorCode:"page_too_large",httpStatus:null,retryable:!1}:/browser (?:has been )?closed|context closed|target page, context or browser has been closed|session closed/i.test(t)?{errorCode:"browser_session_interrupted",httpStatus:null,retryable:!0}:be.has(r??"")||/timeout|navigation_failed|ERR_/i.test(t)?{errorCode:"page_unreachable",httpStatus:null,retryable:!0}:{errorCode:"extraction_failed",httpStatus:null,retryable:!1}}function j(e,t){switch(e){case"page_not_found":return`The page could not be found (HTTP ${t??404}). It may have been moved or deleted.`;case"page_forbidden":return`The site refused the request (HTTP ${t??403}).`;case"page_rate_limited":return"The site is rate-limiting requests right now (HTTP 429). Retrying after a short wait usually works.";case"page_server_error":return`The page's own server returned an error (HTTP ${t}). This is on the target site's side, not something a retry here can fix.`;case"page_http_error":return`The page returned an unexpected HTTP ${t} response.`;case"bot_check_unresolved":return"This site has automated-traffic protection (a bot/CAPTCHA check) that could not be resolved in time. Some sites are simply not extractable this way.";case"page_too_large":return"The page is larger than we can safely process.";case"page_unreachable":return"The page did not respond in time, or the connection could not be completed.";case"browser_session_interrupted":return"The browser session closed before extraction completed. A retry uses a fresh browser session.";case"vendor_unavailable":return"MCP Scraper's internal browser services require MCP Scraper team attention. Servers or IPs are down until this is fixed \u2014 this is not caused by your request. Please retry in a few minutes.";case"extraction_failed":return"The page could not be extracted. Please retry, or contact support if this persists for the same URL."}}function Ie(e,t={}){let r=j(e.errorCode,e.httpStatus);return{...$({errorCode:e.errorCode,retryable:e.retryable,chargeStatus:t.chargeStatus,details:{...t.details??{},...e.httpStatus!=null?{http_status:e.httpStatus}:{}}}),message:r,error:r}}function ke(e){return e.httpStatus===404?404:e.httpStatus===403?403:e.httpStatus===429?429:e.httpStatus!=null&&e.httpStatus>=500&&e.httpStatus<=599?500:e.httpStatus!=null?502:e.errorCode==="vendor_unavailable"?503:502}var Ee="wayback_capture_missing";function Be(e,t){if(e==null)return{failureCode:null,failureReason:null};if(e===Ee)return{failureCode:e,failureReason:t??null};let r=new Error(t??e);r.code=e;let n=xe(r);return{failureCode:n.errorCode,failureReason:j(n.errorCode,n.httpStatus)}}import{neon as Te}from"@neondatabase/serverless";var Se="jina",M=null,z=!1;function W(){return(process.env.JINA_EMBED_MODEL??"jina-embeddings-v5-omni-small").trim()}function Y(){return Number((process.env.JINA_EMBED_DIM??"1024").trim())}function J(){return!!(process.env.JINA_API_KEY?.trim()&&process.env.MEMORY_DATABASE_URL?.trim())}function E(){if(M)return M;let e=process.env.MEMORY_DATABASE_URL?.trim();if(!e)throw new Error("MEMORY_DATABASE_URL is not set; Commons semantic search needs the shared Postgres.");return M=Te(e),M}async function K(){if(z)return;let e=Y();await E().query("CREATE EXTENSION IF NOT EXISTS vector"),await E().query(`
3
+ CREATE TABLE IF NOT EXISTS commons_index_vectors (
4
+ document_id TEXT PRIMARY KEY,
5
+ entity_id TEXT NOT NULL,
6
+ document_type TEXT NOT NULL,
7
+ title TEXT NOT NULL,
8
+ embedding vector(${e}) NOT NULL,
9
+ model TEXT NOT NULL,
10
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
11
+ )
12
+ `),await E().query("CREATE INDEX IF NOT EXISTS commons_index_vectors_entity ON commons_index_vectors(entity_id)"),z=!0}async function V(e){let t=process.env.JINA_API_KEY?.trim();if(!t)throw new Error("JINA_API_KEY is not set; Commons semantic search cannot embed.");if(!e.length)return[];let r=await fetch("https://api.jina.ai/v1/embeddings",{method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({model:W(),dimensions:Y(),input:e.map(a=>({text:a.slice(0,8e3)}))}),signal:AbortSignal.timeout(6e4)});if(!r.ok)throw new Error(`Jina embedding request failed with HTTP ${r.status}: ${(await r.text()).slice(0,200)}`);let g=((await r.json()).data??[]).map(a=>a.embedding);if(g.length!==e.length)throw new Error(`Jina returned ${g.length} embeddings for ${e.length} inputs.`);return g}async function je(e=50){if(!J())return{claimed:0,embedded:0,failed:0,remaining:0};await K();let t=Math.max(1,Math.min(200,Math.floor(e))),n=(await x().execute({sql:`SELECT id, entity_id, document_type, title, text FROM commons_index_documents
13
+ WHERE embedding_status IN ('queued', 'failed') ORDER BY updated_at ASC LIMIT ?`,args:[t]})).rows;if(!n.length)return{claimed:0,embedded:0,failed:0,remaining:await X()};let g=0,a=0,c=W();try{let d=await V(n.map(i=>`${i.title}
14
+
15
+ ${i.text}`));for(let[i,o]of n.entries()){let h=`[${d[i].join(",")}]`;await E().query(`INSERT INTO commons_index_vectors (document_id, entity_id, document_type, title, embedding, model, updated_at)
16
+ VALUES ($1, $2, $3, $4, $5::vector, $6, now())
17
+ ON CONFLICT (document_id) DO UPDATE SET entity_id = EXCLUDED.entity_id, document_type = EXCLUDED.document_type,
18
+ title = EXCLUDED.title, embedding = EXCLUDED.embedding, model = EXCLUDED.model, updated_at = now()`,[o.id,o.entity_id,o.document_type,o.title,h,c]),await x().execute({sql:`UPDATE commons_index_documents SET embedding_status = 'indexed', embedding_provider = ?, embedding_model = ?,
19
+ vector_ref = ?, indexed_at = ?, error = NULL WHERE id = ?`,args:[Se,c,o.id,new Date().toISOString(),o.id]}),g+=1}}catch(d){a=n.length-g;let i=(d instanceof Error?d.message:String(d)).slice(0,500);for(let o of n.slice(g))await x().execute({sql:"UPDATE commons_index_documents SET embedding_status = 'failed', error = ? WHERE id = ?",args:[i,o.id]}).catch(()=>{})}return{claimed:n.length,embedded:g,failed:a,remaining:await X()}}async function X(){let e=await x().execute("SELECT COUNT(*) AS n FROM commons_index_documents WHERE embedding_status IN ('queued', 'failed')");return Number(e.rows[0]?.n??0)}async function ze(e,t=40){let r=new Map;if(!J()||!e.trim())return r;await K();let[n]=await V([e]);if(!n)return r;let g=await E().query(`SELECT entity_id, MAX(1 - (embedding <=> $1::vector)) AS score
20
+ FROM commons_index_vectors GROUP BY entity_id ORDER BY score DESC LIMIT $2`,[`[${n.join(",")}]`,Math.max(1,Math.min(100,t))]);for(let a of g)r.set(String(a.entity_id),Number(a.score));return r}export{q as a,he as b,ye as c,Le as d,xe as e,Ie as f,ke as g,Be as h,W as i,Y as j,J as k,V as l,je as m,X as n,ze as o};
@@ -0,0 +1,13 @@
1
+ import{b as y}from"./chunk-HE45FFBU.js";var $=100*1024,L=new Set(["webp","avif","svg","svg+xml"]);function w(s){return s==null?null:s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(1)} KB`:`${(s/(1024*1024)).toFixed(2)} MB`}var R=s=>s.replace(/&amp;/g,"&").replace(/&#0?38;/g,"&").replace(/&#x26;/gi,"&").trim(),M=s=>s.replace(/^https?:\/\//i,"//").replace(/\/$/,""),E=(s,r)=>{if(s){let c=s.split(";")[0].trim().toLowerCase();if(c.startsWith("image/"))return c.replace("image/","")}return(r.split("?")[0].match(/\.([a-z0-9]+)$/i)?.[1]||"unknown").toLowerCase()};function T(s){let r=new Map;for(let c of s)for(let n of c.imageLinks||[]){let e=R(n);if(!/^https?:\/\//i.test(e)||/[{}]|%7[bd]/i.test(e))continue;let a=M(e),i=r.get(a);(!i||/^https:/i.test(e)&&/^http:/i.test(i))&&r.set(a,e)}return[...r.values()]}async function D(s,r){let c=new AbortController,n=setTimeout(()=>c.abort(),r),e=i=>({len:i.headers.get("content-length"),cr:i.headers.get("content-range"),ct:i.headers.get("content-type"),status:i.status}),a=async i=>{let g=s;for(let p=0;p<=5;p++){let m=await y(g,{field:"image URL"});if(m.error||!m.parsed)throw new Error(m.error??"Image URL was rejected");let u=await fetch(m.parsed.href,{method:i,...i==="GET"?{headers:{Range:"bytes=0-0"}}:{},redirect:"manual",signal:c.signal});if(u.status>=300&&u.status<400){let t=u.headers.get("location");if(!t)throw new Error(`HTTP ${u.status} redirect did not include Location`);g=new URL(t,m.parsed.href).href;continue}return u}throw new Error("Image request exceeded five redirects")};try{let i=null,g=null,p=null;try{let m=e(await a("HEAD"));p=m.status,g=m.ct,m.len&&(i=Number(m.len))}catch{}if(i==null){let m=await a("GET"),u=e(m);if(p=p??u.status,g=g??u.ct,u.cr&&u.cr.includes("/")){let t=u.cr.split("/")[1];t&&t!=="*"&&(i=Number(t))}else u.len&&(i=Number(u.len));try{await m.body?.cancel()}catch{}}return{url:s,status:p,bytes:Number.isFinite(i)?i:null,contentType:g}}catch(i){return{url:s,status:null,bytes:null,contentType:null,error:String(i.message||i)}}finally{clearTimeout(n)}}async function v(s,r,c){let n=new Array(s.length),e=0;return await Promise.all(Array.from({length:Math.min(r,s.length)},async()=>{for(;e<s.length;){let a=e++;n[a]=await c(s[a])}})),n}async function S(s,r={}){return A(T(s),r)}async function A(s,r={}){let c=r.concurrency??12,n=r.timeoutMs??12e3,e=r.max??5e3,a=T([{imageLinks:s}]).slice(0,e),g=(await v(a,c,t=>D(t,n))).map(t=>{let f=E(t.contentType,t.url);return{...t,size:w(t.bytes),format:f,over100kb:t.bytes!=null&&t.bytes>$,legacyFormat:f!=="unknown"&&!L.has(f)}}),p=g.filter(t=>t.bytes!=null),m=p.reduce((t,f)=>t+f.bytes,0),u={};for(let t of g)u[t.format]=(u[t.format]||0)+1;return{rows:g.sort((t,f)=>(f.bytes??0)-(t.bytes??0)),summary:{unique:g.length,sized:p.length,totalBytes:m,totalSize:w(m)??"0 B",avgSize:w(Math.round(m/(p.length||1)))??"0 B",over100kb:g.filter(t=>t.over100kb).length,legacyFormat:g.filter(t=>t.legacyFormat).length,formatCounts:u,...r.sampleTruncated?{sampleTruncated:!0,sampleCap:e}:{}}}}function _(s){let r=s.summary,c=Object.entries(r.formatCounts).sort((a,i)=>i[1]-a[1]).map(([a,i])=>`${a}:${i}`).join(" "),n=s.rows.filter(a=>a.over100kb).slice(0,15),e=["## Images",`**${r.unique} unique images** \xB7 ${r.totalSize} total \xB7 ${r.avgSize} avg \xB7 ${r.over100kb} over 100 KB \xB7 ${r.legacyFormat} legacy format`,`Formats: ${c}`];if(n.length){e.push("","| Size | Format | URL |","|------|--------|-----|");for(let a of n)e.push(`| ${a.size} | ${a.format} | ${a.url} |`)}return e.join(`
2
+ `)}function I(s){let r=s.replace(/^www\./,"").toLowerCase(),c=r.split(".");return c.length<=2?r:c.slice(-2).join(".")}function U(s,r,c){let n="";try{n=I(new URL(c).hostname)}catch{n=""}let e=s.filter(l=>l.internal),a=r.length,i=r.filter(l=>l.orphan).length,g=e.filter(l=>l.targetStatus!=null&&l.targetStatus>=400).length,p=r.reduce((l,h)=>l+h.inlinks,0),m=r.reduce((l,h)=>l+h.outlinksInternal+h.outlinksExternal,0),u={zero:0,oneToTwo:0,threeToTen:0,elevenPlus:0};for(let l of r)l.inlinks===0?u.zero++:l.inlinks<=2?u.oneToTwo++:l.inlinks<=10?u.threeToTen++:u.elevenPlus++;let t=[...r].sort((l,h)=>h.inlinks-l.inlinks).slice(0,20).map(l=>({url:l.url,inlinks:l.inlinks,outlinksInternal:l.outlinksInternal,outlinksExternal:l.outlinksExternal})),f=new Map,d=0;for(let l of s){let h;try{h=I(new URL(l.to).hostname)}catch{continue}if(!h||h===n)continue;d++;let k=f.get(h)??{links:0,nofollow:0,pages:new Set};k.links++,l.nofollow&&k.nofollow++,k.pages.add(l.from),f.set(h,k)}let o=[...f.entries()].map(([l,h])=>({domain:l,links:h.links,nofollow:h.nofollow,pages:h.pages.size})).sort((l,h)=>h.links-l.links),b=l=>Math.round(l*10)/10;return{summary:{internal:{totalLinks:e.length,pages:a,orphans:i,brokenInternal:g,avgInlinks:a?b(p/a):0,avgOutlinks:a?b(m/a):0,distribution:u,topByInlinks:t},external:{totalLinks:d,uniqueDomains:o.length,topDomains:o.slice(0,20)}},externalDomains:o}}function X(s){let r=s.summary;return["## Link analysis",`**Internal:** ${r.internal.totalLinks} links \xB7 ${r.internal.pages} pages \xB7 avg ${r.internal.avgInlinks} inlinks/page \xB7 ${r.internal.orphans} orphans \xB7 ${r.internal.brokenInternal} broken`,`**External:** ${r.external.totalLinks} links to ${r.external.uniqueDomains} domains`,"","### Inlink distribution",`- 0 inlinks (orphans): ${r.internal.distribution.zero}`,`- 1\u20132: ${r.internal.distribution.oneToTwo}`,`- 3\u201310: ${r.internal.distribution.threeToTen}`,`- 11+: ${r.internal.distribution.elevenPlus}`,"","### Top 20 internal pages by inlinks","| inlinks | out (int/ext) | URL |","|---|---|---|",...r.internal.topByInlinks.map(n=>`| ${n.inlinks} | ${n.outlinksInternal}/${n.outlinksExternal} | ${n.url} |`),"","### Top 20 external domains by links","| links | nofollow | from pages | domain |","|---|---|---|---|",...r.external.topDomains.map(n=>`| ${n.links} | ${n.nofollow} | ${n.pages} | ${n.domain} |`)].join(`
3
+ `)}function x(s,r){let c=new Map;for(let n of s){let e=r(n);if(e==null||e==="")continue;let a=String(e);c.has(a)||c.set(a,[]),c.get(a).push(n.url)}return[...c.values()].filter(n=>n.length>1).flat()}function B(s,r,c){let n=t=>({count:t.length,urls:t.slice(0,200)}),e=t=>s.filter(t).map(f=>f.url),a=t=>t.extractionStatus!=="failed",i=t=>a(t)&&t.status===200,g=new Set(s.filter(a).map(t=>t.url)),p=t=>{try{return new URL(t).pathname}catch{return""}},m={"title.missing":n(e(t=>i(t)&&!t.title)),"title.duplicate":n(x(s.filter(i),t=>t.title)),"title.tooLong":n(e(t=>(t.titleLength??0)>60||(t.titlePixels??0)>561)),"title.tooShort":n(e(t=>t.title!=null&&(t.titleLength??0)<30)),"title.sameAsH1":n(e(t=>!!t.title&&!!t.h1&&t.title.trim()===t.h1.trim())),"meta.missing":n(e(t=>i(t)&&!t.metaDescription)),"meta.duplicate":n(x(s.filter(i),t=>t.metaDescription)),"meta.tooLong":n(e(t=>(t.metaDescLength??0)>155)),"meta.tooShort":n(e(t=>t.metaDescription!=null&&(t.metaDescLength??0)<70)),"h1.missing":n(e(t=>i(t)&&!t.h1)),"h1.multiple":n(e(t=>!!t.h1_2)),"h1.duplicate":n(x(s.filter(i),t=>t.h1)),"h1.tooLong":n(e(t=>(t.h1?.length??0)>70)),"h2.missing":n(e(t=>i(t)&&t.h2Count===0)),"crawl.extractionFailed":n(e(t=>!a(t))),"indexability.nonIndexable":n(e(t=>a(t)&&!t.indexable)),"indexability.noindex":n(e(t=>t.indexabilityReason==="noindex")),"canonical.missing":n(e(t=>i(t)&&!t.canonicalUrl)),"canonical.canonicalised":n(e(t=>t.indexabilityReason==="canonicalised")),"response.broken4xx":n(e(t=>(t.status??0)>=400&&(t.status??0)<500)),"response.error5xx":n(e(t=>(t.status??0)>=500)),"response.redirect3xx":n(e(t=>(t.status??0)>=300&&(t.status??0)<400)),"response.noResponse":n(e(t=>t.status===null)),"content.thin":n(e(t=>i(t)&&t.wordCount>0&&t.wordCount<200)),"content.exactDuplicate":n(x(s.filter(t=>i(t)&&t.contentHash),t=>t.contentHash)),"images.missingAlt":n(e(t=>a(t)&&t.imagesMissingAlt>0)),"schema.missing":n(e(t=>i(t)&&t.schemaTypes.length===0)),"url.tooLong":n(e(t=>t.url.length>115)),"url.uppercase":n(e(t=>/[A-Z]/.test(p(t.url)))),"url.underscores":n(e(t=>p(t.url).includes("_"))),"links.orphan":n([...r.values()].filter(t=>t.orphan&&g.has(t.url)).map(t=>t.url))},u=c;if(!u){let t=d=>{try{let o=new URL(d);return o.hash="",(o.origin+o.pathname).replace(/\/+$/,"")+o.search}catch{return d.replace(/#.*$/,"").replace(/\/+$/,"")}},f=new Map(s.map(d=>[t(d.url),d.status]));u=new Set;for(let d of s)for(let o of d.outlinks??[]){if(!o.internal)continue;let b=f.get(t(o.href));b!=null&&b>=400&&u.add(d.url)}}return m["links.brokenInternal"]=n([...u]),m}function C(s,r,c,n){let e=r.length,a=r.filter(o=>o.extractionStatus!=="failed").length,i=e-a,g=o=>o.startsWith("response.broken")||o.startsWith("response.error")||o.startsWith("links.broken")?"\u{1F534}":o.startsWith("title.missing")||o.startsWith("h1.missing")||o.startsWith("indexability")||o.startsWith("canonical.missing")?"\u{1F7E0}":"\u{1F7E1}",p=Object.entries(c).filter(([,o])=>o.count>0).sort((o,b)=>b[1].count-o[1].count).map(([o,b])=>`| ${g(o)} | \`${o}\` | ${b.count} | ${b.urls.slice(0,3).join(" \xB7 ")}${b.urls.length>3?" \u2026":""} |`),m=[...n.values()].map(o=>o.crawlDepth).filter(o=>o!=null),u=m.length?Math.max(...m):0,t=new Set(r.filter(o=>o.extractionStatus!=="failed").map(o=>o.url)),f=[...n.values()].filter(o=>o.orphan&&t.has(o.url)).length,d=[...n.values()].sort((o,b)=>b.inlinks-o.inlinks).slice(0,5);return[`# SEO Crawl Report: ${s}`,`**${e} pages attempted** \xB7 ${a} extracted \xB7 ${i} failed \xB7 max crawl depth ${u} \xB7 ${f} orphan page(s)`,`
4
+ ## Issues
5
+ | | Issue | Count | Examples |
6
+ |---|-------|-------|----------|
7
+ ${p.join(`
8
+ `)||"| \u2705 | none | 0 | \u2014 |"}`,`
9
+ ## Most-linked pages
10
+ ${d.map(o=>`- ${o.inlinks} inlinks \xB7 depth ${o.crawlDepth??"\u2014"} \xB7 ${o.url}`).join(`
11
+ `)}`,`
12
+ _Thresholds: title 60ch/561px, meta 155ch, H1 70ch, thin <200 words, URL 115ch. Pixel widths are estimates._`].join(`
13
+ `)}export{S as a,A as b,_ as c,U as d,X as e,B as f,C as g};
@@ -0,0 +1,5 @@
1
+ import{a as P,c as S}from"./chunk-HE45FFBU.js";var N=20,U=20,H=10,j=20,E=280,q=/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,D=[".png",".jpg",".jpeg",".gif",".svg",".webp",".ico","@2x","sentry","wix.com","wixpress","example.","godaddy","squarespace","schema.org","u003e","core-js"],W=/\b(?:website|site|web)\s+(?:by|built|design(?:ed)?|develop(?:ed)?|powered)\b|\b(?:developer|webmaster)\b/i,z=/(?:^|\/)(?:about|bio|contact|contact-us|meet|our-team|people|profile|staff|team)(?:\/|$)/i,Y={"facebook.com":"facebook","fb.com":"facebook","instagram.com":"instagram","linkedin.com":"linkedin","twitter.com":"twitter","x.com":"x","youtube.com":"youtube","youtu.be":"youtube","tiktok.com":"tiktok","pinterest.com":"pinterest"},F=/(?:\/shar(?:e|er)|\/intent\/|\/dialog\/|\/plugins\/|\/share\?|\/developers?\/|platform\.)/i;function x(t){return(t??"").replace(/\s+/g," ").trim()}function _(t,e){try{let r=new URL(t,e);return!["http:","https:"].includes(r.protocol)||r.username||r.password?null:r}catch{return null}}function g(t){let e=t;try{e=decodeURIComponent(t)}catch{}let r=e.split("?")[0].trim().toLowerCase().replace(/[),.;:]+$/,"");return r.length>254||r.split("@").length!==2||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9.-]+\.[a-z]{2,}$/i.test(r)||D.some(n=>r.includes(n))?null:r}function f(t){let e=t.closest("p,li,address,section,article,div").first();return x(e.length?e.text():t.text()).slice(0,E)}function k(t,e,r,n){let s=g(e);!s||W.test(n)||t.has(s)||t.set(s,{value:s,sourceUrl:r,context:x(n).slice(0,E),sourceType:"first_party_page"})}function G(t){t.hash="";for(let e of[...t.searchParams.keys()])/^(?:utm_|fbclid|gclid)/i.test(e)&&t.searchParams.delete(e);return t.href}function J(t){let e=t.toLowerCase().replace(/^www\./,"");return Object.entries(Y).find(([n])=>e===n||e.endsWith(`.${n}`))?.[1]??null}function V(t,e){let r=_(e);if(!r)throw new Error("pageUrl must be a public HTTP(S) URL");let{$:n}=S(t),s=new Map,p=new Map,o=new Map,c=new Map;return n('a[href^="mailto:" i]').each((u,a)=>{let i=n(a);k(s,(i.attr("href")??"").slice(7),r.href,f(i))}),n("body").find("*").addBack().contents().filter((u,a)=>a.type==="text").each((u,a)=>{let i=n(a.parent??a),l=String(a.data??"");for(let d of l.match(q)??[])k(s,d,r.href,f(i))}),n("a[href]").each((u,a)=>{let i=n(a),l=_(i.attr("href")??"",r.href);if(!l)return;let d=x(`${i.text()} ${f(i)}`).slice(0,E),T=J(l.hostname);if(T&&!F.test(`${l.pathname}${l.search}`)){let v=G(l);p.has(v)||p.set(v,{url:v,network:T,sourceUrl:r.href,context:d});return}if(l.origin!==r.origin||!z.test(l.pathname))return;l.hash="";let y=l.href;c.has(y)||c.set(y,{url:y,sourceUrl:r.href,context:d})}),n("form").each((u,a)=>{let i=n(a),l=_(i.attr("action")||r.href,r.href);if(!l||l.origin!==r.origin)return;l.hash="";let d=l.href;o.has(d)||o.set(d,{url:d,sourceUrl:r.href,context:f(i)})}),{emails:[...s.values()].slice(0,N),socialProfiles:[...p.values()].slice(0,U),contactForms:[...o.values()].slice(0,H),candidatePageUrls:[...c.values()].slice(0,j)}}import{createHash as K}from"crypto";var I="3.0.0",w="analytics_setup_site",B="Install X-Ray",R="Install X-Ray and tell me what drives customers",m=`Call ${w} with { "startUrl": "<site URL>", "goal": "${R}" }; on every later call, reuse the returned setupId and revision.`,C=JSON.stringify({mcpServers:{"mcp-scraper":{command:"npx",args:["-y","--package","mcp-scraper@latest","mcp-scraper"],env:{MCP_SCRAPER_API_KEY:"${env:MCP_SCRAPER_API_KEY}"}}}},null,2),Z=JSON.stringify({mcpServers:{"mcp-scraper":{url:"https://mcpscraper.dev/mcp"}}},null,2),O={schema:"https://mcpscraper.dev/schemas/xray-install-contract-v1.json",protocolVersion:I,product:"Thorbit X-Ray",triggerPhrases:[B,"Install X-Ray on this site and tell me what drives customers"],canonicalUrls:{markdown:"https://mcpscraper.dev/agent-install.md",json:"https://mcpscraper.dev/.well-known/xray-install.json",hostedMcp:"https://mcpscraper.dev/mcp"},facade:{tool:w,initialCall:{startUrl:"<site URL>",goal:R},continuationRule:"Treat setupId plus revision as the durable continuation handle. Reuse both after approval, runtime publication, verification, retry, or return."},topologies:{local_stdio:{label:"Local npm MCP process",authority:"The client starts MCP Scraper locally. After the one-time Pixel insertion, X-Ray setup publishes only owner-confirmed runtime configuration.",secretHandling:"Set MCP_SCRAPER_API_KEY in the local environment or client secret field. Never paste it into chat or commit it."},hosted_remote:{label:"Hosted authenticated MCP",authority:"The hosted MCP inspects approved public pages and publishes owner-confirmed X-Ray runtime configuration. It cannot read or write a caller-local path.",secretHandling:"Use the MCP OAuth/connection flow. Never put a credential in a URL, prompt, or config shown in chat."}},hosts:[{id:"codex",label:"Codex",supportedTopologies:["local_stdio","hosted_remote"],mcpConfigMode:"toml",workspaceRead:!0,workspaceWrite:!0,restartRequired:!0,exactConfig:`[mcp_servers.mcp-scraper]
2
+ command = "npx"
3
+ args = ["-y", "--package", "mcp-scraper@latest", "mcp-scraper"]
4
+ env_vars = ["MCP_SCRAPER_API_KEY"]`,continuation:m,rollback:"Remove the mcp_servers.mcp-scraper table, then restart Codex. Pixel removal is a separate owner-controlled site action."},{id:"claude-code",label:"Claude Code",supportedTopologies:["local_stdio","hosted_remote"],mcpConfigMode:"command",workspaceRead:!0,workspaceWrite:!0,restartRequired:!0,exactConfig:'claude mcp add mcp-scraper --scope user --env MCP_SCRAPER_API_KEY="$MCP_SCRAPER_API_KEY" -- npx -y --package mcp-scraper@latest mcp-scraper',continuation:m,rollback:"Run: claude mcp remove mcp-scraper -s user. Pixel removal is a separate owner-controlled site action."},{id:"claude-desktop",label:"Claude Desktop",supportedTopologies:["local_stdio"],mcpConfigMode:"desktop_extension",workspaceRead:!1,workspaceWrite:!1,restartRequired:!0,exactConfig:"Install https://mcpscraper.dev/downloads/mcp-scraper.mcpb and enter the API key only in Claude Desktop's protected configuration field.",continuation:m,rollback:"Remove the MCP Scraper extension in Claude Desktop. Pixel removal is a separate owner-controlled site action."},{id:"cursor",label:"Cursor",supportedTopologies:["local_stdio","hosted_remote"],mcpConfigMode:"json",workspaceRead:!0,workspaceWrite:!0,restartRequired:!0,exactConfig:C,continuation:m,rollback:"Remove mcp-scraper from .cursor/mcp.json (or the user MCP settings), then restart Cursor."},{id:"windsurf",label:"Windsurf",supportedTopologies:["local_stdio"],mcpConfigMode:"json",workspaceRead:!0,workspaceWrite:!0,restartRequired:!0,exactConfig:C,continuation:m,rollback:"Remove mcp-scraper from the Windsurf MCP configuration, then restart Windsurf."},{id:"cline",label:"Cline",supportedTopologies:["local_stdio"],mcpConfigMode:"json",workspaceRead:!0,workspaceWrite:!0,restartRequired:!0,exactConfig:C,continuation:m,rollback:"Remove mcp-scraper from Cline MCP Servers, then restart the extension host."},{id:"user-action-only",label:"User-action-only MCP host",supportedTopologies:["hosted_remote"],mcpConfigMode:"handoff_only",workspaceRead:!1,workspaceWrite:!1,restartRequired:!1,exactConfig:Z,continuation:m,rollback:"Disconnect MCP Scraper from the host. Pixel removal remains an owner-controlled site action."}],tagBootstrap:{requirement:"one_global_pixel_once",ongoingConfiguration:"xray_runtime_manifest",sourceAccessRequiredAfterInstall:!1,supportedInsertionPaths:["manual","tag_manager","cms_plugin","coding_host"]},workflow:["Resolve Thorbit X-Ray entitlement and the target site without consuming MCP Scraper Credits.","Inspect the whole approved public site; enumerate distinct renderers, routes, and Pixel coverage.","Infer the business model and customer outcome, then propose one privacy-safe measurement plan.","If the Pixel is absent, return the canonical one-time tag and exact uncovered surfaces; do not claim ongoing control there.","Publish an approved measurement revision as a digest-bound runtime manifest; source or repository access is not required.","For SaaS, verify the measurement foundation: global tag coverage, ad-source capture, lifecycle events, currency and timezone, consent, and observed outcome events.","Optionally publish a structured post-purchase survey after approved disclosure evidence; reported influence remains separate from deterministic touches.","Compare observed attribution with customer-reported influence only with explicit weights totaling 1,000,000 micros and a named methodology version.","Keep view-through reporting unavailable until event-level provider evidence can join to an eligible X-Ray subject; aggregate impressions never qualify.","Verify route coverage, consent, PageViews, manifest convergence, bounded rule matches, and persisted definition/version evidence.","Require a separate exact-revision approval before any canary or real-visitor experiment activation.","Return first customer-journey answers when sufficient, or exact evidence-readiness thresholds when not.","On \u201Cimprove\u201D, propose one highest-value uncovered outcome, require approval when needed, and reverify."],safetyRules:["Never invent or hand-author tracking code; use the canonical product-authored Pixel snippet returned by analytics_setup_site.","Never ask for or print API keys, OAuth tokens, signed URLs, cookies, or other credentials.","Never call ad platforms directly or silently activate events, definitions, funnels, or delivery destinations.","Never treat a CTA click as a customer, sale, or revenue event without verified outcome evidence.","Never claim full-domain installation while an in-scope route or renderer is missing, excluded without approval, or unverifiable.","Never treat event-name presence as verification; require persisted definition ID and version evidence.","Never accept survey invitation tokens or exchange codes through MCP inputs or prompts.","Never treat customer-reported influence as identity, CRM mutation authority, ad-activation evidence, or a deterministic touch."],terminalStates:["complete","tag_required","input_required","approval_required","runtime_convergence_required","not_ready","error"]};function b(t){return Array.isArray(t)?`[${t.map(b).join(",")}]`:t&&typeof t=="object"?`{${Object.entries(t).sort(([e],[r])=>e.localeCompare(r)).map(([e,r])=>`${JSON.stringify(e)}:${b(r)}`).join(",")}}`:JSON.stringify(t)}function Q(){return b(O)}var L=`sha256:${K("sha256").update(Q(),"utf8").digest("hex")}`,X={...O,protocolDigest:L};function fe(t){let e=X.hosts.find(r=>r.id===t);if(!e)throw new Error(`Unknown X-Ray host: ${t}`);return e}function ge(){return["# Install X-Ray","",`Protocol: ${I} (${L})`,"",`Use ${w} as the single conversational setup facade. Ask for the target site URL if it is missing, then call it with the goal \u201C${R}\u201D.`,"","Continue the same setup with its setupId and revision. Confirm one global Pixel across all public rendering surfaces; present one measurement plan; publish it as a digest-bound runtime manifest after exact-revision approval; verify manifest and rule versions; then return first customer-journey answers or explicit readiness thresholds. For SaaS, verify the provider-neutral measurement foundation. Browser events never prove paid revenue. GitHub or repository access is not required after the tag is installed.","","Do not request pasted credentials, invent tracking code, silently activate measurement, call ad platforms directly, or claim customers/revenue from CTA clicks."].join(`
5
+ `)}function he(t=X){return JSON.parse(JSON.stringify(t))}var ee=new Set(["admin","contact","customerservice","hello","help","info","inquiries","mail","office","reception","sales","service","support","team"]),te=/(?:^|\/)(?:about|bio|contact|contact-us|meet|our-team|people|profile|staff|team)(?:\/|$)/i,re=/\b(?:our team|meet the team|staff|agents?|brokers?|realtors?|people)\b/i,oe=/\b(?:brokerage|company|corporate|front desk|main office|office|organization|reception)\b/i;function M(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().split(/\s+/).filter(Boolean)}function A(t,e){try{let r=new URL(t,e);return!["http:","https:"].includes(r.protocol)||r.username||r.password?null:r}catch{return null}}function ne(t,e){let r=t.value.split("@")[0].toLowerCase().replace(/[^a-z0-9]+/g," "),n=M(e.name).filter(a=>a.length>1),s=A(t.sourceUrl)?.pathname.toLowerCase()??"",p=`${t.context} ${s}`.toLowerCase(),o=ee.has(r.replace(/\s+/g,"")),c=n.filter(a=>new RegExp(`(?:^|[^a-z0-9])${a}(?:$|[^a-z0-9])`,"i").test(`${r} ${p}`)).length,u=e.entityType==="person"&&n.length>=2&&c>=Math.min(2,n.length)&&(r.includes(n[0])||s.includes(n.join("-"))||s.includes(n.join("/")));return!o&&u?{scope:"person",reasons:["named_person_page_context"]}:o||oe.test(p)?{scope:"office",reasons:o?["generic_mailbox_prefix"]:["organization_page_context"]}:re.test(p)?{scope:"team",reasons:["team_page_context"]}:e.entityType==="business"&&M(e.organization||e.name).filter(i=>i.length>2).some(i=>p.includes(i))?{scope:"team",reasons:["business_context"]}:{scope:"unknown",reasons:["public_occurrence_without_identity_evidence"]}}function ve(t,e){let r=t.map(o=>({...o,...ne(o,e)})),n=e.entityType==="person"?["person","team"]:["person","team","office"],s=["provided","first_party_page","structured_data","serp_snippet"],p=["person","team","office"];return r.filter(o=>n.includes(o.scope)).sort((o,c)=>s.indexOf(o.sourceType)-s.indexOf(c.sourceType)||p.indexOf(o.scope)-p.indexOf(c.scope))[0]??null}function _e(t,e,r){if(!Number.isInteger(r)||r<1||r>4)throw new Error("maxPages must be an integer from 1 to 4");let n=A(t);if(!n)return[];n.hash="";let s=new Set([n.href]),p=e.map(o=>typeof o=="string"?o:o.url).map(o=>A(o,n.href)).filter(o=>!!(o&&o.origin===n.origin&&te.test(o.pathname)));for(let o of p)o.hash="",s.add(o.href);for(let o of["/contact","/contact-us"])s.add(new URL(o,n.origin).href);return[...s].slice(0,r)}var se=/[A-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,ie=/\b(?:website|site|web)\s+(?:by|built|design(?:ed)?|develop(?:ed)?|powered)\b|\b(?:developer|webmaster)\b/i,ae=280,ce=10;function h(t){return t.toLowerCase().replace(/^www\./,"").replace(/\.$/,"")}function le(t){let e=h(t);return e==="localhost"||e.endsWith(".localhost")||e.endsWith(".local")||!e.includes(".")&&!e.includes(":")}function $(t){try{let e=new URL(t.trim());return!["http:","https:"].includes(e.protocol)||e.username||e.password||le(e.hostname)||P(e.hostname)?null:e}catch{return null}}function pe(t,e){return`${t} ${e??""}`.replace(/\s+/g," ").trim().slice(0,ae)}function we(t){let e=$(t);return e?(e.hostname=h(e.hostname),`email for ${e.protocol}//${e.host}/`):null}function Re({websiteUrl:t,results:e}){let r=$(t);if(!r)return[];let n=h(r.hostname),s=new Map,p=e.map((o,c)=>({result:o,index:c})).sort((o,c)=>{let u=Number.isFinite(o.result.position)?o.result.position:Number.MAX_SAFE_INTEGER,a=Number.isFinite(c.result.position)?c.result.position:Number.MAX_SAFE_INTEGER;return u-a||o.index-c.index});for(let{result:o}of p){let c=`${o.title} ${o.snippet??""}`,u=pe(o.title,o.snippet);for(let a of c.match(se)??[]){let i=g(a);!i||ie.test(c)||h(i.slice(i.lastIndexOf("@")+1))!==n||s.has(i)||s.set(i,{value:i,sourceUrl:o.url,sourceTitle:o.title,sourcePosition:o.position,context:u,sourceType:"serp_snippet"})}}return[...s.values()].slice(0,ce)}export{V as a,ne as b,ve as c,_e as d,we as e,Re as f,I as g,w as h,R as i,L as j,X as k,fe as l,ge as m,he as n};