mcp-scraper 0.93.1 → 0.93.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -25
- package/README.md +3 -3
- package/dist/bin/api-server.js +1 -1
- package/dist/bin/mcp-scraper-cli.js +1 -1
- package/dist/bin/mcp-scraper-core.js +1 -1
- package/dist/bin/mcp-scraper-install.js +1 -1
- package/dist/bin/mcp-stdio-server.js +1 -1
- package/dist/bin/paa-harvest.js +1 -1
- package/dist/chunk-2SP57VCG.js +15 -15
- package/dist/{chunk-5QYW4CSJ.js → chunk-5VB3I7UX.js} +5 -5
- package/dist/chunk-73LAMUS5.js +6 -0
- package/dist/{chunk-X6RD3Y4W.js → chunk-CG2FHIBA.js} +1 -1
- package/dist/chunk-DT2FYN6N.js +1 -1
- package/dist/{chunk-XG6GCEUE.js → chunk-EWR7BPPD.js} +1 -1
- package/dist/{chunk-IK5BG7MO.js → chunk-KPDNM7E7.js} +1 -1
- package/dist/{chunk-M5VZVMPC.js → chunk-MJ2OICVY.js} +3 -3
- package/dist/chunk-ORB4RHCK.js +4 -4
- package/dist/{chunk-OD2WLHEN.js → chunk-QWSWHUOK.js} +4 -4
- package/dist/chunk-SH5KB4P7.js +1 -1
- package/dist/{chunk-M5QHXNFZ.js → chunk-VVG7LFFF.js} +3 -3
- package/dist/chunk-WJ4XFLS4.js +15 -15
- package/dist/chunk-XJ6PJWT5.js +1 -0
- package/dist/chunk-Y6MKMSOC.js +1 -1
- package/dist/{extract-bundle-C3N6E6V7.js → extract-bundle-MQOAKQDV.js} +1 -1
- package/dist/index.cjs +21 -21
- package/dist/index.d.cts +14 -14
- package/dist/index.d.ts +14 -14
- package/dist/index.js +1 -1
- package/dist/{server-KWGXYWYO.js → server-GRB6VNT6.js} +42 -42
- package/dist/{worker-ASXALAY7.js → worker-US6CTFYG.js} +1 -1
- package/package.json +136 -17
- package/THIRD_PARTY_NOTICES.html +0 -203
- package/dist/chunk-AYQSKD7D.js +0 -1
- package/dist/chunk-KPQM4UDJ.js +0 -6
package/dist/chunk-SH5KB4P7.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function R(e,_=!1,n="light",r=1){let E=_&&n==="full"?r>=2?75e3:45e3:_?4e4:4e5,t=Math.min(E+5e3,795e3);return{serverMs:E,clientMs:t}}function s(){return(process.env.BROWSER_SERVICE_API_KEY??process.env
|
|
1
|
+
function R(e,_=!1,n="light",r=1){let E=_&&n==="full"?r>=2?75e3:45e3:_?4e4:4e5,t=Math.min(E+5e3,795e3);return{serverMs:E,clientMs:t}}function s(){return(process.env.BROWSER_SERVICE_API_KEY??process.env.KERNEL_API_KEY)?.trim()||void 0}function S(){return(process.env.BROWSER_AGENT_PROFILE_NAME??process.env.BROWSER_SERVICE_PROFILE_NAME??process.env.KERNEL_BROWSER_PROFILE_NAME??process.env.KERNEL_PROFILE_NAME)?.trim()||void 0}function u(){let e=(process.env.BROWSER_AGENT_PROFILE_SAVE_CHANGES??process.env.BROWSER_SERVICE_PROFILE_SAVE_CHANGES??process.env.KERNEL_BROWSER_PROFILE_SAVE_CHANGES??process.env.KERNEL_PROFILE_SAVE_CHANGES)?.trim().toLowerCase();if(e){if(["1","true","yes","on"].includes(e))return!0;if(["0","false","no","off"].includes(e))return!1}}export{R as a,s as b,S as c,u as d};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
function Ue(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var ve=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};var x=class extends Error{},I=class r extends x{constructor(e,t,n,o){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=o,this.error=t}static makeMessage(e,t,n){let o=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,t,n,o){if(!e||!o)return new K({message:n,cause:ve(t)});let s=t;return e===400?new fe(e,s,n,o):e===401?new de(e,s,n,o):e===403?new pe(e,s,n,o):e===404?new he(e,s,n,o):e===409?new me(e,s,n,o):e===422?new ye(e,s,n,o):e===429?new ge(e,s,n,o):e>=500?new we(e,s,n,o):new r(e,s,n,o)}},T=class extends I{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},K=class extends I{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},D=class extends K{constructor({message:e}={}){super({message:e??"Request timed out."})}},fe=class extends I{},de=class extends I{},pe=class extends I{},he=class extends I{},me=class extends I{},ye=class extends I{},ge=class extends I{},we=class extends I{};function S(r,e,t,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!o:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(r,t):o?o.value=t:e.set(r,t),t}function _(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}var ct=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return ct=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};var Er=/^[a-z][a-z0-9+.-]*:/i,vt=r=>Er.test(r),$=r=>($=Array.isArray,$(r)),lt=$;function ut(r){return typeof r!="object"?{}:r??{}}function ft(r){if(!r)return!0;for(let e in r)return!1;return!0}function Dt(r,e){return Object.prototype.hasOwnProperty.call(r,e)}var Nt=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new x(`${r} must be an integer`);if(e<0)throw new x(`${r} must be a positive integer`);return e},Sr=r=>{if(typeof r=="number")return Math.round(r);if(typeof r=="string")return parseInt(r,10);throw new x(`Could not coerce ${r} (type: ${typeof r}) into a number`)};var Ir=r=>typeof r=="boolean"?r:typeof r=="string"?r==="true":!!r,Ht=r=>{if(r!=null)return Sr(r)};var dt=r=>{if(r!=null)return Ir(r)},Bt=r=>{try{return JSON.parse(r)}catch{return}};var Mt=r=>new Promise(e=>setTimeout(e,r));var W="0.93.0";function $r(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var Lr=()=>{let r=$r();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":Kt(Deno.build.os),"X-Stainless-Arch":qt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":Kt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":qt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Tr();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Tr(){if(typeof navigator>"u"||!navigator)return null;let r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${s}.${a}`}}}return null}var qt=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Kt=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),Wt,Xt=()=>Wt??(Wt=Lr());function zt(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new \u004b\u0065\u0072\u006e\u0065\u006c({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function pt(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function ze(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return pt({start(){},async pull(t){let{done:n,value:o}=await e.next();n?t.close():t.enqueue(o)},async cancel(){await e.return?.()}})}function ht(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Vt(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}var Jt=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var mt="RFC3986",yt=r=>String(r),gt={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:yt},Gt="RFC1738";var Ve=(r,e)=>(Ve=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ve(r,e)),v=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var wt=1024,Qt=(r,e,t,n,o)=>{if(r.length===0)return r;let s=r;if(typeof r=="symbol"?s=Symbol.prototype.toString.call(r):typeof r!="string"&&(s=String(r)),t==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let a="";for(let c=0;c<s.length;c+=wt){let f=s.length>=wt?s.slice(c,c+wt):s,d=[];for(let m=0;m<f.length;++m){let l=f.charCodeAt(m);if(l===45||l===46||l===95||l===126||l>=48&&l<=57||l>=65&&l<=90||l>=97&&l<=122||o===Gt&&(l===40||l===41)){d[d.length]=f.charAt(m);continue}if(l<128){d[d.length]=v[l];continue}if(l<2048){d[d.length]=v[192|l>>6]+v[128|l&63];continue}if(l<55296||l>=57344){d[d.length]=v[224|l>>12]+v[128|l>>6&63]+v[128|l&63];continue}m+=1,l=65536+((l&1023)<<10|f.charCodeAt(m)&1023),d[d.length]=v[240|l>>18]+v[128|l>>12&63]+v[128|l>>6&63]+v[128|l&63]}a+=d.join("")}return a};function Yt(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function bt(r,e){if($(r)){let t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}var er={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},tr=function(r,e){Array.prototype.push.apply(r,$(e)?e:[e])},Zt,R={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Qt,encodeValuesOnly:!1,format:mt,formatter:yt,indices:!1,serializeDate(r){return(Zt??(Zt=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function Cr(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var xt={};function rr(r,e,t,n,o,s,a,c,f,d,m,l,g,h,A,E,U,k){let b=r,J=k,G=0,it=!1;for(;(J=J.get(xt))!==void 0&&!it;){let L=J.get(r);if(G+=1,typeof L<"u"){if(L===G)throw new RangeError("Cyclic object value");it=!0}typeof J.get(xt)>"u"&&(G=0)}if(typeof d=="function"?b=d(e,b):b instanceof Date?b=g?.(b):t==="comma"&&$(b)&&(b=bt(b,function(L){return L instanceof Date?g?.(L):L})),b===null){if(s)return f&&!E?f(e,R.encoder,U,"key",h):e;b=""}if(Cr(b)||Yt(b)){if(f){let L=E?e:f(e,R.encoder,U,"key",h);return[A?.(L)+"="+A?.(f(b,R.encoder,U,"value",h))]}return[A?.(e)+"="+A?.(String(b))]}let q=[];if(typeof b>"u")return q;let Fe;if(t==="comma"&&$(b))E&&f&&(b=bt(b,f)),Fe=[{value:b.length>0?b.join(",")||null:void 0}];else if($(d))Fe=d;else{let L=Object.keys(b);Fe=m?L.sort(m):L}let kt=c?String(e).replace(/\./g,"%2E"):String(e),Xe=n&&$(b)&&b.length===1?kt+"[]":kt;if(o&&$(b)&&b.length===0)return Xe+"[]";for(let L=0;L<Fe.length;++L){let ue=Fe[L],Ft=typeof ue=="object"&&typeof ue.value<"u"?ue.value:b[ue];if(a&&Ft===null)continue;let at=l&&c?ue.replace(/\./g,"%2E"):ue,Rr=$(b)?typeof t=="function"?t(Xe,at):Xe:Xe+(l?"."+at:"["+at+"]");k.set(r,G);let Ut=new WeakMap;Ut.set(xt,k),tr(q,rr(Ft,Rr,t,n,o,s,a,c,t==="comma"&&E&&$(b)?null:f,d,m,l,g,h,A,E,U,Ut))}return q}function kr(r=R){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||R.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=mt;if(typeof r.format<"u"){if(!Ve(gt,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=gt[t],o=R.filter;(typeof r.filter=="function"||$(r.filter))&&(o=r.filter);let s;if(r.arrayFormat&&r.arrayFormat in er?s=r.arrayFormat:"indices"in r?s=r.indices?"indices":"repeat":s=R.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:R.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:R.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:R.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:R.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?R.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:R.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:R.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:R.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:R.encodeValuesOnly,filter:o,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:R.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:R.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:R.strictNullHandling}}function nr(r,e={}){let t=r,n=kr(e),o,s;typeof n.filter=="function"?(s=n.filter,t=s("",t)):$(n.filter)&&(s=n.filter,o=s);let a=[];if(typeof t!="object"||t===null)return"";let c=er[n.arrayFormat],f=c==="comma"&&n.commaRoundTrip;o||(o=Object.keys(t)),n.sort&&o.sort(n.sort);let d=new WeakMap;for(let g=0;g<o.length;++g){let h=o[g];n.skipNulls&&t[h]===null||tr(a,rr(t[h],h,c,f,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,d))}let m=a.join(n.delimiter),l=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?l+="utf8=%26%2310003%3B&":l+="utf8=%E2%9C%93&"),m.length>0?l+m:""}function or(r){return nr(r,{arrayFormat:"comma"})}function ar(r){let e=0;for(let o of r)e+=o.length;let t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var sr;function De(r){let e;return(sr??(e=new globalThis.TextEncoder,sr=e.encode.bind(e)))(r)}var ir;function _t(r){let e;return(ir??(e=new globalThis.TextDecoder,ir=e.decode.bind(e)))(r)}var j,C,Q=class{constructor(){j.set(this,void 0),C.set(this,void 0),S(this,j,new Uint8Array,"f"),S(this,C,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?De(e):e;S(this,j,ar([_(this,j,"f"),t]),"f");let n=[],o;for(;(o=Ur(_(this,j,"f"),_(this,C,"f")))!=null;){if(o.carriage&&_(this,C,"f")==null){S(this,C,o.index,"f");continue}if(_(this,C,"f")!=null&&(o.index!==_(this,C,"f")+1||o.carriage)){n.push(_t(_(this,j,"f").subarray(0,_(this,C,"f")-1))),S(this,j,_(this,j,"f").subarray(_(this,C,"f")),"f"),S(this,C,null,"f");continue}let s=_(this,C,"f")!==null?o.preceding-1:o.preceding,a=_t(_(this,j,"f").subarray(0,s));n.push(a),S(this,j,_(this,j,"f").subarray(o.index),"f"),S(this,C,null,"f")}return n}flush(){return _(this,j,"f").length?this.decode(`
|
|
1
|
+
function Ue(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var ve=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};var x=class extends Error{},I=class r extends x{constructor(e,t,n,o){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=o,this.error=t}static makeMessage(e,t,n){let o=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,t,n,o){if(!e||!o)return new K({message:n,cause:ve(t)});let s=t;return e===400?new fe(e,s,n,o):e===401?new de(e,s,n,o):e===403?new pe(e,s,n,o):e===404?new he(e,s,n,o):e===409?new me(e,s,n,o):e===422?new ye(e,s,n,o):e===429?new ge(e,s,n,o):e>=500?new we(e,s,n,o):new r(e,s,n,o)}},T=class extends I{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},K=class extends I{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},D=class extends K{constructor({message:e}={}){super({message:e??"Request timed out."})}},fe=class extends I{},de=class extends I{},pe=class extends I{},he=class extends I{},me=class extends I{},ye=class extends I{},ge=class extends I{},we=class extends I{};function S(r,e,t,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!o:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(r,t):o?o.value=t:e.set(r,t),t}function _(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}var ct=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return ct=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};var Er=/^[a-z][a-z0-9+.-]*:/i,vt=r=>Er.test(r),$=r=>($=Array.isArray,$(r)),lt=$;function ut(r){return typeof r!="object"?{}:r??{}}function ft(r){if(!r)return!0;for(let e in r)return!1;return!0}function Dt(r,e){return Object.prototype.hasOwnProperty.call(r,e)}var Nt=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new x(`${r} must be an integer`);if(e<0)throw new x(`${r} must be a positive integer`);return e},Sr=r=>{if(typeof r=="number")return Math.round(r);if(typeof r=="string")return parseInt(r,10);throw new x(`Could not coerce ${r} (type: ${typeof r}) into a number`)};var Ir=r=>typeof r=="boolean"?r:typeof r=="string"?r==="true":!!r,Ht=r=>{if(r!=null)return Sr(r)};var dt=r=>{if(r!=null)return Ir(r)},Bt=r=>{try{return JSON.parse(r)}catch{return}};var Mt=r=>new Promise(e=>setTimeout(e,r));var W="0.93.0";function $r(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var Lr=()=>{let r=$r();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":Kt(Deno.build.os),"X-Stainless-Arch":qt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":Kt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":qt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Tr();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Tr(){if(typeof navigator>"u"||!navigator)return null;let r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${s}.${a}`}}}return null}var qt=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Kt=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),Wt,Xt=()=>Wt??(Wt=Lr());function zt(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Kernel({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function pt(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function ze(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return pt({start(){},async pull(t){let{done:n,value:o}=await e.next();n?t.close():t.enqueue(o)},async cancel(){await e.return?.()}})}function ht(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Vt(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}var Jt=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var mt="RFC3986",yt=r=>String(r),gt={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:yt},Gt="RFC1738";var Ve=(r,e)=>(Ve=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ve(r,e)),v=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var wt=1024,Qt=(r,e,t,n,o)=>{if(r.length===0)return r;let s=r;if(typeof r=="symbol"?s=Symbol.prototype.toString.call(r):typeof r!="string"&&(s=String(r)),t==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let a="";for(let c=0;c<s.length;c+=wt){let f=s.length>=wt?s.slice(c,c+wt):s,d=[];for(let m=0;m<f.length;++m){let l=f.charCodeAt(m);if(l===45||l===46||l===95||l===126||l>=48&&l<=57||l>=65&&l<=90||l>=97&&l<=122||o===Gt&&(l===40||l===41)){d[d.length]=f.charAt(m);continue}if(l<128){d[d.length]=v[l];continue}if(l<2048){d[d.length]=v[192|l>>6]+v[128|l&63];continue}if(l<55296||l>=57344){d[d.length]=v[224|l>>12]+v[128|l>>6&63]+v[128|l&63];continue}m+=1,l=65536+((l&1023)<<10|f.charCodeAt(m)&1023),d[d.length]=v[240|l>>18]+v[128|l>>12&63]+v[128|l>>6&63]+v[128|l&63]}a+=d.join("")}return a};function Yt(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function bt(r,e){if($(r)){let t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}var er={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},tr=function(r,e){Array.prototype.push.apply(r,$(e)?e:[e])},Zt,R={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Qt,encodeValuesOnly:!1,format:mt,formatter:yt,indices:!1,serializeDate(r){return(Zt??(Zt=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function Cr(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var xt={};function rr(r,e,t,n,o,s,a,c,f,d,m,l,g,h,A,E,U,k){let b=r,J=k,G=0,it=!1;for(;(J=J.get(xt))!==void 0&&!it;){let L=J.get(r);if(G+=1,typeof L<"u"){if(L===G)throw new RangeError("Cyclic object value");it=!0}typeof J.get(xt)>"u"&&(G=0)}if(typeof d=="function"?b=d(e,b):b instanceof Date?b=g?.(b):t==="comma"&&$(b)&&(b=bt(b,function(L){return L instanceof Date?g?.(L):L})),b===null){if(s)return f&&!E?f(e,R.encoder,U,"key",h):e;b=""}if(Cr(b)||Yt(b)){if(f){let L=E?e:f(e,R.encoder,U,"key",h);return[A?.(L)+"="+A?.(f(b,R.encoder,U,"value",h))]}return[A?.(e)+"="+A?.(String(b))]}let q=[];if(typeof b>"u")return q;let Fe;if(t==="comma"&&$(b))E&&f&&(b=bt(b,f)),Fe=[{value:b.length>0?b.join(",")||null:void 0}];else if($(d))Fe=d;else{let L=Object.keys(b);Fe=m?L.sort(m):L}let kt=c?String(e).replace(/\./g,"%2E"):String(e),Xe=n&&$(b)&&b.length===1?kt+"[]":kt;if(o&&$(b)&&b.length===0)return Xe+"[]";for(let L=0;L<Fe.length;++L){let ue=Fe[L],Ft=typeof ue=="object"&&typeof ue.value<"u"?ue.value:b[ue];if(a&&Ft===null)continue;let at=l&&c?ue.replace(/\./g,"%2E"):ue,Rr=$(b)?typeof t=="function"?t(Xe,at):Xe:Xe+(l?"."+at:"["+at+"]");k.set(r,G);let Ut=new WeakMap;Ut.set(xt,k),tr(q,rr(Ft,Rr,t,n,o,s,a,c,t==="comma"&&E&&$(b)?null:f,d,m,l,g,h,A,E,U,Ut))}return q}function kr(r=R){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||R.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=mt;if(typeof r.format<"u"){if(!Ve(gt,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=gt[t],o=R.filter;(typeof r.filter=="function"||$(r.filter))&&(o=r.filter);let s;if(r.arrayFormat&&r.arrayFormat in er?s=r.arrayFormat:"indices"in r?s=r.indices?"indices":"repeat":s=R.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:R.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:R.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:R.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:R.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?R.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:R.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:R.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:R.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:R.encodeValuesOnly,filter:o,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:R.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:R.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:R.strictNullHandling}}function nr(r,e={}){let t=r,n=kr(e),o,s;typeof n.filter=="function"?(s=n.filter,t=s("",t)):$(n.filter)&&(s=n.filter,o=s);let a=[];if(typeof t!="object"||t===null)return"";let c=er[n.arrayFormat],f=c==="comma"&&n.commaRoundTrip;o||(o=Object.keys(t)),n.sort&&o.sort(n.sort);let d=new WeakMap;for(let g=0;g<o.length;++g){let h=o[g];n.skipNulls&&t[h]===null||tr(a,rr(t[h],h,c,f,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,d))}let m=a.join(n.delimiter),l=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?l+="utf8=%26%2310003%3B&":l+="utf8=%E2%9C%93&"),m.length>0?l+m:""}function or(r){return nr(r,{arrayFormat:"comma"})}function ar(r){let e=0;for(let o of r)e+=o.length;let t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var sr;function De(r){let e;return(sr??(e=new globalThis.TextEncoder,sr=e.encode.bind(e)))(r)}var ir;function _t(r){let e;return(ir??(e=new globalThis.TextDecoder,ir=e.decode.bind(e)))(r)}var j,C,Q=class{constructor(){j.set(this,void 0),C.set(this,void 0),S(this,j,new Uint8Array,"f"),S(this,C,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?De(e):e;S(this,j,ar([_(this,j,"f"),t]),"f");let n=[],o;for(;(o=Ur(_(this,j,"f"),_(this,C,"f")))!=null;){if(o.carriage&&_(this,C,"f")==null){S(this,C,o.index,"f");continue}if(_(this,C,"f")!=null&&(o.index!==_(this,C,"f")+1||o.carriage)){n.push(_t(_(this,j,"f").subarray(0,_(this,C,"f")-1))),S(this,j,_(this,j,"f").subarray(_(this,C,"f")),"f"),S(this,C,null,"f");continue}let s=_(this,C,"f")!==null?o.preceding-1:o.preceding,a=_t(_(this,j,"f").subarray(0,s));n.push(a),S(this,j,_(this,j,"f").subarray(o.index),"f"),S(this,C,null,"f")}return n}flush(){return _(this,j,"f").length?this.decode(`
|
|
2
2
|
`):[]}};j=new WeakMap,C=new WeakMap;Q.NEWLINE_CHARS=new Set([`
|
|
3
3
|
`,"\r"]);Q.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ur(r,e){for(let o=e??0;o<r.length;o++){if(r[o]===10)return{preceding:o,index:o+1,carriage:!1};if(r[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function cr(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}var Ge={off:0,error:200,warn:300,info:400,debug:500},At=(r,e,t)=>{if(r){if(Dt(Ge,r))return r;P(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(Ge))}`)}};function Ne(){}function Je(r,e,t){return!e||Ge[r]>Ge[t]?Ne:e[r].bind(e)}var vr={error:Ne,warn:Ne,info:Ne,debug:Ne},lr=new WeakMap;function P(r){let e=r.logger,t=r.logLevel??"off";if(!e)return vr;let n=lr.get(e);if(n&&n[0]===t)return n[1];let o={error:Je("error",e,t),warn:Je("warn",e,t),info:Je("info",e,t),debug:Je("debug",e,t)};return lr.set(e,[t,o]),o}var N=r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r);var He,Qe=class r{constructor(e,t,n){this.iterator=e,He.set(this,void 0),this.controller=t,S(this,He,n,"f")}static fromSSEResponse(e,t,n){let o=!1,s=n?P(n):console;async function*a(){if(o)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let c=!1;try{for await(let f of Dr(e,t))try{yield JSON.parse(f.data)}catch(d){throw s.error("Could not parse message into JSON:",f.data),s.error("From chunk:",f.raw),d}c=!0}catch(f){if(Ue(f))return;throw f}finally{c||t.abort()}}return new r(a,t,n)}static fromReadableStream(e,t,n){let o=!1;async function*s(){let c=new Q,f=ht(e);for await(let d of f)for(let m of c.decode(d))yield m;for(let d of c.flush())yield d}async function*a(){if(o)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let c=!1;try{for await(let f of s())c||f&&(yield JSON.parse(f));c=!0}catch(f){if(Ue(f))return;throw f}finally{c||t.abort()}}return new r(a,t,n)}[(He=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),o=s=>({next:()=>{if(s.length===0){let a=n.next();e.push(a),t.push(a)}return s.shift()}});return[new r(()=>o(e),this.controller,_(this,He,"f")),new r(()=>o(t),this.controller,_(this,He,"f"))]}toReadableStream(){let e=this,t;return pt({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:s}=await t.next();if(s)return n.close();let a=De(JSON.stringify(o)+`
|
|
4
4
|
`);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await t.return?.()}})}};async function*Dr(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new x("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new x("Attempted to iterate over a response with no body");let t=new Rt,n=new Q,o=ht(r.body);for await(let s of Nr(o))for(let a of n.decode(s)){let c=t.decode(a);c&&(yield c)}for(let s of n.flush()){let a=t.decode(s);a&&(yield a)}}async function*Nr(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?De(t):t,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=cr(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var Rt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
|
|
@@ -6,5 +6,5 @@ function Ue(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="Abort
|
|
|
6
6
|
${s.map(g=>g.error).join(`
|
|
7
7
|
`)}
|
|
8
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
|
|
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="KERNEL_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.onkernel.com/",development:"https://localhost:3001/"},y=class{constructor({baseURL:e=ke("KERNEL_BASE_URL"),apiKey:t=ke("KERNEL_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("KERNEL_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 KERNEL_SUPPRESS_BUN_WARNING environment variable to true"),t===void 0)throw new x("The KERNEL_API_KEY environment variable is missing or empty; either provide it, or instantiate the Kernel client with an apiKey option, like new Kernel({ 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 KERNEL_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("KERNEL_LOG"),"process.env['KERNEL_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("KERNEL_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-Kernel-Project-Id":this.projectID,"X-Kernel-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.Kernel=Ct;y.DEFAULT_TIMEOUT=6e4;y.KernelError=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};
|
package/dist/chunk-WJ4XFLS4.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createClient as Ve}from"@libsql/client/http";import{createHash as v,randomBytes as q,randomUUID as N,scryptSync as Ne,timingSafeEqual as ze}from"crypto";import{z as p}from"zod";var k="2026-06-26 21:58:03";var Lt="Google returned a CAPTCHA. Run with --headless=false to re-warm the browser profile, then retry.",ve="This operation is temporarily unavailable. Please retry later.",ke=["request_aborted","captcha_exhausted","captcha_or_blocked","location_mismatch","proxy_tunnel_failed","proxy_unavailable","harvest_timeout","mcp_request_timeout","mcp_http_error","extraction_failed","concurrency_limit_exceeded","unauthorized","forbidden","invalid_request","rate_limited","upstream_rate_limited","insufficient_balance","service_unavailable","response_lost","vendor_unavailable","page_not_found","page_forbidden","page_rate_limited","page_server_error","page_http_error","bot_check_unresolved","page_too_large","page_unreachable","browser_session_interrupted","site_export_not_found","site_export_format_unavailable","site_export_read_failed","site_export_image_not_found","image_url_invalid","image_url_not_https","image_host_unresolvable","image_host_blocked","image_redirect_invalid","image_source_unavailable","image_too_large","image_redirect_limit","image_base64_invalid","image_source_missing","image_source_ambiguous","image_source_type_invalid","image_artifact_not_found","image_page_too_large","page_image_not_found","page_image_candidates_unusable","image_format_unsupported","image_storage_unconfigured","featured_image_unhostable"],Xe=["request_aborted","captcha","location_mismatch","connection","timeout","extraction","concurrency_limit","unauthorized","forbidden","invalid_request","rate_limit","billing","service_unavailable"];function O(e){return e?JSON.stringify(e):null}function ae(e){if(e==null)return null;try{let t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t;if(typeof r.error_code!="string"||!oe.has(r.error_code))return null;let n=Ge({errorCode:r.error_code,errorType:r.error_type,retryable:r.retryable,retryAfterSeconds:r.retry_after_seconds,chargeStatus:r.charge_status,details:r.details});if(typeof r.message=="string"){let s=_e(r.message).trim().slice(0,1e3);s&&!/https?:\/\//i.test(s)&&(n.message=s)}return n}catch{return null}}var oe=new Set(ke),Me=new Set(Xe),Fe=new Set(["active","limit","operation","upgrade_url","topup_url","upgrade_command","slots_per_pack","pack_price_usd","balance_credits","required_credits","retry_guidance","http_status"]),Pe=12,He=500;function j(e){return typeof e=="string"&&oe.has(e)?e:"service_unavailable"}function qe(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t={};for(let[r,n]of Object.entries(e)){if(Object.keys(t).length>=Pe)break;if(Fe.has(r))if(typeof n=="string"){if((r==="upgrade_url"||r==="topup_url")&&!We(n))continue;let s=_e(n).slice(0,He);s&&(t[r]=s)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean"||n===null)&&(t[r]=n)}return Object.keys(t).length>0?t:void 0}function We(e){if(e.startsWith("/")&&!e.startsWith("//"))return!0;try{let t=new URL(e);return t.protocol==="https:"&&(t.hostname==="mcpscraper.dev"||t.hostname.endsWith(".mcpscraper.dev"))}catch{return!1}}function je(e){let t=j(e);switch(t){case"captcha_exhausted":case"captcha_or_blocked":return"captcha";case"proxy_tunnel_failed":case"proxy_unavailable":case"response_lost":return"connection";case"harvest_timeout":case"mcp_request_timeout":return"timeout";case"concurrency_limit_exceeded":return"concurrency_limit";case"rate_limited":case"upstream_rate_limited":return"rate_limit";case"extraction_failed":case"page_not_found":case"page_forbidden":case"page_rate_limited":case"page_server_error":case"page_http_error":case"bot_check_unresolved":case"page_too_large":case"page_unreachable":case"browser_session_interrupted":case"site_export_not_found":case"site_export_format_unavailable":case"site_export_read_failed":case"site_export_image_not_found":return"extraction";case"image_url_invalid":case"image_url_not_https":case"image_host_unresolvable":case"image_host_blocked":case"image_redirect_invalid":case"image_source_unavailable":case"image_too_large":case"image_redirect_limit":case"image_base64_invalid":case"image_source_missing":case"image_source_ambiguous":case"image_source_type_invalid":case"image_artifact_not_found":case"image_page_too_large":case"page_image_not_found":case"page_image_candidates_unusable":case"image_format_unsupported":case"image_storage_unconfigured":case"featured_image_unhostable":return"invalid_request";case"insufficient_balance":return"billing";case"vendor_unavailable":case"mcp_http_error":return"service_unavailable";default:return t}}function Be(e){switch(j(e)){case"request_aborted":return"The request was cancelled before it completed.";case"captcha_exhausted":case"captcha_or_blocked":return"The target site returned a verification challenge. Heavy traffic can temporarily increase these challenges; retry in a few minutes.";case"location_mismatch":return"The target site returned results for a different location. Please retry.";case"proxy_tunnel_failed":case"proxy_unavailable":return"The web request could not establish a working connection. Please retry later.";case"harvest_timeout":return"The request timed out before it completed. Please retry with a smaller request.";case"mcp_request_timeout":return"The MCP caller stopped waiting before a final response arrived. Durable work may still be running; continue with the returned Task or job handle instead of restarting it.";case"concurrency_limit_exceeded":return"The service is available, but this account has reached its parallel-operation limit. Wait for an active operation to finish or add capacity.";case"unauthorized":return"Authentication is required to perform this operation.";case"forbidden":return"This account does not have permission to perform this operation.";case"invalid_request":return"The request is invalid. Check the supplied inputs and try again.";case"rate_limited":return"This account is sending requests too quickly. Wait briefly and retry.";case"upstream_rate_limited":return"The connected provider is temporarily rate-limiting requests. Wait briefly and retry.";case"mcp_http_error":return"The API returned an unexpected HTTP response.";case"insufficient_balance":return"This account does not have enough Credits for the operation.";case"extraction_failed":return"The target could not be extracted. Please retry later.";case"response_lost":return"The connection was lost before the response arrived. The operation may have already completed and been billed on our side \u2014 check credits_info before retrying blind.";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"page_not_found":return"The page could not be found. It may have been moved or deleted.";case"page_forbidden":return"The site refused the request.";case"page_rate_limited":return"The site is rate-limiting requests right now. Retrying after a short wait usually works.";case"page_server_error":return"The page's own server returned an error. 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 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. MCP Scraper will retry once with a fresh session; retry the request if this persists.";case"site_export_not_found":return"The site export or requested page was not found, expired, or does not belong to this account.";case"site_export_format_unavailable":return"That representation was not retained for this export page. Read the export manifest and request one of the formats marked available.";case"site_export_read_failed":return"The stored site export could not be read or did not pass its integrity check.";case"site_export_image_not_found":return"The requested site-export image was not found, expired, or does not belong to this account.";case"image_url_invalid":return"The image source is not a valid URL. Use a stable public HTTPS URL or inline image bytes.";case"image_url_not_https":return"Commons image sources must use a public HTTPS URL or inline image bytes.";case"image_host_unresolvable":return"The image host could not be resolved. Use a different stable public URL or inline image bytes.";case"image_host_blocked":return"The image source resolves to a network address Commons cannot fetch safely.";case"image_redirect_invalid":return"The image source redirected to an invalid or unsafe destination.";case"image_source_unavailable":return"The image source could not be fetched. Host a different stable public URL or provide inline image bytes.";case"image_too_large":return"The image exceeds the Commons image size limit.";case"image_redirect_limit":return"The image source exceeded the Commons redirect limit.";case"image_base64_invalid":return"The supplied inline image bytes are invalid.";case"image_source_missing":return"Provide exactly one of a public image or webpage URL, inline image bytes, or an owner-scoped image artifact.";case"image_source_ambiguous":return"Provide only one image source: sourceUrl, imageBase64, or artifactId.";case"image_source_type_invalid":return"Use sourceType only with inline image bytes or an owner-scoped image artifact.";case"image_artifact_not_found":return"The image artifact was not found, expired, or does not belong to this account.";case"image_page_too_large":return"The webpage is too large for bounded Commons image discovery.";case"page_image_not_found":return"The webpage did not expose a usable featured or content image.";case"page_image_candidates_unusable":return"The webpage exposed image candidates, but none returned supported public image bytes.";case"image_format_unsupported":return"Commons accepts JPEG, PNG, GIF, or WebP image bytes.";case"image_storage_unconfigured":return"Commons image storage is temporarily unavailable.";case"featured_image_unhostable":return"The required featured image could not be hosted for Commons publication.";default:return ve}}function Ge(e){let t=j(e.errorCode),r=typeof e.retryAfterSeconds=="number"&&Number.isFinite(e.retryAfterSeconds)?Math.max(1,Math.min(86400,Math.trunc(e.retryAfterSeconds))):void 0,n=e.chargeStatus==="not_charged"||e.chargeStatus==="refund_pending"||e.chargeStatus==="refunded"||e.chargeStatus==="charged"?e.chargeStatus:void 0,s=typeof e.errorType=="string"&&Me.has(e.errorType)?e.errorType:void 0,a=qe(e.details);return{error_code:t,error_type:s??je(t),message:Be(t),retryable:e.retryable===!0,...r?{retry_after_seconds:r}:{},...n?{charge_status:n}:{},...a?{details:a}:{}}}function _e(e){return e.replace((new RegExp("https?:\\/\\/[^\\s]*(?:\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061|on\u006b\u0065\u0072\u006e\u0065\u006c|\u006b\u0065\u0072\u006e\u0065\u006c\\.sh)[^\\s]*", "gi")),"the service").replace(/bright\s*data/gi,"the service").replace((new RegExp("\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061", "gi")),"the service").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\.sh\\s+sessions?", "gi")),"sessions").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\.sh\\s+session", "gi")),"this session").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\.sh", "gi")),"the service").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\s+sessions?", "gi")),"sessions").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\s+session", "gi")),"this session").replace(/\b(?:sub|cus|sess|proxy)_[A-Za-z0-9_-]+\b/g,"[redacted]").replace((new RegExp("\\b(?:\u004b\u0045\u0052\u004e\u0045\u004c|\u0042\u0052\u0049\u0047\u0048\u0054\u0044\u0041\u0054\u0041|\u0042\u0052\u0049\u0047\u0048\u0054_\u0044\u0041\u0054\u0041)_[A-Z0-9_]*API_KEY\\b", "g")),"BROWSER_SERVICE_API_KEY").replace((new RegExp("\\b\u006b\u0065\u0072\u006e\u0065\u006c\\b", "gi")),"the service").replace(/ +/g," ").trim()}var ee=class extends Error{constructor(r){super(`CAPTCHA detected. ${r}`);this.instructions=r}instructions;name="CaptchaError"},te=class extends Error{constructor(r,n){super(r);this.cause=n}cause;name="ExtractionError"},re=class extends Error{constructor(r){super(`Google Maps search did not reach a complete result state (${r})`);this.pageState=r}pageState;name="MapsSearchIncompletePageError"},ne=class extends Error{name="RequestAbortedError";constructor(t="Request aborted before harvest completed"){super(t)}},se=class extends Error{name="PaaInteractionInterruptedError"},ie=class extends Error{name="LocationMismatchError";constructor(t="Google returned results for a different location than requested"){super(t)}};var I=["oauth_store_metadata","oauth_clients","oauth_client_redirect_uris","oauth_codes","oauth_code_exchanges","oauth_refresh_families","oauth_refresh_tokens","oauth_refresh_rotations","oauth_security_events","oauth_rate_limit_buckets"],x=["oauth_clients_inactivity_idx","oauth_clients_cleanup_idx","oauth_codes_expiry_idx","oauth_codes_client_idx","oauth_code_exchanges_replay_expiry_idx","oauth_refresh_families_lifecycle_idx","oauth_refresh_families_user_status_idx","oauth_refresh_families_client_idx","oauth_refresh_families_cleanup_idx","oauth_refresh_tokens_expiry_idx","oauth_refresh_rotations_replay_expiry_idx","oauth_security_events_retention_idx","oauth_rate_limit_buckets_expiry_idx"],ue={oauth_clients:"oauth_clients_legacy_raw",oauth_codes:"oauth_codes_legacy_raw",oauth_tokens:"oauth_tokens_legacy_raw"},L="strftime('%Y-%m-%dT%H:%M:%fZ','now')";async function y(e,t,r=!1){try{await e.execute(t)}catch(n){let s=n.code;if(!r||s!=="SQL_PARSE_ERROR")throw n}}var Ye=[`CREATE TABLE IF NOT EXISTS oauth_store_metadata (
|
|
1
|
+
import{createClient as Ve}from"@libsql/client/http";import{createHash as v,randomBytes as q,randomUUID as N,scryptSync as Ne,timingSafeEqual as ze}from"crypto";import{z as p}from"zod";var k="2026-06-26 21:58:03";var Lt="Google returned a CAPTCHA. Run with --headless=false to re-warm the browser profile, then retry.",ve="This operation is temporarily unavailable. Please retry later.",ke=["request_aborted","captcha_exhausted","captcha_or_blocked","location_mismatch","proxy_tunnel_failed","proxy_unavailable","harvest_timeout","mcp_request_timeout","mcp_http_error","extraction_failed","concurrency_limit_exceeded","unauthorized","forbidden","invalid_request","rate_limited","upstream_rate_limited","insufficient_balance","service_unavailable","response_lost","vendor_unavailable","page_not_found","page_forbidden","page_rate_limited","page_server_error","page_http_error","bot_check_unresolved","page_too_large","page_unreachable","browser_session_interrupted","site_export_not_found","site_export_format_unavailable","site_export_read_failed","site_export_image_not_found","image_url_invalid","image_url_not_https","image_host_unresolvable","image_host_blocked","image_redirect_invalid","image_source_unavailable","image_too_large","image_redirect_limit","image_base64_invalid","image_source_missing","image_source_ambiguous","image_source_type_invalid","image_artifact_not_found","image_page_too_large","page_image_not_found","page_image_candidates_unusable","image_format_unsupported","image_storage_unconfigured","featured_image_unhostable"],Xe=["request_aborted","captcha","location_mismatch","connection","timeout","extraction","concurrency_limit","unauthorized","forbidden","invalid_request","rate_limit","billing","service_unavailable"];function O(e){return e?JSON.stringify(e):null}function ae(e){if(e==null)return null;try{let t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t;if(typeof r.error_code!="string"||!oe.has(r.error_code))return null;let n=Ge({errorCode:r.error_code,errorType:r.error_type,retryable:r.retryable,retryAfterSeconds:r.retry_after_seconds,chargeStatus:r.charge_status,details:r.details});if(typeof r.message=="string"){let s=_e(r.message).trim().slice(0,1e3);s&&!/https?:\/\//i.test(s)&&(n.message=s)}return n}catch{return null}}var oe=new Set(ke),Me=new Set(Xe),Fe=new Set(["active","limit","operation","upgrade_url","topup_url","upgrade_command","slots_per_pack","pack_price_usd","balance_credits","required_credits","retry_guidance","http_status"]),Pe=12,He=500;function j(e){return typeof e=="string"&&oe.has(e)?e:"service_unavailable"}function qe(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t={};for(let[r,n]of Object.entries(e)){if(Object.keys(t).length>=Pe)break;if(Fe.has(r))if(typeof n=="string"){if((r==="upgrade_url"||r==="topup_url")&&!We(n))continue;let s=_e(n).slice(0,He);s&&(t[r]=s)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean"||n===null)&&(t[r]=n)}return Object.keys(t).length>0?t:void 0}function We(e){if(e.startsWith("/")&&!e.startsWith("//"))return!0;try{let t=new URL(e);return t.protocol==="https:"&&(t.hostname==="mcpscraper.dev"||t.hostname.endsWith(".mcpscraper.dev"))}catch{return!1}}function je(e){let t=j(e);switch(t){case"captcha_exhausted":case"captcha_or_blocked":return"captcha";case"proxy_tunnel_failed":case"proxy_unavailable":case"response_lost":return"connection";case"harvest_timeout":case"mcp_request_timeout":return"timeout";case"concurrency_limit_exceeded":return"concurrency_limit";case"rate_limited":case"upstream_rate_limited":return"rate_limit";case"extraction_failed":case"page_not_found":case"page_forbidden":case"page_rate_limited":case"page_server_error":case"page_http_error":case"bot_check_unresolved":case"page_too_large":case"page_unreachable":case"browser_session_interrupted":case"site_export_not_found":case"site_export_format_unavailable":case"site_export_read_failed":case"site_export_image_not_found":return"extraction";case"image_url_invalid":case"image_url_not_https":case"image_host_unresolvable":case"image_host_blocked":case"image_redirect_invalid":case"image_source_unavailable":case"image_too_large":case"image_redirect_limit":case"image_base64_invalid":case"image_source_missing":case"image_source_ambiguous":case"image_source_type_invalid":case"image_artifact_not_found":case"image_page_too_large":case"page_image_not_found":case"page_image_candidates_unusable":case"image_format_unsupported":case"image_storage_unconfigured":case"featured_image_unhostable":return"invalid_request";case"insufficient_balance":return"billing";case"vendor_unavailable":case"mcp_http_error":return"service_unavailable";default:return t}}function Be(e){switch(j(e)){case"request_aborted":return"The request was cancelled before it completed.";case"captcha_exhausted":case"captcha_or_blocked":return"The target site returned a verification challenge. Heavy traffic can temporarily increase these challenges; retry in a few minutes.";case"location_mismatch":return"The target site returned results for a different location. Please retry.";case"proxy_tunnel_failed":case"proxy_unavailable":return"The web request could not establish a working connection. Please retry later.";case"harvest_timeout":return"The request timed out before it completed. Please retry with a smaller request.";case"mcp_request_timeout":return"The MCP caller stopped waiting before a final response arrived. Durable work may still be running; continue with the returned Task or job handle instead of restarting it.";case"concurrency_limit_exceeded":return"The service is available, but this account has reached its parallel-operation limit. Wait for an active operation to finish or add capacity.";case"unauthorized":return"Authentication is required to perform this operation.";case"forbidden":return"This account does not have permission to perform this operation.";case"invalid_request":return"The request is invalid. Check the supplied inputs and try again.";case"rate_limited":return"This account is sending requests too quickly. Wait briefly and retry.";case"upstream_rate_limited":return"The connected provider is temporarily rate-limiting requests. Wait briefly and retry.";case"mcp_http_error":return"The API returned an unexpected HTTP response.";case"insufficient_balance":return"This account does not have enough Credits for the operation.";case"extraction_failed":return"The target could not be extracted. Please retry later.";case"response_lost":return"The connection was lost before the response arrived. The operation may have already completed and been billed on our side \u2014 check credits_info before retrying blind.";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"page_not_found":return"The page could not be found. It may have been moved or deleted.";case"page_forbidden":return"The site refused the request.";case"page_rate_limited":return"The site is rate-limiting requests right now. Retrying after a short wait usually works.";case"page_server_error":return"The page's own server returned an error. 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 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. MCP Scraper will retry once with a fresh session; retry the request if this persists.";case"site_export_not_found":return"The site export or requested page was not found, expired, or does not belong to this account.";case"site_export_format_unavailable":return"That representation was not retained for this export page. Read the export manifest and request one of the formats marked available.";case"site_export_read_failed":return"The stored site export could not be read or did not pass its integrity check.";case"site_export_image_not_found":return"The requested site-export image was not found, expired, or does not belong to this account.";case"image_url_invalid":return"The image source is not a valid URL. Use a stable public HTTPS URL or inline image bytes.";case"image_url_not_https":return"Commons image sources must use a public HTTPS URL or inline image bytes.";case"image_host_unresolvable":return"The image host could not be resolved. Use a different stable public URL or inline image bytes.";case"image_host_blocked":return"The image source resolves to a network address Commons cannot fetch safely.";case"image_redirect_invalid":return"The image source redirected to an invalid or unsafe destination.";case"image_source_unavailable":return"The image source could not be fetched. Host a different stable public URL or provide inline image bytes.";case"image_too_large":return"The image exceeds the Commons image size limit.";case"image_redirect_limit":return"The image source exceeded the Commons redirect limit.";case"image_base64_invalid":return"The supplied inline image bytes are invalid.";case"image_source_missing":return"Provide exactly one of a public image or webpage URL, inline image bytes, or an owner-scoped image artifact.";case"image_source_ambiguous":return"Provide only one image source: sourceUrl, imageBase64, or artifactId.";case"image_source_type_invalid":return"Use sourceType only with inline image bytes or an owner-scoped image artifact.";case"image_artifact_not_found":return"The image artifact was not found, expired, or does not belong to this account.";case"image_page_too_large":return"The webpage is too large for bounded Commons image discovery.";case"page_image_not_found":return"The webpage did not expose a usable featured or content image.";case"page_image_candidates_unusable":return"The webpage exposed image candidates, but none returned supported public image bytes.";case"image_format_unsupported":return"Commons accepts JPEG, PNG, GIF, or WebP image bytes.";case"image_storage_unconfigured":return"Commons image storage is temporarily unavailable.";case"featured_image_unhostable":return"The required featured image could not be hosted for Commons publication.";default:return ve}}function Ge(e){let t=j(e.errorCode),r=typeof e.retryAfterSeconds=="number"&&Number.isFinite(e.retryAfterSeconds)?Math.max(1,Math.min(86400,Math.trunc(e.retryAfterSeconds))):void 0,n=e.chargeStatus==="not_charged"||e.chargeStatus==="refund_pending"||e.chargeStatus==="refunded"||e.chargeStatus==="charged"?e.chargeStatus:void 0,s=typeof e.errorType=="string"&&Me.has(e.errorType)?e.errorType:void 0,a=qe(e.details);return{error_code:t,error_type:s??je(t),message:Be(t),retryable:e.retryable===!0,...r?{retry_after_seconds:r}:{},...n?{charge_status:n}:{},...a?{details:a}:{}}}function _e(e){return e.replace(/https?:\/\/[^\s]*(?:brightdata|onkernel|kernel\.sh)[^\s]*/gi,"the service").replace(/bright\s*data/gi,"the service").replace(/brightdata/gi,"the service").replace(/kernel\.sh\s+sessions?/gi,"sessions").replace(/kernel\.sh\s+session/gi,"this session").replace(/kernel\.sh/gi,"the service").replace(/kernel\s+sessions?/gi,"sessions").replace(/kernel\s+session/gi,"this session").replace(/\b(?:sub|cus|sess|proxy)_[A-Za-z0-9_-]+\b/g,"[redacted]").replace(/\b(?:KERNEL|BRIGHTDATA|BRIGHT_DATA)_[A-Z0-9_]*API_KEY\b/g,"BROWSER_SERVICE_API_KEY").replace(/\bkernel\b/gi,"the service").replace(/ +/g," ").trim()}var ee=class extends Error{constructor(r){super(`CAPTCHA detected. ${r}`);this.instructions=r}instructions;name="CaptchaError"},te=class extends Error{constructor(r,n){super(r);this.cause=n}cause;name="ExtractionError"},re=class extends Error{constructor(r){super(`Google Maps search did not reach a complete result state (${r})`);this.pageState=r}pageState;name="MapsSearchIncompletePageError"},ne=class extends Error{name="RequestAbortedError";constructor(t="Request aborted before harvest completed"){super(t)}},se=class extends Error{name="PaaInteractionInterruptedError"},ie=class extends Error{name="LocationMismatchError";constructor(t="Google returned results for a different location than requested"){super(t)}};var I=["oauth_store_metadata","oauth_clients","oauth_client_redirect_uris","oauth_codes","oauth_code_exchanges","oauth_refresh_families","oauth_refresh_tokens","oauth_refresh_rotations","oauth_security_events","oauth_rate_limit_buckets"],x=["oauth_clients_inactivity_idx","oauth_clients_cleanup_idx","oauth_codes_expiry_idx","oauth_codes_client_idx","oauth_code_exchanges_replay_expiry_idx","oauth_refresh_families_lifecycle_idx","oauth_refresh_families_user_status_idx","oauth_refresh_families_client_idx","oauth_refresh_families_cleanup_idx","oauth_refresh_tokens_expiry_idx","oauth_refresh_rotations_replay_expiry_idx","oauth_security_events_retention_idx","oauth_rate_limit_buckets_expiry_idx"],ue={oauth_clients:"oauth_clients_legacy_raw",oauth_codes:"oauth_codes_legacy_raw",oauth_tokens:"oauth_tokens_legacy_raw"},L="strftime('%Y-%m-%dT%H:%M:%fZ','now')";async function y(e,t,r=!1){try{await e.execute(t)}catch(n){let s=n.code;if(!r||s!=="SQL_PARSE_ERROR")throw n}}var Ye=[`CREATE TABLE IF NOT EXISTS oauth_store_metadata (
|
|
2
2
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
3
|
store_id TEXT NOT NULL UNIQUE,
|
|
4
4
|
schema_version INTEGER NOT NULL CHECK (schema_version > 0),
|
|
@@ -230,14 +230,14 @@ import{createClient as Ve}from"@libsql/client/http";import{createHash as v,rando
|
|
|
230
230
|
max_questions INTEGER NOT NULL,
|
|
231
231
|
status TEXT NOT NULL,
|
|
232
232
|
outcome TEXT,
|
|
233
|
-
|
|
233
|
+
kernel_session_id TEXT,
|
|
234
234
|
question_count INTEGER,
|
|
235
235
|
duration_ms INTEGER,
|
|
236
236
|
error TEXT,
|
|
237
237
|
will_retry INTEGER,
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
238
|
+
kernel_delete_started INTEGER NOT NULL DEFAULT 0,
|
|
239
|
+
kernel_delete_succeeded INTEGER,
|
|
240
|
+
kernel_delete_error TEXT,
|
|
241
241
|
browser_close_succeeded INTEGER,
|
|
242
242
|
browser_close_error TEXT,
|
|
243
243
|
debug_json TEXT,
|
|
@@ -922,8 +922,8 @@ import{createClient as Ve}from"@libsql/client/http";import{createHash as v,rando
|
|
|
922
922
|
id TEXT PRIMARY KEY,
|
|
923
923
|
user_id INTEGER NOT NULL REFERENCES users(id),
|
|
924
924
|
name TEXT NOT NULL,
|
|
925
|
-
|
|
926
|
-
|
|
925
|
+
kernel_profile_name TEXT NOT NULL,
|
|
926
|
+
kernel_proxy_id TEXT NOT NULL,
|
|
927
927
|
proxy_type TEXT NOT NULL DEFAULT 'isp',
|
|
928
928
|
country TEXT NOT NULL DEFAULT 'US',
|
|
929
929
|
status TEXT NOT NULL DEFAULT 'ready',
|
|
@@ -982,7 +982,7 @@ import{createClient as Ve}from"@libsql/client/http";import{createHash as v,rando
|
|
|
982
982
|
ON CONFLICT(scope, key_hash, window_start)
|
|
983
983
|
DO UPDATE SET count = count + 1, updated_at = datetime('now')
|
|
984
984
|
RETURNING count
|
|
985
|
-
`,args:[e,_,a]}),c=Number(o.rows[0]?.count);if(!Number.isSafeInteger(c)||c<1)throw new Error("Rate-limit bucket mutation did not return a valid count");return{allowed:c<=r,count:c,remaining:Math.max(0,r-c),resetSeconds:Math.max(1,a+n-s)}}async function nr(e){let t=q(32).toString("hex"),r=v("sha256").update(t).digest("hex"),n=new Date(Date.now()+3600*1e3).toISOString();return await i().execute({sql:"INSERT INTO password_reset_tokens (token, user_id, expires_at) VALUES (?, ?, ?)",args:[r,e,n]}),t}async function sr(e){let t=i(),r=v("sha256").update(e).digest("hex"),s=(await t.execute({sql:"SELECT user_id, expires_at, used FROM password_reset_tokens WHERE token = ?",args:[r]})).rows[0];return!s||Number(s.used)||new Date(String(s.expires_at))<new Date?null:(await t.execute({sql:"UPDATE password_reset_tokens SET used = 1 WHERE token = ?",args:[r]}),Number(s.user_id))}async function ir(e){let t=Re();return await i().execute({sql:"UPDATE users SET api_key = ?, key_active = 1 WHERE id = ?",args:[t,e]}),t}async function ar(e){await i().execute({sql:"UPDATE users SET key_active = 0 WHERE id = ?",args:[e]})}async function or(){return(await i().execute("SELECT id, email, name, created_at, active FROM users ORDER BY created_at DESC")).rows.map(t=>S({...t,api_key:"",key_active:1}))}async function _r(e){await i().execute({sql:"UPDATE users SET active = 0 WHERE id = ?",args:[e]})}function R(e){return{id:String(e.id),user_id:Number(e.user_id),status:String(e.status),query:String(e.query),options:String(e.options),callback_url:e.callback_url!=null?String(e.callback_url):null,result:e.result!=null?String(e.result):null,error:e.error!=null?String(e.error):null,public_error_json:e.public_error_json!=null?String(e.public_error_json):null,created_at:String(e.created_at),started_at:e.started_at!=null?String(e.started_at):null,completed_at:e.completed_at!=null?String(e.completed_at):null}}function C(e){return e==null?null:Number(e)===1}function H(e){if(e==null)return null;try{return JSON.parse(String(e))}catch{return null}}function we(e){return{id:String(e.id),job_id:String(e.job_id),user_id:Number(e.user_id),attempt_number:Number(e.attempt_number),max_attempts:Number(e.max_attempts),query:String(e.query),location:e.location!=null?String(e.location):null,max_questions:Number(e.max_questions),status:String(e.status),outcome:e.outcome!=null?String(e.outcome):null
|
|
985
|
+
`,args:[e,_,a]}),c=Number(o.rows[0]?.count);if(!Number.isSafeInteger(c)||c<1)throw new Error("Rate-limit bucket mutation did not return a valid count");return{allowed:c<=r,count:c,remaining:Math.max(0,r-c),resetSeconds:Math.max(1,a+n-s)}}async function nr(e){let t=q(32).toString("hex"),r=v("sha256").update(t).digest("hex"),n=new Date(Date.now()+3600*1e3).toISOString();return await i().execute({sql:"INSERT INTO password_reset_tokens (token, user_id, expires_at) VALUES (?, ?, ?)",args:[r,e,n]}),t}async function sr(e){let t=i(),r=v("sha256").update(e).digest("hex"),s=(await t.execute({sql:"SELECT user_id, expires_at, used FROM password_reset_tokens WHERE token = ?",args:[r]})).rows[0];return!s||Number(s.used)||new Date(String(s.expires_at))<new Date?null:(await t.execute({sql:"UPDATE password_reset_tokens SET used = 1 WHERE token = ?",args:[r]}),Number(s.user_id))}async function ir(e){let t=Re();return await i().execute({sql:"UPDATE users SET api_key = ?, key_active = 1 WHERE id = ?",args:[t,e]}),t}async function ar(e){await i().execute({sql:"UPDATE users SET key_active = 0 WHERE id = ?",args:[e]})}async function or(){return(await i().execute("SELECT id, email, name, created_at, active FROM users ORDER BY created_at DESC")).rows.map(t=>S({...t,api_key:"",key_active:1}))}async function _r(e){await i().execute({sql:"UPDATE users SET active = 0 WHERE id = ?",args:[e]})}function R(e){return{id:String(e.id),user_id:Number(e.user_id),status:String(e.status),query:String(e.query),options:String(e.options),callback_url:e.callback_url!=null?String(e.callback_url):null,result:e.result!=null?String(e.result):null,error:e.error!=null?String(e.error):null,public_error_json:e.public_error_json!=null?String(e.public_error_json):null,created_at:String(e.created_at),started_at:e.started_at!=null?String(e.started_at):null,completed_at:e.completed_at!=null?String(e.completed_at):null}}function C(e){return e==null?null:Number(e)===1}function H(e){if(e==null)return null;try{return JSON.parse(String(e))}catch{return null}}function we(e){return{id:String(e.id),job_id:String(e.job_id),user_id:Number(e.user_id),attempt_number:Number(e.attempt_number),max_attempts:Number(e.max_attempts),query:String(e.query),location:e.location!=null?String(e.location):null,max_questions:Number(e.max_questions),status:String(e.status),outcome:e.outcome!=null?String(e.outcome):null,kernel_session_id:e.kernel_session_id!=null?String(e.kernel_session_id):null,question_count:e.question_count!=null?Number(e.question_count):null,duration_ms:e.duration_ms!=null?Number(e.duration_ms):null,error:e.error!=null?String(e.error):null,will_retry:C(e.will_retry),kernel_delete_started:Number(e.kernel_delete_started??0)===1,kernel_delete_succeeded:C(e.kernel_delete_succeeded),kernel_delete_error:e.kernel_delete_error!=null?String(e.kernel_delete_error):null,browser_close_succeeded:C(e.browser_close_succeeded),browser_close_error:e.browser_close_error!=null?String(e.browser_close_error):null,browser_provider:e.browser_provider!=null?String(e.browser_provider):null,provider_session_id:e.provider_session_id!=null?String(e.provider_session_id):null,provider_session_observed_at:e.provider_session_observed_at!=null?String(e.provider_session_observed_at):null,provider_lookup_status:e.provider_lookup_status!=null?String(e.provider_lookup_status):null,provider_status:e.provider_status!=null?String(e.provider_status):null,provider_error_code:e.provider_error_code!=null?String(e.provider_error_code):null,provider_error_message:e.provider_error_message!=null?String(e.provider_error_message):null,provider_reason_source:e.provider_reason_source!=null?String(e.provider_reason_source):null,provider_duration_ms:e.provider_duration_ms!=null?Number(e.provider_duration_ms):null,provider_bandwidth_bytes:e.provider_bandwidth_bytes!=null?Number(e.provider_bandwidth_bytes):null,provider_captcha:C(e.provider_captcha),provider_checked_at:e.provider_checked_at!=null?String(e.provider_checked_at):null,provider_detail:H(e.provider_detail_json),provider_disconnect_observed:C(e.provider_disconnect_observed),provider_disconnect_message:e.provider_disconnect_message!=null?String(e.provider_disconnect_message):null,debug:H(e.debug_json),created_at:String(e.created_at),completed_at:e.completed_at!=null?String(e.completed_at):null}}function h(e){let{public_error_json:t,...r}=e;return{...r,options:JSON.parse(e.options),result:e.result?JSON.parse(e.result):null,publicError:ae(t)}}async function ur(e,t,r,n){let s=N();return await it(s,e,t,r,n),s}async function it(e,t,r,n,s){if(!/^[a-zA-Z0-9-]{1,100}$/.test(e))throw new Error("job id is invalid");await i().execute({sql:"INSERT INTO jobs (id, user_id, query, options, callback_url) VALUES (?, ?, ?, ?, ?)",args:[e,t,r,JSON.stringify(n),s??null]})}async function cr(e,t,r){let n=N();return await i().execute({sql:"INSERT INTO jobs (id, user_id, query, options, status, started_at) VALUES (?, ?, ?, ?, 'running', datetime('now'))",args:[n,e,t,JSON.stringify(r)]}),n}async function dr(e,t,r,n){let s=await i().execute({sql:`INSERT INTO jobs (id, user_id, query, options, status, started_at)
|
|
986
986
|
VALUES (?, ?, ?, ?, 'running', datetime('now'))
|
|
987
987
|
ON CONFLICT(id) DO NOTHING`,args:[e,t,r,JSON.stringify(n)]}),a=await K(e,t);if(!a)throw new Error(`getOrCreateRunningJob: row missing immediately after insert/lookup for ${e}`);return{job:a,created:s.rowsAffected===1}}async function lr(e){await i().execute({sql:`
|
|
988
988
|
INSERT INTO harvest_attempts (
|
|
@@ -1017,14 +1017,14 @@ import{createClient as Ve}from"@libsql/client/http";import{createHash as v,rando
|
|
|
1017
1017
|
UPDATE harvest_attempts SET
|
|
1018
1018
|
status = 'finished',
|
|
1019
1019
|
outcome = ?,
|
|
1020
|
-
|
|
1020
|
+
kernel_session_id = ?,
|
|
1021
1021
|
question_count = ?,
|
|
1022
1022
|
duration_ms = ?,
|
|
1023
1023
|
error = ?,
|
|
1024
1024
|
will_retry = ?,
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1025
|
+
kernel_delete_started = ?,
|
|
1026
|
+
kernel_delete_succeeded = ?,
|
|
1027
|
+
kernel_delete_error = ?,
|
|
1028
1028
|
browser_close_succeeded = ?,
|
|
1029
1029
|
browser_close_error = ?,
|
|
1030
1030
|
browser_provider = COALESCE(browser_provider, ?),
|
|
@@ -1056,7 +1056,7 @@ import{createClient as Ve}from"@libsql/client/http";import{createHash as v,rando
|
|
|
1056
1056
|
debug_json = ?,
|
|
1057
1057
|
completed_at = ?
|
|
1058
1058
|
WHERE job_id = ? AND attempt_number = ?
|
|
1059
|
-
`,args:[e.outcome,e
|
|
1059
|
+
`,args:[e.outcome,e.kernelSessionId,e.questionCount,e.durationMs,e.error,e.willRetry?1:0,e.kernelDeleteStarted?1:0,e.kernelDeleteSucceeded==null?null:e.kernelDeleteSucceeded?1:0,e.kernelDeleteError,e.browserCloseSucceeded==null?null:e.browserCloseSucceeded?1:0,e.browserCloseError,e.browserProvider??null,e.providerSessionId??null,e.providerLookupStatus??null,e.providerStatus??null,e.providerErrorCode??null,e.providerErrorMessage??null,e.providerReasonSource??null,e.providerDurationMs??null,e.providerBandwidthBytes??null,e.providerCaptcha==null?null:e.providerCaptcha?1:0,e.providerCheckedAt??null,e.providerDetail==null?null:Oe(e.providerDetail),e.providerDisconnectObserved==null?null:e.providerDisconnectObserved?1:0,e.providerDisconnectMessage??null,e.debug==null?null:JSON.stringify(e.debug),e.completedAt,e.jobId,e.attemptNumber]})}function Oe(e,t=4096){let r=JSON.stringify(e);return r.length<=t?r:JSON.stringify({truncated:!0})}async function mr(e){return(await i().execute({sql:`
|
|
1060
1060
|
UPDATE harvest_attempts SET
|
|
1061
1061
|
provider_lookup_status = ?,
|
|
1062
1062
|
provider_status = ?,
|
|
@@ -1071,12 +1071,12 @@ import{createClient as Ve}from"@libsql/client/http";import{createHash as v,rando
|
|
|
1071
1071
|
WHERE id = ?
|
|
1072
1072
|
AND job_id = ?
|
|
1073
1073
|
AND user_id = ?
|
|
1074
|
-
AND browser_provider = '
|
|
1074
|
+
AND browser_provider = 'bright_data_browser_api'
|
|
1075
1075
|
AND provider_session_id = ?
|
|
1076
1076
|
AND COALESCE(provider_lookup_status, '') <> 'complete'
|
|
1077
1077
|
`,args:[e.lookupStatus,e.providerStatus??null,e.errorCode??null,e.errorMessage??null,e.reasonSource??null,e.durationMs??null,e.bandwidthBytes??null,e.captcha==null?null:e.captcha?1:0,e.checkedAt,e.detail==null?null:Oe(e.detail),e.attemptId,e.jobId,e.userId,e.providerSessionId]})).rowsAffected===1}async function Nr(e=25){let t=Math.max(1,Math.min(100,Math.trunc(e)));return(await i().execute({sql:`
|
|
1078
1078
|
SELECT * FROM harvest_attempts
|
|
1079
|
-
WHERE browser_provider = '
|
|
1079
|
+
WHERE browser_provider = 'bright_data_browser_api'
|
|
1080
1080
|
AND provider_session_id IS NOT NULL
|
|
1081
1081
|
AND provider_lookup_status IN ('pending', 'temporary_error')
|
|
1082
1082
|
ORDER BY COALESCE(provider_checked_at, created_at) ASC
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var o="0.93.2";export{o as a};
|
package/dist/chunk-Y6MKMSOC.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{z as e}from"zod";var i="none",a="none";function c(t){switch(t){case"day":return"qdr:d";case"week":return"qdr:w";case"month":return"qdr:m";case"year":return"qdr:y";default:return}}var u=e.object({businessName:e.string().min(1),location:e.string().min(1),gl:e.string().length(2).default("us"),hl:e.string().length(2).default("en"),includeReviews:e.boolean().default(!1),maxReviews:e.number().int().min(1).max(500).default(50),includeServices:e.boolean().default(!1),includeImages:e.boolean().default(!1),imageScope:e.enum(["owner","all"]).default("all"),maxImages:e.number().int().min(1).max(250).default(100),maxInlineImages:e.number().int().min(0).max(5).default(3)
|
|
1
|
+
import{z as e}from"zod";var i="none",a="none";function c(t){switch(t){case"day":return"qdr:d";case"week":return"qdr:w";case"month":return"qdr:m";case"year":return"qdr:y";default:return}}var u=e.object({businessName:e.string().min(1),location:e.string().min(1),gl:e.string().length(2).default("us"),hl:e.string().length(2).default("en"),includeReviews:e.boolean().default(!1),maxReviews:e.number().int().min(1).max(500).default(50),includeServices:e.boolean().default(!1),includeImages:e.boolean().default(!1),imageScope:e.enum(["owner","all"]).default("all"),maxImages:e.number().int().min(1).max(250).default(100),maxInlineImages:e.number().int().min(0).max(5).default(3),kernelApiKey:e.string().optional(),kernelProxyId:e.string().optional(),headless:e.boolean().default(!0)}),g=e.object({query:e.string().min(1),location:e.string().optional(),gl:e.string().length(2).default("us"),hl:e.string().length(2).default("en"),maxResults:e.number().int().min(1).max(50).default(10),includeServices:e.boolean().default(!1),proxyMode:e.enum(["location","configured","none"]).default(a),proxyZip:e.string().regex(/^\d{5}$/).optional(),serpRedirect:e.boolean().optional(),forceDirectEgress:e.boolean().optional(),debug:e.boolean().default(!1),kernelApiKey:e.string().optional(),kernelProxyId:e.string().optional(),kernelProxyResolution:e.unknown().optional(),headless:e.boolean().default(!0)}),p=e.object({name:e.string().nullable(),rating:e.string().nullable(),reviewCount:e.string().nullable(),category:e.string().nullable(),address:e.string().nullable(),hoursSummary:e.string().nullable(),phone:e.string().nullable(),phoneDisplay:e.string().nullable(),website:e.string().nullable(),plusCode:e.string().nullable(),bookingUrl:e.string().nullable()}),d=e.object({day:e.string(),hours:e.string()}),b=e.object({reviewHistogram:e.array(e.object({stars:e.number(),count:e.string()})),reviewTopics:e.array(e.object({label:e.string(),count:e.string()}))}),m=e.object({reviewId:e.string(),author:e.string().nullable(),stars:e.string().nullable(),date:e.string().nullable(),text:e.string().nullable(),ownerResponse:e.string().nullable()}),f=e.object({section:e.string(),attribute:e.string()});async function R(t){if((process.env.NODE_ENV==="test"||process.env.VITEST)&&process.env.MCP_SCRAPER_ENABLE_MEMORY_LIBRARY_SINK_IN_TESTS!=="1")return;let r=process.env.MCP_SCRAPER_API_KEY?.trim(),s=(process.env.MCP_SCRAPER_BASE_URL??"https://mcpscraper.dev").replace(/\/$/,"");if(r)try{let n=await fetch(`${s}/memory/mcp-call`,{method:"POST",headers:{"content-type":"application/json","x-api-key":r},body:JSON.stringify({toolName:"libraryIngestTool",args:t})}),o=await n.json().catch(()=>null);(!n.ok||o?.ok===!1)&&console.warn("[memory-library-sink] ingest not accepted:",n.status,o?.error??"")}catch(n){console.warn("[memory-library-sink] ingest failed:",n?.message)}}export{i as a,a as b,c,u as d,g as e,p as f,d as g,b as h,f as i,R as j};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{c as Ge,h as ke,i as Qe,j as Ve,l as et}from"./chunk-
|
|
1
|
+
import{c as Ge,h as ke,i as Qe,j as Ve,l as et}from"./chunk-KPDNM7E7.js";import"./chunk-EWR7BPPD.js";import{b as Ye,c as Xe,h as Ze,j as Ke}from"./chunk-5JKBFNYF.js";import"./chunk-VVG7LFFF.js";import{c as ze,e as Fe,f as He,g as We}from"./chunk-W2BVJ7S2.js";import{c as Je}from"./chunk-RK2VCTZI.js";import"./chunk-ORB4RHCK.js";import"./chunk-TMB56NCA.js";import"./chunk-UN6FVDJQ.js";import"./chunk-6DTXIZY2.js";import"./chunk-HE45FFBU.js";import{t as qe}from"./chunk-WJ4XFLS4.js";import{createWriteStream as se,mkdirSync as ie,readFileSync as xt,readdirSync as kt,rmSync as _t,statSync as Pt,writeFileSync as g}from"fs";import{createHash as G}from"crypto";import{basename as Mt,join as a}from"path";import{tmpdir as It}from"os";import{createGzip as Ct}from"zlib";import{once as Y}from"events";import{finished as ae}from"stream/promises";import{ZipFile as At}from"yazl";import Rt from"p-limit";import{createHash as _e}from"crypto";var gt=500,ht=.9,ft=1e4,yt=5e4;function ge(r,s){let n=10**s;return Math.round(r*n)/n}function wt(r,s){if(r.length===0||r.length!==s.length)throw new Error("Similarity vectors must have the same non-zero dimension.");let n=0,c=0,b=0;for(let w=0;w<r.length;w++)n+=r[w]*s[w],c+=r[w]*r[w],b+=s[w]*s[w];return c===0||b===0?0:Math.max(-1,Math.min(1,n/(Math.sqrt(c)*Math.sqrt(b))))}function St(r){let s=_e("sha256");for(let n of[...r].sort((c,b)=>c.url.localeCompare(b.url)))s.update(n.url),s.update("\0"),s.update(n.contentHash),s.update("\0");return s.digest("hex")}function tt(r){let s=r.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/https?:\/\/\S+/gi," ").replace(/&(?:amp|nbsp|quot|#39);/gi," ").replace(/[#>*_`~|\\-]+/g," ").replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim().toLowerCase();return s.length>=12?s:null}function bt(r){let s=r.map(f=>f.bodyMarkdown.split(/\n{2,}/).map(M=>M.trim()).filter(Boolean)),n=r.length>=4?Math.max(3,Math.ceil(r.length*.5)):null,c=new Map;for(let f of s){let M=new Set(f.map(tt).filter(I=>!!I));for(let I of M)c.set(I,(c.get(I)??0)+1)}let b=new Set;if(n!=null)for(let[f,M]of c)M>=n&&b.add(f);let w=0;return{texts:r.map((f,M)=>{let I=[];for(let _ of s[M]){let T=tt(_);if(T&&b.has(T)){w+=_.length;continue}I.push(_)}let A=I.join(`
|
|
2
2
|
|
|
3
3
|
`).trim(),C=A.length>=60?A:f.bodyMarkdown;return`${f.title?.trim()||"Untitled page"}
|
|
4
4
|
|