mcp-scraper 0.96.0 → 0.96.1

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 (41) hide show
  1. package/CHANGELOG.md +20 -1
  2. package/README.md +3 -1
  3. package/dist/{actions-YCMJY3PF.js → actions-R4EJDLRO.js} +1 -1
  4. package/dist/bin/api-server.js +1 -1
  5. package/dist/bin/mcp-scraper-cli.js +1 -1
  6. package/dist/bin/mcp-scraper-core.js +1 -1
  7. package/dist/bin/mcp-scraper-install.js +1 -1
  8. package/dist/bin/mcp-stdio-server.js +1 -1
  9. package/dist/bin/paa-harvest.js +1 -1
  10. package/dist/{bundle-TTJP6DHU.js → bundle-FCXZMIRB.js} +1 -1
  11. package/dist/{chunk-ZPQNY5TI.js → chunk-5LYINW7Z.js} +8 -1
  12. package/dist/{chunk-R5LJL6IR.js → chunk-6BD75VKS.js} +30 -37
  13. package/dist/{chunk-6SNOUSSZ.js → chunk-7WPCGRD7.js} +1 -1
  14. package/dist/{chunk-DGAW7FD7.js → chunk-BPKTUCV7.js} +1 -1
  15. package/dist/{chunk-QWE7VKIX.js → chunk-CORWWDHL.js} +1 -1
  16. package/dist/chunk-CVQUHVHX.js +1 -0
  17. package/dist/{chunk-VAC3SQ5T.js → chunk-FB4KBB5W.js} +1 -1
  18. package/dist/{chunk-HJIOH7HF.js → chunk-H6MODA7W.js} +2 -2
  19. package/dist/{chunk-JAV5V3JT.js → chunk-HVQZRQRJ.js} +19 -19
  20. package/dist/{chunk-2PRH4Z3N.js → chunk-IY6ZUUY7.js} +29 -37
  21. package/dist/chunk-JHT6A4U6.js +11 -0
  22. package/dist/{chunk-ARSQZCTJ.js → chunk-RIHI3KH7.js} +255 -245
  23. package/dist/{chunk-LFRAA3MY.js → chunk-RN4VG3VH.js} +1 -1
  24. package/dist/{chunk-SNJR5N36.js → chunk-RYX4FJVH.js} +1 -1
  25. package/dist/{chunk-JW4GDY7S.js → chunk-SE4VKLEC.js} +1 -1
  26. package/dist/{chunk-TPN25AFZ.js → chunk-SFUOSJ3A.js} +1 -1
  27. package/dist/{chunk-GVYGAZV7.js → chunk-UXNR3K6I.js} +1 -1
  28. package/dist/{chunk-FRXKMOXI.js → chunk-ZTMQEDIB.js} +1 -1
  29. package/dist/{dispatch-3HY4735M.js → dispatch-P7IY75LH.js} +1 -1
  30. package/dist/index.cjs +36 -36
  31. package/dist/index.d.cts +3 -0
  32. package/dist/index.d.ts +3 -0
  33. package/dist/index.js +1 -1
  34. package/dist/{queue-HUP2GNXF.js → queue-AC4XKD6Z.js} +1 -1
  35. package/dist/{reconciliation-ANXNJWME.js → reconciliation-UZUZ6B74.js} +1 -1
  36. package/dist/{server-VQU6S24A.js → server-DXZ27KQO.js} +488 -488
  37. package/dist/{settlement-6CCE2PDH.js → settlement-6CS4JZTY.js} +1 -1
  38. package/dist/{worker-5G5BK23B.js → worker-ATRD6VKM.js} +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunk-7UHDOIUE.js +0 -1
  41. package/dist/chunk-OB6E6UTD.js +0 -1
package/CHANGELOG.md CHANGED
@@ -4,6 +4,24 @@ All notable changes to MCP Scraper are documented here. The format is based on [
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.96.1] - 2026-10-13
8
+
9
+ ### Fixed
10
+
11
+ - Wait at least 20 seconds between PAA progress checks, while preserving other operations' retry timing.
12
+ - Preserve complete loaded PAA answers, including lists, mathematical notation, entity names and source details. Continue discovering questions when their answers are already prefetched, and avoid repeated DOM reads and unnecessary or uncertain repeat clicks.
13
+ - Let managed CAPTCHA recovery finish within the original request deadline. Keep challenge and session traffic in the browser, and avoid unrelated searches during PAA-only extraction.
14
+ - Show initial People Also Ask questions, available answer snippets and source labels in full SERP text and structured responses. Distinguish these previews from fully expanded PAA answers.
15
+ - Run isolated test fixtures from clean checkouts without requiring one developer's path or branch, and validate Memory package layout against its current versions.
16
+
17
+ ### Changed
18
+
19
+ - Give acquisition diagnostics a dedicated scripts directory, move contributor guidance into documentation and keep generated output out of the source tree.
20
+
21
+ ### Removed
22
+
23
+ - Remove the unused crawler UI prototype, broken root acquisition probes and tracked operating-system and Python cache files.
24
+
7
25
  ## [0.96.0] - 2026-10-12
8
26
 
9
27
  ### Security
@@ -2200,7 +2218,7 @@ All notable changes to MCP Scraper are documented here. The format is based on [
2200
2218
  - Write actions remain unavailable until the account owner explicitly enables them.
2201
2219
  - Provider-specific connection data is normalized into one agent-facing contract.
2202
2220
 
2203
- [Unreleased]: https://github.com/VilovietaSEO/mcp-scraper/compare/v0.96.0...HEAD
2221
+ [Unreleased]: https://github.com/VilovietaSEO/mcp-scraper/compare/v0.96.1...HEAD
2204
2222
  [0.95.2]: https://github.com/VilovietaSEO/mcp-scraper/compare/v0.95.1...v0.95.2
2205
2223
  [0.95.1]: https://github.com/VilovietaSEO/mcp-scraper/compare/v0.95.0...v0.95.1
2206
2224
  [0.95.0]: https://github.com/VilovietaSEO/mcp-scraper/compare/v0.94.4...v0.95.0
@@ -2370,3 +2388,4 @@ All notable changes to MCP Scraper are documented here. The format is based on [
2370
2388
  [0.89.4]: https://github.com/VilovietaSEO/mcp-scraper/compare/v0.89.3...v0.89.4
2371
2389
  [0.89.5]: https://github.com/VilovietaSEO/mcp-scraper/compare/v0.89.4...v0.89.5
2372
2390
  [0.96.0]: https://github.com/VilovietaSEO/mcp-scraper/compare/v0.95.2...v0.96.0
2391
+ [0.96.1]: https://github.com/VilovietaSEO/mcp-scraper/compare/v0.96.0...v0.96.1
package/README.md CHANGED
@@ -18,6 +18,8 @@ deployment boundaries:
18
18
  and [`product-topology.json`](product-topology.json) for exact ownership, source receipts, release units,
19
19
  deployment roots, and verification commands.
20
20
 
21
+ Contributors can begin with [START-HERE.md](START-HERE.md) and the [codebase edit guide](docs/architecture/codebase-file-tree.md). Current product guidance lives in `docs/product/`, reference material in `docs/reference/`, and historical designs and diagnostics in `docs/archive/`. Manual acquisition probes live in `scripts/diagnostics/`; `bin/` contains package entrypoints.
22
+
21
23
  ## Install
22
24
 
23
25
  Use the MCPB Desktop Extension for the branded Claude Desktop install, or use the npm package from any MCP client that can run stdio commands.
@@ -175,7 +177,7 @@ Build the branded one-click bundle:
175
177
  npm run build:mcpb
176
178
  ```
177
179
 
178
- The generated bundle is written to `build/mcpb/mcp-scraper-<version>.mcpb` and copied to `public/downloads/` for the hosted download. The current public bundle is `https://mcpscraper.dev/downloads/mcp-scraper.mcpb` (`0.96.0`, SHA-256 `72fd074fb10f0d4dc4bbf7d0dff35b45f7fa228bba3aa201185e7e036791cefa`). Install it by opening or dragging it into Claude Desktop. Claude displays the `MCP Scraper` install card, icon, API-key configuration field, and manually curated current-release message from the bundle manifest.
180
+ The generated bundle is written to `build/mcpb/mcp-scraper-<version>.mcpb` and copied to `public/downloads/` for the hosted download. The current public bundle is `https://mcpscraper.dev/downloads/mcp-scraper.mcpb` (`0.96.1`, SHA-256 `ae0752f8b13bab71fb57cd11b0afe349b384957594b408cc64422a83bd844a67`). Install it by opening or dragging it into Claude Desktop. Claude displays the `MCP Scraper` install card, icon, API-key configuration field, and manually curated current-release message from the bundle manifest.
179
181
 
180
182
  The MCPB install exposes every tool — web-intelligence plus all `browser_*` tools — through the one `mcp-scraper` server.
181
183
 
@@ -1 +1 @@
1
- import{e as a,f as b,g as c,h as d,i as e,j as f,k as g,l as h}from"./chunk-JW4GDY7S.js";import"./chunk-TPN25AFZ.js";import"./chunk-NALXKTUU.js";import"./chunk-R5LJL6IR.js";import"./chunk-RDHGQ2WZ.js";import"./chunk-QWE7VKIX.js";import"./chunk-ZPQNY5TI.js";import"./chunk-SEZETSB3.js";import"./chunk-SDQW7IJN.js";import"./chunk-VVSHZV5S.js";import"./chunk-4ZVO6GX4.js";import"./chunk-WNUXMPVX.js";import"./chunk-WP3QS4CJ.js";import"./chunk-OILOHQNL.js";export{d as GMAIL_ATTACHMENT_REF_TTL_MS,c as GMAIL_INLINE_BODY_BYTES,b as GMAIL_MAIN_CONTRACT_HASH,a as GMAIL_MAIN_CONTRACT_VERSION,h as GmailService,e as GmailServiceError,g as normalizeGmailMessage,f as parseGmailAddresses};
1
+ import{e as a,f as b,g as c,h as d,i as e,j as f,k as g,l as h}from"./chunk-SE4VKLEC.js";import"./chunk-SFUOSJ3A.js";import"./chunk-NALXKTUU.js";import"./chunk-6BD75VKS.js";import"./chunk-RDHGQ2WZ.js";import"./chunk-CORWWDHL.js";import"./chunk-5LYINW7Z.js";import"./chunk-SEZETSB3.js";import"./chunk-SDQW7IJN.js";import"./chunk-VVSHZV5S.js";import"./chunk-4ZVO6GX4.js";import"./chunk-WNUXMPVX.js";import"./chunk-WP3QS4CJ.js";import"./chunk-OILOHQNL.js";export{d as GMAIL_ATTACHMENT_REF_TTL_MS,c as GMAIL_INLINE_BODY_BYTES,b as GMAIL_MAIN_CONTRACT_HASH,a as GMAIL_MAIN_CONTRACT_VERSION,h as GmailService,e as GmailServiceError,g as normalizeGmailMessage,f as parseGmailAddresses};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import{readFileSync as s}from"fs";function c(){try{for(let r of s(".env","utf8").split(`
3
- `)){let o=r.indexOf("=");if(o<1||r.trimStart().startsWith("#"))continue;let e=r.slice(0,o).trim();process.env[e]||(process.env[e]=r.slice(o+1).trim())}}catch{}}c();async function a(){let[{serve:r},{app:o},{startWorker:e},{migrate:i}]=await Promise.all([import("@hono/node-server"),import("../server-VQU6S24A.js"),import("../worker-5G5BK23B.js"),import("../core-schema-423BSTE6.js")]),n=parseInt(process.env.PORT??"3001");try{if(await i(),process.env.ANALYTICS_DATABASE_URL){let{migrateAnalytics:t}=await import("../migrations-3AKEC5QE.js");await t()}e(),r({fetch:o.fetch,port:n},t=>{console.log(`[server] http://localhost:${t.port}`),console.log(`[server] admin auth: ${process.env.ADMIN_KEY?"configured":"not configured"}`)})}catch(t){console.error("[startup] server preflight failed",t instanceof Error?t.name:"unknown_error"),process.exit(1)}}a();
3
+ `)){let o=r.indexOf("=");if(o<1||r.trimStart().startsWith("#"))continue;let e=r.slice(0,o).trim();process.env[e]||(process.env[e]=r.slice(o+1).trim())}}catch{}}c();async function a(){let[{serve:r},{app:o},{startWorker:e},{migrate:i}]=await Promise.all([import("@hono/node-server"),import("../server-DXZ27KQO.js"),import("../worker-ATRD6VKM.js"),import("../core-schema-423BSTE6.js")]),n=parseInt(process.env.PORT??"3001");try{if(await i(),process.env.ANALYTICS_DATABASE_URL){let{migrateAnalytics:t}=await import("../migrations-3AKEC5QE.js");await t()}e(),r({fetch:o.fetch,port:n},t=>{console.log(`[server] http://localhost:${t.port}`),console.log(`[server] admin auth: ${process.env.ADMIN_KEY?"configured":"not configured"}`)})}catch(t){console.error("[startup] server preflight failed",t instanceof Error?t.name:"unknown_error"),process.exit(1)}}a();
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{k as N,l as j,m as L,n as T,r as U}from"../chunk-4HZXATHB.js";import"../chunk-KJQXUZ4Y.js";import"../chunk-6N5EC7ZO.js";import{g as v,j as b,k as D,l as K,m as H}from"../chunk-24YDQ3EO.js";import"../chunk-OLYPLX5C.js";import"../chunk-B3JRL45T.js";import{c as _}from"../chunk-OILOHQNL.js";import{a as P}from"../chunk-7UHDOIUE.js";import{Command as he}from"commander";import{spawn as te}from"child_process";import{mkdir as ke,writeFile as Pe}from"fs/promises";import{basename as Ce,join as X}from"path";function ie(e){return e.apiKey?.trim()||"sk_live_your_key"}function ae(e){return e.packageSpec?.trim()||"mcp-scraper@latest"}function A(e={}){return["-y","--package",ae(e),"mcp-scraper"]}function se(e){let n={MCP_SCRAPER_API_KEY:ie(e)},c=e.browserProfileName?.trim();return c&&(n.BROWSER_AGENT_PROFILE_NAME=c),e.browserProfileSaveChanges===!0&&(n.BROWSER_AGENT_PROFILE_SAVE_CHANGES="true"),n}function q(){return["mcp","remove","mcp-scraper","-s","user"]}function B(){return["mcp","get","mcp-scraper"]}function J(e){let n=e.match(/^\s*Command:\s*(.+?)\s*$/m)?.[1];if(!n)return null;let c=e.match(/^\s*Args:\s*(.*?)\s*$/m)?.[1]??"",i=c.length?c.split(/\s+/):[],p={},u=e.split(/^\s*Environment:\s*$/m)[1];if(u)for(let a of u.split(`
2
+ import{k as N,l as j,m as L,n as T,r as U}from"../chunk-4HZXATHB.js";import"../chunk-KJQXUZ4Y.js";import"../chunk-6N5EC7ZO.js";import{g as v,j as b,k as D,l as K,m as H}from"../chunk-24YDQ3EO.js";import"../chunk-OLYPLX5C.js";import"../chunk-B3JRL45T.js";import{c as _}from"../chunk-OILOHQNL.js";import{a as P}from"../chunk-CVQUHVHX.js";import{Command as he}from"commander";import{spawn as te}from"child_process";import{mkdir as ke,writeFile as Pe}from"fs/promises";import{basename as Ce,join as X}from"path";function ie(e){return e.apiKey?.trim()||"sk_live_your_key"}function ae(e){return e.packageSpec?.trim()||"mcp-scraper@latest"}function A(e={}){return["-y","--package",ae(e),"mcp-scraper"]}function se(e){let n={MCP_SCRAPER_API_KEY:ie(e)},c=e.browserProfileName?.trim();return c&&(n.BROWSER_AGENT_PROFILE_NAME=c),e.browserProfileSaveChanges===!0&&(n.BROWSER_AGENT_PROFILE_SAVE_CHANGES="true"),n}function q(){return["mcp","remove","mcp-scraper","-s","user"]}function B(){return["mcp","get","mcp-scraper"]}function J(e){let n=e.match(/^\s*Command:\s*(.+?)\s*$/m)?.[1];if(!n)return null;let c=e.match(/^\s*Args:\s*(.*?)\s*$/m)?.[1]??"",i=c.length?c.split(/\s+/):[],p={},u=e.split(/^\s*Environment:\s*$/m)[1];if(u)for(let a of u.split(`
3
3
  `)){let l=a.match(/^\s{2,}([A-Za-z_][A-Za-z0-9_]*)=(.*)$/);if(!l){if(a.trim().length&&!/^\s{2,}/.test(a))break;continue}p[l[1]]=l[2]}return{command:n,args:i,env:p}}function O(e){let n=["mcp","add","mcp-scraper","--scope","user"];for(let[c,i]of Object.entries(e.env))n.push("--env",`${c}=${i}`);return n.push("--",e.command,...e.args),n}function G(e={}){let n=["mcp","add","mcp-scraper","--scope","user"];for(let[c,i]of Object.entries(se(e)))n.push("--env",`${c}=${i}`);return n.push("--","npx",...A(e)),n}function I(e){if(e==="claude-code")return"claude";if(e==="claude"||D.hosts.some(n=>n.id===e))return e;throw new Error('Unknown host "'+e+'". Use: codex, claude, claude-code, claude-desktop, cursor, windsurf, cline, or user-action-only')}function ce(e){return K(e==="claude"?"claude-code":e)}function W(e,n={}){let c=I(e),i=ce(c),p="Restart the MCP client so it starts a fresh npx process.",u='MCP_SCRAPER_API_KEY="$MCP_SCRAPER_API_KEY" npx -y -p mcp-scraper@latest mcp-scraper-cli agent install claude --apply',a=`X-Ray install protocol: ${v} (${b})`;return c==="codex"?["# Codex MCP config",a,i.exactConfig,"",`Continuation: ${i.continuation}`,`Rollback: ${i.rollback}`,"",p].join(`
4
4
  `):c==="claude"?["# Claude Code command",a,i.exactConfig,"","# One-command Claude Code setup",u,"",`Continuation: ${i.continuation}`,`Rollback: ${i.rollback}`,"",p].join(`
5
5
  `):c==="claude-desktop"?["# Claude Desktop config",a,i.exactConfig,"","Desktop Extension: https://mcpscraper.dev/downloads/mcp-scraper.mcpb",`Continuation: ${i.continuation}`,`Rollback: ${i.rollback}`,p].join(`
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{a as e}from"../chunk-LFRAA3MY.js";import"../chunk-ARSQZCTJ.js";import"../chunk-QER2ELZP.js";import"../chunk-OB6E6UTD.js";import"../chunk-7POHNTVW.js";import"../chunk-MVMWPKRC.js";import"../chunk-63VWBMYR.js";import"../chunk-3F7AFM53.js";import"../chunk-RDHGQ2WZ.js";import"../chunk-2IATUJO6.js";import"../chunk-QWE7VKIX.js";import"../chunk-ZPQNY5TI.js";import"../chunk-CNSVZTTT.js";import"../chunk-5BKSKLHX.js";import"../chunk-7SR7MEU5.js";import"../chunk-HUNSEGUN.js";import"../chunk-SEZETSB3.js";import"../chunk-SDQW7IJN.js";import"../chunk-B4ZKPLSP.js";import"../chunk-VVSHZV5S.js";import"../chunk-C7MGJUTU.js";import"../chunk-4ZVO6GX4.js";import"../chunk-WNUXMPVX.js";import"../chunk-VAC3SQ5T.js";import"../chunk-WP3QS4CJ.js";import"../chunk-24YDQ3EO.js";import"../chunk-OLYPLX5C.js";import"../chunk-B3JRL45T.js";import"../chunk-OILOHQNL.js";import"../chunk-7UHDOIUE.js";import"../chunk-HNNYXMSI.js";var _=["harvest_paa","search_serp","extract_url","diff_page","map_site_urls","map_wayback_snapshots","extract_site","analyze_site_similarity","audit_site","check_site_export","site_export_read","site_export_image","archive_read","youtube_harvest","youtube_transcribe","facebook_page_intel","facebook_ad_search","reddit_thread","reddit_trending","video_frame_analysis","video_frame_analysis_status","facebook_ad_transcribe","google_ads_search","google_ads_page_intel","google_ads_transcribe","facebook_video_transcribe","instagram_profile_content","instagram_media_download","maps_place_intel","maps_search","trustpilot_reviews","g2_reviews","capture_serp_snapshot","capture_serp_page_snapshots"];e({toolsets:new Set(["paa","serp"]),allowedToolNames:_});
2
+ import{a as e}from"../chunk-RN4VG3VH.js";import"../chunk-RIHI3KH7.js";import"../chunk-QER2ELZP.js";import"../chunk-JHT6A4U6.js";import"../chunk-7POHNTVW.js";import"../chunk-MVMWPKRC.js";import"../chunk-63VWBMYR.js";import"../chunk-3F7AFM53.js";import"../chunk-RDHGQ2WZ.js";import"../chunk-2IATUJO6.js";import"../chunk-CORWWDHL.js";import"../chunk-5LYINW7Z.js";import"../chunk-CNSVZTTT.js";import"../chunk-5BKSKLHX.js";import"../chunk-7SR7MEU5.js";import"../chunk-HUNSEGUN.js";import"../chunk-SEZETSB3.js";import"../chunk-SDQW7IJN.js";import"../chunk-B4ZKPLSP.js";import"../chunk-VVSHZV5S.js";import"../chunk-C7MGJUTU.js";import"../chunk-4ZVO6GX4.js";import"../chunk-WNUXMPVX.js";import"../chunk-FB4KBB5W.js";import"../chunk-WP3QS4CJ.js";import"../chunk-24YDQ3EO.js";import"../chunk-OLYPLX5C.js";import"../chunk-B3JRL45T.js";import"../chunk-OILOHQNL.js";import"../chunk-CVQUHVHX.js";import"../chunk-HNNYXMSI.js";var _=["harvest_paa","search_serp","extract_url","diff_page","map_site_urls","map_wayback_snapshots","extract_site","analyze_site_similarity","audit_site","check_site_export","site_export_read","site_export_image","archive_read","youtube_harvest","youtube_transcribe","facebook_page_intel","facebook_ad_search","reddit_thread","reddit_trending","video_frame_analysis","video_frame_analysis_status","facebook_ad_transcribe","google_ads_search","google_ads_page_intel","google_ads_transcribe","facebook_video_transcribe","instagram_profile_content","instagram_media_download","maps_place_intel","maps_search","trustpilot_reviews","g2_reviews","capture_serp_snapshot","capture_serp_page_snapshots"];e({toolsets:new Set(["paa","serp"]),allowedToolNames:_});
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{a as s}from"../chunk-VAC3SQ5T.js";import"../chunk-WP3QS4CJ.js";import{a as e}from"../chunk-7UHDOIUE.js";var r=process.argv.includes("--no-color")||process.env.NO_COLOR!==void 0||process.env.FORCE_COLOR==="0"||!process.stdout.isTTY,n=process.argv.includes("--help")||process.argv.includes("-h");n&&(process.stdout.write(["Usage: mcp-scraper-install [--no-color]","","Prints the branded MCP Scraper terminal install card and copyable install commands.","mcp-scraper prints the same card in a human terminal and runs as the MCP stdio server in clients.",""].join(`
2
+ import{a as s}from"../chunk-FB4KBB5W.js";import"../chunk-WP3QS4CJ.js";import{a as e}from"../chunk-CVQUHVHX.js";var r=process.argv.includes("--no-color")||process.env.NO_COLOR!==void 0||process.env.FORCE_COLOR==="0"||!process.stdout.isTTY,n=process.argv.includes("--help")||process.argv.includes("-h");n&&(process.stdout.write(["Usage: mcp-scraper-install [--no-color]","","Prints the branded MCP Scraper terminal install card and copyable install commands.","mcp-scraper prints the same card in a human terminal and runs as the MCP stdio server in clients.",""].join(`
3
3
  `)),process.exit(0));process.stdout.write(s({version:e,color:!r,apiKeyConfigured:!!process.env.MCP_SCRAPER_API_KEY?.trim()}));
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{a as r}from"../chunk-LFRAA3MY.js";import"../chunk-ARSQZCTJ.js";import"../chunk-QER2ELZP.js";import"../chunk-OB6E6UTD.js";import"../chunk-7POHNTVW.js";import"../chunk-MVMWPKRC.js";import"../chunk-63VWBMYR.js";import"../chunk-3F7AFM53.js";import"../chunk-RDHGQ2WZ.js";import"../chunk-2IATUJO6.js";import"../chunk-QWE7VKIX.js";import"../chunk-ZPQNY5TI.js";import"../chunk-CNSVZTTT.js";import"../chunk-5BKSKLHX.js";import"../chunk-7SR7MEU5.js";import"../chunk-HUNSEGUN.js";import"../chunk-SEZETSB3.js";import"../chunk-SDQW7IJN.js";import"../chunk-B4ZKPLSP.js";import"../chunk-VVSHZV5S.js";import"../chunk-C7MGJUTU.js";import"../chunk-4ZVO6GX4.js";import"../chunk-WNUXMPVX.js";import"../chunk-VAC3SQ5T.js";import"../chunk-WP3QS4CJ.js";import"../chunk-24YDQ3EO.js";import"../chunk-OLYPLX5C.js";import"../chunk-B3JRL45T.js";import"../chunk-OILOHQNL.js";import"../chunk-7UHDOIUE.js";import"../chunk-HNNYXMSI.js";r();
2
+ import{a as r}from"../chunk-RN4VG3VH.js";import"../chunk-RIHI3KH7.js";import"../chunk-QER2ELZP.js";import"../chunk-JHT6A4U6.js";import"../chunk-7POHNTVW.js";import"../chunk-MVMWPKRC.js";import"../chunk-63VWBMYR.js";import"../chunk-3F7AFM53.js";import"../chunk-RDHGQ2WZ.js";import"../chunk-2IATUJO6.js";import"../chunk-CORWWDHL.js";import"../chunk-5LYINW7Z.js";import"../chunk-CNSVZTTT.js";import"../chunk-5BKSKLHX.js";import"../chunk-7SR7MEU5.js";import"../chunk-HUNSEGUN.js";import"../chunk-SEZETSB3.js";import"../chunk-SDQW7IJN.js";import"../chunk-B4ZKPLSP.js";import"../chunk-VVSHZV5S.js";import"../chunk-C7MGJUTU.js";import"../chunk-4ZVO6GX4.js";import"../chunk-WNUXMPVX.js";import"../chunk-FB4KBB5W.js";import"../chunk-WP3QS4CJ.js";import"../chunk-24YDQ3EO.js";import"../chunk-OLYPLX5C.js";import"../chunk-B3JRL45T.js";import"../chunk-OILOHQNL.js";import"../chunk-CVQUHVHX.js";import"../chunk-HNNYXMSI.js";r();
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{J as t}from"../chunk-JAV5V3JT.js";import"../chunk-M5QHXNFZ.js";import{d as r}from"../chunk-B4ZKPLSP.js";import"../chunk-VVSHZV5S.js";import"../chunk-C7MGJUTU.js";import"../chunk-4ZVO6GX4.js";import"../chunk-WNUXMPVX.js";import"../chunk-6N5EC7ZO.js";import"../chunk-HNNYXMSI.js";import{Command as s,Option as a}from"commander";var i=new s;i.name("paa-harvest").description("Recursively extract Google People Also Ask questions").requiredOption("-q, --query <query>","Seed query").option("-l, --location <location>",'Location name (e.g. "austin" or "Austin,Texas,United States")').option("--gl <gl>","Google country code","us").option("--hl <hl>","Google language code","en").option("-d, --depth <depth>","BFS depth (1-30)","3").option("-m, --max-questions <n>","Max questions to harvest","100").option("-o, --output <dir>","Output directory","./paa-output").option("-f, --format <format>","Output format: json, csv, or both","both").option("--headless","Run browser in headless mode",!1).option("--profile <dir>","Persistent browser profile directory").option("--proxy <url>","Proxy server URL").option("--browser-api-key <key>","Browser service API key (or set BROWSER_SERVICE_API_KEY env var)").addOption(new a("--\u006b\u0065\u0072\u006e\u0065\u006c-api-key <key>").hideHelp()).action(async e=>{try{let o=await t({query:e.query,location:e.location,gl:e.gl,hl:e.hl,depth:parseInt(e.depth,10),maxQuestions:parseInt(e.maxQuestions,10),outputDir:e.output,format:e.format,headless:e.headless,profileDir:e.profile,proxy:e.proxy,\u006b\u0065\u0072\u006e\u0065\u006cApiKey:e.browserApiKey??e.\u006b\u0065\u0072\u006e\u0065\u006cApiKey??r()});console.log(JSON.stringify({totalQuestions:o.totalQuestions,outputDir:o.stats.seed}))}catch(o){console.error(o instanceof Error?o.message:String(o)),process.exit(1)}});async function n(){await i.parseAsync()}n();
2
+ import{J as t}from"../chunk-HVQZRQRJ.js";import"../chunk-M5QHXNFZ.js";import{d as r}from"../chunk-B4ZKPLSP.js";import"../chunk-VVSHZV5S.js";import"../chunk-C7MGJUTU.js";import"../chunk-4ZVO6GX4.js";import"../chunk-WNUXMPVX.js";import"../chunk-6N5EC7ZO.js";import"../chunk-HNNYXMSI.js";import{Command as s,Option as a}from"commander";var i=new s;i.name("paa-harvest").description("Recursively extract Google People Also Ask questions").requiredOption("-q, --query <query>","Seed query").option("-l, --location <location>",'Location name (e.g. "austin" or "Austin,Texas,United States")').option("--gl <gl>","Google country code","us").option("--hl <hl>","Google language code","en").option("-d, --depth <depth>","BFS depth (1-30)","3").option("-m, --max-questions <n>","Max questions to harvest","100").option("-o, --output <dir>","Output directory","./paa-output").option("-f, --format <format>","Output format: json, csv, or both","both").option("--headless","Run browser in headless mode",!1).option("--profile <dir>","Persistent browser profile directory").option("--proxy <url>","Proxy server URL").option("--browser-api-key <key>","Browser service API key (or set BROWSER_SERVICE_API_KEY env var)").addOption(new a("--\u006b\u0065\u0072\u006e\u0065\u006c-api-key <key>").hideHelp()).action(async e=>{try{let o=await t({query:e.query,location:e.location,gl:e.gl,hl:e.hl,depth:parseInt(e.depth,10),maxQuestions:parseInt(e.maxQuestions,10),outputDir:e.output,format:e.format,headless:e.headless,profileDir:e.profile,proxy:e.proxy,\u006b\u0065\u0072\u006e\u0065\u006cApiKey:e.browserApiKey??e.\u006b\u0065\u0072\u006e\u0065\u006cApiKey??r()});console.log(JSON.stringify({totalQuestions:o.totalQuestions,outputDir:o.stats.seed}))}catch(o){console.error(o instanceof Error?o.message:String(o)),process.exit(1)}});async function n(){await i.parseAsync()}n();
@@ -1 +1 @@
1
- import{j as b,k as c}from"./chunk-FRXKMOXI.js";import"./chunk-U4WIJZCX.js";import{E as a}from"./chunk-6SNOUSSZ.js";import"./chunk-KXJCGV3H.js";import"./chunk-JMZIDHYQ.js";import"./chunk-M5QHXNFZ.js";import"./chunk-CNSVZTTT.js";import"./chunk-5BKSKLHX.js";import"./chunk-7SR7MEU5.js";import"./chunk-HUNSEGUN.js";import"./chunk-SEZETSB3.js";import"./chunk-SDQW7IJN.js";import"./chunk-C7MGJUTU.js";import"./chunk-4ZVO6GX4.js";import"./chunk-WNUXMPVX.js";import"./chunk-OLYPLX5C.js";import"./chunk-B3JRL45T.js";import"./chunk-OILOHQNL.js";import"./chunk-HNNYXMSI.js";export{b as MAX_ANALYZED_LINK_EDGES,a as SITE_EXTRACT_PAGE_CHUNK,c as assembleExtractArtifacts};
1
+ import{j as b,k as c}from"./chunk-ZTMQEDIB.js";import"./chunk-U4WIJZCX.js";import{E as a}from"./chunk-7WPCGRD7.js";import"./chunk-KXJCGV3H.js";import"./chunk-JMZIDHYQ.js";import"./chunk-M5QHXNFZ.js";import"./chunk-CNSVZTTT.js";import"./chunk-5BKSKLHX.js";import"./chunk-7SR7MEU5.js";import"./chunk-HUNSEGUN.js";import"./chunk-SEZETSB3.js";import"./chunk-SDQW7IJN.js";import"./chunk-C7MGJUTU.js";import"./chunk-4ZVO6GX4.js";import"./chunk-WNUXMPVX.js";import"./chunk-OLYPLX5C.js";import"./chunk-B3JRL45T.js";import"./chunk-OILOHQNL.js";import"./chunk-HNNYXMSI.js";export{b as MAX_ANALYZED_LINK_EDGES,a as SITE_EXTRACT_PAGE_CHUNK,c as assembleExtractArtifacts};
@@ -1 +1,8 @@
1
- var e={serp:6e3,serp_headless:6e3,serp_headful:6e3,paa:1e3,paa_base:4e4,page_scrape:100,url_map:500,yt_channel:200,yt_transcription:200,fb_ad:700,maps_search:500,maps_place:6e3,maps_review:100,fb_search:800,fb_search_result:100,fb_page_intel:700,fb_page_intel_ad:50,fb_reels_inventory:400,fb_transcribe:33300,tiktok_transcribe:33300,google_ads_search:600,google_ads_intel:200,google_ads_transcribe:33300,instagram_profile:400,instagram_media:400,instagram_transcribe:33300,browser_minute:12e3,reddit_thread:3e3,reddit_comment:200,video_analysis:666700,trustpilot_reviews:500,trustpilot_review:100,g2_reviews:500,g2_review:200,diff_page:100,listing_create:1e3,listing_edit:200},n={TOPUP:"topup",SUBSCRIPTION:"subscription",SIGNUP_GRANT:"signup_grant",MONTHLY_REFRESH:"monthly_free_refresh",PAA:"paa",PAA_REFUND:"paa_refund",SERP:"serp",SERP_REFUND:"serp_refund",REFUND:"refund",TRANSCRIPTION:"transcription",TRANSCRIPTION_HOLD:"transcription_hold",TRANSCRIPTION_REFUND:"transcription_refund",YT_CHANNEL:"yt_channel",FB_AD:"fb_ad",MAPS_SEARCH:"maps_search",DIRECTORY_WORKFLOW_HOLD:"directory_workflow_hold",DIRECTORY_WORKFLOW_REFUND:"directory_workflow_refund",LEAD_LIST_ENRICHMENT_HOLD:"lead_list_enrichment_hold",LEAD_LIST_ENRICHMENT_REFUND:"lead_list_enrichment_refund",MAPS_PLACE:"maps_place",MAPS_REVIEW:"maps_review",MAPS_REVIEW_REFUND:"maps_review_refund",EXTRACT_SITE:"extract_site",EXTRACT_SITE_REFUND:"extract_site_refund",EXTRACT_URL:"page_scrape",URL_MAP:"url_map",EXTRACT_SITE_HOLD:"extract_site_hold",YT_CHANNEL_REFUND:"yt_channel_refund",FB_AD_REFUND:"fb_ad_refund",URL_MAP_REFUND:"url_map_refund",FB_SEARCH:"fb_search",FB_REELS_INVENTORY:"fb_reels_inventory",FB_REELS_INVENTORY_REFUND:"fb_reels_inventory_refund",FB_TRANSCRIBE:"fb_transcribe",TIKTOK_TRANSCRIBE:"tiktok_transcribe",FB_SEARCH_REFUND:"fb_search_refund",FB_SEARCH_RESULT:"fb_search_result",FB_SEARCH_RESULT_REFUND:"fb_search_result_refund",FB_PAGE_INTEL:"fb_page_intel",FB_PAGE_INTEL_REFUND:"fb_page_intel_refund",FB_PAGE_INTEL_AD:"fb_page_intel_ad",FB_PAGE_INTEL_AD_REFUND:"fb_page_intel_ad_refund",FB_TRANSCRIBE_REFUND:"fb_transcribe_refund",TIKTOK_TRANSCRIBE_REFUND:"tiktok_transcribe_refund",GOOGLE_ADS_SEARCH:"google_ads_search",GOOGLE_ADS_SEARCH_REFUND:"google_ads_search_refund",GOOGLE_ADS_INTEL:"google_ads_intel",GOOGLE_ADS_INTEL_REFUND:"google_ads_intel_refund",GOOGLE_ADS_TRANSCRIBE:"google_ads_transcribe",GOOGLE_ADS_TRANSCRIBE_REFUND:"google_ads_transcribe_refund",INSTAGRAM_PROFILE:"instagram_profile",INSTAGRAM_PROFILE_REFUND:"instagram_profile_refund",INSTAGRAM_MEDIA:"instagram_media",INSTAGRAM_MEDIA_REFUND:"instagram_media_refund",INSTAGRAM_TRANSCRIBE:"instagram_transcribe",INSTAGRAM_TRANSCRIBE_REFUND:"instagram_transcribe_refund",BROWSER_SESSION:"browser_session",REDDIT_THREAD:"reddit_thread",REDDIT_THREAD_REFUND:"reddit_thread_refund",REDDIT_COMMENT:"reddit_comment",REDDIT_COMMENT_REFUND:"reddit_comment_refund",VIDEO_ANALYSIS:"video_analysis",VIDEO_ANALYSIS_REFUND:"video_analysis_refund",VIDEO_ANALYSIS_ADJUST:"video_analysis_adjust",VIDEO_ANALYSIS_LLM:"video_analysis_llm",MEMORY_AI:"memory_ai",MEMORY_AI_REFUND:"memory_ai_refund",TRUSTPILOT_REVIEWS:"trustpilot_reviews",TRUSTPILOT_REVIEWS_REFUND:"trustpilot_reviews_refund",TRUSTPILOT_REVIEW:"trustpilot_review",TRUSTPILOT_REVIEW_REFUND:"trustpilot_review_refund",G2_REVIEWS:"g2_reviews",G2_REVIEWS_REFUND:"g2_reviews_refund",G2_REVIEW:"g2_review",G2_REVIEW_REFUND:"g2_review_refund",DIFF_PAGE:"diff_page",DIFF_PAGE_REFUND:"diff_page_refund",LOCAL_SOURCEBOOK_CREATE:"local_sourcebook_create",LOCAL_SOURCEBOOK_CREATE_REFUND:"local_sourcebook_create_refund",LOCAL_SOURCEBOOK_EDIT:"local_sourcebook_edit",LOCAL_SOURCEBOOK_EDIT_REFUND:"local_sourcebook_edit_refund",COMMONS_CREATE:"commons_create",COMMONS_CREATE_REFUND:"commons_create_refund",COMMONS_EDIT:"commons_edit",COMMONS_EDIT_REFUND:"commons_edit_refund",SITE_AUDIT_LLM:"site_audit_llm",SCHEDULED_RUN:"scheduled_run",CONNECTED_USAGE:"connected_usage",CONNECTED_ACCOUNT_FEE:"connected_account_fee",ADMIN_GRANT:"admin_grant",ADMIN_REVOKE:"admin_revoke"};function R(_){return _===!0?e.serp_headless:e.serp_headful}var E=100,t=20,a=35;function s(_,r){return _*E*(r==="apify"?t:a)}export{e as a,n as b,R as c,E as d,t as e,a as f,s as g};
1
+ var t={serp:6e3,serp_headless:6e3,serp_headful:6e3,paa:1e3,paa_base:4e4,page_scrape:100,url_map:500,yt_channel:200,yt_transcription:200,fb_ad:700,maps_search:500,maps_place:6e3,maps_review:100,fb_search:800,fb_search_result:100,fb_page_intel:700,fb_page_intel_ad:50,fb_reels_inventory:400,fb_transcribe:33300,tiktok_transcribe:33300,google_ads_search:600,google_ads_intel:200,google_ads_transcribe:33300,instagram_profile:400,instagram_media:400,instagram_transcribe:33300,browser_minute:12e3,reddit_thread:3e3,reddit_comment:200,video_analysis:666700,trustpilot_reviews:500,trustpilot_review:100,g2_reviews:500,g2_review:200,diff_page:100,listing_create:1e3,listing_edit:200},o={TOPUP:"topup",SUBSCRIPTION:"subscription",SIGNUP_GRANT:"signup_grant",MONTHLY_REFRESH:"monthly_free_refresh",PAA:"paa",PAA_REFUND:"paa_refund",SERP:"serp",SERP_REFUND:"serp_refund",REFUND:"refund",TRANSCRIPTION:"transcription",TRANSCRIPTION_HOLD:"transcription_hold",TRANSCRIPTION_REFUND:"transcription_refund",YT_CHANNEL:"yt_channel",FB_AD:"fb_ad",MAPS_SEARCH:"maps_search",DIRECTORY_WORKFLOW_HOLD:"directory_workflow_hold",DIRECTORY_WORKFLOW_REFUND:"directory_workflow_refund",LEAD_LIST_ENRICHMENT_HOLD:"lead_list_enrichment_hold",LEAD_LIST_ENRICHMENT_REFUND:"lead_list_enrichment_refund",MAPS_PLACE:"maps_place",MAPS_REVIEW:"maps_review",MAPS_REVIEW_REFUND:"maps_review_refund",EXTRACT_SITE:"extract_site",EXTRACT_SITE_REFUND:"extract_site_refund",EXTRACT_URL:"page_scrape",URL_MAP:"url_map",EXTRACT_SITE_HOLD:"extract_site_hold",YT_CHANNEL_REFUND:"yt_channel_refund",FB_AD_REFUND:"fb_ad_refund",URL_MAP_REFUND:"url_map_refund",FB_SEARCH:"fb_search",FB_REELS_INVENTORY:"fb_reels_inventory",FB_REELS_INVENTORY_REFUND:"fb_reels_inventory_refund",FB_TRANSCRIBE:"fb_transcribe",TIKTOK_TRANSCRIBE:"tiktok_transcribe",FB_SEARCH_REFUND:"fb_search_refund",FB_SEARCH_RESULT:"fb_search_result",FB_SEARCH_RESULT_REFUND:"fb_search_result_refund",FB_PAGE_INTEL:"fb_page_intel",FB_PAGE_INTEL_REFUND:"fb_page_intel_refund",FB_PAGE_INTEL_AD:"fb_page_intel_ad",FB_PAGE_INTEL_AD_REFUND:"fb_page_intel_ad_refund",FB_TRANSCRIBE_REFUND:"fb_transcribe_refund",TIKTOK_TRANSCRIBE_REFUND:"tiktok_transcribe_refund",GOOGLE_ADS_SEARCH:"google_ads_search",GOOGLE_ADS_SEARCH_REFUND:"google_ads_search_refund",GOOGLE_ADS_INTEL:"google_ads_intel",GOOGLE_ADS_INTEL_REFUND:"google_ads_intel_refund",GOOGLE_ADS_TRANSCRIBE:"google_ads_transcribe",GOOGLE_ADS_TRANSCRIBE_REFUND:"google_ads_transcribe_refund",INSTAGRAM_PROFILE:"instagram_profile",INSTAGRAM_PROFILE_REFUND:"instagram_profile_refund",INSTAGRAM_MEDIA:"instagram_media",INSTAGRAM_MEDIA_REFUND:"instagram_media_refund",INSTAGRAM_TRANSCRIBE:"instagram_transcribe",INSTAGRAM_TRANSCRIBE_REFUND:"instagram_transcribe_refund",BROWSER_SESSION:"browser_session",REDDIT_THREAD:"reddit_thread",REDDIT_THREAD_REFUND:"reddit_thread_refund",REDDIT_COMMENT:"reddit_comment",REDDIT_COMMENT_REFUND:"reddit_comment_refund",VIDEO_ANALYSIS:"video_analysis",VIDEO_ANALYSIS_REFUND:"video_analysis_refund",VIDEO_ANALYSIS_ADJUST:"video_analysis_adjust",VIDEO_ANALYSIS_LLM:"video_analysis_llm",MEMORY_AI:"memory_ai",MEMORY_AI_REFUND:"memory_ai_refund",TRUSTPILOT_REVIEWS:"trustpilot_reviews",TRUSTPILOT_REVIEWS_REFUND:"trustpilot_reviews_refund",TRUSTPILOT_REVIEW:"trustpilot_review",TRUSTPILOT_REVIEW_REFUND:"trustpilot_review_refund",G2_REVIEWS:"g2_reviews",G2_REVIEWS_REFUND:"g2_reviews_refund",G2_REVIEW:"g2_review",G2_REVIEW_REFUND:"g2_review_refund",DIFF_PAGE:"diff_page",DIFF_PAGE_REFUND:"diff_page_refund",LOCAL_SOURCEBOOK_CREATE:"local_sourcebook_create",LOCAL_SOURCEBOOK_CREATE_REFUND:"local_sourcebook_create_refund",LOCAL_SOURCEBOOK_EDIT:"local_sourcebook_edit",LOCAL_SOURCEBOOK_EDIT_REFUND:"local_sourcebook_edit_refund",COMMONS_CREATE:"commons_create",COMMONS_CREATE_REFUND:"commons_create_refund",COMMONS_EDIT:"commons_edit",COMMONS_EDIT_REFUND:"commons_edit_refund",SITE_AUDIT_LLM:"site_audit_llm",SCHEDULED_RUN:"scheduled_run",CONNECTED_USAGE:"connected_usage",CONNECTED_ACCOUNT_FEE:"connected_account_fee",ADMIN_GRANT:"admin_grant",ADMIN_REVOKE:"admin_revoke"};function E(e){return e===!0?t.serp_headless:t.serp_headful}var a=100,i=20,s=35;function d(e,_){return e*a*(_==="apify"?i:s)}var n=class extends Error{constructor(){super("Current operation wallet claim and matching durable plan are required"),this.name="WalletClaimLostError"}},r=class extends Error{constructor(){super("Named operation debit plan conflicts with durable billing history"),this.name="DebitPlanConflictError"}};function l(e){if(!Number.isSafeInteger(e.userId)||e.userId<=0||!Number.isSafeInteger(e.amountMc)||e.amountMc<=0||!e.key||e.key.length>500||!e.operation||!e.description||e.description.length>500)throw new r;return{sql:`EXISTS (SELECT 1 FROM billing_debits d WHERE d.idempotency_key=? AND d.user_id=?
2
+ AND d.amount_mc=? AND d.operation=? AND d.description=? AND d.status='applied'
3
+ AND NOT EXISTS (SELECT 1 FROM billing_events b WHERE b.user_id=d.user_id
4
+ AND b.billing_class='wallet_hold_settlement'
5
+ AND json_extract(b.metadata,'$.debitIdempotencyKey')=d.idempotency_key))`,args:[e.key,e.userId,e.amountMc,e.operation,e.description]}}function c(e,_){if(!/^[a-z_]+\.[a-z_]+$/.test(e)||!/^json_extract\([a-z_]+\.[a-z_]+,'\$\.hold\.key'\)$/.test(_))throw new Error("Invalid stored hold selector");return`EXISTS (SELECT 1 FROM billing_debits d WHERE d.user_id=${e}
6
+ AND d.idempotency_key=${_} AND d.status='applied'
7
+ AND NOT EXISTS (SELECT 1 FROM billing_events b WHERE b.user_id=d.user_id
8
+ AND b.billing_class='wallet_hold_settlement' AND json_extract(b.metadata,'$.debitIdempotencyKey')=d.idempotency_key))`}export{n as a,r as b,l as c,c as d,t as e,o as f,E as g,a as h,i,s as j,d as k};
@@ -1,4 +1,4 @@
1
- import{a as u}from"./chunk-WNUXMPVX.js";var L="2026-06-26 21:58:03";var W="+3 months";function R(e){return{sql:`INSERT INTO credit_lots (user_id, amount_mc, remaining_mc, source, expires_at)
1
+ import{a as _,b as N,c as I}from"./chunk-5LYINW7Z.js";import{a as u}from"./chunk-WNUXMPVX.js";var y="2026-06-26 21:58:03";var k="+3 months";function D(t){return{sql:`INSERT INTO credit_lots (user_id, amount_mc, remaining_mc, source, expires_at)
2
2
  SELECT ?, legacy.balance_mc, legacy.balance_mc, 'migration', datetime('now', ?)
3
3
  FROM (
4
4
  SELECT COALESCE(SUM(amount_mc), 0) AS balance_mc
@@ -12,36 +12,29 @@ import{a as u}from"./chunk-WNUXMPVX.js";var L="2026-06-26 21:58:03";var W="+3 mo
12
12
  )
13
13
  AND NOT EXISTS (
14
14
  SELECT 1 FROM credit_lots WHERE user_id = ?
15
- )`,args:[e,W,e,e,L,e]}}async function T(e){return(await u().execute(R(e))).rowsAffected}import{createHash as O,randomUUID as A}from"crypto";var _=class extends Error{constructor(){super("Current operation wallet claim and matching durable plan are required"),this.name="WalletClaimLostError"}},b=class extends Error{constructor(){super("Named operation debit plan conflicts with durable billing history"),this.name="DebitPlanConflictError"}};function y(e){if(!Number.isSafeInteger(e.userId)||e.userId<=0||!Number.isSafeInteger(e.amountMc)||e.amountMc<=0||!e.key||e.key.length>500||!e.operation||!e.description||e.description.length>500)throw new b;return{sql:`EXISTS (SELECT 1 FROM billing_debits d WHERE d.idempotency_key=? AND d.user_id=?
16
- AND d.amount_mc=? AND d.operation=? AND d.description=? AND d.status='applied'
17
- AND NOT EXISTS (SELECT 1 FROM billing_events b WHERE b.user_id=d.user_id
18
- AND b.billing_class='wallet_hold_settlement'
19
- AND json_extract(b.metadata,'$.debitIdempotencyKey')=d.idempotency_key))`,args:[e.key,e.userId,e.amountMc,e.operation,e.description]}}function v(e,t){if(!/^[a-z_]+\.[a-z_]+$/.test(e)||!/^json_extract\([a-z_]+\.[a-z_]+,'\$\.hold\.key'\)$/.test(t))throw new Error("Invalid stored hold selector");return`EXISTS (SELECT 1 FROM billing_debits d WHERE d.user_id=${e}
20
- AND d.idempotency_key=${t} AND d.status='applied'
21
- AND NOT EXISTS (SELECT 1 FROM billing_events b WHERE b.user_id=d.user_id
22
- AND b.billing_class='wallet_hold_settlement' AND json_extract(b.metadata,'$.debitIdempotencyKey')=d.idempotency_key))`}var D="(CAST(strftime('%s', 'now') AS INTEGER) * 1000)",f="operation-debit:",w=e=>e==="execute"?"e.phase = 'effects_started' AND r.status = 'running'":"e.phase = 'unknown' AND r.status = 'unknown'";function C(e,t,r){if(!r){if(t.startsWith(f))throw new _;return}if(r.userId!==e||!r.runId||!r.token||!["execute","compensate"].includes(r.mode))throw new _}var h=e=>String(e).includes("operation_wallet_claim_current");function x(e,t,r,n){if(C(e,t,r),!r){let a=A(),c="NOT EXISTS (SELECT 1 FROM operation_debit_plans WHERE debit_key = ?)";return{before:[{sql:`INSERT INTO operation_wallet_fences (id, allowed)
23
- SELECT ?, CASE WHEN ${c} THEN 1 ELSE 0 END`,args:[a,t]}],after:[{sql:"DELETE FROM operation_wallet_fences WHERE id = ?",args:[a]}],current:async p=>!!(await p.execute({sql:`SELECT ${c} AS allowed`,args:[t]})).rows[0]?.allowed}}if(n.kind==="debit"&&r.mode!=="execute"||r.mode==="compensate"&&n.amountMc!==0&&!r.settlementPlanId)throw new _;let i=r.settlementPlanId?" AND EXISTS (SELECT 1 FROM operation_final_settlements s WHERE s.id=? AND s.run_id=p.run_id AND s.user_id=r.user_id AND s.debit_key=p.debit_key AND s.final_amount_mc=? AND s.refund_operation=? AND s.source_surface=?)":"",l=`SELECT 1 FROM operation_debit_plans p
15
+ )`,args:[t,k,t,t,y,t]}}async function O(t){return(await u().execute(D(t))).rowsAffected}import{createHash as T,randomUUID as A}from"crypto";var R="(CAST(strftime('%s', 'now') AS INTEGER) * 1000)",f="operation-debit:",w=t=>t==="execute"?"e.phase = 'effects_started' AND r.status = 'running'":"e.phase = 'unknown' AND r.status = 'unknown'";function C(t,e,r){if(!r){if(e.startsWith(f))throw new _;return}if(r.userId!==t||!r.runId||!r.token||!["execute","compensate"].includes(r.mode))throw new _}var W=t=>String(t).includes("operation_wallet_claim_current");function h(t,e,r,i){if(C(t,e,r),!r){let a=A(),d="NOT EXISTS (SELECT 1 FROM operation_debit_plans WHERE debit_key = ?)";return{before:[{sql:`INSERT INTO operation_wallet_fences (id, allowed)
16
+ SELECT ?, CASE WHEN ${d} THEN 1 ELSE 0 END`,args:[a,e]}],after:[{sql:"DELETE FROM operation_wallet_fences WHERE id = ?",args:[a]}],current:async p=>!!(await p.execute({sql:`SELECT ${d} AS allowed`,args:[e]})).rows[0]?.allowed}}if(i.kind==="debit"&&r.mode!=="execute"||r.mode==="compensate"&&i.amountMc!==0&&!r.settlementPlanId)throw new _;let n=r.settlementPlanId?" AND EXISTS (SELECT 1 FROM operation_final_settlements s WHERE s.id=? AND s.run_id=p.run_id AND s.user_id=r.user_id AND s.debit_key=p.debit_key AND s.final_amount_mc=? AND s.refund_operation=? AND s.source_surface=?)":"",l=`SELECT 1 FROM operation_debit_plans p
24
17
  JOIN operation_runs r ON r.id = p.run_id JOIN operation_executions e ON e.run_id = r.id
25
18
  WHERE p.debit_key = ? AND r.id = ? AND r.user_id = ? AND e.claim_token = ?
26
- AND e.expires_at_ms > ${D} AND ${w(r.mode)}
27
- AND ${n.kind==="debit"?"p.amount_mc = ? AND p.operation = ? AND p.description = ?":"p.refund_operation = ? AND p.source_surface = ?"}${i}`,d=[t,r.runId,e,r.token,...n.kind==="debit"?[n.amountMc,n.operation,n.description]:[n.operation,n.sourceSurface],...r.settlementPlanId?[r.settlementPlanId,n.amountMc,n.operation,n.sourceSurface]:[]],o=A(),s=n.kind==="debit"?{sql:`INSERT OR IGNORE INTO operation_billing_links (run_id, billing_table, billing_key, relation, amount_mc)
19
+ AND e.expires_at_ms > ${R} AND ${w(r.mode)}
20
+ AND ${i.kind==="debit"?"p.amount_mc = ? AND p.operation = ? AND p.description = ?":"p.refund_operation = ? AND p.source_surface = ?"}${n}`,c=[e,r.runId,t,r.token,...i.kind==="debit"?[i.amountMc,i.operation,i.description]:[i.operation,i.sourceSurface],...r.settlementPlanId?[r.settlementPlanId,i.amountMc,i.operation,i.sourceSurface]:[]],o=A(),s=i.kind==="debit"?{sql:`INSERT OR IGNORE INTO operation_billing_links (run_id, billing_table, billing_key, relation, amount_mc)
28
21
  SELECT p.run_id, 'billing_debits', d.idempotency_key, 'debit', d.amount_mc FROM operation_debit_plans p
29
22
  JOIN billing_debits d ON d.idempotency_key = p.debit_key
30
- WHERE p.debit_key = ? AND d.user_id = ? AND d.status = 'applied'`,args:[t,e]}:{sql:`INSERT OR IGNORE INTO operation_billing_links (run_id, billing_table, billing_key, relation, amount_mc)
23
+ WHERE p.debit_key = ? AND d.user_id = ? AND d.status = 'applied'`,args:[e,t]}:{sql:`INSERT OR IGNORE INTO operation_billing_links (run_id, billing_table, billing_key, relation, amount_mc)
31
24
  SELECT p.run_id, 'billing_events', b.id, 'settlement', b.amount_mc FROM operation_debit_plans p
32
25
  JOIN billing_events b ON b.idempotency_key = ?
33
- WHERE p.debit_key = ? AND b.user_id = ? AND b.status = 'settled'`,args:[`debit-settlement:${O("sha256").update(t).digest("hex")}`,t,e]};return{before:[{sql:`INSERT INTO operation_wallet_fences (id, allowed)
34
- SELECT ?, CASE WHEN EXISTS (${l}) THEN 1 ELSE 0 END`,args:[o,...d]},R(e)],after:[s,{sql:"DELETE FROM operation_wallet_fences WHERE id = ?",args:[o]}],current:async a=>(await a.execute({sql:l,args:d})).rows.length===1}}function M(e){return{label:String(e.label),key:String(e.debit_key),amountMc:Number(e.amount_mc),operation:String(e.operation),description:String(e.description),refundOperation:String(e.refund_operation),sourceSurface:String(e.source_surface)}}async function B(e,t){if(e.mode!=="execute"||!Number.isSafeInteger(t.amountMc)||t.amountMc<=0||!t.label||t.label.length>200||!t.operation||!t.refundOperation||!t.sourceSurface)throw new b;let r=u(),n=f+A();C(e.userId,n,e);let i=`EXISTS (SELECT 1 FROM operation_runs r JOIN operation_executions e ON e.run_id = r.id
35
- WHERE r.id = ? AND r.user_id = ? AND e.claim_token = ? AND e.expires_at_ms > ${D}
36
- AND ${w("execute")})`,l=[e.runId,e.userId,e.token],d;try{await r.batch([{sql:`INSERT OR IGNORE INTO operation_debit_plans
26
+ WHERE p.debit_key = ? AND b.user_id = ? AND b.status = 'settled'`,args:[`debit-settlement:${T("sha256").update(e).digest("hex")}`,e,t]};return{before:[{sql:`INSERT INTO operation_wallet_fences (id, allowed)
27
+ SELECT ?, CASE WHEN EXISTS (${l}) THEN 1 ELSE 0 END`,args:[o,...c]},D(t)],after:[s,{sql:"DELETE FROM operation_wallet_fences WHERE id = ?",args:[o]}],current:async a=>(await a.execute({sql:l,args:c})).rows.length===1}}function M(t){return{label:String(t.label),key:String(t.debit_key),amountMc:Number(t.amount_mc),operation:String(t.operation),description:String(t.description),refundOperation:String(t.refund_operation),sourceSurface:String(t.source_surface)}}async function X(t,e){if(t.mode!=="execute"||!Number.isSafeInteger(e.amountMc)||e.amountMc<=0||!e.label||e.label.length>200||!e.operation||!e.refundOperation||!e.sourceSurface)throw new N;let r=u(),i=f+A();C(t.userId,i,t);let n=`EXISTS (SELECT 1 FROM operation_runs r JOIN operation_executions e ON e.run_id = r.id
28
+ WHERE r.id = ? AND r.user_id = ? AND e.claim_token = ? AND e.expires_at_ms > ${R}
29
+ AND ${w("execute")})`,l=[t.runId,t.userId,t.token],c;try{await r.batch([{sql:`INSERT OR IGNORE INTO operation_debit_plans
37
30
  (run_id, label, debit_key, amount_mc, operation, description, refund_operation, source_surface)
38
- SELECT ?, ?, ?, ?, ?, ?, ?, ? WHERE ${i}`,args:[e.runId,t.label,n,t.amountMc,t.operation,t.description,t.refundOperation,t.sourceSurface,...l]},{sql:`UPDATE operation_debit_plans SET amount_mc = ? WHERE run_id = ? AND label = ?
39
- AND operation = ? AND description = ? AND refund_operation = ? AND source_surface = ? AND ${i}
31
+ SELECT ?, ?, ?, ?, ?, ?, ?, ? WHERE ${n}`,args:[t.runId,e.label,i,e.amountMc,e.operation,e.description,e.refundOperation,e.sourceSurface,...l]},{sql:`UPDATE operation_debit_plans SET amount_mc = ? WHERE run_id = ? AND label = ?
32
+ AND operation = ? AND description = ? AND refund_operation = ? AND source_surface = ? AND ${n}
40
33
  AND EXISTS (SELECT 1 FROM billing_debits d WHERE d.idempotency_key = operation_debit_plans.debit_key
41
34
  AND d.user_id = ? AND d.status = 'claimed' AND d.amount_mc = operation_debit_plans.amount_mc
42
- AND d.operation = operation_debit_plans.operation AND d.description = operation_debit_plans.description)`,args:[t.amountMc,e.runId,t.label,t.operation,t.description,t.refundOperation,t.sourceSurface,...l,e.userId]}],"write")}catch(a){d=a}let o;try{o=(await r.execute({sql:`SELECT p.* FROM operation_debit_plans p WHERE p.run_id = ? AND p.label = ? AND ${i}`,args:[e.runId,t.label,...l]})).rows[0]}catch(a){throw d??a}if(!o)throw d||new _;let s=M(o);if(s.amountMc!==t.amountMc||s.operation!==t.operation||s.description!==t.description||s.refundOperation!==t.refundOperation||s.sourceSurface!==t.sourceSurface)throw new b;return s}async function J(e){C(e.userId,f,e);let t=u();if(!(await t.execute({sql:`SELECT 1 FROM operation_executions e JOIN operation_runs r ON r.id = e.run_id
43
- WHERE r.id = ? AND r.user_id = ? AND e.claim_token = ? AND e.expires_at_ms > ${D}
44
- AND ${w(e.mode)}`,args:[e.runId,e.userId,e.token]})).rows.length)throw new _;return(await t.execute({sql:"SELECT * FROM operation_debit_plans WHERE run_id = ? ORDER BY label",args:[e.runId]})).rows.map(M)}async function V(e,t){let n=(await u().execute({sql:"SELECT user_id, amount_mc, operation, description, status FROM billing_debits WHERE idempotency_key = ? AND user_id = ? LIMIT 1",args:[t,e]})).rows[0];return n?{amountMc:Number(n.amount_mc),operation:String(n.operation),description:String(n.description),status:String(n.status)}:null}async function Y(e,t,r,n,i,l){if(!Number.isSafeInteger(t)||t<=0)throw new Error("idempotent debit amount must be a positive integer");if(!i||i.length>500)throw new Error("idempotent debit key is required and must be bounded");let d=u(),o=x(e,i,l,{kind:"debit",amountMc:t,operation:r,description:n});l||await T(e);let s;try{s=await d.batch([...o.before,{sql:"UPDATE billing_debits SET amount_mc = ? WHERE idempotency_key = ? AND user_id = ? AND operation = ? AND description = ? AND status = 'claimed'",args:[t,i,e,r,n]},{sql:"INSERT OR IGNORE INTO billing_debits (idempotency_key, user_id, amount_mc, operation, description, status) VALUES (?, ?, ?, ?, ?, 'claimed')",args:[i,e,t,r,n]},{sql:`UPDATE users
35
+ AND d.operation = operation_debit_plans.operation AND d.description = operation_debit_plans.description)`,args:[e.amountMc,t.runId,e.label,e.operation,e.description,e.refundOperation,e.sourceSurface,...l,t.userId]}],"write")}catch(a){c=a}let o;try{o=(await r.execute({sql:`SELECT p.* FROM operation_debit_plans p WHERE p.run_id = ? AND p.label = ? AND ${n}`,args:[t.runId,e.label,...l]})).rows[0]}catch(a){throw c??a}if(!o)throw c||new _;let s=M(o);if(s.amountMc!==e.amountMc||s.operation!==e.operation||s.description!==e.description||s.refundOperation!==e.refundOperation||s.sourceSurface!==e.sourceSurface)throw new N;return s}async function B(t){C(t.userId,f,t);let e=u();if(!(await e.execute({sql:`SELECT 1 FROM operation_executions e JOIN operation_runs r ON r.id = e.run_id
36
+ WHERE r.id = ? AND r.user_id = ? AND e.claim_token = ? AND e.expires_at_ms > ${R}
37
+ AND ${w(t.mode)}`,args:[t.runId,t.userId,t.token]})).rows.length)throw new _;return(await e.execute({sql:"SELECT * FROM operation_debit_plans WHERE run_id = ? ORDER BY label",args:[t.runId]})).rows.map(M)}async function j(t,e){let i=(await u().execute({sql:"SELECT user_id, amount_mc, operation, description, status FROM billing_debits WHERE idempotency_key = ? AND user_id = ? LIMIT 1",args:[e,t]})).rows[0];return i?{amountMc:Number(i.amount_mc),operation:String(i.operation),description:String(i.description),status:String(i.status)}:null}async function J(t,e,r,i,n,l){if(!Number.isSafeInteger(e)||e<=0)throw new Error("idempotent debit amount must be a positive integer");if(!n||n.length>500)throw new Error("idempotent debit key is required and must be bounded");let c=u(),o=h(t,n,l,{kind:"debit",amountMc:e,operation:r,description:i});l||await O(t);let s;try{s=await c.batch([...o.before,{sql:"UPDATE billing_debits SET amount_mc = ? WHERE idempotency_key = ? AND user_id = ? AND operation = ? AND description = ? AND status = 'claimed'",args:[e,n,t,r,i]},{sql:"INSERT OR IGNORE INTO billing_debits (idempotency_key, user_id, amount_mc, operation, description, status) VALUES (?, ?, ?, ?, ?, 'claimed')",args:[n,t,e,r,i]},{sql:`UPDATE users
45
38
  SET balance_mc = balance_mc - ?
46
39
  WHERE id = ?
47
40
  AND balance_mc >= ?
@@ -50,7 +43,7 @@ import{a as u}from"./chunk-WNUXMPVX.js";var L="2026-06-26 21:58:03";var W="+3 mo
50
43
  WHERE user_id = ?
51
44
  AND remaining_mc > 0
52
45
  AND (never_expires = 1 OR expires_at > datetime('now'))) >= ?
53
- AND EXISTS (SELECT 1 FROM billing_debits WHERE idempotency_key = ? AND user_id = ? AND amount_mc = ? AND operation = ? AND description = ? AND status = 'claimed')`,args:[t,e,t,e,t,i,e,t,r,n]},{sql:"UPDATE billing_debits SET status = 'applying' WHERE idempotency_key = ? AND user_id = ? AND amount_mc = ? AND operation = ? AND description = ? AND status = 'claimed' AND changes() = 1",args:[i,e,t,r,n]},{sql:`INSERT OR IGNORE INTO billing_debit_allocations
46
+ AND EXISTS (SELECT 1 FROM billing_debits WHERE idempotency_key = ? AND user_id = ? AND amount_mc = ? AND operation = ? AND description = ? AND status = 'claimed')`,args:[e,t,e,t,e,n,t,e,r,i]},{sql:"UPDATE billing_debits SET status = 'applying' WHERE idempotency_key = ? AND user_id = ? AND amount_mc = ? AND operation = ? AND description = ? AND status = 'claimed' AND changes() = 1",args:[n,t,e,r,i]},{sql:`INSERT OR IGNORE INTO billing_debit_allocations
54
47
  (debit_idempotency_key, lot_id, user_id, amount_mc, expires_at)
55
48
  WITH ordered AS MATERIALIZED (
56
49
  SELECT id,
@@ -69,7 +62,7 @@ import{a as u}from"./chunk-WNUXMPVX.js";var L="2026-06-26 21:58:03";var W="+3 mo
69
62
  SELECT ?, id, ?, take_mc, expires_at
70
63
  FROM allocation
71
64
  WHERE take_mc > 0
72
- AND EXISTS (SELECT 1 FROM billing_debits WHERE idempotency_key = ? AND status = 'applying')`,args:[e,t,i,e,i]},{sql:`UPDATE credit_lots
65
+ AND EXISTS (SELECT 1 FROM billing_debits WHERE idempotency_key = ? AND status = 'applying')`,args:[t,e,n,t,n]},{sql:`UPDATE credit_lots
73
66
  SET remaining_mc = remaining_mc - COALESCE((
74
67
  SELECT amount_mc FROM billing_debit_allocations
75
68
  WHERE debit_idempotency_key = ? AND lot_id = credit_lots.id
@@ -77,9 +70,9 @@ import{a as u}from"./chunk-WNUXMPVX.js";var L="2026-06-26 21:58:03";var W="+3 mo
77
70
  WHERE id IN (
78
71
  SELECT lot_id FROM billing_debit_allocations WHERE debit_idempotency_key = ?
79
72
  )
80
- AND EXISTS (SELECT 1 FROM billing_debits WHERE idempotency_key = ? AND status = 'applying')`,args:[i,i,i]},{sql:"INSERT INTO ledger (user_id, amount_mc, operation, description) SELECT user_id, -amount_mc, operation, description FROM billing_debits WHERE idempotency_key = ? AND status = 'applying'",args:[i]},{sql:"UPDATE billing_debits SET status = 'applied', applied_at = datetime('now') WHERE idempotency_key = ? AND status = 'applying'",args:[i]},...o.after],"write")}catch(g){if(h(g))throw new _;try{if(!await o.current(d))throw new _;let E=(await d.execute({sql:"SELECT user_id, amount_mc, operation, description, status FROM billing_debits WHERE idempotency_key = ? AND status = 'applied' LIMIT 1",args:[i]})).rows[0];if(E&&Number(E.user_id)===e&&Number(E.amount_mc)===t&&String(E.operation)===r&&String(E.description)===n){let S=await d.execute({sql:"SELECT balance_mc FROM users WHERE id = ?",args:[e]});return{ok:!0,balance_mc:Number(S.rows[0]?.balance_mc??0),duplicate:!0}}}catch(m){if(m instanceof _)throw m}throw g}let c=(await d.execute({sql:"SELECT user_id, amount_mc, operation, description, status FROM billing_debits WHERE idempotency_key = ? LIMIT 1",args:[i]})).rows[0];if(!c||Number(c.user_id)!==e||Number(c.amount_mc)!==t||String(c.operation)!==r||String(c.description)!==n)throw new Error("idempotent debit key conflicts with another debit");let p=await d.execute({sql:"SELECT balance_mc FROM users WHERE id = ?",args:[e]});return{ok:String(c.status)==="applied",balance_mc:Number(p.rows[0]?.balance_mc??0),duplicate:s[2+o.before.length]?.rowsAffected===0&&String(c.status)==="applied"}}async function z(e,t,r,n,i,l,d){if(!Number.isSafeInteger(r)||r<0)throw new Error("idempotent debit settlement amount must be a non-negative integer");if(!t||t.length>500)throw new Error("idempotent debit settlement key is required and must be bounded");if(!n||!l)throw new Error("idempotent debit settlement operation and source are required");let o=u(),s=x(e,t,d,{kind:"settlement",amountMc:r,operation:n,description:i,sourceSurface:l});d||await T(e);let a=`debit-settlement:${O("sha256").update(t).digest("hex")}`,c="wallet_hold_settlement",p=A(),g=JSON.stringify({debitIdempotencyKey:t,refundOperation:n,description:i}),m=()=>k(e,t,l),E;try{E=await o.batch([...s.before,{sql:`INSERT OR IGNORE INTO billing_events
73
+ AND EXISTS (SELECT 1 FROM billing_debits WHERE idempotency_key = ? AND status = 'applying')`,args:[n,n,n]},{sql:"INSERT INTO ledger (user_id, amount_mc, operation, description) SELECT user_id, -amount_mc, operation, description FROM billing_debits WHERE idempotency_key = ? AND status = 'applying'",args:[n]},{sql:"UPDATE billing_debits SET status = 'applied', applied_at = datetime('now') WHERE idempotency_key = ? AND status = 'applying'",args:[n]},...o.after],"write")}catch(b){if(W(b))throw new _;try{if(!await o.current(c))throw new _;let E=(await c.execute({sql:"SELECT user_id, amount_mc, operation, description, status FROM billing_debits WHERE idempotency_key = ? AND status = 'applied' LIMIT 1",args:[n]})).rows[0];if(E&&Number(E.user_id)===t&&Number(E.amount_mc)===e&&String(E.operation)===r&&String(E.description)===i){let S=await c.execute({sql:"SELECT balance_mc FROM users WHERE id = ?",args:[t]});return{ok:!0,balance_mc:Number(S.rows[0]?.balance_mc??0),duplicate:!0}}}catch(m){if(m instanceof _)throw m}throw b}let d=(await c.execute({sql:"SELECT user_id, amount_mc, operation, description, status FROM billing_debits WHERE idempotency_key = ? LIMIT 1",args:[n]})).rows[0];if(!d||Number(d.user_id)!==t||Number(d.amount_mc)!==e||String(d.operation)!==r||String(d.description)!==i)throw new Error("idempotent debit key conflicts with another debit");let p=await c.execute({sql:"SELECT balance_mc FROM users WHERE id = ?",args:[t]});return{ok:String(d.status)==="applied",balance_mc:Number(p.rows[0]?.balance_mc??0),duplicate:s[2+o.before.length]?.rowsAffected===0&&String(d.status)==="applied"}}async function V(t,e,r,i,n,l,c){if(!Number.isSafeInteger(r)||r<0)throw new Error("idempotent debit settlement amount must be a non-negative integer");if(!e||e.length>500)throw new Error("idempotent debit settlement key is required and must be bounded");if(!i||!l)throw new Error("idempotent debit settlement operation and source are required");let o=u(),s=h(t,e,c,{kind:"settlement",amountMc:r,operation:i,description:n,sourceSurface:l});c||await O(t);let a=`debit-settlement:${T("sha256").update(e).digest("hex")}`,d="wallet_hold_settlement",p=A(),b=JSON.stringify({debitIdempotencyKey:e,refundOperation:i,description:n}),m=()=>x(t,e,l),E;try{E=await o.batch([...s.before,{sql:`INSERT OR IGNORE INTO billing_events
81
74
  (id, user_id, idempotency_key, billing_class, source_surface, status, amount_mc, metadata)
82
- VALUES (?, ?, ?, ?, ?, 'settling', ?, ?)`,args:[p,e,a,c,l,r,g]},{sql:`WITH ordered AS (
75
+ VALUES (?, ?, ?, ?, ?, 'settling', ?, ?)`,args:[p,t,a,d,l,r,b]},{sql:`WITH ordered AS (
83
76
  SELECT a.lot_id,
84
77
  a.amount_mc,
85
78
  a.expires_at,
@@ -120,14 +113,14 @@ import{a as u}from"./chunk-WNUXMPVX.js";var L="2026-06-26 21:58:03";var W="+3 mo
120
113
  AND d.user_id = e.user_id
121
114
  AND d.status = 'applied'
122
115
  AND e.amount_mc BETWEEN 0 AND d.amount_mc
123
- )`,args:[t,r,e,t,a,e,c,l]},{sql:`UPDATE billing_events
116
+ )`,args:[e,r,t,e,a,t,d,l]},{sql:`UPDATE billing_events
124
117
  SET status = 'applying'
125
118
  WHERE idempotency_key = ?
126
119
  AND user_id = ?
127
120
  AND billing_class = ?
128
121
  AND source_surface = ?
129
122
  AND status = 'settling'
130
- AND changes() = 1`,args:[a,e,c,l]},{sql:`WITH ordered AS (
123
+ AND changes() = 1`,args:[a,t,d,l]},{sql:`WITH ordered AS (
131
124
  SELECT a.lot_id,
132
125
  a.amount_mc,
133
126
  a.expires_at,
@@ -149,7 +142,7 @@ import{a as u}from"./chunk-WNUXMPVX.js";var L="2026-06-26 21:58:03";var W="+3 mo
149
142
  SELECT lot_id FROM refunds
150
143
  WHERE refund_mc > 0 AND expires_at > datetime('now')
151
144
  )
152
- AND EXISTS (SELECT 1 FROM billing_events WHERE idempotency_key = ? AND status = 'applying')`,args:[t,r,a]},{sql:`WITH ordered AS (
145
+ AND EXISTS (SELECT 1 FROM billing_events WHERE idempotency_key = ? AND status = 'applying')`,args:[e,r,a]},{sql:`WITH ordered AS (
153
146
  SELECT a.amount_mc,
154
147
  a.expires_at,
155
148
  COALESCE(SUM(a.amount_mc) OVER (
@@ -182,19 +175,19 @@ import{a as u}from"./chunk-WNUXMPVX.js";var L="2026-06-26 21:58:03";var W="+3 mo
182
175
  ?,
183
176
  ?
184
177
  FROM credited
185
- WHERE refund_mc > 0`,args:[t,r,t,a,n,i]},{sql:`UPDATE billing_events
178
+ WHERE refund_mc > 0`,args:[e,r,e,a,i,n]},{sql:`UPDATE billing_events
186
179
  SET status = 'settled', settled_at = datetime('now')
187
180
  WHERE idempotency_key = ?
188
- AND status = 'applying'`,args:[a]},...s.after],"write")}catch(I){if(h(I))throw new _;try{if(!await s.current(o))throw new _;let N=await m();if(N)return N}catch(N){if(N instanceof _)throw N}throw I}let S=await m();if(!S)throw new Error("idempotent debit settlement did not reach a durable settled state");return{...S,duplicate:E[s.before.length]?.rowsAffected===0}}async function Z(e,t){let{hold:r}=t,n=y(r);if(r.userId!==e.userId||!e.runId||!e.token||!t.label||t.label.length>200||!t.refundOperation||!t.sourceSurface||!t.tool||!t.jobId)throw new b;let i=`EXISTS (SELECT 1 FROM operation_runs r JOIN operation_executions e ON e.run_id=r.id
181
+ AND status = 'applying'`,args:[a]},...s.after],"write")}catch(L){if(W(L))throw new _;try{if(!await s.current(o))throw new _;let g=await m();if(g)return g}catch(g){if(g instanceof _)throw g}throw L}let S=await m();if(!S)throw new Error("idempotent debit settlement did not reach a durable settled state");return{...S,duplicate:E[s.before.length]?.rowsAffected===0}}async function Y(t,e){let{hold:r}=e,i=I(r);if(r.userId!==t.userId||!t.runId||!t.token||!e.label||e.label.length>200||!e.refundOperation||!e.sourceSurface||!e.tool||!e.jobId)throw new N;let n=`EXISTS (SELECT 1 FROM operation_runs r JOIN operation_executions e ON e.run_id=r.id
189
182
  WHERE r.id=? AND r.user_id=? AND r.tool=? AND r.job_id=? AND r.status='running'
190
183
  AND json_extract(r.normalized_flags_json,'$._storeGateRequired') IS 1
191
- AND e.claim_token=? AND e.phase='claimed' AND e.expires_at_ms > ${D})`,l=[e.runId,e.userId,t.tool,t.jobId,e.token],d=u(),o;try{await d.batch([{sql:`INSERT OR IGNORE INTO operation_debit_plans
184
+ AND e.claim_token=? AND e.phase='claimed' AND e.expires_at_ms > ${R})`,l=[t.runId,t.userId,e.tool,e.jobId,t.token],c=u(),o;try{await c.batch([{sql:`INSERT OR IGNORE INTO operation_debit_plans
192
185
  (run_id,label,debit_key,amount_mc,operation,description,refund_operation,source_surface)
193
- SELECT ?,?,?,?,?,?,?,? WHERE ${i} AND (${n.sql})`,args:[e.runId,t.label,r.key,r.amountMc,r.operation,r.description,t.refundOperation,t.sourceSurface,...l,...n.args]},{sql:`INSERT OR IGNORE INTO operation_billing_links (run_id,billing_table,billing_key,relation,amount_mc)
186
+ SELECT ?,?,?,?,?,?,?,? WHERE ${n} AND (${i.sql})`,args:[t.runId,e.label,r.key,r.amountMc,r.operation,r.description,e.refundOperation,e.sourceSurface,...l,...i.args]},{sql:`INSERT OR IGNORE INTO operation_billing_links (run_id,billing_table,billing_key,relation,amount_mc)
194
187
  SELECT p.run_id,'billing_debits',p.debit_key,'hold',p.amount_mc FROM operation_debit_plans p
195
188
  WHERE p.run_id=? AND p.label=? AND p.debit_key=? AND p.amount_mc=? AND p.operation=? AND p.description=?
196
- AND p.refund_operation=? AND p.source_surface=? AND ${i} AND (${n.sql})`,args:[e.runId,t.label,r.key,r.amountMc,r.operation,r.description,t.refundOperation,t.sourceSurface,...l,...n.args]}],"write")}catch(c){o=c}let s;try{s=(await d.execute({sql:`SELECT p.* FROM operation_debit_plans p
197
- WHERE p.run_id=? AND p.label=? AND ${i} AND (${n.sql})`,args:[e.runId,t.label,...l,...n.args]})).rows[0]}catch(c){throw o??c}if(!s)throw o||new _;let a=M(s);if(a.key!==r.key||a.amountMc!==r.amountMc||a.operation!==r.operation||a.description!==r.description||a.refundOperation!==t.refundOperation||a.sourceSurface!==t.sourceSurface)throw new b;return a}async function k(e,t,r){if(!Number.isSafeInteger(e)||e<=0||!t||!r)throw new _;let n=u(),i=`debit-settlement:${O("sha256").update(t).digest("hex")}`,l="wallet_hold_settlement",o=(await n.execute({sql:`SELECT e.user_id,
189
+ AND p.refund_operation=? AND p.source_surface=? AND ${n} AND (${i.sql})`,args:[t.runId,e.label,r.key,r.amountMc,r.operation,r.description,e.refundOperation,e.sourceSurface,...l,...i.args]}],"write")}catch(d){o=d}let s;try{s=(await c.execute({sql:`SELECT p.* FROM operation_debit_plans p
190
+ WHERE p.run_id=? AND p.label=? AND ${n} AND (${i.sql})`,args:[t.runId,e.label,...l,...i.args]})).rows[0]}catch(d){throw o??d}if(!s)throw o||new _;let a=M(s);if(a.key!==r.key||a.amountMc!==r.amountMc||a.operation!==r.operation||a.description!==r.description||a.refundOperation!==e.refundOperation||a.sourceSurface!==e.sourceSurface)throw new N;return a}async function x(t,e,r){if(!Number.isSafeInteger(t)||t<=0||!e||!r)throw new _;let i=u(),n=`debit-settlement:${T("sha256").update(e).digest("hex")}`,l="wallet_hold_settlement",o=(await i.execute({sql:`SELECT e.user_id,
198
191
  e.status,
199
192
  e.amount_mc AS final_amount_mc,
200
193
  e.billing_class,
@@ -206,7 +199,7 @@ import{a as u}from"./chunk-WNUXMPVX.js";var L="2026-06-26 21:58:03";var W="+3 mo
206
199
  WHERE e.idempotency_key = ?
207
200
  AND d.user_id = e.user_id
208
201
  AND d.status = 'applied'
209
- LIMIT 1`,args:[t,i]})).rows[0];if(!o)return null;if(Number(o.user_id)!==e||String(o.billing_class)!==l||String(o.source_surface)!==r)throw new Error("idempotent debit settlement key conflicts with another settlement");if(String(o.status)!=="settled")return null;let s=Number(o.held_amount_mc),a=Number(o.final_amount_mc);if(!Number.isSafeInteger(s)||!Number.isSafeInteger(a)||a<0||a>s)throw new Error("idempotent debit settlement receipt is invalid");let c=s-a,p=await n.execute({sql:`WITH ordered AS (
202
+ LIMIT 1`,args:[e,n]})).rows[0];if(!o)return null;if(Number(o.user_id)!==t||String(o.billing_class)!==l||String(o.source_surface)!==r)throw new Error("idempotent debit settlement key conflicts with another settlement");if(String(o.status)!=="settled")return null;let s=Number(o.held_amount_mc),a=Number(o.final_amount_mc);if(!Number.isSafeInteger(s)||!Number.isSafeInteger(a)||a<0||a>s)throw new Error("idempotent debit settlement receipt is invalid");let d=s-a,p=await i.execute({sql:`WITH ordered AS (
210
203
  SELECT a.amount_mc,
211
204
  a.expires_at,
212
205
  COALESCE(SUM(a.amount_mc) OVER (
@@ -222,4 +215,4 @@ import{a as u}from"./chunk-WNUXMPVX.js";var L="2026-06-26 21:58:03";var W="+3 mo
222
215
  )
223
216
  SELECT (SELECT COUNT(*) FROM ordered) AS allocation_count,
224
217
  COALESCE(SUM(CASE WHEN expires_at > ? THEN refund_mc ELSE 0 END), 0) AS credited_refund_mc
225
- FROM refunds`,args:[t,a,String(o.settled_at)]}),m=Number(p.rows[0]?.allocation_count??0)>0?Number(p.rows[0]?.credited_refund_mc??0):0,E=await n.execute({sql:"SELECT balance_mc FROM users WHERE id = ?",args:[e]});return{balance_mc:Number(E.rows[0]?.balance_mc??0),final_amount_mc:a,refund_mc:m,expired_refund_mc:c-m,duplicate:!0}}export{W as a,T as b,y as c,v as d,B as e,J as f,V as g,Y as h,z as i,Z as j,k};
218
+ FROM refunds`,args:[e,a,String(o.settled_at)]}),m=Number(p.rows[0]?.allocation_count??0)>0?Number(p.rows[0]?.credited_refund_mc??0):0,E=await i.execute({sql:"SELECT balance_mc FROM users WHERE id = ?",args:[t]});return{balance_mc:Number(E.rows[0]?.balance_mc??0),final_amount_mc:a,refund_mc:m,expired_refund_mc:d-m,duplicate:!0}}export{k as a,O as b,X as c,B as d,j as e,J as f,V as g,Y as h,x as i};
@@ -175,7 +175,7 @@ import{i as j,m as T}from"./chunk-KXJCGV3H.js";import{m as f,q as b}from"./chunk
175
175
  public_error_json = CASE WHEN json_valid(public_error_json) THEN json_set(public_error_json, '$.charge_status', ?) ELSE public_error_json END,
176
176
  updated_at = datetime('now')
177
177
  WHERE id = ? AND user_id = ? AND execution_generation = ? AND status = ?
178
- AND billed_mc IS NULL AND settlement_plan_json = ?`,args:[e.netChargeMc,JSON.stringify(e),n,t.jobId,t.userId,t.generation,t.status,JSON.stringify(t)]})}async function jt(t,e,n,r,a,s=0){let{settleExtractJobCharge:i}=await import("./settlement-6CCE2PDH.js");return i(t,e,n,r,a,s)}var B=25;async function*Tt(t){let e=o(),n=0;for(;;){let r=await e.execute({sql:`SELECT rowid AS cursor_id, page
178
+ AND billed_mc IS NULL AND settlement_plan_json = ?`,args:[e.netChargeMc,JSON.stringify(e),n,t.jobId,t.userId,t.generation,t.status,JSON.stringify(t)]})}async function jt(t,e,n,r,a,s=0){let{settleExtractJobCharge:i}=await import("./settlement-6CS4JZTY.js");return i(t,e,n,r,a,s)}var B=25;async function*Tt(t){let e=o(),n=0;for(;;){let r=await e.execute({sql:`SELECT rowid AS cursor_id, page
179
179
  FROM site_extract_pages
180
180
  WHERE job_id = ? AND rowid > ?
181
181
  ORDER BY rowid
@@ -1,4 +1,4 @@
1
- import{a as D,e as A,f as T,g as C,h as w,i as p}from"./chunk-R5LJL6IR.js";import{B as k,C as x,D as v,b as E,g,x as I}from"./chunk-6SNOUSSZ.js";import{a as P,b as S}from"./chunk-ZPQNY5TI.js";import{a as _}from"./chunk-WNUXMPVX.js";import{randomUUID as O}from"crypto";var L=class{constructor(t,r,i){this.userId=t;this.sourceSurface=r;this.fence=i;if(i&&i.userId!==t)throw Error("Billing scope principal differs from execution claim")}userId;sourceSurface;fence;identity=`debit:${O()}`;charges=new Map;pending=new Map;compensating=new Set;closing=!1;async debit(t,r,i,c,a){if(this.closing||this.compensating.has(t))throw Error("Billing scope is compensating; new charges are forbidden");let s=this.charges.get(t);if(s?.outcome==="pending")throw Error("Named debit outcome is pending; reconcile before retrying");if(s?.outcome==="funded"&&s.amountMc!==r)throw Error("An applied debit amount cannot change");let o={key:s?.key??`${this.identity}:${t}`,amountMc:r,operation:i,description:c,refundOperation:a,outcome:"pending"};if(s&&(s.operation!==i||s.description!==c||s.refundOperation!==a))throw Error("Named charge identity cannot change");this.charges.set(t,o);let u=(async()=>{if(this.fence){let f=await A(this.fence,{label:t,amountMc:r,operation:i,description:c,refundOperation:a,sourceSurface:this.sourceSurface});if(o.key=f.key,this.closing||this.compensating.has(t))throw Error("Billing scope began compensating while planning")}return this.fence?w(this.userId,r,i,c,o.key,this.fence):w(this.userId,r,i,c,o.key)})();this.pending.set(t,u);try{let f=await u;return o.outcome=f.ok?"funded":"unfunded",{...f,billingKey:o.key}}finally{this.pending.delete(t)}}async compensate(t){this.compensating.add(t),await this.pending.get(t)?.catch(()=>{});try{this.fence&&await this.loadDurablePlans();let r=this.charges.get(t);if(!r)return"not_charged";let i=await C(this.userId,r.key);return i?i.amountMc!==r.amountMc||i.operation!==r.operation||i.description!==r.description?"refund_pending":i.status==="claimed"?this.fence?.mode==="compensate"||r.outcome==="unfunded"?"not_charged":"refund_pending":i.status!=="applied"?"refund_pending":(this.fence?await p(this.userId,r.key,0,r.refundOperation,`${this.sourceSurface} failed`,this.sourceSurface,this.fence):await p(this.userId,r.key,0,r.refundOperation,`${this.sourceSurface} failed`,this.sourceSurface)).final_amount_mc===0?"refunded":"refund_pending":this.fence?.mode==="compensate"||r.outcome==="unfunded"?"not_charged":"refund_pending"}catch{return"refund_pending"}}async compensateAll(){if(this.closing=!0,await Promise.allSettled([...this.pending.values()]),this.fence)try{await this.loadDurablePlans()}catch{return"refund_pending"}let t=await Promise.all([...this.charges.keys()].map(r=>this.compensate(r)));return t.includes("refund_pending")?"refund_pending":t.includes("refunded")?"refunded":"not_charged"}async loadDurablePlans(){if(this.fence)for(let t of await T(this.fence)){let r=this.charges.get(t.label);if(t.sourceSurface!==this.sourceSurface)throw Error("Persisted billing source differs from scope");this.charges.set(t.label,{key:t.key,amountMc:t.amountMc,operation:t.operation,description:t.description,refundOperation:t.refundOperation,outcome:r?.key===t.key?r.outcome:"pending"})}}};async function H(e){if(!Number.isSafeInteger(e.userId)||e.userId<=0||!Number.isSafeInteger(e.refundMc)||e.refundMc<0)throw Error("invalid_legacy_refund");await _().batch([e.admission,{sql:`INSERT INTO credit_lots (user_id, amount_mc, remaining_mc, source, expires_at)
1
+ import{a as D,c as A,d as T,e as C,f as w,g as p}from"./chunk-6BD75VKS.js";import{B as k,C as x,D as v,b as E,g,x as I}from"./chunk-7WPCGRD7.js";import{e as P,f as S}from"./chunk-5LYINW7Z.js";import{a as _}from"./chunk-WNUXMPVX.js";import{randomUUID as O}from"crypto";var L=class{constructor(t,r,i){this.userId=t;this.sourceSurface=r;this.fence=i;if(i&&i.userId!==t)throw Error("Billing scope principal differs from execution claim")}userId;sourceSurface;fence;identity=`debit:${O()}`;charges=new Map;pending=new Map;compensating=new Set;closing=!1;async debit(t,r,i,c,a){if(this.closing||this.compensating.has(t))throw Error("Billing scope is compensating; new charges are forbidden");let s=this.charges.get(t);if(s?.outcome==="pending")throw Error("Named debit outcome is pending; reconcile before retrying");if(s?.outcome==="funded"&&s.amountMc!==r)throw Error("An applied debit amount cannot change");let o={key:s?.key??`${this.identity}:${t}`,amountMc:r,operation:i,description:c,refundOperation:a,outcome:"pending"};if(s&&(s.operation!==i||s.description!==c||s.refundOperation!==a))throw Error("Named charge identity cannot change");this.charges.set(t,o);let u=(async()=>{if(this.fence){let f=await A(this.fence,{label:t,amountMc:r,operation:i,description:c,refundOperation:a,sourceSurface:this.sourceSurface});if(o.key=f.key,this.closing||this.compensating.has(t))throw Error("Billing scope began compensating while planning")}return this.fence?w(this.userId,r,i,c,o.key,this.fence):w(this.userId,r,i,c,o.key)})();this.pending.set(t,u);try{let f=await u;return o.outcome=f.ok?"funded":"unfunded",{...f,billingKey:o.key}}finally{this.pending.delete(t)}}async compensate(t){this.compensating.add(t),await this.pending.get(t)?.catch(()=>{});try{this.fence&&await this.loadDurablePlans();let r=this.charges.get(t);if(!r)return"not_charged";let i=await C(this.userId,r.key);return i?i.amountMc!==r.amountMc||i.operation!==r.operation||i.description!==r.description?"refund_pending":i.status==="claimed"?this.fence?.mode==="compensate"||r.outcome==="unfunded"?"not_charged":"refund_pending":i.status!=="applied"?"refund_pending":(this.fence?await p(this.userId,r.key,0,r.refundOperation,`${this.sourceSurface} failed`,this.sourceSurface,this.fence):await p(this.userId,r.key,0,r.refundOperation,`${this.sourceSurface} failed`,this.sourceSurface)).final_amount_mc===0?"refunded":"refund_pending":this.fence?.mode==="compensate"||r.outcome==="unfunded"?"not_charged":"refund_pending"}catch{return"refund_pending"}}async compensateAll(){if(this.closing=!0,await Promise.allSettled([...this.pending.values()]),this.fence)try{await this.loadDurablePlans()}catch{return"refund_pending"}let t=await Promise.all([...this.charges.keys()].map(r=>this.compensate(r)));return t.includes("refund_pending")?"refund_pending":t.includes("refunded")?"refunded":"not_charged"}async loadDurablePlans(){if(this.fence)for(let t of await T(this.fence)){let r=this.charges.get(t.label);if(t.sourceSurface!==this.sourceSurface)throw Error("Persisted billing source differs from scope");this.charges.set(t.label,{key:t.key,amountMc:t.amountMc,operation:t.operation,description:t.description,refundOperation:t.refundOperation,outcome:r?.key===t.key?r.outcome:"pending"})}}};async function H(e){if(!Number.isSafeInteger(e.userId)||e.userId<=0||!Number.isSafeInteger(e.refundMc)||e.refundMc<0)throw Error("invalid_legacy_refund");await _().batch([e.admission,{sql:`INSERT INTO credit_lots (user_id, amount_mc, remaining_mc, source, expires_at)
2
2
  SELECT ?, ?, ?, ?, ? WHERE changes() = 1 AND ? > 0 AND datetime(?) > datetime('now')`,args:[e.userId,e.refundMc,e.refundMc,e.operation,e.expiresAt,e.refundMc,e.expiresAt]},{sql:"UPDATE users SET balance_mc = balance_mc + ? WHERE id = ? AND ? > 0 AND changes() = 1",args:[e.refundMc,e.userId,e.refundMc]},{sql:`INSERT INTO ledger (user_id, amount_mc, operation, description)
3
3
  SELECT ?, ?, ?, ? WHERE ? > 0 AND changes() = 1`,args:[e.userId,e.refundMc,e.operation,e.description,e.refundMc]},e.acknowledgment],"write")}function J(e){return e.status==="complete"||e.status==="partial"||e.status==="failed"}function y(e,t,r){return e.userId===t&&(e.executionGeneration??0)===r&&J(e)}function W(e){let t=e.options.xraySetupReceipt;return e.options.heldMc===0&&e.options.debitKey==null&&t?.billingClass===E&&t.consumesMcpScraperCredits===!1&&t.heldMc===0&&t.billedMc===0}function b(e,t){if(!e||!y(e,t.userId,t.generation)||JSON.stringify(e.settlementPlan)!==JSON.stringify(t))return null;let r=e.settlementReceipt;return!r||r.jobId!==t.jobId||r.userId!==t.userId||r.generation!==t.generation||e.billedMc!==r.netChargeMc?null:r}async function Q(e,t,r,i,c,a=0){let s=await g(e);if(!s||!y(s,t,a))throw Error("extract_settlement_identity_or_terminal_conflict");if(s.billedMc!=null)return s.settlementReceipt??null;let o=Number(s.options.heldMc??0);if(![o,r,i].every(d=>Number.isSafeInteger(d)&&d>=0)||r+i!==o)throw Error("extract_settlement_amount_conflict");let u=String(s.options.billingClass??"credits");if(u===E&&!W(s))throw Error("xray_extract_zero_charge_finalization_rejected");let f={version:1,jobId:e,userId:t,generation:a,status:s.status,heldMc:o,debitKey:typeof s.options.debitKey=="string"?s.options.debitKey:null,billingClass:u,netChargeMc:i,refundMc:r,reference:c},l;try{l=await k(f)}catch(d){if(l=await g(e).catch(()=>null),!l?.settlementPlan||!y(l,t,a))throw d}if(!l||!y(l,t,a)||!l.settlementPlan)throw Error("extract_settlement_admission_conflict");let n=l.settlementPlan;if(n.jobId!==e||n.userId!==t||n.generation!==a||n.status!==l.status||n.heldMc!==o||n.debitKey!==f.debitKey||n.billingClass!==u)throw Error("extract_settlement_plan_conflict");let N=b(l,n);if(N)return N;let m={version:1,jobId:e,userId:t,generation:a,netChargeMc:n.netChargeMc,refundMc:0,expiredRefundMc:0};try{if(u===E)await x(n,m);else if(n.debitKey){let d=await p(t,n.debitKey,n.netChargeMc,S.EXTRACT_SITE_REFUND,n.reference,"extract_site");m.netChargeMc=d.final_amount_mc,m.refundMc=d.refund_mc,m.expiredRefundMc=d.expired_refund_mc??0,await x(n,m)}else{let h=await _().execute({sql:"SELECT datetime(created_at, ?) AS expires_at FROM site_extract_jobs WHERE id = ?",args:[D,e]}),R=[e,t,a,n.status,JSON.stringify(n)];await H({userId:t,refundMc:n.refundMc,expiresAt:String(h.rows[0]?.expires_at),operation:S.EXTRACT_SITE_REFUND,description:n.reference,admission:{sql:`UPDATE site_extract_jobs SET billed_mc = -1
4
4
  WHERE id = ? AND user_id = ? AND execution_generation = ? AND status = ?
@@ -1 +1 @@
1
- import{a as t,d as o,e as _,f as l}from"./chunk-ZPQNY5TI.js";import{a as g}from"./chunk-WP3QS4CJ.js";var F=t.browser_minute/6e4;function de(e){return Math.round(e*F)}var pe=1e3,ue=_,$=t.serp_headful/o,me=t.paa_base/o,ge=t.paa/o,be=t.page_scrape/o,V={billingMode:"credits",chargeEvent:"accepted_write",validationCredits:0,create:{credits:t.listing_create/o,mc:t.listing_create},edit:{credits:t.listing_edit/o,mc:t.listing_edit},surfaces:["local_sourcebook","transparent_commons"],sourcebookAcquisitionIncluded:!0},H=2e6,K=3,v=1e4,y=1e9,j=75,fe=j*o,Q=15e3,Ce=Q/v,Ee=5e3,W="2026-08-03.connected-usage-v3",S=15e3,Re=S*o,I=2,A=2,x=5,N=I*o,k=A*o,M=x*o,he={schemaVersion:2,ratePolicyVersion:W,effectiveAt:"2026-08-03T00:00:00.000Z",provider:"nango",entitlement:"paid_plan_add_on",connection:{billingMode:"flat_recurring_credits",amountCredits:S,interval:"month",unit:"active_connection",proration:"none"},usage:{billingMode:"credits",settlementMode:"authoritative_receipt",rounding:"aggregate_then_ceil_to_mc",functionRun:{credits:I,mc:N,unit:"per_function_run"},proxyRequest:{credits:A,mc:k,unit:"per_proxy_request"},compute:{creditsPerSecond:x,mcPerSecond:M,sourceUnit:"millisecond",unit:"per_compute_second",formula:"ceil(computeMilliseconds * mcPerSecond / 1000)"}}};function b(e,r){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${r} must be a non-negative safe integer`);return BigInt(e)}function p(e){if(e>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("connected usage charge exceeds the safe integer range");return Number(e)}function ye(e){let r=b(e.functionRuns,"functionRuns"),a=b(e.proxyRequests,"proxyRequests"),s=b(e.computeMilliseconds,"computeMilliseconds"),n=r*BigInt(N),c=a*BigInt(k),d=s*BigInt(M),m=d===0n?0n:(d+999n)/1000n,h=n+c+m;return{functionRunMc:p(n),proxyRequestMc:p(c),computeMc:p(m),amountMc:p(h),credits:p(h)/o}}function Te(e,r){if(!Number.isFinite(e)||e<0)throw new Error("costUsd must be a finite non-negative number");if(!Number.isInteger(r)||r<0)throw new Error("markupBps must be a non-negative integer");let s=BigInt(Math.round(e*y))*BigInt(r)*BigInt(H),n=BigInt(y)*BigInt(v)*BigInt(K),c=s===0n?0n:(s+n-1n)/n;if(c>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("calculated mc exceeds the safe integer range");return Number(c)}var Z=[{key:"serp",label:"SERP search",aliases:["search_serp","serp","google search","organic results"],credits:_,unit:"per page (ordinary search)",notes:`search_serp light mode returns one page of organic positions, URLs, titles, and descriptions by default. Unfiltered one-page full mode returns available same-page SERP features. Either mode requests two pages only when pages:2 is explicit. Unfiltered light searches cost ${_} credits per delivered page, or ${l} credits per delivered page if the backup supplies the result. One-page full searches cost ${l} credits. Setting recency to week or month applies Google's date filter through a managed browser and returns organic results only. It costs ${l} credits for one page; filtered pages:2 follows Google's page-two control and costs ${l*2} credits when both pages are delivered. Unfiltered searches use the managed browser only as the last backup. Unfiltered two-page full searches return organic results only for ${_*2} credits, with rich features marked unsupported. If only page 1 is delivered, the search is marked partial and billed for one delivered page. A temporary ${l}-credit-per-requested-page hold is settled to the delivered rate. Location, language, device, and optional module fields do not change ordinary searches. Saved browser identity and capture_serp_snapshot searches retain their ${$}-credit base price; optional page snapshots add ${i(t.page_scrape)} credit per attempted URL.`},{key:"paa",label:"PAA harvest",aliases:["harvest_paa","paa","people also ask","questions"],credits:i(t.paa),unit:`per question (+${i(t.paa_base)} credit base)`,notes:`Returns original-query PAA questions with answers and sources plus organic results and Google entity IDs. Optional same-page SERP modules are flag-controlled. Billed ${i(t.paa_base)} credit base + ${i(t.paa)} per question actually returned (unused estimate refunded).`},{key:"page_scrape",label:"Page crawl / extract",aliases:["extract_url","extract_site","page scrape","url scrape","single page","site crawl"],credits:i(t.page_scrape),unit:"per page",notes:"Applies to both single-URL extraction and per-page site crawls."},{key:"listing_create",label:"Directory or wiki listing creation",aliases:["local-sourcebook-capture","commons_submit_entity","directory listing","wiki listing"],credits:i(t.listing_create),unit:"per new listing",notes:"Fixed total price for a new Local Sourcebook directory listing or Transparent Commons wiki entity. Sourcebook acquisition is included."},{key:"listing_edit",label:"Directory or wiki listing edit",aliases:["local_sourcebook_refresh","commons_submit_entity","listing refresh","wiki edit"],credits:i(t.listing_edit),unit:"per existing listing revision",notes:"Fixed total price for refreshing an existing Local Sourcebook listing or revising an existing Transparent Commons entity."},{key:"url_map",label:"Site URL mapping",aliases:["map_site_urls","url map","site map","crawl urls"],credits:i(t.url_map),unit:"per mapping operation",notes:"Flat rate for the full /map-urls call regardless of URL count discovered."},{key:"yt_channel",label:"YouTube search / channel harvest",aliases:["youtube_harvest","youtube search","youtube channel","yt_channel"],credits:i(t.yt_channel),unit:"per call"},{key:"yt_transcription",label:"YouTube transcription",aliases:["youtube_transcribe","youtube transcript","transcription","yt_transcription"],credits:i(2e4),unit:"base + 2/min of video",notes:"Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},{key:"fb_ad",label:"Facebook search / ad lookup",aliases:["facebook_page_intel","facebook_ad_search","facebook_ad","facebook ads","fb ads"],credits:i(t.fb_ad),unit:"per call"},{key:"maps_search",label:"Maps business search",aliases:["maps_search","google maps search","gmb search","gbp search","business profiles"],credits:i(t.maps_search),unit:"per search",notes:"Returns up to 50 Google Maps business/profile candidates. Use maps_place_intel to hydrate selected businesses."},{key:"maps_place",label:"Maps business lookup",aliases:["maps_place_intel","google maps","maps place","place intel"],credits:i(t.maps_place),unit:"per business",notes:"Maps place runs reserve the 60-credit base plus the declared review maximum before browsing. Completed runs settle to the base plus unique saved reviews; stopped attempts are refunded."},{key:"maps_review",label:"Maps review",aliases:["maps_reviews","google reviews","review cards","reviews"],credits:i(t.maps_review),unit:"per review card",notes:"One credit per unique saved review on a completed Maps place run. The declared maximum is held before browsing; unused credits are refunded."},{key:"fb_search",label:"Facebook ad library search",aliases:["facebook_search","fb_search","fb ad search"],credits:i(t.fb_search),unit:"per search",notes:"Browser automation to search Facebook Ads Library by keyword."},{key:"google_ads_search",label:"Google Ads Transparency search",aliases:["google_ads_search","google ads search","ads transparency search"],credits:i(t.google_ads_search),unit:"per search",notes:"Browser automation to find advertisers in Google Ads Transparency Center by domain or name."},{key:"google_ads_intel",label:"Google Ads Transparency advertiser intel",aliases:["google_ads_page_intel","google ads intel","ads transparency intel"],credits:i(t.google_ads_intel),unit:"per call",notes:"Lists and hydrates an advertiser's creatives with image URLs and video references."},{key:"google_ads_transcribe",label:"Google ad video transcription",aliases:["google_ads_transcribe","google ad transcript"],credits:i(2e4),unit:"base + 2/min of video",notes:"Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},{key:"fb_transcribe",label:"Facebook video / ad transcription",aliases:["facebook_transcribe","facebook_video_transcribe","fb_transcribe","fb ad transcript"],credits:i(2e4),unit:"base + 2/min of video",notes:"Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},{key:"fb_reels_inventory",label:"Facebook Reel URL inventory",aliases:["facebook_reels_inventory","facebook reels","facebook reel urls","facebook profile reels"],credits:i(t.fb_reels_inventory),unit:"per profile scan",notes:"Collects canonical Reel URLs from a Facebook profile. Logged-out scans are capped at 60 URLs; saved browser profiles can request larger inventories."},{key:"tiktok_transcribe",label:"TikTok video transcription",aliases:["tiktok_video_transcribe","tiktok transcript"],credits:i(2e4),unit:"base + 2/min of video",notes:"Transcribes a public TikTok video from its playback media. Flat 200-credit base plus 2 credits per minute, reconciled after transcription."},{key:"instagram_profile",label:"Instagram profile content discovery",aliases:["instagram_profile_content","instagram profile","instagram content list","ig profile"],credits:i(t.instagram_profile),unit:"per profile scan",notes:"Browser extraction of public Instagram profile grid links. Complete history may require a logged-in profile."},{key:"instagram_media",label:"Instagram media download",aliases:["instagram_media_download","instagram reel download","instagram post download","ig media"],credits:i(t.instagram_media),unit:"per post or reel",notes:"Extracts post text, image URLs, and reel audio/video tracks, with local downloads when the server can write files."},{key:"instagram_transcribe",label:"Instagram media transcription",aliases:["instagram transcript","instagram reel transcript","ig transcribe"],credits:i(2e4),unit:"base + 2/min of video",notes:"Whisper transcription of selected Instagram audio/video media. Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},{key:"browser_minute",label:"Interactive browser session",aliases:["browser_open","browser agent","browser_agent","live browser","browse","browser control","interactive browser"],credits:i(t.browser_minute),unit:"per minute of use",notes:"Metered per minute of use for the whole time the browser session is open. Close the session to stop the meter; abandoned sessions are auto-closed after a short idle window."},{key:"reddit_thread",label:"Reddit thread base lookup",aliases:["reddit","reddit_thread","reddit comments","subreddit","reddit post"],credits:i(t.reddit_thread),unit:"per thread",notes:"Base lookup for the post itself. Comments billed separately per comment at reddit_comment rate. Refunded if the thread cannot be retrieved."},{key:"reddit_comment",label:"Reddit comment",aliases:["reddit_comment","reddit comments"],credits:i(t.reddit_comment),unit:"per comment",notes:"Charged per comment actually extracted, billed down automatically if the balance runs out mid-thread."},{key:"video_analysis",label:"Video breakdown (frame-by-frame + transcript)",aliases:["video_frame_analysis","video breakdown","video analysis","analyze video"],credits:i(t.video_analysis),unit:"per 120 frames (max 480)",notes:`Full video breakdown: samples frames across a video up to 60 minutes, analyzes visuals and audio, then produces a summary, pacing, topic outline, key points, hook, style, and replication guidance. Reserves ${i(t.video_analysis)} Credits per requested 120-frame tier, up to 480 frames. Unused frame tiers and failed-run frame charges are refunded. Incurred analysis-model usage is billed separately, including usage before a failure; terminal status checks settle the original run.`},{key:"trustpilot_reviews",label:"Trustpilot review harvest",aliases:["trustpilot_reviews","trustpilot","trustpilot reviews"],credits:i(t.trustpilot_reviews),unit:"per call",notes:"Base lookup. Reviews billed separately per card at trustpilot_review rate. Refunded if no reviews are found."},{key:"trustpilot_review",label:"Trustpilot review card",aliases:["trustpilot_review","trustpilot card"],credits:i(t.trustpilot_review),unit:"per review card",notes:"Charged per review actually extracted, billed down automatically if the balance runs out mid-page."},{key:"g2_reviews",label:"G2 review harvest",aliases:["g2_reviews","g2","g2 reviews"],credits:i(t.g2_reviews),unit:"per call",notes:"Base lookup. Reviews billed separately per card at g2_review rate. Refunded if no reviews are found."},{key:"g2_review",label:"G2 review card",aliases:["g2_review","g2 card"],credits:i(t.g2_review),unit:"per review card",notes:"Charged per review actually extracted (each card carries up to 3 Q&A sections), billed down automatically if the balance runs out mid-page."},{key:"diff_page",label:"Page change check",aliases:["diff_page","page diff","change detection"],credits:i(t.diff_page),unit:"per check",notes:"Same cost as a single page extract \u2014 one scrape is performed per check, then compared against your last stored snapshot for that URL."}],ve="price_1Ta1NRS8aAcsk3TGwsRnYbix";function w(e){return e.billing_interval??"month"}function P(e){return e.billed_usd??e.monthly_usd}function O(e){return e.credits_mc/o}var u={price_1TmiHRS8aAcsk3TGwmSNfNIa:{tier:"starter",label:"Starter",price_id:"price_1TmiHRS8aAcsk3TGwmSNfNIa",monthly_usd:12,credits_mc:8e6,concurrency:3,intro_coupon:"mcp-starter-1dollar-intro-12"},price_1TrgihS8aAcsk3TG5cglrq4D:{tier:"growth",label:"Growth",price_id:"price_1TrgihS8aAcsk3TG5cglrq4D",monthly_usd:40,credits_mc:26666700,concurrency:10,intro_coupon:null},price_1TrgihS8aAcsk3TG4HnG4gbY:{tier:"scale",label:"Scale",price_id:"price_1TrgihS8aAcsk3TG4HnG4gbY",monthly_usd:100,credits_mc:8e7,concurrency:20,intro_coupon:null},price_1TwqIVS8aAcsk3TG0FE3ddDM:{tier:"sonic",label:"Sonic Annual",price_id:"price_1TwqIVS8aAcsk3TG0FE3ddDM",monthly_usd:25,billed_usd:300,credits_mc:25e7,concurrency:3,intro_coupon:null,billing_interval:"year",credits_never_expire:!0,private_offer:!0},price_1TwqIWS8aAcsk3TGbGbtlLak:{tier:"sonic-memory",label:"Sonic Annual + Memory Pro",price_id:"price_1TwqIWS8aAcsk3TGbGbtlLak",monthly_usd:34.5,billed_usd:414,credits_mc:25e7,concurrency:3,intro_coupon:null,billing_interval:"year",credits_never_expire:!0,includes_memory:!0,private_offer:!0}},C=Object.fromEntries(Object.values(u).map(e=>[e.tier,e])),E={sonic:{slug:"sonic",label:"Sonic annual partner offer",headline:"A full year of MCP Scraper, with Credits that never expire.",tier_keys:["sonic","sonic-memory"]}};function X(e){let r=Object.values(E).find(a=>a.tier_keys.includes(e));return r?`/${r.slug}/claim`:null}function z(e){return e?Object.values(E).find(r=>r.tier_keys.includes(e))??null:null}function Se(e,r){let a=z(e);return a?!a.tier_keys.includes(r):!1}function Ie(e){if(!e)return null;let r=C[e];return r?{tier:r.tier,label:r.label,amount_usd:P(r),interval:w(r),monthly_equivalent_usd:r.monthly_usd,credits_per_interval:O(r),concurrency:r.concurrency,credits_never_expire:!!r.credits_never_expire,includes_memory:!!r.includes_memory,private_offer:!!r.private_offer,offer_claim_path:X(r.tier)}:null}function Ae(e){let r=E[e];if(!r)return null;let a=r.tier_keys.map(s=>C[s]).filter(s=>!!s).map(s=>({tier:s.tier,label:s.label,amount_usd:P(s),interval:w(s),monthly_equivalent_usd:s.monthly_usd,credits:O(s),credits_never_expire:!!s.credits_never_expire,includes_memory:!!s.includes_memory,concurrency:s.concurrency}));return a.length?{slug:r.slug,label:r.label,headline:r.headline,options:a}:null}function xe(){let e=C.starter,r=Z.map(({aliases:n,...c})=>({...c,...c.notes?{notes:c.notes.replace(/ via fal\.ai/g,"")}:{}})),a=Object.fromEntries(r.map(n=>[n.key,{credits:n.credits,unit:n.unit,label:n.label,...n.notes?{notes:n.notes}:{}}])),s=Object.values(u).filter(n=>!n.private_offer).map(n=>({tier:n.tier,label:n.label,monthlyUsd:n.monthly_usd,credits:n.credits_mc/o,concurrency:n.concurrency}));return{...g,operationCosts:a,publicTiers:s,concurrencyPack:{ratePolicyVersion:B,monthlyUsd:U,currency:L,interval:D,billingUnit:"pack",slotsPerPack:f},scaleCreditPack:{ratePolicyVersion:ee,eligibleTier:"scale",incrementUsd:G,creditsPerIncrement:R,maxQuantity:re,currency:"usd",expiryMonths:3},creditsPerDollarStarter:Math.round(i(e.credits_mc)/e.monthly_usd),costs:r,scheduling:g.addons.scheduling,connectedAccounts:g.addons.connectedAccounts,listingWrites:V}}var U=5,L="usd",D="month",f=2,B="2026-08-14.concurrency-pack-v1",J="$5/month for 2 extra browsers",Ne="MCP Scraper browser concurrency pack \u2014 each $5 monthly pack adds 2 browsers.",ke="Billed monthly until canceled. A receipt is emailed after each successful payment.",T="npx -y -p mcp-scraper@latest mcp-scraper-cli billing concurrency checkout",ee="2026-09-21.scale-credit-pack-v1",G=10,R=8e4,Me=R*o,re=100;function we(){let e=process.env.CONCURRENCY_BILLING_URL??"https://mcpscraper.dev/billing";return{product:"Extra browser concurrency pack",rate_policy_version:B,price_label:J,unit_amount_usd:U,currency:L,interval:D,billing_unit:"pack",pack_quantity:1,slots_per_pack:f,extra_slots:f,billing_url:e,terminal_command:T,terminal_command_with_api_key_env:`MCP_SCRAPER_API_KEY=sk_live_your_key ${T}`}}function i(e){return e/o}var te="npx -y -p mcp-scraper@latest mcp-scraper-cli billing subscribe";function ie(){return Object.values(u).filter(e=>!e.private_offer).sort((e,r)=>e.credits_mc-r.credits_mc)}function Pe(e,r){let a=process.env.TOPUP_URL??"https://mcpscraper.dev/billing",s=i(e),n=i(r),c=ie().map(m=>m.tier).join("|"),d=`${te} <${c}>`;return{error:"insufficient_balance",error_code:"insufficient_balance",message:`Insufficient credits. Balance: ${s} credits. This call requires ${n} credits. Credits refresh when your plan renews. Scale customers can buy ${R} Credits per $${G} increment; other customers can move to a larger plan at ${a} (terminal: ${d})`,balance_credits:s,required_credits:n,topup_url:a,upgrade_command:d}}var ne=1e7*1,Oe={price_1TnMSTS8aAcsk3TGBgiwuvqL:{plan:"pro",label:"Pro",price_id:"price_1TnMSTS8aAcsk3TGBgiwuvqL",interval:"month",monthly_usd:19,quota_bytes:5e9},price_1TnMSTS8aAcsk3TGWBVU2agY:{plan:"pro",label:"Pro",price_id:"price_1TnMSTS8aAcsk3TGWBVU2agY",interval:"year",monthly_usd:19,quota_bytes:5e9}},Ue={free:ne,pro:5e9,team:5e10},se=3;var Le=19/se,De=3,Be=1.5,Ge=1.5,Y=2e4,q=200;function Ye(e){let r=Math.max(1,Math.ceil((e||60)/60));return Y+q*r}var qe=Y+q*30,Fe=u.price_1TmiHRS8aAcsk3TGwmSNfNIa.credits_mc/u.price_1TmiHRS8aAcsk3TGwmSNfNIa.monthly_usd;export{de as a,pe as b,ue as c,$ as d,me as e,ge as f,be as g,V as h,y as i,j,fe as k,Q as l,Ce as m,Ee as n,W as o,S as p,Re as q,I as r,A as s,x as t,N as u,he as v,ye as w,Te as x,Z as y,ve as z,w as A,P as B,O as C,u as D,C as E,X as F,z as G,Se as H,Ie as I,Ae as J,xe as K,U as L,f as M,Ne as N,ke as O,G as P,R as Q,Me as R,re as S,we as T,i as U,Pe as V,Oe as W,Ue as X,De as Y,Be as Z,Ge as _,Y as $,q as aa,Ye as ba,qe as ca,Fe as da};
1
+ import{e as t,h as o,i as _,j as l}from"./chunk-5LYINW7Z.js";import{a as g}from"./chunk-WP3QS4CJ.js";var F=t.browser_minute/6e4;function de(e){return Math.round(e*F)}var pe=1e3,ue=_,$=t.serp_headful/o,me=t.paa_base/o,ge=t.paa/o,be=t.page_scrape/o,V={billingMode:"credits",chargeEvent:"accepted_write",validationCredits:0,create:{credits:t.listing_create/o,mc:t.listing_create},edit:{credits:t.listing_edit/o,mc:t.listing_edit},surfaces:["local_sourcebook","transparent_commons"],sourcebookAcquisitionIncluded:!0},H=2e6,K=3,v=1e4,y=1e9,j=75,fe=j*o,Q=15e3,Ce=Q/v,Ee=5e3,W="2026-08-03.connected-usage-v3",S=15e3,Re=S*o,I=2,A=2,x=5,N=I*o,k=A*o,M=x*o,he={schemaVersion:2,ratePolicyVersion:W,effectiveAt:"2026-08-03T00:00:00.000Z",provider:"nango",entitlement:"paid_plan_add_on",connection:{billingMode:"flat_recurring_credits",amountCredits:S,interval:"month",unit:"active_connection",proration:"none"},usage:{billingMode:"credits",settlementMode:"authoritative_receipt",rounding:"aggregate_then_ceil_to_mc",functionRun:{credits:I,mc:N,unit:"per_function_run"},proxyRequest:{credits:A,mc:k,unit:"per_proxy_request"},compute:{creditsPerSecond:x,mcPerSecond:M,sourceUnit:"millisecond",unit:"per_compute_second",formula:"ceil(computeMilliseconds * mcPerSecond / 1000)"}}};function b(e,r){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${r} must be a non-negative safe integer`);return BigInt(e)}function p(e){if(e>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("connected usage charge exceeds the safe integer range");return Number(e)}function ye(e){let r=b(e.functionRuns,"functionRuns"),a=b(e.proxyRequests,"proxyRequests"),s=b(e.computeMilliseconds,"computeMilliseconds"),n=r*BigInt(N),c=a*BigInt(k),d=s*BigInt(M),m=d===0n?0n:(d+999n)/1000n,h=n+c+m;return{functionRunMc:p(n),proxyRequestMc:p(c),computeMc:p(m),amountMc:p(h),credits:p(h)/o}}function Te(e,r){if(!Number.isFinite(e)||e<0)throw new Error("costUsd must be a finite non-negative number");if(!Number.isInteger(r)||r<0)throw new Error("markupBps must be a non-negative integer");let s=BigInt(Math.round(e*y))*BigInt(r)*BigInt(H),n=BigInt(y)*BigInt(v)*BigInt(K),c=s===0n?0n:(s+n-1n)/n;if(c>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("calculated mc exceeds the safe integer range");return Number(c)}var Z=[{key:"serp",label:"SERP search",aliases:["search_serp","serp","google search","organic results"],credits:_,unit:"per page (ordinary search)",notes:`search_serp light mode returns one page of organic positions, URLs, titles, and descriptions by default. Unfiltered one-page full mode returns available same-page SERP features. Either mode requests two pages only when pages:2 is explicit. Unfiltered light searches cost ${_} credits per delivered page, or ${l} credits per delivered page if the backup supplies the result. One-page full searches cost ${l} credits. Setting recency to week or month applies Google's date filter through a managed browser and returns organic results only. It costs ${l} credits for one page; filtered pages:2 follows Google's page-two control and costs ${l*2} credits when both pages are delivered. Unfiltered searches use the managed browser only as the last backup. Unfiltered two-page full searches return organic results only for ${_*2} credits, with rich features marked unsupported. If only page 1 is delivered, the search is marked partial and billed for one delivered page. A temporary ${l}-credit-per-requested-page hold is settled to the delivered rate. Location, language, device, and optional module fields do not change ordinary searches. Saved browser identity and capture_serp_snapshot searches retain their ${$}-credit base price; optional page snapshots add ${i(t.page_scrape)} credit per attempted URL.`},{key:"paa",label:"PAA harvest",aliases:["harvest_paa","paa","people also ask","questions"],credits:i(t.paa),unit:`per question (+${i(t.paa_base)} credit base)`,notes:`Returns original-query PAA questions with answers and sources plus organic results and Google entity IDs. Optional same-page SERP modules are flag-controlled. Billed ${i(t.paa_base)} credit base + ${i(t.paa)} per question actually returned (unused estimate refunded).`},{key:"page_scrape",label:"Page crawl / extract",aliases:["extract_url","extract_site","page scrape","url scrape","single page","site crawl"],credits:i(t.page_scrape),unit:"per page",notes:"Applies to both single-URL extraction and per-page site crawls."},{key:"listing_create",label:"Directory or wiki listing creation",aliases:["local-sourcebook-capture","commons_submit_entity","directory listing","wiki listing"],credits:i(t.listing_create),unit:"per new listing",notes:"Fixed total price for a new Local Sourcebook directory listing or Transparent Commons wiki entity. Sourcebook acquisition is included."},{key:"listing_edit",label:"Directory or wiki listing edit",aliases:["local_sourcebook_refresh","commons_submit_entity","listing refresh","wiki edit"],credits:i(t.listing_edit),unit:"per existing listing revision",notes:"Fixed total price for refreshing an existing Local Sourcebook listing or revising an existing Transparent Commons entity."},{key:"url_map",label:"Site URL mapping",aliases:["map_site_urls","url map","site map","crawl urls"],credits:i(t.url_map),unit:"per mapping operation",notes:"Flat rate for the full /map-urls call regardless of URL count discovered."},{key:"yt_channel",label:"YouTube search / channel harvest",aliases:["youtube_harvest","youtube search","youtube channel","yt_channel"],credits:i(t.yt_channel),unit:"per call"},{key:"yt_transcription",label:"YouTube transcription",aliases:["youtube_transcribe","youtube transcript","transcription","yt_transcription"],credits:i(2e4),unit:"base + 2/min of video",notes:"Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},{key:"fb_ad",label:"Facebook search / ad lookup",aliases:["facebook_page_intel","facebook_ad_search","facebook_ad","facebook ads","fb ads"],credits:i(t.fb_ad),unit:"per call"},{key:"maps_search",label:"Maps business search",aliases:["maps_search","google maps search","gmb search","gbp search","business profiles"],credits:i(t.maps_search),unit:"per search",notes:"Returns up to 50 Google Maps business/profile candidates. Use maps_place_intel to hydrate selected businesses."},{key:"maps_place",label:"Maps business lookup",aliases:["maps_place_intel","google maps","maps place","place intel"],credits:i(t.maps_place),unit:"per business",notes:"Maps place runs reserve the 60-credit base plus the declared review maximum before browsing. Completed runs settle to the base plus unique saved reviews; stopped attempts are refunded."},{key:"maps_review",label:"Maps review",aliases:["maps_reviews","google reviews","review cards","reviews"],credits:i(t.maps_review),unit:"per review card",notes:"One credit per unique saved review on a completed Maps place run. The declared maximum is held before browsing; unused credits are refunded."},{key:"fb_search",label:"Facebook ad library search",aliases:["facebook_search","fb_search","fb ad search"],credits:i(t.fb_search),unit:"per search",notes:"Browser automation to search Facebook Ads Library by keyword."},{key:"google_ads_search",label:"Google Ads Transparency search",aliases:["google_ads_search","google ads search","ads transparency search"],credits:i(t.google_ads_search),unit:"per search",notes:"Browser automation to find advertisers in Google Ads Transparency Center by domain or name."},{key:"google_ads_intel",label:"Google Ads Transparency advertiser intel",aliases:["google_ads_page_intel","google ads intel","ads transparency intel"],credits:i(t.google_ads_intel),unit:"per call",notes:"Lists and hydrates an advertiser's creatives with image URLs and video references."},{key:"google_ads_transcribe",label:"Google ad video transcription",aliases:["google_ads_transcribe","google ad transcript"],credits:i(2e4),unit:"base + 2/min of video",notes:"Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},{key:"fb_transcribe",label:"Facebook video / ad transcription",aliases:["facebook_transcribe","facebook_video_transcribe","fb_transcribe","fb ad transcript"],credits:i(2e4),unit:"base + 2/min of video",notes:"Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},{key:"fb_reels_inventory",label:"Facebook Reel URL inventory",aliases:["facebook_reels_inventory","facebook reels","facebook reel urls","facebook profile reels"],credits:i(t.fb_reels_inventory),unit:"per profile scan",notes:"Collects canonical Reel URLs from a Facebook profile. Logged-out scans are capped at 60 URLs; saved browser profiles can request larger inventories."},{key:"tiktok_transcribe",label:"TikTok video transcription",aliases:["tiktok_video_transcribe","tiktok transcript"],credits:i(2e4),unit:"base + 2/min of video",notes:"Transcribes a public TikTok video from its playback media. Flat 200-credit base plus 2 credits per minute, reconciled after transcription."},{key:"instagram_profile",label:"Instagram profile content discovery",aliases:["instagram_profile_content","instagram profile","instagram content list","ig profile"],credits:i(t.instagram_profile),unit:"per profile scan",notes:"Browser extraction of public Instagram profile grid links. Complete history may require a logged-in profile."},{key:"instagram_media",label:"Instagram media download",aliases:["instagram_media_download","instagram reel download","instagram post download","ig media"],credits:i(t.instagram_media),unit:"per post or reel",notes:"Extracts post text, image URLs, and reel audio/video tracks, with local downloads when the server can write files."},{key:"instagram_transcribe",label:"Instagram media transcription",aliases:["instagram transcript","instagram reel transcript","ig transcribe"],credits:i(2e4),unit:"base + 2/min of video",notes:"Whisper transcription of selected Instagram audio/video media. Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},{key:"browser_minute",label:"Interactive browser session",aliases:["browser_open","browser agent","browser_agent","live browser","browse","browser control","interactive browser"],credits:i(t.browser_minute),unit:"per minute of use",notes:"Metered per minute of use for the whole time the browser session is open. Close the session to stop the meter; abandoned sessions are auto-closed after a short idle window."},{key:"reddit_thread",label:"Reddit thread base lookup",aliases:["reddit","reddit_thread","reddit comments","subreddit","reddit post"],credits:i(t.reddit_thread),unit:"per thread",notes:"Base lookup for the post itself. Comments billed separately per comment at reddit_comment rate. Refunded if the thread cannot be retrieved."},{key:"reddit_comment",label:"Reddit comment",aliases:["reddit_comment","reddit comments"],credits:i(t.reddit_comment),unit:"per comment",notes:"Charged per comment actually extracted, billed down automatically if the balance runs out mid-thread."},{key:"video_analysis",label:"Video breakdown (frame-by-frame + transcript)",aliases:["video_frame_analysis","video breakdown","video analysis","analyze video"],credits:i(t.video_analysis),unit:"per 120 frames (max 480)",notes:`Full video breakdown: samples frames across a video up to 60 minutes, analyzes visuals and audio, then produces a summary, pacing, topic outline, key points, hook, style, and replication guidance. Reserves ${i(t.video_analysis)} Credits per requested 120-frame tier, up to 480 frames. Unused frame tiers and failed-run frame charges are refunded. Incurred analysis-model usage is billed separately, including usage before a failure; terminal status checks settle the original run.`},{key:"trustpilot_reviews",label:"Trustpilot review harvest",aliases:["trustpilot_reviews","trustpilot","trustpilot reviews"],credits:i(t.trustpilot_reviews),unit:"per call",notes:"Base lookup. Reviews billed separately per card at trustpilot_review rate. Refunded if no reviews are found."},{key:"trustpilot_review",label:"Trustpilot review card",aliases:["trustpilot_review","trustpilot card"],credits:i(t.trustpilot_review),unit:"per review card",notes:"Charged per review actually extracted, billed down automatically if the balance runs out mid-page."},{key:"g2_reviews",label:"G2 review harvest",aliases:["g2_reviews","g2","g2 reviews"],credits:i(t.g2_reviews),unit:"per call",notes:"Base lookup. Reviews billed separately per card at g2_review rate. Refunded if no reviews are found."},{key:"g2_review",label:"G2 review card",aliases:["g2_review","g2 card"],credits:i(t.g2_review),unit:"per review card",notes:"Charged per review actually extracted (each card carries up to 3 Q&A sections), billed down automatically if the balance runs out mid-page."},{key:"diff_page",label:"Page change check",aliases:["diff_page","page diff","change detection"],credits:i(t.diff_page),unit:"per check",notes:"Same cost as a single page extract \u2014 one scrape is performed per check, then compared against your last stored snapshot for that URL."}],ve="price_1Ta1NRS8aAcsk3TGwsRnYbix";function w(e){return e.billing_interval??"month"}function P(e){return e.billed_usd??e.monthly_usd}function O(e){return e.credits_mc/o}var u={price_1TmiHRS8aAcsk3TGwmSNfNIa:{tier:"starter",label:"Starter",price_id:"price_1TmiHRS8aAcsk3TGwmSNfNIa",monthly_usd:12,credits_mc:8e6,concurrency:3,intro_coupon:"mcp-starter-1dollar-intro-12"},price_1TrgihS8aAcsk3TG5cglrq4D:{tier:"growth",label:"Growth",price_id:"price_1TrgihS8aAcsk3TG5cglrq4D",monthly_usd:40,credits_mc:26666700,concurrency:10,intro_coupon:null},price_1TrgihS8aAcsk3TG4HnG4gbY:{tier:"scale",label:"Scale",price_id:"price_1TrgihS8aAcsk3TG4HnG4gbY",monthly_usd:100,credits_mc:8e7,concurrency:20,intro_coupon:null},price_1TwqIVS8aAcsk3TG0FE3ddDM:{tier:"sonic",label:"Sonic Annual",price_id:"price_1TwqIVS8aAcsk3TG0FE3ddDM",monthly_usd:25,billed_usd:300,credits_mc:25e7,concurrency:3,intro_coupon:null,billing_interval:"year",credits_never_expire:!0,private_offer:!0},price_1TwqIWS8aAcsk3TGbGbtlLak:{tier:"sonic-memory",label:"Sonic Annual + Memory Pro",price_id:"price_1TwqIWS8aAcsk3TGbGbtlLak",monthly_usd:34.5,billed_usd:414,credits_mc:25e7,concurrency:3,intro_coupon:null,billing_interval:"year",credits_never_expire:!0,includes_memory:!0,private_offer:!0}},C=Object.fromEntries(Object.values(u).map(e=>[e.tier,e])),E={sonic:{slug:"sonic",label:"Sonic annual partner offer",headline:"A full year of MCP Scraper, with Credits that never expire.",tier_keys:["sonic","sonic-memory"]}};function X(e){let r=Object.values(E).find(a=>a.tier_keys.includes(e));return r?`/${r.slug}/claim`:null}function z(e){return e?Object.values(E).find(r=>r.tier_keys.includes(e))??null:null}function Se(e,r){let a=z(e);return a?!a.tier_keys.includes(r):!1}function Ie(e){if(!e)return null;let r=C[e];return r?{tier:r.tier,label:r.label,amount_usd:P(r),interval:w(r),monthly_equivalent_usd:r.monthly_usd,credits_per_interval:O(r),concurrency:r.concurrency,credits_never_expire:!!r.credits_never_expire,includes_memory:!!r.includes_memory,private_offer:!!r.private_offer,offer_claim_path:X(r.tier)}:null}function Ae(e){let r=E[e];if(!r)return null;let a=r.tier_keys.map(s=>C[s]).filter(s=>!!s).map(s=>({tier:s.tier,label:s.label,amount_usd:P(s),interval:w(s),monthly_equivalent_usd:s.monthly_usd,credits:O(s),credits_never_expire:!!s.credits_never_expire,includes_memory:!!s.includes_memory,concurrency:s.concurrency}));return a.length?{slug:r.slug,label:r.label,headline:r.headline,options:a}:null}function xe(){let e=C.starter,r=Z.map(({aliases:n,...c})=>({...c,...c.notes?{notes:c.notes.replace(/ via fal\.ai/g,"")}:{}})),a=Object.fromEntries(r.map(n=>[n.key,{credits:n.credits,unit:n.unit,label:n.label,...n.notes?{notes:n.notes}:{}}])),s=Object.values(u).filter(n=>!n.private_offer).map(n=>({tier:n.tier,label:n.label,monthlyUsd:n.monthly_usd,credits:n.credits_mc/o,concurrency:n.concurrency}));return{...g,operationCosts:a,publicTiers:s,concurrencyPack:{ratePolicyVersion:B,monthlyUsd:U,currency:L,interval:D,billingUnit:"pack",slotsPerPack:f},scaleCreditPack:{ratePolicyVersion:ee,eligibleTier:"scale",incrementUsd:G,creditsPerIncrement:R,maxQuantity:re,currency:"usd",expiryMonths:3},creditsPerDollarStarter:Math.round(i(e.credits_mc)/e.monthly_usd),costs:r,scheduling:g.addons.scheduling,connectedAccounts:g.addons.connectedAccounts,listingWrites:V}}var U=5,L="usd",D="month",f=2,B="2026-08-14.concurrency-pack-v1",J="$5/month for 2 extra browsers",Ne="MCP Scraper browser concurrency pack \u2014 each $5 monthly pack adds 2 browsers.",ke="Billed monthly until canceled. A receipt is emailed after each successful payment.",T="npx -y -p mcp-scraper@latest mcp-scraper-cli billing concurrency checkout",ee="2026-09-21.scale-credit-pack-v1",G=10,R=8e4,Me=R*o,re=100;function we(){let e=process.env.CONCURRENCY_BILLING_URL??"https://mcpscraper.dev/billing";return{product:"Extra browser concurrency pack",rate_policy_version:B,price_label:J,unit_amount_usd:U,currency:L,interval:D,billing_unit:"pack",pack_quantity:1,slots_per_pack:f,extra_slots:f,billing_url:e,terminal_command:T,terminal_command_with_api_key_env:`MCP_SCRAPER_API_KEY=sk_live_your_key ${T}`}}function i(e){return e/o}var te="npx -y -p mcp-scraper@latest mcp-scraper-cli billing subscribe";function ie(){return Object.values(u).filter(e=>!e.private_offer).sort((e,r)=>e.credits_mc-r.credits_mc)}function Pe(e,r){let a=process.env.TOPUP_URL??"https://mcpscraper.dev/billing",s=i(e),n=i(r),c=ie().map(m=>m.tier).join("|"),d=`${te} <${c}>`;return{error:"insufficient_balance",error_code:"insufficient_balance",message:`Insufficient credits. Balance: ${s} credits. This call requires ${n} credits. Credits refresh when your plan renews. Scale customers can buy ${R} Credits per $${G} increment; other customers can move to a larger plan at ${a} (terminal: ${d})`,balance_credits:s,required_credits:n,topup_url:a,upgrade_command:d}}var ne=1e7*1,Oe={price_1TnMSTS8aAcsk3TGBgiwuvqL:{plan:"pro",label:"Pro",price_id:"price_1TnMSTS8aAcsk3TGBgiwuvqL",interval:"month",monthly_usd:19,quota_bytes:5e9},price_1TnMSTS8aAcsk3TGWBVU2agY:{plan:"pro",label:"Pro",price_id:"price_1TnMSTS8aAcsk3TGWBVU2agY",interval:"year",monthly_usd:19,quota_bytes:5e9}},Ue={free:ne,pro:5e9,team:5e10},se=3;var Le=19/se,De=3,Be=1.5,Ge=1.5,Y=2e4,q=200;function Ye(e){let r=Math.max(1,Math.ceil((e||60)/60));return Y+q*r}var qe=Y+q*30,Fe=u.price_1TmiHRS8aAcsk3TGwmSNfNIa.credits_mc/u.price_1TmiHRS8aAcsk3TGwmSNfNIa.monthly_usd;export{de as a,pe as b,ue as c,$ as d,me as e,ge as f,be as g,V as h,y as i,j,fe as k,Q as l,Ce as m,Ee as n,W as o,S as p,Re as q,I as r,A as s,x as t,N as u,he as v,ye as w,Te as x,Z as y,ve as z,w as A,P as B,O as C,u as D,C as E,X as F,z as G,Se as H,Ie as I,Ae as J,xe as K,U as L,f as M,Ne as N,ke as O,G as P,R as Q,Me as R,re as S,we as T,i as U,Pe as V,Oe as W,Ue as X,De as Y,Be as Z,Ge as _,Y as $,q as aa,Ye as ba,qe as ca,Fe as da};
@@ -0,0 +1 @@
1
+ var o="0.96.1";export{o as a};
@@ -1,4 +1,4 @@
1
- import{a as s}from"./chunk-WP3QS4CJ.js";var _={message:"Read complete retained results and transcripts through artifact tools. Tool guidance now clarifies CRM and Research choices, video limits, ongoing browser costs, and safe recovery. Updated clients preserve request IDs and client labels for troubleshooting."};var c={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?`${c[e]}${t}${c.reset}`:t}function o(t,e,n){let a=t.padEnd(9," ");return` ${r(a,"muted",n)} ${e.join(r(" . ","muted",n))}`}function b(t){let e=t.color??!0,n=t.apiKeyConfigured?"$MCP_SCRAPER_API_KEY":"sk_live_your_key",a=String.raw`
1
+ import{a as s}from"./chunk-WP3QS4CJ.js";var _={message:"PAA progress checks now wait at least 20 seconds. Expanded answers preserve loaded lists, mathematical notation and sources, and extraction avoids repeated reads and clicks. Full SERP responses now show initial PAA questions, available snippets and source labels."};var c={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?`${c[e]}${t}${c.reset}`:t}function o(t,e,n){let a=t.padEnd(9," ");return` ${r(a,"muted",n)} ${e.join(r(" . ","muted",n))}`}function b(t){let e=t.color??!0,n=t.apiKeyConfigured?"$MCP_SCRAPER_API_KEY":"sk_live_your_key",a=String.raw`
2
2
  __ __ ____ ____
3
3
  | \/ |/ ___| _ \
4
4
  | |\/| | | | |_) |