mcp-scraper 0.92.1 → 0.93.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CHANGELOG.md +39 -26
  2. package/README.md +4 -4
  3. package/THIRD_PARTY_NOTICES.html +203 -0
  4. package/dist/bin/api-server.js +1 -1
  5. package/dist/bin/mcp-scraper-cli.js +1 -1
  6. package/dist/bin/mcp-scraper-core.js +1 -1
  7. package/dist/bin/mcp-scraper-install.js +1 -1
  8. package/dist/bin/mcp-stdio-server.js +1 -1
  9. package/dist/bin/paa-harvest.js +1 -1
  10. package/dist/chunk-2SP57VCG.js +15 -15
  11. package/dist/{chunk-ZJZMDWDI.js → chunk-35QGIWR6.js} +4 -4
  12. package/dist/{chunk-GPZ7ITF6.js → chunk-4YLZR4OR.js} +1 -1
  13. package/dist/{chunk-T2IJVEHG.js → chunk-5KQO27NH.js} +1 -1
  14. package/dist/chunk-DT2FYN6N.js +1 -0
  15. package/dist/chunk-DUJ56SHU.js +1 -0
  16. package/dist/{chunk-TCLSPE3P.js → chunk-H3SJLJYM.js} +1 -1
  17. package/dist/{chunk-YXUPFECS.js → chunk-LBMRUR4E.js} +2 -2
  18. package/dist/chunk-M5QHXNFZ.js +3 -3
  19. package/dist/{chunk-ZMNUI5LB.js → chunk-M5VZVMPC.js} +8 -8
  20. package/dist/chunk-ORB4RHCK.js +4 -4
  21. package/dist/{chunk-QHHOKLQY.js → chunk-PMOPJOSJ.js} +1 -1
  22. package/dist/chunk-RZEZJAID.js +1 -0
  23. package/dist/chunk-SH5KB4P7.js +1 -0
  24. package/dist/{chunk-QXAXPIHM.js → chunk-VRVO4OQ3.js} +243 -240
  25. package/dist/{chunk-JHMI6HEO.js → chunk-W2T4NTCE.js} +1 -1
  26. package/dist/chunk-WJ4XFLS4.js +15 -15
  27. package/dist/chunk-XASDACRP.js +6 -0
  28. package/dist/chunk-Y6MKMSOC.js +1 -0
  29. package/dist/{extract-bundle-5QTPVIWO.js → extract-bundle-M2XM4BEW.js} +1 -1
  30. package/dist/{gmail-service-EOC7KJSK.js → gmail-service-EGATZIBE.js} +1 -1
  31. package/dist/index.cjs +57 -57
  32. package/dist/index.d.cts +162 -121
  33. package/dist/index.d.ts +162 -121
  34. package/dist/index.js +6 -6
  35. package/dist/{server-NAQTBNPX.js → server-JLR2YJ7V.js} +71 -71
  36. package/dist/{site-extract-repository-U4G25TR2.js → site-extract-repository-3NFFFPXQ.js} +1 -1
  37. package/dist/{stripe-event-worker-KW3DR6GB.js → stripe-event-worker-PUYXT5DS.js} +1 -1
  38. package/dist/worker-UG4OXZWR.js +1 -0
  39. package/package.json +17 -136
  40. package/dist/chunk-2BN2TB3U.js +0 -1
  41. package/dist/chunk-2TZBO52D.js +0 -1
  42. package/dist/chunk-4FROKQJN.js +0 -1
  43. package/dist/chunk-GCLSGYYE.js +0 -1
  44. package/dist/chunk-K6MN7UED.js +0 -2
  45. package/dist/chunk-RECKUOEF.js +0 -1
  46. package/dist/chunk-RSPA4IWH.js +0 -1
  47. package/dist/worker-MSLXSR4M.js +0 -1
@@ -1,4 +1,4 @@
1
- var s={message:"search_serp returns organic Google results with positions, URLs, titles, and descriptions. It requests one page by default or two when pages is 2. Location, language, device, recency, and optional SERP fields are accepted for compatibility but do not change ordinary search results. The customer cost remains 60 Credits per search."};var _={reset:"\x1B[0m",cyan:"\x1B[36m",lime:"\x1B[32m",amber:"\x1B[33m",red:"\x1B[31m",muted:"\x1B[90m",bold:"\x1B[1m"};function r(t,e,n){return n?`${_[e]}${t}${_.reset}`:t}function o(t,e,n){let a=t.padEnd(9," ");return` ${r(a,"muted",n)} ${e.join(r(" . ","muted",n))}`}function p(t){let e=t.color??!0,n=t.apiKeyConfigured?"$MCP_SCRAPER_API_KEY":"sk_live_your_key",a=String.raw`
1
+ var a={message:"search_serp light mode returns organic Google positions, URLs, titles, and descriptions. Full mode adds available same-page SERP features. Both default to one page; request pages:2 explicitly for two. Light costs 20 Credits per delivered page, or 35 Credits when the backup supplies it. Full costs 35 Credits per delivered page."};var _={reset:"\x1B[0m",cyan:"\x1B[36m",lime:"\x1B[32m",amber:"\x1B[33m",red:"\x1B[31m",muted:"\x1B[90m",bold:"\x1B[1m"};function r(t,e,n){return n?`${_[e]}${t}${_.reset}`:t}function o(t,e,n){let s=t.padEnd(9," ");return` ${r(s,"muted",n)} ${e.join(r(" . ","muted",n))}`}function p(t){let e=t.color??!0,n=t.apiKeyConfigured?"$MCP_SCRAPER_API_KEY":"sk_live_your_key",s=String.raw`
2
2
  __ __ ____ ____
3
3
  | \/ |/ ___| _ \
4
4
  | |\/| | | | |_) |
@@ -10,7 +10,7 @@ var s={message:"search_serp returns organic Google results with positions, URLs,
10
10
  \___ \| | | |_) | / _ \ | |_) | _| | |_) |
11
11
  ___) | |___| _ < / ___ \| __/| |___| _ <
12
12
  |____/ \____|_| \_\/_/ \_\_| |_____|_| \_\
13
- `,c=[`MCP_SCRAPER_API_KEY=${n} npx -y -p mcp-scraper@latest \\`," mcp-scraper-cli agent install claude --apply"].join(`
14
- `),i=["[mcp_servers.mcp-scraper]",'command = "npx"','args = ["-y", "-p", "mcp-scraper@latest", "mcp-scraper"]',`env = { MCP_SCRAPER_API_KEY = "${n}" }`].join(`
15
- `);return[r(`mcp-scraper v${t.version}`,"bold",e),r("> mcp-scraper-install","muted",e),r(a,"amber",e),`${r("MCP Scraper Agent","cyan",e)} . v${t.version} . mcpscraper.dev`,"1/1 install surfaces ready",r(`Newest in v${t.version}: ${s.message}`,"lime",e),"",`${r("Tools","cyan",e)} ${r("(362 MCP tools)","muted",e)}`,o("search",["harvest_paa","search_serp","maps_search","maps_place_intel"],e),o("extract",["extract_url","map_site_urls","extract_site","audit_site","directory_workflow"],e),o("build",["create_editorial_reading_room","rank_tracker_workflow","portable HTML"],e),o("media",["youtube_harvest","youtube_transcribe","facebook_reels_inventory","facebook_ad_search","facebook_page_intel","facebook_ad_transcribe","facebook_video_transcribe","tiktok_video_transcribe","instagram_profile_content","instagram_media_download","reddit_thread"],e),o("browser",["serp_identity_create","serp_identity_list","browser_open","browser_profile_connect","browser_profile_list","browser_close","browser_screenshot","browser_read","browser_locate","browser_replay_mark","browser_replay_annotate"],e),o("connect",["list_service_connections","describe_service_connection_tool","import_service_connection_to_memory","export_connected_service_data","renew_connected_data_download","read_service_connection","call_service_connection_action"],e),o("commons",["commons_search_entities","commons_get_entity_linkset","commons_prepare_entity","commons_submit_entity","commons_prepare_publication","commons_claim_publication","commons_publish_editorial","commons_get_publication"],e),o("account",["credits_info","reports","MCP resources"],e),o("memory",["memory-put","memory-get","memory-search","list-vaults","record-fact","list-scheduled-actions"],e),`${r("Workflows","cyan",e)} ${r("(MCP + CLI + API)","muted",e)}`,o("route",["workflow_list","workflow_suggest","workflow_run","workflow_step","workflow_status","workflow_artifact_read"],e),o("seo",["directory","agent-packet","competitive audit","map/serp comparison","PAA/AIO briefs","scheduled runs"],e),"",r("Usage tips:","amber",e),"Run mcp-scraper-install for this visible card. Run mcp-scraper-cli for setup utilities and subcommands.","Run mcp-scraper in a human terminal to print this card; MCP clients get the same command as a silent stdio server.","Explicit card command: npx -y -p mcp-scraper@latest mcp-scraper-install","Hosted browser sessions use direct/no-proxy egress by default.","Customer auth setup: run browser_profile_connect, send the watch_url, let the user sign in, then call browser_profile_list until AUTHENTICATED.","Connected account ranges: call export_connected_service_data once. It handles Gmail, Calendar, Zoom, and Resend pagination; do not loop read_service_connection over individual records.","Connected account RAG: call import_service_connection_to_memory for one bounded approved read. It writes a redacted, untrusted snapshot to a stable Memory path and embeds it for search.","Stack logins / reconnect: run browser_profile_connect again with the same profile name and another domain to add accounts or refresh a login.","Start with workflow_suggest for broad jobs like market analysis, ICP research, CRO audits, brand briefs, content gaps, and AI visibility.","For MCP clients, use mcp-scraper so one install can mix SERP, Maps, browser, reports, and saved MCP resources.","If you hit the concurrency limit, add 2 browsers for $5/month with mcp-scraper-cli billing concurrency checkout.","",`${r("Ready.","lime",e)} Install the combined MCP server with one command:`,"",r("Setup doctor","amber",e),"npx -y -p mcp-scraper@latest mcp-scraper-cli doctor","",r("Hosted profile setup","amber",e),'In your MCP client, call browser_profile_connect with email="seo@example.com" and domain="chatgpt.com".',"Give the returned watch_url to the user. After they sign in, call browser_profile_list, then browser_open with the returned profile. Add more logins by calling browser_profile_connect again with the same profile and a new domain.","",r("Claude Code one-command setup","amber",e),c,"Then fully exit Claude Code and open a new Claude terminal. Check with: claude mcp list","",r("Codex config","amber",e),i,"",r("Claude Desktop Extension","amber",e),"Download: https://mcpscraper.dev/downloads/mcp-scraper.mcpb","",r("Safety note:","muted",e),"mcp-scraper prints this card only when stdin/stdout are an interactive TTY. In MCP clients it writes only JSON-RPC to stdout.","Use --stdio or MCP_SCRAPER_FORCE_STDIO=1 to force server mode from a terminal.",""].join(`
13
+ `,i=[`MCP_SCRAPER_API_KEY=${n} npx -y -p mcp-scraper@latest \\`," mcp-scraper-cli agent install claude --apply"].join(`
14
+ `),c=["[mcp_servers.mcp-scraper]",'command = "npx"','args = ["-y", "-p", "mcp-scraper@latest", "mcp-scraper"]',`env = { MCP_SCRAPER_API_KEY = "${n}" }`].join(`
15
+ `);return[r(`mcp-scraper v${t.version}`,"bold",e),r("> mcp-scraper-install","muted",e),r(s,"amber",e),`${r("MCP Scraper Agent","cyan",e)} . v${t.version} . mcpscraper.dev`,"1/1 install surfaces ready",r(`Newest in v${t.version}: ${a.message}`,"lime",e),"",`${r("Tools","cyan",e)} ${r("(362 MCP tools)","muted",e)}`,o("search",["harvest_paa","search_serp","maps_search","maps_place_intel"],e),o("extract",["extract_url","map_site_urls","extract_site","audit_site","directory_workflow"],e),o("build",["create_editorial_reading_room","rank_tracker_workflow","portable HTML"],e),o("media",["youtube_harvest","youtube_transcribe","facebook_reels_inventory","facebook_ad_search","facebook_page_intel","facebook_ad_transcribe","facebook_video_transcribe","tiktok_video_transcribe","instagram_profile_content","instagram_media_download","reddit_thread"],e),o("browser",["serp_identity_create","serp_identity_list","browser_open","browser_profile_connect","browser_profile_list","browser_close","browser_screenshot","browser_read","browser_locate","browser_replay_mark","browser_replay_annotate"],e),o("connect",["list_service_connections","describe_service_connection_tool","import_service_connection_to_memory","export_connected_service_data","renew_connected_data_download","read_service_connection","call_service_connection_action"],e),o("commons",["commons_search_entities","commons_get_entity_linkset","commons_prepare_entity","commons_submit_entity","commons_prepare_publication","commons_claim_publication","commons_publish_editorial","commons_get_publication"],e),o("account",["credits_info","reports","MCP resources"],e),o("memory",["memory-put","memory-get","memory-search","list-vaults","record-fact","list-scheduled-actions"],e),`${r("Workflows","cyan",e)} ${r("(MCP + CLI + API)","muted",e)}`,o("route",["workflow_list","workflow_suggest","workflow_run","workflow_step","workflow_status","workflow_artifact_read"],e),o("seo",["directory","agent-packet","competitive audit","map/serp comparison","PAA/AIO briefs","scheduled runs"],e),"",r("Usage tips:","amber",e),"Run mcp-scraper-install for this visible card. Run mcp-scraper-cli for setup utilities and subcommands.","Run mcp-scraper in a human terminal to print this card; MCP clients get the same command as a silent stdio server.","Explicit card command: npx -y -p mcp-scraper@latest mcp-scraper-install","Hosted browser sessions use direct/no-proxy egress by default.","Customer auth setup: run browser_profile_connect, send the watch_url, let the user sign in, then call browser_profile_list until AUTHENTICATED.","Connected account ranges: call export_connected_service_data once. It handles Gmail, Calendar, Zoom, and Resend pagination; do not loop read_service_connection over individual records.","Connected account RAG: call import_service_connection_to_memory for one bounded approved read. It writes a redacted, untrusted snapshot to a stable Memory path and embeds it for search.","Stack logins / reconnect: run browser_profile_connect again with the same profile name and another domain to add accounts or refresh a login.","Start with workflow_suggest for broad jobs like market analysis, ICP research, CRO audits, brand briefs, content gaps, and AI visibility.","For MCP clients, use mcp-scraper so one install can mix SERP, Maps, browser, reports, and saved MCP resources.","If you hit the concurrency limit, add 2 browsers for $5/month with mcp-scraper-cli billing concurrency checkout.","",`${r("Ready.","lime",e)} Install the combined MCP server with one command:`,"",r("Setup doctor","amber",e),"npx -y -p mcp-scraper@latest mcp-scraper-cli doctor","",r("Hosted profile setup","amber",e),'In your MCP client, call browser_profile_connect with email="seo@example.com" and domain="chatgpt.com".',"Give the returned watch_url to the user. After they sign in, call browser_profile_list, then browser_open with the returned profile. Add more logins by calling browser_profile_connect again with the same profile and a new domain.","",r("Claude Code one-command setup","amber",e),i,"Then fully exit Claude Code and open a new Claude terminal. Check with: claude mcp list","",r("Codex config","amber",e),c,"",r("Claude Desktop Extension","amber",e),"Download: https://mcpscraper.dev/downloads/mcp-scraper.mcpb","",r("Safety note:","muted",e),"mcp-scraper prints this card only when stdin/stdout are an interactive TTY. In MCP clients it writes only JSON-RPC to stdout.","Use --stdio or MCP_SCRAPER_FORCE_STDIO=1 to force server mode from a terminal.",""].join(`
16
16
  `)}export{p as a};
@@ -1,4 +1,4 @@
1
- import{A as f,Ga as T,Ia as h,Ja as w,Ka as _,La as y,Ma as C,ga as g,ia as S,va as R,wa as E,ya as v,z as u}from"./chunk-QXAXPIHM.js";import{a as P}from"./chunk-ZJZMDWDI.js";import{a as m}from"./chunk-GCLSGYYE.js";import{readFileSync as N}from"fs";import{homedir as I}from"os";import{join as A}from"path";import{serveStdio as b}from"@modelcontextprotocol/server/stdio";import{McpServer as k}from"@modelcontextprotocol/server";var x=new Map(w.map(r=>[r.upstreamName,r.id]));function O(r){let s=r.split(`
1
+ import{A as f,Ga as T,Ia as h,Ja as w,Ka as _,La as y,Ma as C,ga as g,ia as S,va as R,wa as E,ya as v,z as u}from"./chunk-VRVO4OQ3.js";import{a as P}from"./chunk-35QGIWR6.js";import{a as m}from"./chunk-DUJ56SHU.js";import{readFileSync as N}from"fs";import{homedir as I}from"os";import{join as A}from"path";import{serveStdio as b}from"@modelcontextprotocol/server/stdio";import{McpServer as k}from"@modelcontextprotocol/server";var x=new Map(w.map(r=>[r.upstreamName,r.id]));function O(r){let s=r.split(`
2
2
  `).filter(o=>o.startsWith("data:")).map(o=>o.slice(5).trim()).filter(Boolean);if(!s.length)return JSON.parse(r);for(let o of s){let e=JSON.parse(o);if(e.result||e.error)return e}throw new Error("hosted MCP returned no JSON-RPC result")}function a(r){return{content:[{type:"text",text:JSON.stringify({ok:!1,error:r})}],isError:!0}}var c=class{baseUrl;apiKey;constructor(s,o){this.baseUrl=s.replace(/\/$/,""),this.apiKey=o}async callMemoryTool(s,o){let e=x.get(s);if(!e)return a(`unknown memory tool: ${s}`);try{let n=await fetch(`${this.baseUrl}/mcp`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json, text/event-stream","x-api-key":this.apiKey},body:JSON.stringify({jsonrpc:"2.0",id:`memory:${e}`,method:"tools/call",params:{name:e,arguments:o}})}),l=await n.text();if(!n.ok)return a(`hosted memory ${e} failed (HTTP ${n.status})`);let t=O(l);return t.error?a(t.error.message??`hosted memory ${e} failed`):t.result??a(`hosted memory ${e} returned no result`)}catch(n){return a(n instanceof Error?n.message:`hosted memory ${e} call failed`)}}};function M(r,s){if(s.length===0)throw new Error("Restricted MCP tool allowlist must contain at least one tool name");let o=new Set;for(let t of s){if(typeof t!="string"||t.trim()!==t||t.length===0)throw new Error("Restricted MCP tool allowlist contains a malformed tool name");if(o.has(t))throw new Error(`Restricted MCP tool allowlist contains duplicate tool name: ${t}`);o.add(t)}let e=new Set,n=r,l=n.registerTool.bind(r);return n.registerTool=(t,i,p)=>{if(o.has(t))return e.add(t),l(t,i,p)},{assertComplete(){let t=[...o].filter(i=>!e.has(i));if(t.length>0)throw new Error(`Restricted MCP tool allowlist contains unknown or unavailable tool names: ${t.join(", ")}`)},registeredToolNames(){return[...e]}}}var L=new Set(["paa","serp","browser-agent","scheduled-results","memory"]);function $(){let s=[process.env.MCP_SCRAPER_KEY_PATH?.trim(),A(I(),".mcp-scraper-key")].filter(Boolean);for(let o of s)try{let e=N(o,"utf8").trim();if(e)return e}catch{}}function Y(r,s={}){let o=s.toolsets??L,e=process.env.MCP_SCRAPER_BASE_URL?.trim()||process.env.MCP_BASE_URL?.trim()||"https://mcpscraper.dev",n=g(),l=S({deploymentProfile:n,transportProfile:"stdio",baseUrl:e,explicitlyEnabled:process.env.MCP_SCRAPER_ALLOW_PRIVATE_NETWORK==="1"}),t=process.env.BROWSER_AGENT_CONSOLE_URL?.trim()||e,i=new k({name:"mcp-scraper",version:m},{instructions:u,cacheHints:{"server/discover":{ttlMs:3e5,cacheScope:"private"},"tools/list":{ttlMs:3e5,cacheScope:"private"},"prompts/list":{ttlMs:3e5,cacheScope:"private"},"resources/list":{ttlMs:3e5,cacheScope:"private"},"resources/templates/list":{ttlMs:3e5,cacheScope:"private"},"resources/read":{ttlMs:6e4,cacheScope:"private"}}});f(i);let p=s.allowedToolNames?M(i,s.allowedToolNames):void 0,d=s.httpExecutor??new T(e,r,{localNetworkAccess:l});return o.has("paa")&&v(i,d,{ownerId:R(r),deploymentProfile:n,transportProfile:"stdio",baseUrl:e,localNetworkAccess:l,taskHandleSecret:r}),o.has("serp")&&E(i,d,{exposeDevelopmentDiagnostics:n==="development"||n==="test"}),o.has("browser-agent")&&h(i,{baseUrl:e,apiKey:r,consoleBaseUrl:t}),o.has("scheduled-results")&&C(i,new y(e,r)),o.has("memory")&&_(i,new c(e,r)),p?.assertComplete(),i}function se(r={}){let s=process.argv.includes("--stdio")||process.env.MCP_SCRAPER_FORCE_STDIO==="1",o=!!(process.stdin.isTTY&&process.stdout.isTTY),e=process.argv.includes("--help")||process.argv.includes("-h");if(!s&&(o||e)){let l=process.argv.includes("--no-color")||process.env.NO_COLOR!==void 0||process.env.FORCE_COLOR==="0"||!process.stdout.isTTY;process.stdout.write(P({version:m,color:!l,apiKeyConfigured:!!process.env.MCP_SCRAPER_API_KEY?.trim()})),process.exit(0)}let n=(process.env.MCP_SCRAPER_API_KEY??process.env.MCP_SCRAPER_KEY??process.env.MCP_API_KEY??$())?.trim();n||(process.stderr.write(`MCP_SCRAPER_API_KEY env var or ~/.mcp-scraper-key is required
3
3
  `),process.exit(1)),b(()=>Y(n,r),{legacy:"serve",onerror(l){process.stderr.write(`${l.message}
4
4
  `)}})}export{se as a};
@@ -1,4 +1,4 @@
1
- import{k as K}from"./chunk-TCLSPE3P.js";import{a as X}from"./chunk-QTDLZTQ7.js";import{c as J,d as H}from"./chunk-HUV2WTRW.js";import{t as f}from"./chunk-WJ4XFLS4.js";import{createHash as U,createHmac as re,timingSafeEqual as he}from"crypto";import{createHash as fe,randomUUID as Y}from"crypto";var ge=1440*60*1e3,F=5e3,h=class extends Error{constructor(n,i,o=400){super(i);this.code=n;this.status=o;this.name="GmailSelectionError"}code;status},k=null,P=null;function $(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map($).join(",")}]`:`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${$(n)}`).join(",")}}`}function b(e){return fe("sha256").update($(e)).digest("hex")}async function x(){let e=f();return k&&P===e||(P=e,k=(async()=>{await e.execute(`
1
+ import{k as K}from"./chunk-H3SJLJYM.js";import{a as X}from"./chunk-QTDLZTQ7.js";import{c as J,d as H}from"./chunk-HUV2WTRW.js";import{t as f}from"./chunk-WJ4XFLS4.js";import{createHash as U,createHmac as re,timingSafeEqual as he}from"crypto";import{createHash as fe,randomUUID as Y}from"crypto";var ge=1440*60*1e3,F=5e3,h=class extends Error{constructor(n,i,o=400){super(i);this.code=n;this.status=o;this.name="GmailSelectionError"}code;status},k=null,P=null;function $(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map($).join(",")}]`:`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${$(n)}`).join(",")}}`}function b(e){return fe("sha256").update($(e)).digest("hex")}async function x(){let e=f();return k&&P===e||(P=e,k=(async()=>{await e.execute(`
2
2
  CREATE TABLE IF NOT EXISTS gmail_selections (
3
3
  selection_id TEXT PRIMARY KEY,
4
4
  owner_identity TEXT NOT NULL,
@@ -0,0 +1 @@
1
+ import{g as S,i as b}from"./chunk-WJ4XFLS4.js";import{createHash as C}from"crypto";var P=["observed_present","observed_absent","incomplete","not_requested","unknown","unsupported"],A=["provider_transport","invalid_payload","serp_readiness","query_integrity","pagination","optional_feature_parsing","unknown"],v=class extends Error{stage;failureCode;constructor(r,n,t){super(t),this.name="SerpExtractionError",this.stage=r,this.failureCode=n}};function K(e){return e instanceof v?e.stage:null}function p(e){return C("sha256").update(e).digest("hex")}function I(e){return e.normalize("NFKC").toLocaleLowerCase("en-US").split(/[^\p{L}\p{N}]+/u).filter(Boolean).slice(0,64)}function W(e){try{let r=new URL(e);return r.hash="",r.pathname.length>1&&(r.pathname=r.pathname.replace(/\/+$/,"")),r.toString()}catch{return e.trim()}}function Z(e,r){let n=e===2?[1,2]:[1],t=r.filter(o=>o.attempted).map(o=>o.page),s=r.filter(o=>o.captured&&o.resultCount>0).map(o=>o.page),a=r.find(o=>o.failureCode);return{status:n.every(o=>s.includes(o))?"complete":"incomplete",requestedPages:n,attemptedPages:t,capturedPages:s,pageResultCounts:n.map(o=>({page:o,resultCount:r.find(g=>g.page===o)?.resultCount??0})),providerRequestCount:t.length,evidence:r,failureCode:a?.failureCode??null}}function $(e){return e.requested?e.moduleObserved?!e.rawShapeValid||e.rawCount>0&&e.mappedCount===0?"incomplete":e.mappedCount>0?"observed_present":"observed_absent":"unknown":"not_requested"}function X(e){let r=p(e.query),n=e.finalQuery==null?null:p(e.finalQuery),t=e.locationResolutionSource==="unresolved";return{status:n!==null&&n!==r?"query_mismatch":t?"unresolved_location":"matched",queryHash:r,normalizedQueryTokens:I(e.query),canonicalLocation:e.canonicalLocation??null,locationResolutionSource:e.locationResolutionSource,locationAmbiguousCandidates:Math.max(0,Math.trunc(e.locationAmbiguousCandidates??0)),uulePresent:!!e.uule,uuleHash:e.uule?p(e.uule):null,outboundProviderMethod:e.outboundProviderMethod,finalQueryHash:n}}function J(e){return p(JSON.stringify(Object.fromEntries(Object.entries(e).filter(([r,n])=>r!=="requestFingerprint"&&n!==void 0).sort(([r],[n])=>r.localeCompare(n)))))}function l(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function m(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.trunc(e):0}function u(e,r){return typeof e=="string"&&e.length<=r?e:null}function ee(e){let r=l(e),n=l(r.pagination),t=l(r.features),s=l(r.queryIntegrity),a=i=>Array.isArray(i)?i.filter(d=>d===1||d===2).slice(0,2):[],o=a(n.requestedPages);if(o.length===0)return null;let g=new Set(P),k=new Set(A);return{pagination:{status:n.status==="complete"?"complete":"incomplete",requestedPages:o,attemptedPages:a(n.attemptedPages),capturedPages:a(n.capturedPages),pageResultCounts:Array.isArray(n.pageResultCounts)?n.pageResultCounts.slice(0,2).map(i=>{let d=l(i);return{page:d.page===2?2:1,resultCount:m(d.resultCount)}}):[],providerRequestCount:m(n.providerRequestCount),failureCode:u(n.failureCode,100)},features:Object.fromEntries(["localPack","forums","videos","aiOverview","whatPeopleSaying","aiMode","paaPreview","entityIds"].map(i=>[i,g.has(String(t[i]))?t[i]:"unknown"])),queryIntegrity:{status:["matched","unresolved_location","query_mismatch"].includes(String(s.status))?s.status:"query_mismatch",queryHash:u(s.queryHash,64)??"",normalizedQueryTokens:Array.isArray(s.normalizedQueryTokens)?s.normalizedQueryTokens.slice(0,64).flatMap(i=>typeof i=="string"?[i.slice(0,100)]:[]):[],canonicalLocation:u(s.canonicalLocation,500),locationResolutionSource:u(s.locationResolutionSource,100)??"unknown",locationAmbiguousCandidates:m(s.locationAmbiguousCandidates),uulePresent:s.uulePresent===!0,uuleHash:u(s.uuleHash,64),outboundProviderMethod:"search",finalQueryHash:u(s.finalQueryHash,64)},failureStage:k.has(String(r.failureStage))?r.failureStage:null}}var T={\u006b\u0065\u0072\u006e\u0065\u006c:"browserRuntime"},f=/error|message/i,O=(new RegExp("(?:spending|billing|organization|account).{0,80}(?:cap|limit|blocked|disabled)|(?:quota|capacity).{0,40}(?:reached|exceeded)|https?:\\/\\/\\S*(?:dashboard|on\u006b\u0065\u0072\u006e\u0065\u006c)", "i")),x=/\b(?:ENOENT|ENOTDIR|EACCES|EPERM|EISDIR|EMFILE|ENFILE)\b|\b(?:mkdir|open|stat|lstat|readFile|writeFile)\s+['"]?(?:\/|[A-Za-z]:\\)|(?:^|[\s'"])(?:\/Users|\/home|\/tmp|\/var|\/private|\/opt|\/srv|\/root)\//i,q=new Set(["\u006b\u0065\u0072\u006e\u0065\u006c_session_id","browser_session_id","\u006b\u0065\u0072\u006e\u0065\u006cSessionId","browserSessionId","sessionId","\u006b\u0065\u0072\u006e\u0065\u006c_delete_started","session_cleanup_started","\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted","sessionCleanupStarted","\u006b\u0065\u0072\u006e\u0065\u006c_delete_succeeded","session_cleanup_succeeded","\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded","sessionCleanupSucceeded","\u006b\u0065\u0072\u006e\u0065\u006c_delete_error","session_cleanup_error","\u006b\u0065\u0072\u006e\u0065\u006cDeleteError","sessionCleanupError","\u006b\u0065\u0072\u006e\u0065\u006cProxyId","proxyId","requestedProxyIdSuffix","retrievedProxyIdSuffix","provider","providerName","service","serviceName","vendor","vendorName","organization","organizationId","accountId","browser_provider","provider_session_id","provider_session_observed_at","provider_lookup_status","provider_status","provider_error_code","provider_error_message","provider_reason_source","provider_duration_ms","provider_bandwidth_bytes","provider_captcha","provider_checked_at","provider_detail","provider_detail_json","provider_disconnect_observed","provider_disconnect_message","browserProvider","providerSessionId","providerLookupStatus","providerStatus","providerErrorCode","providerErrorMessage","providerReasonSource","providerDurationMs","providerBandwidthBytes","providerCaptcha","providerCheckedAt","providerDetail","providerDisconnectObserved","providerDisconnectMessage"]),F=new Set(["hosted_url","hostedUrl","live_view_url","liveViewUrl","cdp_ws_url","cdpWsUrl","browser_live_view_url"]),L=(new RegExp("\\b(?:wss?|https?):\\/\\/[^\\s\"'<>]*\\bon\u006b\u0065\u0072\u006e\u0065\u006c\\.com[^\\s\"'<>]*", "gi"));function R(e){return e.replace(L,"[browser-service]")}var N=new Set(["\u0062\u0072\u0069\u0067\u0068\u0074_\u0064\u0061\u0074\u0061_browser_api","\u006b\u0065\u0072\u006e\u0065\u006c","local"]),D=new Set(["pending","complete","not_found","unavailable_credentials","temporary_error","invalid_payload","not_applicable"]),U=new Set(["active","running","complete","completed","failed","closed","stopped","terminated","timed_out"]),M=new Set(["provider_session_api","client_runtime","extractor","unknown"]),z=new Set(["browser_disconnected","worker_disconnect","job_killed","cdp_cmd_timeout","network_inactivity_timeout","session_timeout","client_timeout","navigate_domains_limit","cdp_error","browser_session_interrupted","provider_detail_pending","provider_lookup_unavailable","provider_reported_no_error","provider_session_not_found","provider_invalid_json","provider_invalid_payload","provider_lookup_timeout","provider_lookup_network_error","unknown"]),V=new Set(["browser_provider","provider_session_id","provider_lookup_status","provider_status","provider_error_code","provider_error_message","provider_reason_source","provider_duration_ms","provider_bandwidth_bytes","provider_captcha","provider_checked_at","provider_detail","provider_detail_json","provider_disconnect_observed","provider_disconnect_message"]),H=512,Q=320;function _(e,r){return typeof e=="string"&&r.has(e)?e:null}function j(e){return typeof e!="string"?null:z.has(e)||/^provider_http_(?:429|5\d\d)$/.test(e)?e:null}function B(e){return typeof e!="string"||e.length<1||e.length>H||/^(?:authorization|bearer|password|secret|token|api[_-]?key|account)/i.test(e)?null:/^[A-Za-z0-9._:-]+$/.test(e)&&!e.includes("://")?e:null}function y(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:null}function h(e){if(typeof e!="string"||e.length>40)return null;let r=Date.parse(e);return Number.isFinite(r)&&new Date(r).toISOString()===e?e:null}function w(e){if(typeof e!="string")return null;let r=e.replace(/[\u0000-\u001f\u007f]+/g," ").replace(/\s+/g," ").trim();if(!r||r.startsWith("{")||r.startsWith("["))return null;let n=r.replace(/\b(?:wss?|https?):\/\/\S+/gi,"[redacted endpoint]").replace(/\b(?:authorization|proxy-authorization)\s*:\s*(?:Bearer\s+)?\S+/gi,"[redacted credential]").replace(/\bBearer\s+\S+/gi,"[redacted credential]").replace(/\b(?:api[_-]?key|password|secret|token|account[_-]?id)\s*[=:]\s*[^\s,;]+/gi,"[redacted credential]").replace(/\b(?:account|organization)\s+(?:id\s+)?[A-Za-z0-9_-]{4,}/gi,"[redacted account]");return R(n).slice(0,Q)}function E(e){return typeof e=="boolean"?e:null}function G(e){return{browser_provider:_(e.browser_provider,N),provider_session_id:B(e.provider_session_id),provider_session_observed_at:h(e.provider_session_observed_at),provider_lookup_status:_(e.provider_lookup_status,D),provider_status:_(e.provider_status,U),provider_error_code:j(e.provider_error_code),provider_error_message:w(e.provider_error_message),provider_reason_source:_(e.provider_reason_source,M),provider_duration_ms:y(e.provider_duration_ms),provider_bandwidth_bytes:y(e.provider_bandwidth_bytes),provider_captcha:E(e.provider_captcha),provider_checked_at:h(e.provider_checked_at),provider_disconnect_observed:E(e.provider_disconnect_observed),provider_disconnect_message:w(e.provider_disconnect_message)}}function c(e,r=""){if(typeof e=="string"){let n=R(e);return f.test(r)&&(O.test(e)||x.test(e))?n=S("service_unavailable"):f.test(r)&&(n=b(n)),n}if(Array.isArray(e))return e.map(n=>c(n,r));if(e!==null&&typeof e=="object"){let n={};for(let[t,s]of Object.entries(e)){if(q.has(t))continue;let a=T[t]??t;if(F.has(t)){n[a]=null;continue}n[a]=c(s,t)}return n}return e}function te(e){return e.map(r=>{if(r===null||typeof r!="object"||Array.isArray(r))return c(r);let n=r,t=c(n);return Object.keys(n).some(a=>V.has(a))?{...t,...G(n)}:t})}function oe(e){let r=e?.diagnostics;if(!r)return e;let n=r.serpCompleteness,t=n?.queryIntegrity;return!r.debug&&!t?e:{...e,diagnostics:{...r,...r.debug?{debug:c(r.debug)}:{},...t?{serpCompleteness:{...n,queryIntegrity:{...t,outboundProviderMethod:"search"}}}:{}}}}export{v as a,K as b,W as c,Z as d,$ as e,X as f,J as g,ee as h,c as i,te as j,oe as k};
@@ -0,0 +1 @@
1
+ var o="0.93.0";export{o as a};
@@ -1,4 +1,4 @@
1
- import{f as F,h as V,i as re,j as ae,l as $}from"./chunk-QTDLZTQ7.js";import{B as ie,ba as R,e as U,t as _,w as G,x as ne,y as oe,z as M}from"./chunk-RSPA4IWH.js";import{h as L}from"./chunk-2SP57VCG.js";import{b as K}from"./chunk-6DTXIZY2.js";import{R as te,Sb as D,Xb as x,t as C}from"./chunk-WJ4XFLS4.js";import{createHash as Te,randomUUID as Ne}from"crypto";import{z as f}from"zod";async function at(e,t){!Number.isFinite(t)||t<=0||await K({op:R.CONNECTED_ACCOUNT_FEE,userId:Number(e)},()=>L({vendor:"nango_connection",units:t,unitType:"connection_month"}))}async function se(e,t){let n=[{vendor:"nango_function_run",units:t.functionRuns,unitType:"function_run"},{vendor:"nango_proxy_request",units:t.proxyRequests,unitType:"proxy_request"},{vendor:"nango_compute",units:t.computeMilliseconds/1e3,unitType:"compute_second"}];await K({op:R.CONNECTED_USAGE,userId:Number(e)},async()=>{for(let o of n)!Number.isFinite(o.units)||o.units<=0||await L(o)})}var E="connected_usage",Re="mastra_scheduler",Ie=f.object({toolName:f.string().trim().min(1).max(200).optional(),operationKind:f.enum(["read","action","sync","export","proxy","other"]).optional(),outcome:f.enum(["success","error","partial"]).optional(),requestId:f.string().trim().min(1).max(200).optional(),occurrenceId:f.string().trim().min(1).max(200).optional(),scheduleId:f.string().trim().min(1).max(200).optional(),nangoOperationId:f.string().trim().min(1).max(200).optional(),startedAt:f.string().datetime({offset:!0}).optional(),completedAt:f.string().datetime({offset:!0}).optional()}).strict(),Ae=f.object({identity:f.string().trim().min(1).max(320),idempotencyKey:f.string().trim().min(1).max(500),ratePolicyVersion:f.string().trim().min(1).max(100),connectionId:f.string().trim().min(1).max(500),providerConfigKey:f.string().trim().min(1).max(200),functionRuns:f.number().int().safe().nonnegative(),proxyRequests:f.number().int().safe().nonnegative(),computeMilliseconds:f.number().int().safe().nonnegative(),sourceSurface:f.enum(["main_mcp","mastra_scheduler","nango_reconciliation"]).default(Re),metadata:Ie.optional()}).strict(),Pe=f.object({identity:f.string().trim().min(1).max(320),ratePolicyVersion:f.string().trim().min(1).max(100)}).strict(),h=class extends Error{constructor(n,o,a,i={}){super(o);this.code=n;this.httpStatus=a;this.details=i;this.name="ConnectedUsageBillingError"}code;httpStatus;details};function z(e){return Te("sha256").update(e).digest("hex")}function xe(e){return`connected-usage:${z(e)}`}function Ue(e){return`connected-usage-debit:${z(e)}`}function Me(e){return e.trim().toLowerCase()}async function ce(e){let t=await te(Me(e));if(!t)throw new h("user_not_found","billing identity was not found",404);return t}function Oe(e){let t={toolName:e.metadata.toolName??null,operationKind:e.metadata.operationKind??null,outcome:e.metadata.outcome??null,requestId:e.metadata.requestId??null,occurrenceId:e.metadata.occurrenceId??null,scheduleId:e.metadata.scheduleId??null,nangoOperationId:e.metadata.nangoOperationId??null,startedAt:e.metadata.startedAt??null,completedAt:e.metadata.completedAt??null};return z(JSON.stringify({ratePolicyVersion:_,connectionId:e.connectionId,providerConfigKey:e.providerConfigKey,usage:e.usage,sourceSurface:e.sourceSurface,metadata:t}))}function A(e){let t=JSON.stringify(e);if(t.length>4e3)throw new h("invalid_request","connected usage metadata is too large",400);return t}function W(e){try{let t=JSON.parse(e.metadata??"");if(t.contract!=="connected_usage_receipt"||t.ratePolicyVersion!==_||typeof t.fingerprint!="string"||typeof t.connectionId!="string"||typeof t.providerConfigKey!="string"||!t.usage||!t.charge)throw new Error("invalid connected usage receipt metadata");return t}catch{throw new h("idempotency_key_conflict","the idempotency key is already bound to an incompatible billing receipt",409)}}async function H(e){let t=await C().execute({sql:"SELECT id, user_id, billing_class, source_surface, status, amount_mc, metadata FROM billing_events WHERE idempotency_key = ? LIMIT 1",args:[e]});return t.rows[0]?t.rows[0]:null}async function de(e,t){return(await C().execute({sql:`SELECT 1
1
+ import{f as F,h as V,i as re,j as ae,l as $}from"./chunk-QTDLZTQ7.js";import{B as ie,ba as R,e as U,t as _,w as G,x as ne,y as oe,z as M}from"./chunk-RZEZJAID.js";import{h as L}from"./chunk-2SP57VCG.js";import{b as K}from"./chunk-6DTXIZY2.js";import{R as te,Sb as D,Xb as x,t as C}from"./chunk-WJ4XFLS4.js";import{createHash as Te,randomUUID as Ne}from"crypto";import{z as f}from"zod";async function at(e,t){!Number.isFinite(t)||t<=0||await K({op:R.CONNECTED_ACCOUNT_FEE,userId:Number(e)},()=>L({vendor:"nango_connection",units:t,unitType:"connection_month"}))}async function se(e,t){let n=[{vendor:"nango_function_run",units:t.functionRuns,unitType:"function_run"},{vendor:"nango_proxy_request",units:t.proxyRequests,unitType:"proxy_request"},{vendor:"nango_compute",units:t.computeMilliseconds/1e3,unitType:"compute_second"}];await K({op:R.CONNECTED_USAGE,userId:Number(e)},async()=>{for(let o of n)!Number.isFinite(o.units)||o.units<=0||await L(o)})}var E="connected_usage",Re="mastra_scheduler",Ie=f.object({toolName:f.string().trim().min(1).max(200).optional(),operationKind:f.enum(["read","action","sync","export","proxy","other"]).optional(),outcome:f.enum(["success","error","partial"]).optional(),requestId:f.string().trim().min(1).max(200).optional(),occurrenceId:f.string().trim().min(1).max(200).optional(),scheduleId:f.string().trim().min(1).max(200).optional(),nangoOperationId:f.string().trim().min(1).max(200).optional(),startedAt:f.string().datetime({offset:!0}).optional(),completedAt:f.string().datetime({offset:!0}).optional()}).strict(),Ae=f.object({identity:f.string().trim().min(1).max(320),idempotencyKey:f.string().trim().min(1).max(500),ratePolicyVersion:f.string().trim().min(1).max(100),connectionId:f.string().trim().min(1).max(500),providerConfigKey:f.string().trim().min(1).max(200),functionRuns:f.number().int().safe().nonnegative(),proxyRequests:f.number().int().safe().nonnegative(),computeMilliseconds:f.number().int().safe().nonnegative(),sourceSurface:f.enum(["main_mcp","mastra_scheduler","nango_reconciliation"]).default(Re),metadata:Ie.optional()}).strict(),Pe=f.object({identity:f.string().trim().min(1).max(320),ratePolicyVersion:f.string().trim().min(1).max(100)}).strict(),h=class extends Error{constructor(n,o,a,i={}){super(o);this.code=n;this.httpStatus=a;this.details=i;this.name="ConnectedUsageBillingError"}code;httpStatus;details};function z(e){return Te("sha256").update(e).digest("hex")}function xe(e){return`connected-usage:${z(e)}`}function Ue(e){return`connected-usage-debit:${z(e)}`}function Me(e){return e.trim().toLowerCase()}async function ce(e){let t=await te(Me(e));if(!t)throw new h("user_not_found","billing identity was not found",404);return t}function Oe(e){let t={toolName:e.metadata.toolName??null,operationKind:e.metadata.operationKind??null,outcome:e.metadata.outcome??null,requestId:e.metadata.requestId??null,occurrenceId:e.metadata.occurrenceId??null,scheduleId:e.metadata.scheduleId??null,nangoOperationId:e.metadata.nangoOperationId??null,startedAt:e.metadata.startedAt??null,completedAt:e.metadata.completedAt??null};return z(JSON.stringify({ratePolicyVersion:_,connectionId:e.connectionId,providerConfigKey:e.providerConfigKey,usage:e.usage,sourceSurface:e.sourceSurface,metadata:t}))}function A(e){let t=JSON.stringify(e);if(t.length>4e3)throw new h("invalid_request","connected usage metadata is too large",400);return t}function W(e){try{let t=JSON.parse(e.metadata??"");if(t.contract!=="connected_usage_receipt"||t.ratePolicyVersion!==_||typeof t.fingerprint!="string"||typeof t.connectionId!="string"||typeof t.providerConfigKey!="string"||!t.usage||!t.charge)throw new Error("invalid connected usage receipt metadata");return t}catch{throw new h("idempotency_key_conflict","the idempotency key is already bound to an incompatible billing receipt",409)}}async function H(e){let t=await C().execute({sql:"SELECT id, user_id, billing_class, source_surface, status, amount_mc, metadata FROM billing_events WHERE idempotency_key = ? LIMIT 1",args:[e]});return t.rows[0]?t.rows[0]:null}async function de(e,t){return(await C().execute({sql:`SELECT 1
2
2
  FROM billing_events
3
3
  WHERE user_id = ?
4
4
  AND billing_class = ?
@@ -1,4 +1,4 @@
1
- import{a as Zt,s as tn}from"./chunk-TCLSPE3P.js";import{T as cn,a as de,b as Ne,c as yt,d as an,e as on,q as f,r as v,sa as G,ta as Ce,v as U,w as J}from"./chunk-LI7WHOII.js";import{a as Fe,e as en}from"./chunk-QTDLZTQ7.js";import{d as nn,g as je,i as qe,k as _t,m as mt,o as rn,r as He,t as sn,u as pt}from"./chunk-YGBTTW5D.js";import{$ as ce,A as zt,E as dt,I as D,J as Yt,S as Xt,T as Gt,U as he,V as lt,W as Qt,X as ut,Z as X,ba as Ue,u as Me,v as Jt}from"./chunk-RSPA4IWH.js";import{Ab as ot,Bb as Wt,Fb as oe,H as qt,Ib as Bt,Jb as ct,Ob as Vt,R as ke,Sb as Kt,T as Ht,t as ae,vb as T,wb as Pe,yb as st,zb as at}from"./chunk-WJ4XFLS4.js";import{createCipheriv as Di,createDecipheriv as Ti,randomBytes as xi,scryptSync as Li}from"crypto";import{setScheduleEntitlementTool as $i}from"mcpscraper-memory-tools/tools/schedule/set-schedule-entitlement";import{createHash as Si,randomUUID as hi}from"crypto";import{exportJWK as Ni,importPKCS8 as Ci,SignJWT as Ri}from"jose";function wi(e=process.env.OAUTH_ISSUER){let t=e?.trim()||"https://mcpscraper.dev",n=new URL(t);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/"&&n.pathname!=="")throw new Error("OAUTH_ISSUER must be an HTTPS origin without credentials, path, query, or fragment");return n.origin}var Oi=wi(),We=null;async function dn(){if(We)return We;let e=process.env.OAUTH_SIGNING_KEY;if(!e?.trim())throw new Error("OAUTH_SIGNING_KEY is not set");let t=e.includes("BEGIN")?e:Buffer.from(e,"base64").toString("utf8"),n=await Ci(t,"RS256",{extractable:!0}),i=await Ni(n),r={kty:i.kty,n:i.n,e:i.e},s=Si("sha256").update(JSON.stringify({e:r.e,kty:r.kty,n:r.n})).digest("base64url").slice(0,16);return r.kid=s,r.alg="RS256",r.use="sig",We={privateKey:n,publicJwk:r,kid:s},We}async function Ls(){return(await dn()).publicJwk}async function ln(e){let{privateKey:t,kid:n}=await dn();return new Ri({scope:e.scope,plan:e.plan}).setProtectedHeader({alg:"RS256",kid:n}).setIssuer(Oi).setSubject(e.identity).setAudience(e.audience).setIssuedAt().setJti(hi()).setExpirationTime(`${e.ttlSeconds}s`).sign(t)}var ki=()=>(process.env.MCP_MEMORY_BASE_URL??"https://memory.mcpscraper.dev").replace(/\/$/,""),Pi=()=>(process.env.MCP_MEMORY_RESOURCE_URL??"https://memory.mcpscraper.dev/mcp").replace(/\/$/,""),Mi=()=>process.env.MCP_MEMORY_ADMIN_KEY?.trim()??"",Ui=300;function Fi(e){let t=e.split(`
1
+ import{a as Zt,s as tn}from"./chunk-H3SJLJYM.js";import{T as cn,a as de,b as Ne,c as yt,d as an,e as on,q as f,r as v,sa as G,ta as Ce,v as U,w as J}from"./chunk-LI7WHOII.js";import{a as Fe,e as en}from"./chunk-QTDLZTQ7.js";import{d as nn,g as je,i as qe,k as _t,m as mt,o as rn,r as He,t as sn,u as pt}from"./chunk-YGBTTW5D.js";import{$ as ce,A as zt,E as dt,I as D,J as Yt,S as Xt,T as Gt,U as he,V as lt,W as Qt,X as ut,Z as X,ba as Ue,u as Me,v as Jt}from"./chunk-RZEZJAID.js";import{Ab as ot,Bb as Wt,Fb as oe,H as qt,Ib as Bt,Jb as ct,Ob as Vt,R as ke,Sb as Kt,T as Ht,t as ae,vb as T,wb as Pe,yb as st,zb as at}from"./chunk-WJ4XFLS4.js";import{createCipheriv as Di,createDecipheriv as Ti,randomBytes as xi,scryptSync as Li}from"crypto";import{setScheduleEntitlementTool as $i}from"mcpscraper-memory-tools/tools/schedule/set-schedule-entitlement";import{createHash as Si,randomUUID as hi}from"crypto";import{exportJWK as Ni,importPKCS8 as Ci,SignJWT as Ri}from"jose";function wi(e=process.env.OAUTH_ISSUER){let t=e?.trim()||"https://mcpscraper.dev",n=new URL(t);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/"&&n.pathname!=="")throw new Error("OAUTH_ISSUER must be an HTTPS origin without credentials, path, query, or fragment");return n.origin}var Oi=wi(),We=null;async function dn(){if(We)return We;let e=process.env.OAUTH_SIGNING_KEY;if(!e?.trim())throw new Error("OAUTH_SIGNING_KEY is not set");let t=e.includes("BEGIN")?e:Buffer.from(e,"base64").toString("utf8"),n=await Ci(t,"RS256",{extractable:!0}),i=await Ni(n),r={kty:i.kty,n:i.n,e:i.e},s=Si("sha256").update(JSON.stringify({e:r.e,kty:r.kty,n:r.n})).digest("base64url").slice(0,16);return r.kid=s,r.alg="RS256",r.use="sig",We={privateKey:n,publicJwk:r,kid:s},We}async function Ls(){return(await dn()).publicJwk}async function ln(e){let{privateKey:t,kid:n}=await dn();return new Ri({scope:e.scope,plan:e.plan}).setProtectedHeader({alg:"RS256",kid:n}).setIssuer(Oi).setSubject(e.identity).setAudience(e.audience).setIssuedAt().setJti(hi()).setExpirationTime(`${e.ttlSeconds}s`).sign(t)}var ki=()=>(process.env.MCP_MEMORY_BASE_URL??"https://memory.mcpscraper.dev").replace(/\/$/,""),Pi=()=>(process.env.MCP_MEMORY_RESOURCE_URL??"https://memory.mcpscraper.dev/mcp").replace(/\/$/,""),Mi=()=>process.env.MCP_MEMORY_ADMIN_KEY?.trim()??"",Ui=300;function Fi(e){let t=e.split(`
2
2
  `).find(i=>i.startsWith("data:")),n=t?t.slice(5).trim():e;return JSON.parse(n)}function gt(e){return e?(process.env.MEMORY_OPERATOR_IDENTITIES??"").split(",").map(n=>n.trim().toLowerCase()).filter(Boolean).includes(e.trim().toLowerCase()):!1}function un(){return Li(Fe(),"mcp-memory-key-v1",32)}function qs(e){let t=xi(12),n=Di("aes-256-gcm",un(),t),i=Buffer.concat([n.update(e,"utf8"),n.final()]),r=n.getAuthTag();return`${t.toString("base64")}:${r.toString("base64")}:${i.toString("base64")}`}function Hs(e){try{let[t,n,i]=e.split(":"),r=Ti("aes-256-gcm",un(),Buffer.from(t,"base64"));return r.setAuthTag(Buffer.from(n,"base64")),Buffer.concat([r.update(Buffer.from(i,"base64")),r.final()]).toString("utf8")}catch{return null}}async function _n(e,t,n){try{let i=await fetch(`${ki()}/mcp`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json, text/event-stream",authorization:`Bearer ${n}`},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:e,arguments:t}})}),r=await i.text();if(!i.ok)return{ok:!1,error:`memory ${e} failed (${i.status})`};let s=Fi(r);if(s.error)return{ok:!1,error:s.error.message??`memory ${e} failed`};if(s.result?.structuredContent)return s.result.structuredContent;let a=s.result?.content?.find(o=>o.type==="text")?.text;if(a)try{return JSON.parse(a)}catch{return{ok:!1,error:a}}return{ok:!1,error:`memory ${e} returned no result`}}catch(i){return{ok:!1,error:i?.message??"memory call failed"}}}function mn(e){return e.email}function ji(e){return mn(e)}function Ws(e){return gt(e.email)?"unlimited":e.memory_plan==="pro"||e.memory_plan==="team"?e.memory_plan:"free"}async function Bs(e){try{let{key:t}=await pn(e);if(!t)return;(await _n("listVaultsTool",{},t)).ok&&await Bt(e.id,!0)}catch{}}function qi(e){return e?!!Yt[e]?.includes_memory:!1}function F(e){return e.memory_plan==="team"?"team":qi(e.subscription_tier)||e.memory_plan==="pro"?"pro":"free"}async function pn(e,t){try{let n=gt(e.email),i=n?"unlimited":t??F(e),r=n?"memory.read memory.write memory.admin":"memory.read memory.write";return{key:await ln({identity:mn(e),scope:r,plan:i,audience:Pi(),ttlSeconds:Ui})}}catch(n){return{key:null,error:n instanceof Error?n.message:"memory service authorization unavailable"}}}async function z(e,t){let n=gt(e.email)?"unlimited":t,{key:i,error:r}=await pn(e,n);if(!i)return{ok:!1,error:r??"memory unavailable"};let s=await _n("listVaultsTool",{},i);return{ok:s.ok,error:s.error}}async function Be(e){let t=Mi();if(!t)return{ok:!1,error:"memory not configured (MCP_MEMORY_ADMIN_KEY missing)"};let n=ji(e),i=await $i.execute({apiKey:t,granteeIdentity:n,mcpScraperApiKey:e.api_key},{});return{ok:i.ok,error:i.error}}var yn=["active","trialing","past_due"];function Re(e){return yn.includes(e)}function gn(e,t){for(let n of yn){let i=e.find(r=>r.status===n&&t(r));if(i)return i}}var Hi="price_1TtYPAS8aAcsk3TGHOgrDZiQ";function Wi(e=new Date){return`${e.getUTCFullYear()}-${String(e.getUTCMonth()+1).padStart(2,"0")}`}var Bi=new Set(["connected","needs_reauth"]);function Vi(e){return Bi.has(String(e.lifecycleStatus??""))}async function Ki(e,t){let n=await ae().execute({sql:"SELECT connection_id FROM connected_account_charges WHERE user_id = ? AND period_start = ?",args:[Number(e),t]});return new Set(n.rows.map(i=>String(i.connection_id)))}async function Ji(e,t,n){await en();let i=Number(e),r=ae();return await r.batch([{sql:`
3
3
  INSERT OR IGNORE INTO connected_account_charge_transfers (
4
4
  user_id, period_start, from_connection_id, to_connection_id, provider_config_key
@@ -817,4 +817,4 @@ MCowBQYDK2VwAyEAi2HR1srL4o18O8BRa7gVJY7G7bupbN3H9AwJrHCDiOg=
817
817
  )
818
818
  ORDER BY edge.confidence DESC, edge.last_seen_at DESC
819
819
  LIMIT 1
820
- FOR SHARE OF p, ns, cs, receipt`,[t.siteId,Ce("customer_id",t.stableUserId)])).rows[0]??null}async function Ut(e,t){let n=process.env.MCP_SCRAPER_XRAY_SITE_ID?.trim();if(!n)return{status:"skipped",eventName:Le,reason:"site_not_configured"};if(!vs(n))return{status:"skipped",eventName:Le,reason:"site_id_invalid"};let i=String(e.userId).trim();if(!i||!e.invoiceId.trim()||!Number.isSafeInteger(e.amountPaidMinor)||e.amountPaidMinor<0||!/^[a-z]{3}$/i.test(e.currency)||!Number.isFinite(new Date(e.occurredAt).getTime()))throw new Error("analytics_first_party_outcome_invalid");let r=t??{db:v(),record:(a,o)=>oi({...a,transactionClient:o})},s=await r.db.connect();try{await s.query("BEGIN");let a=await Es(s,{siteId:n,stableUserId:i});if(!a)return await s.query("ROLLBACK"),{status:"skipped",eventName:Le,reason:"identity_or_consent_unavailable"};let o={schemaVersion:1,eventId:`mcp_invoice_${e.invoiceId}`.slice(0,200),sourceEventId:`stripe:invoice:${e.invoiceId}`.slice(0,300),source:"mcp_scraper",sourceAccountRef:"first_party_billing",eventKind:"transaction",eventName:Le,occurredAt:e.occurredAt,personRef:i,orderId:e.invoiceId,valueMinor:e.amountPaidMinor,currency:e.currency.toUpperCase(),consent:{analytics:"granted",adUserData:"granted",adPersonalization:a.advertising_measurement?"granted":"denied",globalPrivacyControl:!1,occurredAt:new Date(a.effective_at).toISOString(),receiptId:a.receipt_id,policyVersion:a.policy_version,purposes:{site_analytics:"granted",enhanced_matching:"granted",advertising_measurement:a.advertising_measurement?"granted":"denied"}},properties:{product:"mcp_scraper",billingKind:"base_plan_paid_invoice",revenueProvenance:"stripe_paid_invoice"}},c=await r.record({siteId:n,event:o},s);return await s.query("COMMIT"),{status:"recorded",eventName:Le,reason:"recorded",created:c.created,conversionIds:c.conversionIds}}catch(a){throw await s.query("ROLLBACK").catch(()=>{}),a}finally{s.release()}}function ci(e){let t=e;return t?.price?.id??t?.pricing?.price_details?.price??t?.plan?.id}function Ie(e){if(typeof e=="string")return e;if(e&&typeof e=="object"&&"id"in e)return String(e.id)}function bs(e){let t=e.subscription;if(t)return Ie(t);let n=e.parent;return Ie(n?.subscription_details?.subscription)}async function As(e,t){let n=await T(e);return n||!t||(n=await ke(t),n&&await Pe(n.id,e)),n}async function Is(e,t,n){let i=t.memory_subscription_id;if(!(!i||i===n))try{let r=await e.subscriptions.retrieve(i);r.status!=="canceled"&&!r.cancel_at_period_end&&await e.subscriptions.update(i,{cancel_at_period_end:!0})}catch(r){console.error("[stripe] could not wind down standalone memory subscription",i,r instanceof Error?r.message:r)}}async function Ft(e,t,n){if(!t.id||t.status!=="paid")return{status:"not_applicable",invoiceId:t.id??null};let i=t.lines.data.some(y=>{let E=ci(y);return!!E&&E in D});if(!fn(i,t.total))return{status:"not_applicable",invoiceId:t.id};let r=bs(t),a=(r?le(await e.subscriptions.retrieve(r))?.price?.id:void 0)??t.lines.data.map(ci).find(y=>!!y&&y in D),o=a?D[a]:void 0;if(!o)return{status:"not_applicable",invoiceId:t.id};let c=Ie(t.customer);if(!c)throw new Error("Paid subscription invoice has no Stripe customer");let d=await As(c,t.customer_email);if(!d)throw new Error("Paid subscription invoice does not map to an MCP Scraper account");let _=await Wt({invoiceId:t.id,userId:d.id,subscriptionId:r??d.subscription_id,tier:o.tier,concurrency:o.concurrency,creditsMc:o.credits_mc,description:`${o.label} subscription credits`,neverExpires:!!o.credits_never_expire,includedMemoryPlan:o.includes_memory?"pro":null});o.includes_memory&&(await Is(e,d,r??d.subscription_id),await z(d,F({...d,memory_plan:"pro",subscription_tier:o.tier})));let u=await Be(d);u.ok||console.warn("[stripe] scheduled-action credential sync failed:",u.error??"unknown error");try{await Ut({userId:d.id,invoiceId:t.id,amountPaidMinor:t.amount_paid,currency:t.currency,occurredAt:new Date(((t.status_transitions?.paid_at??n)||Math.floor(Date.now()/1e3))*1e3).toISOString()})}catch(y){console.error("[stripe] X-Ray paid outcome failed",{invoiceId:t.id,error:y instanceof Error?y.message:String(y)})}return{status:_.granted?"fulfilled":"already_fulfilled",invoiceId:t.id,userId:d.id,tier:o.tier}}async function di(e,t,n){let i=await e.checkout.sessions.retrieve(t,{expand:["invoice"]});if(i.mode!=="subscription")throw new Error("Checkout session is not a subscription purchase");if(i.payment_status!=="paid"&&i.payment_status!=="no_payment_required")return{status:"not_applicable",invoiceId:Ie(i.invoice)??null};let r=Ie(i.customer);if(n&&r!==n)throw new Error("Checkout session does not belong to this billing account");let s=typeof i.invoice=="object"&&i.invoice&&!("deleted"in i.invoice)?i.invoice:await e.invoices.retrieve(Ie(i.invoice)??"");if(!s?.id)throw new Error("Paid subscription checkout has no invoice");return Ft(e,s,i.created)}var li="scale_credit_pack";function rt(e){if(typeof e=="string")return e;if(e&&typeof e=="object"&&"id"in e)return String(e.id)}function ui(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>ut)throw new Error(`quantity must be a whole number from 1 to ${ut}`);return t}function Tc(e){return e.subscription_tier==="scale"}function xc(e,t){let n=ui(t);return{purchase_kind:li,account_user_id:String(e),eligible_tier:"scale",increment_quantity:String(n),increment_usd:String(he),credits_per_increment:String(lt)}}async function _i(e,t,n){let i=await e.checkout.sessions.retrieve(t);if(i.mode!=="payment"||i.metadata?.purchase_kind!==li)return{status:"not_applicable",paymentIntentId:rt(i.payment_intent)??null};if(i.payment_status!=="paid")return{status:"not_applicable",paymentIntentId:rt(i.payment_intent)??null};let r=rt(i.customer);if(!r)throw new Error("Paid Scale credit-pack checkout has no Stripe customer");if(n&&r!==n)throw new Error("Checkout session does not belong to this billing account");let s=ui(i.metadata.increment_quantity),a=s*he*100;if(i.currency!=="usd"||i.amount_subtotal!==a)throw new Error("Scale credit-pack checkout amount does not match the product contract");let o=await e.checkout.sessions.listLineItems(i.id,{limit:2}),c=o.data[0];if(o.data.length!==1||c?.quantity!==s||c.price?.currency!=="usd"||c.price?.unit_amount!==he*100)throw new Error("Scale credit-pack checkout line item does not match the product contract");let d=await T(r);if(!d)throw new Error("Paid Scale credit-pack checkout does not map to an MCP Scraper account");if(i.metadata.account_user_id!==String(d.id)||i.metadata.eligible_tier!=="scale")throw new Error("Scale credit-pack checkout account metadata does not match the billing account");let _=rt(i.payment_intent);if(!_)throw new Error("Paid Scale credit-pack checkout has no payment intent");let u=s*lt;return{status:(await Vt(d.id,s*Qt,Ue.TOPUP,`$${s*he} Scale credit pack (${u.toLocaleString("en-US")} credits)`,`stripe-payment-intent:${_}`,{neverExpires:!1})).duplicate?"already_fulfilled":"fulfilled",paymentIntentId:_,userId:d.id,quantity:s,credits:u}}import Ss from"stripe";import{Hono as hs}from"hono";import{waitUntil as Ns}from"@vercel/functions";var x=new Ss(process.env.STRIPE_SECRET_KEY,{apiVersion:"2026-02-25.clover"});async function Cs(e,t){if(!(!e||e===t))try{let n=await x.subscriptions.retrieve(e),i=n.items.data[0]?.price?.id,r=n.status!=="canceled"&&!n.cancel_at_period_end;i&&i in ce&&r&&await x.subscriptions.update(e,{cancel_at_period_end:!0})}catch(n){console.error("[stripe] could not wind down standalone memory subscription",e,n instanceof Error?n.message:n)}}var Rs=new hs;Rs.post("/webhooks",async e=>{let t=e.req.header("stripe-signature"),n=await e.req.text(),i;try{i=x.webhooks.constructEvent(n,t,process.env.STRIPE_WEBHOOK_SECRET)}catch{return e.json({error:"Invalid signature"},400)}try{let r=await qt(i.id,i.type,i.created);return r==="queued"&&ws(),e.json({received:!0,disposition:r})}catch(r){let s=r instanceof Error?r.message:String(r);return console.error("[stripe] webhook enqueue failed",i.id,s),e.json({error:"Webhook enqueue failed"},500)}});function ws(){let e=import("./stripe-event-worker-KW3DR6GB.js").then(({drainStripeEventQueue:t})=>t({limit:10,leaseSeconds:300})).catch(t=>{console.error("[stripe] immediate queue drain failed; the scheduled drain will retry",t instanceof Error?t.message:String(t))});Ns(e)}async function Kc(e){if(e.type==="checkout.session.completed"||e.type==="checkout.session.async_payment_succeeded"){let t=e.data.object;t.mode==="payment"?await _i(x,t.id):await di(x,t.id);return}if(e.type==="invoice.created"){let t=e.data.object;mi(t)&&t.status==="draft"&&await x.invoices.update(t.id,{description:Xt,footer:Gt,custom_fields:[{name:"Pack benefit",value:"2 browsers per $5 monthly pack"},{name:"Billing cadence",value:"Monthly"}]});return}if(e.type==="invoice.paid"||e.type==="invoice.payment_succeeded"){let t=e.data.object;if(mi(t)){let i=t.customer_email?void 0:await yi(t.customer,void 0),r=t.customer_email??i?.email;if(!r)throw new Error("Paid concurrency invoice has no customer receipt email");await Os(t.id,r);return}if(t.lines.data.map(gi).find(i=>i&&i in ce))return;await Ft(x,t,e.created)}if(e.type==="customer.subscription.created"||e.type==="customer.subscription.updated"){let t=e.data.object,n=pi(t);if(n){let s=await T(t.customer);if(!s)return;let a=Re(t.status);await st(s.id,a?Ds(n):0),await at(s.id,a?t.id:null);return}let i=le(t)?.price?.id??t.items.data[0]?.price?.id;if(i&&i in ce){let s=ce[i],a=await yi(t.customer,t.customer_email);if(a){let o=Re(t.status),c=o?s.plan:"free";await oe(a.id,c,o?t.id:null),await z(a,F({...a,memory_plan:c}))}return}let r=await T(t.customer);if(!r)return;if(i&&i in D){let s=D[i],a=Re(t.status),o=a?s.tier:null;if(await ot(r.id,o,a?s.concurrency:0,a?t.id:null),s.includes_memory){let c=a?"pro":"free";a&&await Cs(r.memory_subscription_id,t.id),await oe(r.id,c,null),await z(r,F({...r,memory_plan:c}))}else r.memory_subscription_id===t.id&&(await oe(r.id,"free",null),await z(r,F({...r,memory_plan:"free"})));if(a){let c=await Be(r);c.ok||console.warn("[stripe] scheduled-action credential sync failed:",c.error??"unknown error")}}}if(e.type==="customer.subscription.deleted"){let t=e.data.object;if(pi(t)){let i=await T(t.customer);i&&(await st(i.id,0),await at(i.id,null));return}let n=le(t)?.price?.id??t.items.data[0]?.price?.id;if(n&&n in D){let i=D[n],r=await T(t.customer);r&&(await ot(r.id,null,0,null),(i.includes_memory||r.memory_subscription_id===t.id)&&(await oe(r.id,"free",null),await z(r,F({...r,memory_plan:"free"}))));return}if(n&&n in ce||await ct(t.id)){let i=await ct(t.id)??await T(t.customer);i&&(await oe(i.id,"free",null),await z(i,F({...i,memory_plan:"free"})));return}}}function mi(e){return e.lines.data.some(t=>gi(t)===dt)}async function Os(e,t){let i=(await x.invoicePayments.list({invoice:e,status:"paid",limit:10})).data.find(a=>a.status==="paid");if(!i)throw new Error("Paid concurrency invoice has no paid Stripe payment");let r;if(i.payment.type==="charge")r=i.payment.charge;else if(i.payment.type==="payment_intent"&&i.payment.payment_intent){let a=typeof i.payment.payment_intent=="string"?i.payment.payment_intent:i.payment.payment_intent.id;r=(await x.paymentIntents.retrieve(a,{expand:["latest_charge"]})).latest_charge}if(!r)throw new Error("Paid concurrency invoice has no receipt-capable charge");let s=typeof r=="string"?await x.charges.retrieve(r):r;s.receipt_email!==t&&await x.charges.update(s.id,{receipt_email:t})}function pi(e){return e.items.data.find(t=>t.price?.id===dt)}function Ds(e){let t=e.quantity??1;if(!Number.isSafeInteger(t)||t<1)throw new Error("Stripe concurrency pack quantity must be a positive safe integer");return t}function gi(e){let t=e;return t?.price?.id??t?.pricing?.price_details?.price??t?.plan?.id}async function yi(e,t){let n=await T(e);if(n)return n;if(t)return n=await ke(t),n&&await Pe(n.id,e),n}export{Oi as a,Ls as b,ln as c,gt as d,qs as e,Hs as f,_n as g,ji as h,Ws as i,Bs as j,qi as k,pn as l,Be as m,Et as n,j as o,le as p,Qs as q,Zs as r,ea as s,ze as t,Ye as u,Sn as v,dr as w,ur as x,At as y,ua as z,_a as A,ma as B,pa as C,Aa as D,wn as E,Ca as F,Ra as G,wa as H,Oa as I,Da as J,Ta as K,xa as L,La as M,$a as N,ka as O,Pa as P,Ma as Q,Ua as R,Dn as S,Fa as T,gr as U,ja as V,te as W,Ze as X,$ as Y,qa as Z,Er as _,Va as $,Ka as aa,Ja as ba,Un as ca,Fn as da,za as ea,so as fa,Bn as ga,Vn as ha,lo as ia,uo as ja,Kn as ka,po as la,Jn as ma,zn as na,Yn as oa,Xn as pa,Gn as qa,Qn as ra,it as sa,Co as ta,Ro as ua,wo as va,Oo as wa,Do as xa,To as ya,ei as za,ti as Aa,$t as Ba,ni as Ca,ii as Da,ss as Ea,Qo as Fa,Zo as Ga,ec as Ha,tc as Ia,nc as Ja,ic as Ka,rc as La,sc as Ma,ac as Na,oc as Oa,cc as Pa,dc as Qa,lc as Ra,uc as Sa,_c as Ta,mc as Ua,ri as Va,pc as Wa,yc as Xa,oi as Ya,gc as Za,fc as _a,Ft as $a,di as ab,ui as bb,Tc as cb,xc as db,_i as eb,x as fb,Rs as gb,Kc as hb};
820
+ FOR SHARE OF p, ns, cs, receipt`,[t.siteId,Ce("customer_id",t.stableUserId)])).rows[0]??null}async function Ut(e,t){let n=process.env.MCP_SCRAPER_XRAY_SITE_ID?.trim();if(!n)return{status:"skipped",eventName:Le,reason:"site_not_configured"};if(!vs(n))return{status:"skipped",eventName:Le,reason:"site_id_invalid"};let i=String(e.userId).trim();if(!i||!e.invoiceId.trim()||!Number.isSafeInteger(e.amountPaidMinor)||e.amountPaidMinor<0||!/^[a-z]{3}$/i.test(e.currency)||!Number.isFinite(new Date(e.occurredAt).getTime()))throw new Error("analytics_first_party_outcome_invalid");let r=t??{db:v(),record:(a,o)=>oi({...a,transactionClient:o})},s=await r.db.connect();try{await s.query("BEGIN");let a=await Es(s,{siteId:n,stableUserId:i});if(!a)return await s.query("ROLLBACK"),{status:"skipped",eventName:Le,reason:"identity_or_consent_unavailable"};let o={schemaVersion:1,eventId:`mcp_invoice_${e.invoiceId}`.slice(0,200),sourceEventId:`stripe:invoice:${e.invoiceId}`.slice(0,300),source:"mcp_scraper",sourceAccountRef:"first_party_billing",eventKind:"transaction",eventName:Le,occurredAt:e.occurredAt,personRef:i,orderId:e.invoiceId,valueMinor:e.amountPaidMinor,currency:e.currency.toUpperCase(),consent:{analytics:"granted",adUserData:"granted",adPersonalization:a.advertising_measurement?"granted":"denied",globalPrivacyControl:!1,occurredAt:new Date(a.effective_at).toISOString(),receiptId:a.receipt_id,policyVersion:a.policy_version,purposes:{site_analytics:"granted",enhanced_matching:"granted",advertising_measurement:a.advertising_measurement?"granted":"denied"}},properties:{product:"mcp_scraper",billingKind:"base_plan_paid_invoice",revenueProvenance:"stripe_paid_invoice"}},c=await r.record({siteId:n,event:o},s);return await s.query("COMMIT"),{status:"recorded",eventName:Le,reason:"recorded",created:c.created,conversionIds:c.conversionIds}}catch(a){throw await s.query("ROLLBACK").catch(()=>{}),a}finally{s.release()}}function ci(e){let t=e;return t?.price?.id??t?.pricing?.price_details?.price??t?.plan?.id}function Ie(e){if(typeof e=="string")return e;if(e&&typeof e=="object"&&"id"in e)return String(e.id)}function bs(e){let t=e.subscription;if(t)return Ie(t);let n=e.parent;return Ie(n?.subscription_details?.subscription)}async function As(e,t){let n=await T(e);return n||!t||(n=await ke(t),n&&await Pe(n.id,e)),n}async function Is(e,t,n){let i=t.memory_subscription_id;if(!(!i||i===n))try{let r=await e.subscriptions.retrieve(i);r.status!=="canceled"&&!r.cancel_at_period_end&&await e.subscriptions.update(i,{cancel_at_period_end:!0})}catch(r){console.error("[stripe] could not wind down standalone memory subscription",i,r instanceof Error?r.message:r)}}async function Ft(e,t,n){if(!t.id||t.status!=="paid")return{status:"not_applicable",invoiceId:t.id??null};let i=t.lines.data.some(y=>{let E=ci(y);return!!E&&E in D});if(!fn(i,t.total))return{status:"not_applicable",invoiceId:t.id};let r=bs(t),a=(r?le(await e.subscriptions.retrieve(r))?.price?.id:void 0)??t.lines.data.map(ci).find(y=>!!y&&y in D),o=a?D[a]:void 0;if(!o)return{status:"not_applicable",invoiceId:t.id};let c=Ie(t.customer);if(!c)throw new Error("Paid subscription invoice has no Stripe customer");let d=await As(c,t.customer_email);if(!d)throw new Error("Paid subscription invoice does not map to an MCP Scraper account");let _=await Wt({invoiceId:t.id,userId:d.id,subscriptionId:r??d.subscription_id,tier:o.tier,concurrency:o.concurrency,creditsMc:o.credits_mc,description:`${o.label} subscription credits`,neverExpires:!!o.credits_never_expire,includedMemoryPlan:o.includes_memory?"pro":null});o.includes_memory&&(await Is(e,d,r??d.subscription_id),await z(d,F({...d,memory_plan:"pro",subscription_tier:o.tier})));let u=await Be(d);u.ok||console.warn("[stripe] scheduled-action credential sync failed:",u.error??"unknown error");try{await Ut({userId:d.id,invoiceId:t.id,amountPaidMinor:t.amount_paid,currency:t.currency,occurredAt:new Date(((t.status_transitions?.paid_at??n)||Math.floor(Date.now()/1e3))*1e3).toISOString()})}catch(y){console.error("[stripe] X-Ray paid outcome failed",{invoiceId:t.id,error:y instanceof Error?y.message:String(y)})}return{status:_.granted?"fulfilled":"already_fulfilled",invoiceId:t.id,userId:d.id,tier:o.tier}}async function di(e,t,n){let i=await e.checkout.sessions.retrieve(t,{expand:["invoice"]});if(i.mode!=="subscription")throw new Error("Checkout session is not a subscription purchase");if(i.payment_status!=="paid"&&i.payment_status!=="no_payment_required")return{status:"not_applicable",invoiceId:Ie(i.invoice)??null};let r=Ie(i.customer);if(n&&r!==n)throw new Error("Checkout session does not belong to this billing account");let s=typeof i.invoice=="object"&&i.invoice&&!("deleted"in i.invoice)?i.invoice:await e.invoices.retrieve(Ie(i.invoice)??"");if(!s?.id)throw new Error("Paid subscription checkout has no invoice");return Ft(e,s,i.created)}var li="scale_credit_pack";function rt(e){if(typeof e=="string")return e;if(e&&typeof e=="object"&&"id"in e)return String(e.id)}function ui(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>ut)throw new Error(`quantity must be a whole number from 1 to ${ut}`);return t}function Tc(e){return e.subscription_tier==="scale"}function xc(e,t){let n=ui(t);return{purchase_kind:li,account_user_id:String(e),eligible_tier:"scale",increment_quantity:String(n),increment_usd:String(he),credits_per_increment:String(lt)}}async function _i(e,t,n){let i=await e.checkout.sessions.retrieve(t);if(i.mode!=="payment"||i.metadata?.purchase_kind!==li)return{status:"not_applicable",paymentIntentId:rt(i.payment_intent)??null};if(i.payment_status!=="paid")return{status:"not_applicable",paymentIntentId:rt(i.payment_intent)??null};let r=rt(i.customer);if(!r)throw new Error("Paid Scale credit-pack checkout has no Stripe customer");if(n&&r!==n)throw new Error("Checkout session does not belong to this billing account");let s=ui(i.metadata.increment_quantity),a=s*he*100;if(i.currency!=="usd"||i.amount_subtotal!==a)throw new Error("Scale credit-pack checkout amount does not match the product contract");let o=await e.checkout.sessions.listLineItems(i.id,{limit:2}),c=o.data[0];if(o.data.length!==1||c?.quantity!==s||c.price?.currency!=="usd"||c.price?.unit_amount!==he*100)throw new Error("Scale credit-pack checkout line item does not match the product contract");let d=await T(r);if(!d)throw new Error("Paid Scale credit-pack checkout does not map to an MCP Scraper account");if(i.metadata.account_user_id!==String(d.id)||i.metadata.eligible_tier!=="scale")throw new Error("Scale credit-pack checkout account metadata does not match the billing account");let _=rt(i.payment_intent);if(!_)throw new Error("Paid Scale credit-pack checkout has no payment intent");let u=s*lt;return{status:(await Vt(d.id,s*Qt,Ue.TOPUP,`$${s*he} Scale credit pack (${u.toLocaleString("en-US")} credits)`,`stripe-payment-intent:${_}`,{neverExpires:!1})).duplicate?"already_fulfilled":"fulfilled",paymentIntentId:_,userId:d.id,quantity:s,credits:u}}import Ss from"stripe";import{Hono as hs}from"hono";import{waitUntil as Ns}from"@vercel/functions";var x=new Ss(process.env.STRIPE_SECRET_KEY,{apiVersion:"2026-02-25.clover"});async function Cs(e,t){if(!(!e||e===t))try{let n=await x.subscriptions.retrieve(e),i=n.items.data[0]?.price?.id,r=n.status!=="canceled"&&!n.cancel_at_period_end;i&&i in ce&&r&&await x.subscriptions.update(e,{cancel_at_period_end:!0})}catch(n){console.error("[stripe] could not wind down standalone memory subscription",e,n instanceof Error?n.message:n)}}var Rs=new hs;Rs.post("/webhooks",async e=>{let t=e.req.header("stripe-signature"),n=await e.req.text(),i;try{i=x.webhooks.constructEvent(n,t,process.env.STRIPE_WEBHOOK_SECRET)}catch{return e.json({error:"Invalid signature"},400)}try{let r=await qt(i.id,i.type,i.created);return r==="queued"&&ws(),e.json({received:!0,disposition:r})}catch(r){let s=r instanceof Error?r.message:String(r);return console.error("[stripe] webhook enqueue failed",i.id,s),e.json({error:"Webhook enqueue failed"},500)}});function ws(){let e=import("./stripe-event-worker-PUYXT5DS.js").then(({drainStripeEventQueue:t})=>t({limit:10,leaseSeconds:300})).catch(t=>{console.error("[stripe] immediate queue drain failed; the scheduled drain will retry",t instanceof Error?t.message:String(t))});Ns(e)}async function Kc(e){if(e.type==="checkout.session.completed"||e.type==="checkout.session.async_payment_succeeded"){let t=e.data.object;t.mode==="payment"?await _i(x,t.id):await di(x,t.id);return}if(e.type==="invoice.created"){let t=e.data.object;mi(t)&&t.status==="draft"&&await x.invoices.update(t.id,{description:Xt,footer:Gt,custom_fields:[{name:"Pack benefit",value:"2 browsers per $5 monthly pack"},{name:"Billing cadence",value:"Monthly"}]});return}if(e.type==="invoice.paid"||e.type==="invoice.payment_succeeded"){let t=e.data.object;if(mi(t)){let i=t.customer_email?void 0:await yi(t.customer,void 0),r=t.customer_email??i?.email;if(!r)throw new Error("Paid concurrency invoice has no customer receipt email");await Os(t.id,r);return}if(t.lines.data.map(gi).find(i=>i&&i in ce))return;await Ft(x,t,e.created)}if(e.type==="customer.subscription.created"||e.type==="customer.subscription.updated"){let t=e.data.object,n=pi(t);if(n){let s=await T(t.customer);if(!s)return;let a=Re(t.status);await st(s.id,a?Ds(n):0),await at(s.id,a?t.id:null);return}let i=le(t)?.price?.id??t.items.data[0]?.price?.id;if(i&&i in ce){let s=ce[i],a=await yi(t.customer,t.customer_email);if(a){let o=Re(t.status),c=o?s.plan:"free";await oe(a.id,c,o?t.id:null),await z(a,F({...a,memory_plan:c}))}return}let r=await T(t.customer);if(!r)return;if(i&&i in D){let s=D[i],a=Re(t.status),o=a?s.tier:null;if(await ot(r.id,o,a?s.concurrency:0,a?t.id:null),s.includes_memory){let c=a?"pro":"free";a&&await Cs(r.memory_subscription_id,t.id),await oe(r.id,c,null),await z(r,F({...r,memory_plan:c}))}else r.memory_subscription_id===t.id&&(await oe(r.id,"free",null),await z(r,F({...r,memory_plan:"free"})));if(a){let c=await Be(r);c.ok||console.warn("[stripe] scheduled-action credential sync failed:",c.error??"unknown error")}}}if(e.type==="customer.subscription.deleted"){let t=e.data.object;if(pi(t)){let i=await T(t.customer);i&&(await st(i.id,0),await at(i.id,null));return}let n=le(t)?.price?.id??t.items.data[0]?.price?.id;if(n&&n in D){let i=D[n],r=await T(t.customer);r&&(await ot(r.id,null,0,null),(i.includes_memory||r.memory_subscription_id===t.id)&&(await oe(r.id,"free",null),await z(r,F({...r,memory_plan:"free"}))));return}if(n&&n in ce||await ct(t.id)){let i=await ct(t.id)??await T(t.customer);i&&(await oe(i.id,"free",null),await z(i,F({...i,memory_plan:"free"})));return}}}function mi(e){return e.lines.data.some(t=>gi(t)===dt)}async function Os(e,t){let i=(await x.invoicePayments.list({invoice:e,status:"paid",limit:10})).data.find(a=>a.status==="paid");if(!i)throw new Error("Paid concurrency invoice has no paid Stripe payment");let r;if(i.payment.type==="charge")r=i.payment.charge;else if(i.payment.type==="payment_intent"&&i.payment.payment_intent){let a=typeof i.payment.payment_intent=="string"?i.payment.payment_intent:i.payment.payment_intent.id;r=(await x.paymentIntents.retrieve(a,{expand:["latest_charge"]})).latest_charge}if(!r)throw new Error("Paid concurrency invoice has no receipt-capable charge");let s=typeof r=="string"?await x.charges.retrieve(r):r;s.receipt_email!==t&&await x.charges.update(s.id,{receipt_email:t})}function pi(e){return e.items.data.find(t=>t.price?.id===dt)}function Ds(e){let t=e.quantity??1;if(!Number.isSafeInteger(t)||t<1)throw new Error("Stripe concurrency pack quantity must be a positive safe integer");return t}function gi(e){let t=e;return t?.price?.id??t?.pricing?.price_details?.price??t?.plan?.id}async function yi(e,t){let n=await T(e);if(n)return n;if(t)return n=await ke(t),n&&await Pe(n.id,e),n}export{Oi as a,Ls as b,ln as c,gt as d,qs as e,Hs as f,_n as g,ji as h,Ws as i,Bs as j,qi as k,pn as l,Be as m,Et as n,j as o,le as p,Qs as q,Zs as r,ea as s,ze as t,Ye as u,Sn as v,dr as w,ur as x,At as y,ua as z,_a as A,ma as B,pa as C,Aa as D,wn as E,Ca as F,Ra as G,wa as H,Oa as I,Da as J,Ta as K,xa as L,La as M,$a as N,ka as O,Pa as P,Ma as Q,Ua as R,Dn as S,Fa as T,gr as U,ja as V,te as W,Ze as X,$ as Y,qa as Z,Er as _,Va as $,Ka as aa,Ja as ba,Un as ca,Fn as da,za as ea,so as fa,Bn as ga,Vn as ha,lo as ia,uo as ja,Kn as ka,po as la,Jn as ma,zn as na,Yn as oa,Xn as pa,Gn as qa,Qn as ra,it as sa,Co as ta,Ro as ua,wo as va,Oo as wa,Do as xa,To as ya,ei as za,ti as Aa,$t as Ba,ni as Ca,ii as Da,ss as Ea,Qo as Fa,Zo as Ga,ec as Ha,tc as Ia,nc as Ja,ic as Ka,rc as La,sc as Ma,ac as Na,oc as Oa,cc as Pa,dc as Qa,lc as Ra,uc as Sa,_c as Ta,mc as Ua,ri as Va,pc as Wa,yc as Xa,oi as Ya,gc as Za,fc as _a,Ft as $a,di as ab,ui as bb,Tc as cb,xc as db,_i as eb,x as fb,Rs as gb,Kc as hb};
@@ -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 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(`
1
+ function Ue(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var ve=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};var x=class extends Error{},I=class r extends x{constructor(e,t,n,o){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=o,this.error=t}static makeMessage(e,t,n){let o=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,t,n,o){if(!e||!o)return new K({message:n,cause:ve(t)});let s=t;return e===400?new fe(e,s,n,o):e===401?new de(e,s,n,o):e===403?new pe(e,s,n,o):e===404?new he(e,s,n,o):e===409?new me(e,s,n,o):e===422?new ye(e,s,n,o):e===429?new ge(e,s,n,o):e>=500?new we(e,s,n,o):new r(e,s,n,o)}},T=class extends I{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},K=class extends I{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},D=class extends K{constructor({message:e}={}){super({message:e??"Request timed out."})}},fe=class extends I{},de=class extends I{},pe=class extends I{},he=class extends I{},me=class extends I{},ye=class extends I{},ge=class extends I{},we=class extends I{};function S(r,e,t,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!o:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(r,t):o?o.value=t:e.set(r,t),t}function _(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}var ct=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return ct=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};var Er=/^[a-z][a-z0-9+.-]*:/i,vt=r=>Er.test(r),$=r=>($=Array.isArray,$(r)),lt=$;function ut(r){return typeof r!="object"?{}:r??{}}function ft(r){if(!r)return!0;for(let e in r)return!1;return!0}function Dt(r,e){return Object.prototype.hasOwnProperty.call(r,e)}var Nt=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new x(`${r} must be an integer`);if(e<0)throw new x(`${r} must be a positive integer`);return e},Sr=r=>{if(typeof r=="number")return Math.round(r);if(typeof r=="string")return parseInt(r,10);throw new x(`Could not coerce ${r} (type: ${typeof r}) into a number`)};var Ir=r=>typeof r=="boolean"?r:typeof r=="string"?r==="true":!!r,Ht=r=>{if(r!=null)return Sr(r)};var dt=r=>{if(r!=null)return Ir(r)},Bt=r=>{try{return JSON.parse(r)}catch{return}};var Mt=r=>new Promise(e=>setTimeout(e,r));var W="0.93.0";function $r(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var Lr=()=>{let r=$r();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":Kt(Deno.build.os),"X-Stainless-Arch":qt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":Kt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":qt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Tr();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Tr(){if(typeof navigator>"u"||!navigator)return null;let r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${s}.${a}`}}}return null}var qt=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Kt=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),Wt,Xt=()=>Wt??(Wt=Lr());function zt(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new \u004b\u0065\u0072\u006e\u0065\u006c({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function pt(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function ze(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return pt({start(){},async pull(t){let{done:n,value:o}=await e.next();n?t.close():t.enqueue(o)},async cancel(){await e.return?.()}})}function ht(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Vt(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}var Jt=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var mt="RFC3986",yt=r=>String(r),gt={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:yt},Gt="RFC1738";var Ve=(r,e)=>(Ve=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ve(r,e)),v=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var wt=1024,Qt=(r,e,t,n,o)=>{if(r.length===0)return r;let s=r;if(typeof r=="symbol"?s=Symbol.prototype.toString.call(r):typeof r!="string"&&(s=String(r)),t==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let a="";for(let c=0;c<s.length;c+=wt){let f=s.length>=wt?s.slice(c,c+wt):s,d=[];for(let m=0;m<f.length;++m){let l=f.charCodeAt(m);if(l===45||l===46||l===95||l===126||l>=48&&l<=57||l>=65&&l<=90||l>=97&&l<=122||o===Gt&&(l===40||l===41)){d[d.length]=f.charAt(m);continue}if(l<128){d[d.length]=v[l];continue}if(l<2048){d[d.length]=v[192|l>>6]+v[128|l&63];continue}if(l<55296||l>=57344){d[d.length]=v[224|l>>12]+v[128|l>>6&63]+v[128|l&63];continue}m+=1,l=65536+((l&1023)<<10|f.charCodeAt(m)&1023),d[d.length]=v[240|l>>18]+v[128|l>>12&63]+v[128|l>>6&63]+v[128|l&63]}a+=d.join("")}return a};function Yt(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function bt(r,e){if($(r)){let t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}var er={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},tr=function(r,e){Array.prototype.push.apply(r,$(e)?e:[e])},Zt,R={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Qt,encodeValuesOnly:!1,format:mt,formatter:yt,indices:!1,serializeDate(r){return(Zt??(Zt=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function Cr(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var xt={};function rr(r,e,t,n,o,s,a,c,f,d,m,l,g,h,A,E,U,k){let b=r,J=k,G=0,it=!1;for(;(J=J.get(xt))!==void 0&&!it;){let L=J.get(r);if(G+=1,typeof L<"u"){if(L===G)throw new RangeError("Cyclic object value");it=!0}typeof J.get(xt)>"u"&&(G=0)}if(typeof d=="function"?b=d(e,b):b instanceof Date?b=g?.(b):t==="comma"&&$(b)&&(b=bt(b,function(L){return L instanceof Date?g?.(L):L})),b===null){if(s)return f&&!E?f(e,R.encoder,U,"key",h):e;b=""}if(Cr(b)||Yt(b)){if(f){let L=E?e:f(e,R.encoder,U,"key",h);return[A?.(L)+"="+A?.(f(b,R.encoder,U,"value",h))]}return[A?.(e)+"="+A?.(String(b))]}let q=[];if(typeof b>"u")return q;let Fe;if(t==="comma"&&$(b))E&&f&&(b=bt(b,f)),Fe=[{value:b.length>0?b.join(",")||null:void 0}];else if($(d))Fe=d;else{let L=Object.keys(b);Fe=m?L.sort(m):L}let kt=c?String(e).replace(/\./g,"%2E"):String(e),Xe=n&&$(b)&&b.length===1?kt+"[]":kt;if(o&&$(b)&&b.length===0)return Xe+"[]";for(let L=0;L<Fe.length;++L){let ue=Fe[L],Ft=typeof ue=="object"&&typeof ue.value<"u"?ue.value:b[ue];if(a&&Ft===null)continue;let at=l&&c?ue.replace(/\./g,"%2E"):ue,Rr=$(b)?typeof t=="function"?t(Xe,at):Xe:Xe+(l?"."+at:"["+at+"]");k.set(r,G);let Ut=new WeakMap;Ut.set(xt,k),tr(q,rr(Ft,Rr,t,n,o,s,a,c,t==="comma"&&E&&$(b)?null:f,d,m,l,g,h,A,E,U,Ut))}return q}function kr(r=R){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||R.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=mt;if(typeof r.format<"u"){if(!Ve(gt,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=gt[t],o=R.filter;(typeof r.filter=="function"||$(r.filter))&&(o=r.filter);let s;if(r.arrayFormat&&r.arrayFormat in er?s=r.arrayFormat:"indices"in r?s=r.indices?"indices":"repeat":s=R.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:R.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:R.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:R.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:R.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?R.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:R.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:R.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:R.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:R.encodeValuesOnly,filter:o,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:R.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:R.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:R.strictNullHandling}}function nr(r,e={}){let t=r,n=kr(e),o,s;typeof n.filter=="function"?(s=n.filter,t=s("",t)):$(n.filter)&&(s=n.filter,o=s);let a=[];if(typeof t!="object"||t===null)return"";let c=er[n.arrayFormat],f=c==="comma"&&n.commaRoundTrip;o||(o=Object.keys(t)),n.sort&&o.sort(n.sort);let d=new WeakMap;for(let g=0;g<o.length;++g){let h=o[g];n.skipNulls&&t[h]===null||tr(a,rr(t[h],h,c,f,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,d))}let m=a.join(n.delimiter),l=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?l+="utf8=%26%2310003%3B&":l+="utf8=%E2%9C%93&"),m.length>0?l+m:""}function or(r){return nr(r,{arrayFormat:"comma"})}function ar(r){let e=0;for(let o of r)e+=o.length;let t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var sr;function De(r){let e;return(sr??(e=new globalThis.TextEncoder,sr=e.encode.bind(e)))(r)}var ir;function _t(r){let e;return(ir??(e=new globalThis.TextDecoder,ir=e.decode.bind(e)))(r)}var j,C,Q=class{constructor(){j.set(this,void 0),C.set(this,void 0),S(this,j,new Uint8Array,"f"),S(this,C,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?De(e):e;S(this,j,ar([_(this,j,"f"),t]),"f");let n=[],o;for(;(o=Ur(_(this,j,"f"),_(this,C,"f")))!=null;){if(o.carriage&&_(this,C,"f")==null){S(this,C,o.index,"f");continue}if(_(this,C,"f")!=null&&(o.index!==_(this,C,"f")+1||o.carriage)){n.push(_t(_(this,j,"f").subarray(0,_(this,C,"f")-1))),S(this,j,_(this,j,"f").subarray(_(this,C,"f")),"f"),S(this,C,null,"f");continue}let s=_(this,C,"f")!==null?o.preceding-1:o.preceding,a=_t(_(this,j,"f").subarray(0,s));n.push(a),S(this,j,_(this,j,"f").subarray(o.index),"f"),S(this,C,null,"f")}return n}flush(){return _(this,j,"f").length?this.decode(`
2
2
  `):[]}};j=new WeakMap,C=new WeakMap;Q.NEWLINE_CHARS=new Set([`
3
3
  `,"\r"]);Q.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ur(r,e){for(let o=e??0;o<r.length;o++){if(r[o]===10)return{preceding:o,index:o+1,carriage:!1};if(r[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function cr(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}var Ge={off:0,error:200,warn:300,info:400,debug:500},At=(r,e,t)=>{if(r){if(Dt(Ge,r))return r;P(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(Ge))}`)}};function Ne(){}function Je(r,e,t){return!e||Ge[r]>Ge[t]?Ne:e[r].bind(e)}var vr={error:Ne,warn:Ne,info:Ne,debug:Ne},lr=new WeakMap;function P(r){let e=r.logger,t=r.logLevel??"off";if(!e)return vr;let n=lr.get(e);if(n&&n[0]===t)return n[1];let o={error:Je("error",e,t),warn:Je("warn",e,t),info:Je("info",e,t),debug:Je("debug",e,t)};return lr.set(e,[t,o]),o}var N=r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r);var He,Qe=class r{constructor(e,t,n){this.iterator=e,He.set(this,void 0),this.controller=t,S(this,He,n,"f")}static fromSSEResponse(e,t,n){let o=!1,s=n?P(n):console;async function*a(){if(o)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let c=!1;try{for await(let f of Dr(e,t))try{yield JSON.parse(f.data)}catch(d){throw s.error("Could not parse message into JSON:",f.data),s.error("From chunk:",f.raw),d}c=!0}catch(f){if(Ue(f))return;throw f}finally{c||t.abort()}}return new r(a,t,n)}static fromReadableStream(e,t,n){let o=!1;async function*s(){let c=new Q,f=ht(e);for await(let d of f)for(let m of c.decode(d))yield m;for(let d of c.flush())yield d}async function*a(){if(o)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let c=!1;try{for await(let f of s())c||f&&(yield JSON.parse(f));c=!0}catch(f){if(Ue(f))return;throw f}finally{c||t.abort()}}return new r(a,t,n)}[(He=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),o=s=>({next:()=>{if(s.length===0){let a=n.next();e.push(a),t.push(a)}return s.shift()}});return[new r(()=>o(e),this.controller,_(this,He,"f")),new r(()=>o(t),this.controller,_(this,He,"f"))]}toReadableStream(){let e=this,t;return pt({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:s}=await t.next();if(s)return n.close();let a=De(JSON.stringify(o)+`
4
4
  `);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await t.return?.()}})}};async function*Dr(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new x("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new x("Attempted to iterate over a response with no body");let t=new Rt,n=new Q,o=ht(r.body);for await(let s of Nr(o))for(let a of n.decode(s)){let c=t.decode(a);c&&(yield c)}for(let s of n.flush()){let a=t.decode(s);a&&(yield a)}}async function*Nr(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?De(t):t,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=cr(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var Rt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
@@ -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="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};
9
+ ${l}`)}return a},i=Gr(mr);var Z=class extends p{create(e,t){return this._client.post("/org/api_keys",{body:e,...t})}retrieve(e,t={},n){return this._client.get(i`/org/api_keys/${e}`,{query:t,...n})}update(e,t,n){return this._client.patch(i`/org/api_keys/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/org/api_keys",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/org/api_keys/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}rotate(e,t={},n){return this._client.post(i`/org/api_keys/${e}/rotate`,{body:t,...n})}};var ee=class extends p{list(e={},t){return this._client.getAPIList("/apps",w,{query:e,...t})}};var xe=class extends p{create(e,t){return this._client.post("/audit-logs/export/destinations",{body:e,...t})}retrieve(e,t){return this._client.get(i`/audit-logs/export/destinations/${e}`,t)}update(e,t,n){return this._client.patch(i`/audit-logs/export/destinations/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/audit-logs/export/destinations",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/audit-logs/export/destinations/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}test(e,t){return this._client.post(i`/audit-logs/export/destinations/${e}/test`,t)}};var Yr=6,Zr=5e4,en=8e3,F=class extends x{};async function gr(r,e,t,n,o={}){if(!t||typeof t.write!="function")throw new TypeError("audit log download destination must provide write()");let{onProgress:s,maxTransferRetries:a=Yr,...c}=o;if(!Number.isInteger(a)||a<0)throw new TypeError("maxTransferRetries must be a non-negative integer");let f=c.timeout??n,d,m={bytesWritten:0,chunks:0,rows:0},l=new Set;for(;;){let g=await tn(r,d?{...e,cursor:d}:e,c,a,f),{nextCursor:h,hasMore:A,rows:E}=rn(g.headers,d);if(A&&h){if(l.has(h))throw new F("response repeated X-Next-Cursor header");l.add(h)}if(await sn(t,g.body),d=h,m.bytesWritten+=g.body.byteLength,m.chunks+=1,m.rows+=E,s&&await s({...m,chunkRows:E}),!A)return m}}async function tn(r,e,t,n,o){for(let s=0;;s+=1){let a=new AbortController,c=()=>a.abort();t.signal?.aborted?a.abort():t.signal?.addEventListener("abort",c,{once:!0});let f;try{f=await r(e,{...t,signal:a.signal})}catch(l){throw t.signal?.removeEventListener("abort",c),l}let d=!1,m=setTimeout(()=>{d=!0,a.abort()},o);try{let l=new Uint8Array(await f.arrayBuffer());if(clearTimeout(m),t.signal?.aborted)throw new T;if(d)throw new D;let g=f.headers.get("x-content-sha256");if(!g)throw new F("response missing X-Content-Sha256 header");let h=await nn(l);if(t.signal?.aborted)throw new T;if(h!==g)throw new F(`audit log chunk checksum mismatch (got ${h}, want ${g})`);return{body:l,headers:f.headers}}catch(l){if(t.signal?.aborted&&!(l instanceof T)?l=new T:d&&(l=new D),s===n||l instanceof T)throw l;await on(s+1,t.signal)}finally{clearTimeout(m),t.signal?.removeEventListener("abort",c)}}}function rn(r,e){let t=r.get("x-has-more");if(t!=="true"&&t!=="false")throw new F("response missing or invalid X-Has-More header");let n=t==="true",o=r.get("x-row-count");if(o===null||!/^[0-9]+$/.test(o))throw new F("response missing or invalid X-Row-Count header");let s=Number(o);if(!Number.isSafeInteger(s)||s>Zr)throw new F("response missing or invalid X-Row-Count header");let a=r.get("x-next-cursor")||void 0;if(n&&(!a||a===e))throw new F("response has invalid X-Next-Cursor header");if(!n&&a)throw new F("response returned a cursor after the final chunk");return{rows:s,nextCursor:a,hasMore:n}}async function nn(r){let e=await globalThis.crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(e),t=>t.toString(16).padStart(2,"0")).join("")}async function on(r,e){let t=Math.min(1e3*2**(r-1),en);await new Promise((n,o)=>{if(e?.aborted){o(new T);return}let s=()=>{clearTimeout(a),o(new T)},a=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t);e?.addEventListener("abort",s,{once:!0})})}async function sn(r,e){let t=0;for(;t<e.byteLength;){let n=await r.write(t===0?e:e.subarray(t));if(typeof n=="number"){t+=yr(n,e.byteLength-t);continue}if(n&&typeof n=="object"&&"bytesWritten"in n){let o=n.bytesWritten;t+=yr(o,e.byteLength-t);continue}return}}function yr(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new F("audit log download destination performed a short write");return r}var X=class extends p{constructor(){super(...arguments),this.exportDestinations=new xe(this._client)}list(e,t){return this._client.getAPIList("/audit-logs",tt,{query:e,...t})}exportChunk(e,t){return this._client.get("/audit-logs/export/chunk",{query:e,...t,headers:u([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}download(e,t,n){return gr((o,s)=>this.exportChunk(o,s),e,t,this._client.timeout,n)}};X.ExportDestinations=xe;var _e=class extends p{create(e,t){return this._client.post("/auth/connections",{body:e,...t})}retrieve(e,t){return this._client.get(i`/auth/connections/${e}`,t)}update(e,t,n){return this._client.patch(i`/auth/connections/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/auth/connections",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/auth/connections/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}follow(e,t){return this._client.get(i`/auth/connections/${e}/events`,{...t,headers:u([{Accept:"text/event-stream"},t?.headers]),stream:!0})}login(e,t={},n){return this._client.post(i`/auth/connections/${e}/login`,{body:t,...n})}submit(e,t,n){return this._client.post(i`/auth/connections/${e}/submit`,{body:t,...n})}timeline(e,t={},n){return this._client.getAPIList(i`/auth/connections/${e}/timeline`,w,{query:t,...n})}};var Ae=class extends p{retrieve(e){return this._client.get("/auth/context",e)}};var B=class extends p{constructor(){super(...arguments),this.context=new Ae(this._client),this.connections=new _e(this._client)}};B.Context=Ae;B.Connections=_e;var te=class extends p{create(e,t){return this._client.post("/browser_pools",{body:e,...t})}retrieve(e,t){return this._client.get(i`/browser_pools/${e}`,t)}update(e,t,n){return this._client.patch(i`/browser_pools/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/browser_pools",w,{query:e,...t})}delete(e,t={},n){return this._client.delete(i`/browser_pools/${e}`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}acquire(e,t,n){return this._client.post(i`/browser_pools/${e}/acquire`,{body:t,...n})}flush(e,t){return this._client.post(i`/browser_pools/${e}/flush`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}release(e,t,n){return this._client.post(i`/browser_pools/${e}/release`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}};var Re=class extends p{batch(e,t,n){return this._client.post(i`/browsers/${e}/computer/batch`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}captureScreenshot(e,t={},n){return this._client.post(i`/browsers/${e}/computer/screenshot`,{body:t,...n,headers:u([{Accept:"image/png"},n?.headers]),__binaryResponse:!0})}clickMouse(e,t,n){return this._client.post(i`/browsers/${e}/computer/click_mouse`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}dragMouse(e,t,n){return this._client.post(i`/browsers/${e}/computer/drag_mouse`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}getMousePosition(e,t){return this._client.post(i`/browsers/${e}/computer/get_mouse_position`,t)}moveMouse(e,t,n){return this._client.post(i`/browsers/${e}/computer/move_mouse`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}pressKey(e,t,n){return this._client.post(i`/browsers/${e}/computer/press_key`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}readClipboard(e,t){return this._client.post(i`/browsers/${e}/computer/clipboard/read`,t)}scroll(e,t,n){return this._client.post(i`/browsers/${e}/computer/scroll`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}setCursorVisibility(e,t,n){return this._client.post(i`/browsers/${e}/computer/cursor`,{body:t,...n})}typeText(e,t,n){return this._client.post(i`/browsers/${e}/computer/type`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}writeClipboard(e,t,n){return this._client.post(i`/browsers/${e}/computer/clipboard/write`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}};var Pe=class extends p{stream(e,t,n){return this._client.get(i`/browsers/${e}/logs/stream`,{query:t,...n,headers:u([{Accept:"text/event-stream"},n?.headers]),stream:!0})}};var Ee=class extends p{execute(e,t,n){return this._client.post(i`/browsers/${e}/playwright/execute`,{body:t,...n})}};var Se=class extends p{exec(e,t,n){return this._client.post(i`/browsers/${e}/process/exec`,{body:t,...n})}kill(e,t,n){let{id:o,...s}=t;return this._client.post(i`/browsers/${o}/process/${e}/kill`,{body:s,...n})}resize(e,t,n){let{id:o,...s}=t;return this._client.post(i`/browsers/${o}/process/${e}/resize`,{body:s,...n})}spawn(e,t,n){return this._client.post(i`/browsers/${e}/process/spawn`,{body:t,...n})}status(e,t,n){let{id:o}=t;return this._client.get(i`/browsers/${o}/process/${e}/status`,n)}stdin(e,t,n){let{id:o,...s}=t;return this._client.post(i`/browsers/${o}/process/${e}/stdin`,{body:s,...n})}stdoutStream(e,t,n){let{id:o}=t;return this._client.get(i`/browsers/${o}/process/${e}/stdout/stream`,{...n,headers:u([{Accept:"text/event-stream"},n?.headers]),stream:!0})}};var Ie=class extends p{list(e,t){return this._client.get(i`/browsers/${e}/replays`,t)}download(e,t,n){let{id:o}=t;return this._client.get(i`/browsers/${o}/replays/${e}`,{...n,headers:u([{Accept:"video/mp4"},n?.headers]),__binaryResponse:!0})}start(e,t={},n){return this._client.post(i`/browsers/${e}/replays`,{body:t,...n})}stop(e,t,n){let{id:o}=t;return this._client.post(i`/browsers/${o}/replays/${e}/stop`,{...n,headers:u([{Accept:"*/*"},n?.headers])})}};var $e=class extends p{events(e,t={},n){return this._client.getAPIList(i`/browsers/${e}/telemetry/events`,w,{query:t,...n})}stream(e,t={},n){let{"Last-Event-ID":o,...s}=t??{};return this._client.get(i`/browsers/${e}/telemetry/stream`,{query:s,...n,headers:u([{Accept:"text/event-stream",...o!=null?{"Last-Event-ID":o}:void 0},n?.headers]),stream:!0})}};var Le=class extends p{events(e,t,n){let{id:o}=t;return this._client.get(i`/browsers/${o}/fs/watch/${e}/events`,{...n,headers:u([{Accept:"text/event-stream"},n?.headers]),stream:!0})}start(e,t,n){return this._client.post(i`/browsers/${e}/fs/watch`,{body:t,...n})}stop(e,t,n){let{id:o}=t;return this._client.delete(i`/browsers/${o}/fs/watch/${e}`,{...n,headers:u([{Accept:"*/*"},n?.headers])})}};var re=class extends p{constructor(){super(...arguments),this.watch=new Le(this._client)}createDirectory(e,t,n){return this._client.put(i`/browsers/${e}/fs/create_directory`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}deleteDirectory(e,t,n){return this._client.put(i`/browsers/${e}/fs/delete_directory`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}deleteFile(e,t,n){return this._client.put(i`/browsers/${e}/fs/delete_file`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}downloadDirZip(e,t,n){return this._client.get(i`/browsers/${e}/fs/download_dir_zip`,{query:t,...n,headers:u([{Accept:"application/zip"},n?.headers]),__binaryResponse:!0})}fileInfo(e,t,n){return this._client.get(i`/browsers/${e}/fs/file_info`,{query:t,...n})}listFiles(e,t,n){return this._client.get(i`/browsers/${e}/fs/list_files`,{query:t,...n})}move(e,t,n){return this._client.put(i`/browsers/${e}/fs/move`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}readFile(e,t,n){return this._client.get(i`/browsers/${e}/fs/read_file`,{query:t,...n,headers:u([{Accept:"application/octet-stream"},n?.headers]),__binaryResponse:!0})}setFilePermissions(e,t,n){return this._client.put(i`/browsers/${e}/fs/set_file_permissions`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}upload(e,t,n){return this._client.post(i`/browsers/${e}/fs/upload`,H({body:t,...n,headers:u([{Accept:"*/*"},n?.headers])},this._client))}uploadZip(e,t,n){return this._client.post(i`/browsers/${e}/fs/upload_zip`,H({body:t,...n,headers:u([{Accept:"*/*"},n?.headers])},this._client))}writeFile(e,t,n,o){let{path:s,mode:a}=n;return this._client.put(i`/browsers/${e}/fs/write_file`,{body:t,query:{path:s,mode:a},...o,headers:u([{"Content-Type":"application/octet-stream",Accept:"*/*"},o?.headers])})}};re.Watch=Le;function ot(r,e){return`${r.replace(/\/+$/,"")}${e.startsWith("/")?e:`/${e}`}`}async function wr(r,e,t,n){let o=r.browserRouteCache.get(e);if(!o)throw new x(`browser route cache does not contain session ${e}; create, retrieve, or list the browser before calling browser.fetch`);let{url:s,method:a,headers:c,body:f,signal:d,duplex:m,timeout_ms:l}=wn(t,n);bn(s);let g={url:s,jwt:o.jwt};l!==void 0&&(g.timeout_ms=l);let h=c.get("accept"),A={method:gn(a),path:ot(o.baseURL,"/curl/raw"),query:g,body:f,headers:u([{Authorization:null},h?{Accept:h}:{Accept:"*/*"},xn(c)]),signal:d??null,__binaryResponse:!0};return m&&(A.fetchOptions={duplex:m}),r.request(A).asResponse()}function gn(r){let e=r.toLowerCase();if(!new Set(["get","post","put","patch","delete"]).has(e))throw new x(`browser.fetch unsupported HTTP method: ${r}`);return e}function wn(r,e){let t=e&&"timeout_ms"in e?e.timeout_ms:void 0;if(r instanceof Request){let o=new Headers(r.headers);e?.headers&&new Headers(e.headers).forEach((d,m)=>{o.set(m,d)});let s={url:r.url,method:(e?.method??r.method)?.toUpperCase()||"GET",headers:o},a=e?.body??r.body;a!=null&&(s.body=a);let c=e?.signal??r.signal;return c!==void 0&&(s.signal=c),e?.duplex!==void 0&&(s.duplex=e.duplex),t!==void 0&&(s.timeout_ms=t),s}let n={url:r instanceof URL?r.href:String(r),method:(e?.method??"GET").toUpperCase(),headers:new Headers(e?.headers)};return e?.body!==void 0&&(n.body=e.body),e?.signal!==void 0&&(n.signal=e.signal),e?.duplex!==void 0&&(n.duplex=e.duplex),t!==void 0&&(n.timeout_ms=t),n}function bn(r){let e;try{e=new URL(r)}catch{throw new x(`browser.fetch target must be an absolute URL; received: ${r}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new x(`browser.fetch only supports http(s) URLs; received: ${e.protocol}`)}function xn(r){let e={};return r.forEach((t,n)=>{switch(n.toLowerCase()){case"accept":case"content-length":case"connection":case"keep-alive":case"proxy-authenticate":case"proxy-authorization":case"te":case"trailers":case"transfer-encoding":case"upgrade":return;default:e[n]=t}}),e}var O=class extends p{constructor(){super(...arguments),this.telemetry=new $e(this._client),this.replays=new Ie(this._client),this.fs=new re(this._client),this.process=new Se(this._client),this.logs=new Pe(this._client),this.computer=new Re(this._client),this.playwright=new Ee(this._client)}create(e={},t){return this._client.post("/browsers",{body:e,...t})}retrieve(e,t={},n){return this._client.get(i`/browsers/${e}`,{query:t,...n})}update(e,t,n){return this._client.patch(i`/browsers/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/browsers",w,{query:e,...t})}curl(e,t,n){return this._client.post(i`/browsers/${e}/curl`,{body:t,...n})}fetch(e,t,n){return wr(this._client,e,t,n)}deleteByID(e,t){return this._client.delete(i`/browsers/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}loadExtensions(e,t,n){return this._client.post(i`/browsers/${e}/extensions`,H({body:t,...n,headers:u([{Accept:"*/*"},n?.headers])},this._client))}};O.Telemetry=$e;O.Replays=Ie;O.Fs=re;O.Process=Se;O.Logs=Pe;O.Computer=Re;O.Playwright=Ee;var ne=class extends p{create(e,t){return this._client.post("/org/credential_providers",{body:e,...t})}retrieve(e,t){return this._client.get(i`/org/credential_providers/${e}`,t)}update(e,t,n){return this._client.patch(i`/org/credential_providers/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/org/credential_providers",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/org/credential_providers/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}listItems(e,t){return this._client.get(i`/org/credential_providers/${e}/items`,t)}test(e,t){return this._client.post(i`/org/credential_providers/${e}/test`,t)}};var oe=class extends p{create(e,t){return this._client.post("/credentials",{body:e,...t})}retrieve(e,t){return this._client.get(i`/credentials/${e}`,t)}update(e,t,n){return this._client.patch(i`/credentials/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/credentials",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/credentials/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}totpCode(e,t){return this._client.get(i`/credentials/${e}/totp-code`,t)}};var se=class extends p{create(e,t){return this._client.post("/deployments",H({body:e,...t},this._client))}retrieve(e,t){return this._client.get(i`/deployments/${e}`,t)}list(e={},t){return this._client.getAPIList("/deployments",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/deployments/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}follow(e,t={},n){return this._client.get(i`/deployments/${e}/events`,{query:t,...n,headers:u([{Accept:"text/event-stream"},n?.headers]),stream:!0})}};var ie=class extends p{list(e={},t){return this._client.getAPIList("/extensions",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/extensions/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}download(e,t){return this._client.get(i`/extensions/${e}`,{...t,headers:u([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}downloadFromChromeStore(e,t){return this._client.get("/extensions/from_chrome_store",{query:e,...t,headers:u([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}get(e,t){return this._client.get(i`/extensions/${e}/metadata`,t)}upload(e,t){return this._client.post("/extensions",H({body:e,...t},this._client))}};var ae=class extends p{create(e,t){return this._client.post("/invocations",{body:e,...t})}retrieve(e,t){return this._client.get(i`/invocations/${e}`,t)}update(e,t,n){return this._client.patch(i`/invocations/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/invocations",w,{query:e,...t})}deleteBrowsers(e,t){return this._client.delete(i`/invocations/${e}/browsers`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}follow(e,t={},n){return this._client.get(i`/invocations/${e}/events`,{query:t,...n,headers:u([{Accept:"text/event-stream"},n?.headers]),stream:!0})}listBrowsers(e,t){return this._client.get(i`/invocations/${e}/browsers`,t)}};var Te=class extends p{retrieve(e){return this._client.get("/org/entitlements",e)}};var Oe=class extends p{retrieve(e){return this._client.get("/org/limits",e)}update(e,t){return this._client.patch("/org/limits",{body:e,...t})}};var M=class extends p{constructor(){super(...arguments),this.entitlements=new Te(this._client),this.limits=new Oe(this._client)}};M.Entitlements=Te;M.Limits=Oe;var ce=class extends p{create(e,t){return this._client.post("/profiles",{body:e,...t})}retrieve(e,t){return this._client.get(i`/profiles/${e}`,t)}update(e,t,n){return this._client.patch(i`/profiles/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/profiles",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/profiles/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}download(e,t={},n){return this._client.get(i`/profiles/${e}/download`,{query:t,...n,headers:u([{Accept:"application/octet-stream"},n?.headers]),__binaryResponse:!0})}};var je=class extends p{retrieve(e,t){return this._client.get(i`/org/projects/${e}/limits`,t)}update(e,t,n){return this._client.patch(i`/org/projects/${e}/limits`,{body:t,...n})}};var z=class extends p{constructor(){super(...arguments),this.limits=new je(this._client)}create(e,t){return this._client.post("/org/projects",{body:e,...t})}retrieve(e,t){return this._client.get(i`/org/projects/${e}`,t)}update(e,t,n){return this._client.patch(i`/org/projects/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/org/projects",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/org/projects/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}};z.Limits=je;var le=class extends p{create(e,t){return this._client.post("/proxies",{body:e,...t})}retrieve(e,t){return this._client.get(i`/proxies/${e}`,t)}update(e,t,n){return this._client.patch(i`/proxies/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/proxies",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/proxies/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}check(e,t={},n){return this._client.post(i`/proxies/${e}/check`,{body:t,...n})}};var Ce=class extends p{create(e,t){return this._client.post("/telemetry/destinations",{body:e,...t})}retrieve(e,t){return this._client.get(i`/telemetry/destinations/${e}`,t)}update(e,t,n){return this._client.patch(i`/telemetry/destinations/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/telemetry/destinations",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/telemetry/destinations/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}};var V=class extends p{constructor(){super(...arguments),this.destinations=new Ce(this._client)}};V.Destinations=Ce;var Ke=class{constructor(){this.entries=new Map}get(e){return this.entries.get(e)}set(e){this.entries.set(e.sessionId,e)}delete(e){this.entries.delete(e)}clear(){this.entries.clear()}},br="\u004b\u0045\u0052\u004e\u0045\u004c_BROWSER_ROUTING_SUBRESOURCES",Sn=["curl","telemetry/stream"],In=/^\/(?:v\d+\/)?browsers(?:\/[^/]+)?\/?$/,$n=/^\/(?:v\d+\/)?browser_pools\/[^/]+\/acquire\/?$/,Ln=/^\/(?:v\d+\/)?browsers\/([^/]+)\/?$/,Tn=/^\/(?:v\d+\/)?browser_pools\/[^/]+\/release\/?$/;function Lt(){let r=qn();return r===void 0?[...Sn]:r.trim()===""?[]:r.split(",").map(e=>e.trim()).filter(Boolean)}function Tt(r,{apiBaseURL:e,subresources:t,cache:n}){let o=[...t].map(a=>a.trim().replace(/^\/+|\/+$/g,"")).filter(Boolean),s=new URL(e).origin;return async(a,c)=>{let f=new Request(a,c),d=On(f,s),m=await Dn(r,{input:a,init:c,request:f},s,o,n);return d&&await Un(m,n),await jn(f,m,s,n),m}}function On(r,e){let t=new URL(r.url);return t.origin===e&&(In.test(t.pathname)||$n.test(t.pathname))}async function jn(r,e,t,n){if(!e.ok)return;let o=new URL(r.url);if(o.origin!==t)return;let s=Cn(r,o.pathname)??await kn(r,o.pathname);s&&n.delete(s)}function Cn(r,e){if(r.method.toUpperCase()!=="DELETE")return;let t=e.match(Ln);return t&&decodeURIComponent(t[1]??"")||void 0}async function kn(r,e){if(!(r.method.toUpperCase()!=="POST"||!Tn.test(e)))try{let t=await r.clone().json();if(!t||typeof t!="object")return;let n=t.session_id;return typeof n=="string"&&n.trim()?n.trim():void 0}catch{return}}function Fn(r){if(!r||typeof r!="object")return;let e=r,t=typeof e.session_id=="string"?e.session_id.trim():"",n=typeof e.base_url=="string"?e.base_url.trim():"";if(!t||!n)return;let o=typeof e.jwt=="string"?e.jwt.trim():"",s=typeof e.cdp_ws_url=="string"?e.cdp_ws_url:void 0,a=o||Mn(s)||"";if(a)return{sessionId:t,baseURL:n,jwt:a}}async function Un(r,e){if((r.headers.get("content-type")?.toLowerCase()??"").includes("application/json"))try{$t(await r.clone().json(),e)}catch{}}function $t(r,e){let t=Fn(r);if(t&&e.set(t),Array.isArray(r)){for(let n of r)$t(n,e);return}if(!(!r||typeof r!="object"))for(let n of Object.values(r))typeof n=="object"&&n!==null&&$t(n,e)}function vn(r,e){let t=r.replace(/^\/+|\/+$/g,"");return e.some(n=>t===n||t.startsWith(n+"/"))}async function Dn(r,{input:e,init:t,request:n},o,s,a){let c=new URL(n.url);if(c.origin!==o)return r(e,t);let f=c.pathname.match(/^\/(?:v\d+\/)?browsers\/([^/]+)\/([^/]+)(\/.*)?$/);if(!f)return r(e,t);let d=decodeURIComponent(f[1]??""),m=f[2]??"";if(!d||!vn(m+(f[3]??""),s))return r(e,t);let l=a.get(d);if(l===void 0)return r(e,t);let g=new URL(ot(l.baseURL,`/${m}${f[3]??""}`));c.searchParams.forEach((A,E)=>{E!=="jwt"&&g.searchParams.append(E,A)}),g.searchParams.get("jwt")||g.searchParams.set("jwt",l.jwt);let h=new Headers(n.headers);return h.delete("authorization"),r(g.toString(),Nn(e,n,t,h))}function Nn(r,e,t,n){let o=e.method.toUpperCase(),s={...t??{},method:o,headers:n,redirect:e.redirect,signal:t?.signal??(r instanceof Request?r.signal:void 0)};if(delete s.body,delete s.duplex,o!=="GET"&&o!=="HEAD"){let a=Hn(e,t);a!==void 0&&(s.body=a),t?.duplex!==void 0?s.duplex=t.duplex:Bn(a)&&(s.duplex="half")}return s}function Hn(r,e){return e?.body!==void 0&&e.body!==null?e.body:r.body??void 0}function Bn(r){return globalThis.ReadableStream&&r instanceof globalThis.ReadableStream||typeof r=="object"&&r!==null&&Symbol.asyncIterator in r}function Mn(r){if(r)try{return new URL(r).searchParams.get("jwt")??void 0}catch{return}}function qn(){if(typeof globalThis.process<"u"){let r=globalThis.process.env?.[br];return typeof r=="string"?r:void 0}if(typeof globalThis.Deno<"u"){let r=globalThis.Deno.env?.get?.(br);return typeof r=="string"?r:void 0}}var st=class{constructor(e){this.actions=new Map,this.name=e,xr.registerApp(this)}action(e,t){let n;if(t.length===0)throw new Error("Action handlers must accept at least the context parameter");if(t.length===1){let o=t;n=async(s,a)=>o(s)}else n=t;return this.actions.set(e,{name:e,handler:n}),n}getActions(){return Array.from(this.actions.values())}getAction(e){return this.actions.get(e)}toJSON(){return{name:this.name,actions:this.getActions().map(e=>({name:e.name}))}}},Ot=class{constructor(){this.apps=new Map}registerApp(e){this.apps.set(e.name,e)}getApps(){return Array.from(this.apps.values())}getAppByName(e){return this.apps.get(e)}export(){return{apps:this.getApps().map(e=>e.toJSON())}}exportJSON(){return JSON.stringify(this.export(),null,2)}},xr=new Ot;var ke=r=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()||void 0};var jt,Ct,We,_r,Ar={production:"https://api.on\u006b\u0065\u0072\u006e\u0065\u006c.com/",development:"https://localhost:3001/"},y=class{constructor({baseURL:e=ke("\u004b\u0045\u0052\u004e\u0045\u004c_BASE_URL"),apiKey:t=ke("\u004b\u0045\u0052\u004e\u0045\u004c_API_KEY"),projectID:n=null,project:o=null,...s}={}){if(jt.add(this),We.set(this,void 0),this.deployments=new se(this),this.apps=new ee(this),this.invocations=new ae(this),this.browsers=new O(this),this.profiles=new ce(this),this.auth=new B(this),this.telemetry=new V(this),this.proxies=new le(this),this.extensions=new ie(this),this.browserPools=new te(this),this.credentials=new oe(this),this.projects=new z(this),this.organization=new M(this),this.auditLogs=new X(this),this.apiKeys=new Z(this),this.credentialProviders=new ne(this),typeof globalThis<"u"&&typeof globalThis.Bun<"u"&&globalThis.Bun.version&&!ke("\u004b\u0045\u0052\u004e\u0045\u004c_SUPPRESS_BUN_WARNING")&&P(this).warn("The Bun runtime was detected. Playwright may have CDP connection issues, proceed with caution. Suppress this warning by setting the \u004b\u0045\u0052\u004e\u0045\u004c_SUPPRESS_BUN_WARNING environment variable to true"),t===void 0)throw new x("The \u004b\u0045\u0052\u004e\u0045\u004c_API_KEY environment variable is missing or empty; either provide it, or instantiate the \u004b\u0065\u0072\u006e\u0065\u006c client with an apiKey option, like new \u004b\u0065\u0072\u006e\u0065\u006c({ apiKey: 'My API Key' }).");let a={apiKey:t,projectID:n,project:o,...s,baseURL:e,environment:s.environment??"production"};if(e&&s.environment)throw new x("Ambiguous URL; The `baseURL` option (or \u004b\u0045\u0052\u004e\u0045\u004c_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null");this.baseURL=a.baseURL||Ar[a.environment||"production"],this.timeout=a.timeout??Ct.DEFAULT_TIMEOUT,this.logger=a.logger??console;let c="warn";this.logLevel=c,this.logLevel=At(a.logLevel,"ClientOptions.logLevel",this)??At(ke("\u004b\u0045\u0052\u004e\u0045\u004c_LOG"),"process.env['\u004b\u0045\u0052\u004e\u0045\u004c_LOG']",this)??c,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.rawFetch=a.fetch??zt(),this.browserRouteCache=new Ke,this.fetch=Tt(this.rawFetch,{apiBaseURL:this.baseURL,subresources:Lt(),cache:this.browserRouteCache}),S(this,We,Jt,"f");let f=ke("\u004b\u0045\u0052\u004e\u0045\u004c_CUSTOM_HEADERS");if(f){let d={};for(let m of f.split(`
10
+ `)){let l=m.indexOf(":");l>=0&&(d[m.substring(0,l).trim()]=m.substring(l+1).trim())}a.defaultHeaders={...d,...a.defaultHeaders}}this._options=a,this.apiKey=t,this.projectID=n,this.project=o}withOptions(e){let t=new this.constructor({...this._options,environment:e.environment?e.environment:void 0,baseURL:e.environment?void 0:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.rawFetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,projectID:this.projectID,project:this.project,...e});return t.browserRouteCache=this.browserRouteCache,t.fetch=Tt(t.rawFetch,{apiBaseURL:t.baseURL,subresources:Lt(),cache:t.browserRouteCache}),t}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return u([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return or(e)}getUserAgent(){return`${this.constructor.name}/JS ${W}`}defaultIdempotencyKey(){return`stainless-node-retry-${ct()}`}makeStatusError(e,t,n,o){return I.generate(e,t,n,o)}buildURL(e,t,n){let o=!_(this,jt,"m",_r).call(this)&&n||this.baseURL,s=vt(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),c=Object.fromEntries(s.searchParams);return(!ft(a)||!ft(c))&&(t={...c,...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(s.search=this.stringifyQuery(t)),s.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(o=>({method:e,path:t,...o})))}request(e,t=null){return new Y(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let o=await e,s=o.maxRetries??this.maxRetries;t==null&&(t=s),await this.prepareOptions(o);let{req:a,url:c,timeout:f}=await this.buildRequest(o,{retryCount:s-t});await this.prepareRequest(a,{url:c,options:o});let d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=n===void 0?"":`, retryOf: ${n}`,l=Date.now();if(P(this).debug(`[${d}] sending request`,N({retryOfRequestLogID:n,method:o.method,url:c,options:o,headers:a.headers})),o.signal?.aborted)throw new T;let g=new AbortController,h=await this.fetchWithTimeout(c,a,f,g).catch(ve),A=Date.now();if(h instanceof globalThis.Error){let U=`retrying, ${t} attempts remaining`;if(o.signal?.aborted)throw new T;let k=Ue(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return P(this).info(`[${d}] connection ${k?"timed out":"failed"} - ${U}`),P(this).debug(`[${d}] connection ${k?"timed out":"failed"} (${U})`,N({retryOfRequestLogID:n,url:c,durationMs:A-l,message:h.message})),this.retryRequest(o,t,n??d);throw P(this).info(`[${d}] connection ${k?"timed out":"failed"} - error; no more retries left`),P(this).debug(`[${d}] connection ${k?"timed out":"failed"} (error; no more retries left)`,N({retryOfRequestLogID:n,url:c,durationMs:A-l,message:h.message})),k?new D:new K({cause:h})}let E=`[${d}${m}] ${a.method} ${c} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${A-l}ms`;if(!h.ok){let U=await this.shouldRetry(h);if(t&&U){let q=`retrying, ${t} attempts remaining`;return await Vt(h.body),P(this).info(`${E} - ${q}`),P(this).debug(`[${d}] response error (${q})`,N({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:A-l})),this.retryRequest(o,t,n??d,h.headers)}let k=U?"error; no more retries left":"error; not retryable";P(this).info(`${E} - ${k}`);let b=await h.text().catch(q=>ve(q).message),J=Bt(b),G=J?void 0:b;throw P(this).debug(`[${d}] response error (${k})`,N({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,message:G,durationMs:Date.now()-l})),this.makeStatusError(h.status,J,G,h.headers)}return P(this).info(E),P(this).debug(`[${d}] response start`,N({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:A-l})),{response:h,options:o,controller:g,requestLogID:d,retryOfRequestLogID:n,startTime:l}}getAPIList(e,t,n){return this.requestAPIList(t,n&&"then"in n?n.then(o=>({method:"get",path:e,...o})):{method:"get",path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new Me(this,n,e)}async fetchWithTimeout(e,t,n,o){let{signal:s,method:a,...c}=t||{},f=this._makeAbort(o);s&&s.addEventListener("abort",f,{once:!0});let d=setTimeout(f,n),m=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,l={signal:o.signal,...m?{duplex:"half"}:{},method:"GET",...c};a&&(l.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,l)}finally{clearTimeout(d)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,o){let s,a=o?.get("retry-after-ms");if(a){let f=parseFloat(a);Number.isNaN(f)||(s=f)}let c=o?.get("retry-after");if(c&&!s){let f=parseFloat(c);Number.isNaN(f)?s=Date.parse(c)-Date.now():s=f*1e3}if(s===void 0){let f=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,f)}return await Mt(s),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let s=t-e,a=Math.min(.5*Math.pow(2,s),8),c=1-Math.random()*.25;return a*c*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:o,path:s,query:a,defaultBaseURL:c}=n,f=this.buildURL(s,a,c);"timeout"in n&&Nt("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:d,body:m}=this.buildBody({options:n}),l=await this.buildHeaders({options:e,method:o,bodyHeaders:d,retryCount:t});return{req:{method:o,headers:l,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"},...m&&{body:m},...this.fetchOptions??{},...n.fetchOptions??{}},url:f,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:o}){let s={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let a=u([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Xt(),"X-\u004b\u0065\u0072\u006e\u0065\u006c-Project-Id":this.projectID,"X-\u004b\u0065\u0072\u006e\u0065\u006c-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:n}=e;if(!t)return t==null&&"body"in e?_(this,We,"f").call(this,{body:t,headers:u([n])}):{bodyHeaders:void 0,body:void 0};let o=u([n]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&o.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:ze(t)}:typeof t=="object"&&o.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(t)}:_(this,We,"f").call(this,{body:t,headers:o})}app(e){return new st(e)}};Ct=y,We=new WeakMap,jt=new WeakSet,_r=function(){return this.baseURL!==Ar[this._options.environment||"production"]};y.\u004b\u0065\u0072\u006e\u0065\u006c=Ct;y.DEFAULT_TIMEOUT=6e4;y.\u004b\u0065\u0072\u006e\u0065\u006cError=x;y.APIError=I;y.APIConnectionError=K;y.APIConnectionTimeoutError=D;y.APIUserAbortError=T;y.NotFoundError=he;y.ConflictError=me;y.RateLimitError=ge;y.BadRequestError=fe;y.AuthenticationError=de;y.InternalServerError=we;y.PermissionDeniedError=pe;y.UnprocessableEntityError=ye;y.toFile=nt;y.Deployments=se;y.Apps=ee;y.Invocations=ae;y.Browsers=O;y.Profiles=ce;y.Auth=B;y.Telemetry=V;y.Proxies=le;y.Extensions=ie;y.BrowserPools=te;y.Credentials=oe;y.Projects=z;y.Organization=M;y.AuditLogs=X;y.APIKeys=Z;y.CredentialProviders=ne;export{K as a,D as b,de as c,pe as d,we as e,y as f};