mcp-scraper 0.97.1 → 0.98.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -2442
- package/README.md +16 -412
- package/dist/bin/api-server.js +3 -2
- package/dist/bin/mcp-scraper-cli.js +33 -27
- package/dist/bin/mcp-scraper-core.js +9 -1
- package/dist/bin/mcp-scraper-install.js +17 -2
- package/dist/bin/mcp-stdio-server.js +9 -1
- package/dist/bin/paa-harvest.js +8 -1
- package/dist/index.cjs +5 -21830
- package/dist/index.d.ts +14 -607
- package/dist/index.js +5 -39
- package/dist/transport.d.ts +35 -0
- package/package.json +11 -51
- package/THIRD_PARTY_NOTICES.html +0 -203
- package/dist/actions-5X5CQAKO.js +0 -1
- package/dist/artifacts-4ZDNP2JW.js +0 -1
- package/dist/artifacts-N62OPIT5.js +0 -1
- package/dist/artifacts-PSADD5OC.js +0 -1
- package/dist/artifacts-RUR3OHAK.js +0 -1
- package/dist/blob-store-GIH26EDO.js +0 -1
- package/dist/bundle-GS657HXG.js +0 -1
- package/dist/chunk-24YDQ3EO.js +0 -5
- package/dist/chunk-2L7CHN5N.js +0 -4
- package/dist/chunk-3F7AFM53.js +0 -1
- package/dist/chunk-4AEW53RU.js +0 -954
- package/dist/chunk-4HZXATHB.js +0 -27
- package/dist/chunk-4YZ74SJ6.js +0 -1
- package/dist/chunk-4ZVO6GX4.js +0 -1
- package/dist/chunk-55ZANTHL.js +0 -3
- package/dist/chunk-5RQWFYXY.js +0 -930
- package/dist/chunk-5TQINRZN.js +0 -12
- package/dist/chunk-5UQAL7HV.js +0 -41
- package/dist/chunk-6D25Q5BR.js +0 -21728
- package/dist/chunk-6N5EC7ZO.js +0 -1
- package/dist/chunk-7POHNTVW.js +0 -1
- package/dist/chunk-7SR7MEU5.js +0 -62
- package/dist/chunk-ANQ4JJVI.js +0 -71
- package/dist/chunk-B3JRL45T.js +0 -1
- package/dist/chunk-B4ZKPLSP.js +0 -1
- package/dist/chunk-B5Y26E3A.js +0 -1
- package/dist/chunk-C3JWX6KM.js +0 -10
- package/dist/chunk-C7MGJUTU.js +0 -1
- package/dist/chunk-CNSVZTTT.js +0 -13
- package/dist/chunk-EYGA6LOU.js +0 -1
- package/dist/chunk-F3M7INSN.js +0 -41
- package/dist/chunk-FLAWC5PF.js +0 -5
- package/dist/chunk-FM7BX2LU.js +0 -159
- package/dist/chunk-HCK6PLM3.js +0 -3
- package/dist/chunk-HNNYXMSI.js +0 -1
- package/dist/chunk-IFPION5D.js +0 -121
- package/dist/chunk-IPQOBOFY.js +0 -1
- package/dist/chunk-J7XDXIB6.js +0 -163
- package/dist/chunk-JHDD6R3O.js +0 -8
- package/dist/chunk-JMZIDHYQ.js +0 -2
- package/dist/chunk-K3VDGJNK.js +0 -1
- package/dist/chunk-KBZY2OGP.js +0 -11
- package/dist/chunk-KJQXUZ4Y.js +0 -4
- package/dist/chunk-KXJCGV3H.js +0 -1
- package/dist/chunk-NALXKTUU.js +0 -1
- package/dist/chunk-NNOX3FYG.js +0 -198
- package/dist/chunk-NQFTETVC.js +0 -189
- package/dist/chunk-OILOHQNL.js +0 -2
- package/dist/chunk-OLYPLX5C.js +0 -1
- package/dist/chunk-P6CDR3RM.js +0 -1
- package/dist/chunk-PKQHHCO4.js +0 -20
- package/dist/chunk-QCBCOEH5.js +0 -1
- package/dist/chunk-QER2ELZP.js +0 -1
- package/dist/chunk-RDHGQ2WZ.js +0 -1
- package/dist/chunk-SDQW7IJN.js +0 -1
- package/dist/chunk-SEZETSB3.js +0 -1
- package/dist/chunk-SJNSTO3C.js +0 -42
- package/dist/chunk-TZYITYL4.js +0 -2
- package/dist/chunk-UIOSADPB.js +0 -1718
- package/dist/chunk-UNEJYZ4T.js +0 -102
- package/dist/chunk-UUJYICAJ.js +0 -1
- package/dist/chunk-VVSHZV5S.js +0 -73
- package/dist/chunk-WNUXMPVX.js +0 -1
- package/dist/chunk-XNTAHMPA.js +0 -218
- package/dist/chunk-ZDECILF6.js +0 -16
- package/dist/chunk-ZNPGM3XE.js +0 -4
- package/dist/compatibility-UPPKZ4KY.js +0 -1
- package/dist/contracts-GUXGFCVV.js +0 -1
- package/dist/core-schema-Y47YFKH2.js +0 -899
- package/dist/direct-completion-ZVPPEBDU.js +0 -1
- package/dist/dispatch-GRMMPKQD.js +0 -1
- package/dist/editorial-reading-room/assets/app.js +0 -433
- package/dist/editorial-reading-room/assets/index.html +0 -139
- package/dist/editorial-reading-room/assets/styles.css +0 -1091
- package/dist/index.d.cts +0 -607
- package/dist/jobs-NRZHGQ7I.js +0 -1
- package/dist/media-artifacts-67CJWI7O.js +0 -1
- package/dist/metering-YHZ46GV4.js +0 -1
- package/dist/migrations-3AKEC5QE.js +0 -1
- package/dist/queue-2VKW7SGH.js +0 -1
- package/dist/reconciliation-QC6SILLR.js +0 -1
- package/dist/report-artifact-offload-PQNFDNPL.js +0 -1
- package/dist/repository-CYXVMYAI.js +0 -1
- package/dist/repository-UKDA4IWP.js +0 -1
- package/dist/server-EYMJROPX.js +0 -5544
- package/dist/settlement-47EUTSGX.js +0 -1
- package/dist/vendor-errors-647LSH6H.js +0 -1
- package/dist/worker-AWJF7UYR.js +0 -1
- package/public/.well-known/xray-install.json +0 -183
- package/public/agent-install.md +0 -200
package/dist/chunk-6N5EC7ZO.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
async function t(o){if((process.env.NODE_ENV==="test"||process.env.VITEST)&&process.env.MCP_SCRAPER_ENABLE_MEMORY_LIBRARY_SINK_IN_TESTS!=="1")return;let r=process.env.MCP_SCRAPER_API_KEY?.trim(),n=(process.env.MCP_SCRAPER_BASE_URL??"https://mcpscraper.dev").replace(/\/$/,"");if(r)try{let e=await fetch(`${n}/memory/mcp-call`,{method:"POST",headers:{"content-type":"application/json","x-api-key":r},body:JSON.stringify({toolName:"libraryIngestTool",args:o})}),s=await e.json().catch(()=>null);(!e.ok||s?.ok===!1)&&console.warn("[memory-library-sink] ingest not accepted:",e.status,s?.error??"")}catch(e){console.warn("[memory-library-sink] ingest failed:",e?.message)}}export{t as a};
|
package/dist/chunk-7POHNTVW.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{AsyncLocalStorage as n}from"async_hooks";var r=new n;function o(t,e){return r.run(t,e)}function i(){return r.getStore()}export{o as a,i as b};
|
package/dist/chunk-7SR7MEU5.js
DELETED
|
@@ -1,62 +0,0 @@
|
|
|
1
|
-
import{a as o}from"./chunk-WNUXMPVX.js";import{c,d as p,e as a}from"./chunk-HNNYXMSI.js";import{randomUUID as m}from"crypto";async function O(e){let r=m();return await o().execute({sql:`INSERT INTO operation_coverage_defects (id, tool, method, phase, error_code, run_id, attempt_id)
|
|
2
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)`,args:[r,a(e.tool,"tool"),a(e.method,"method"),a(e.phase,"phase"),a(e.errorCode,"errorCode").slice(0,200),e.runId??null,e.attemptId??null]}),r}function l(e,r=2e3){return e==null?null:e.slice(0,r)}async function I(e){if(!Number.isInteger(e.attemptNumber)||e.attemptNumber<1)throw new Error("attemptNumber must be a positive integer");if(e.attemptNumber===1&&(e.parentAttemptId||e.edgeKind||e.retryKind))throw new Error("The first attempt cannot have a parent or retry edge");if(e.attemptNumber>1&&(!e.parentAttemptId||!e.edgeKind))throw new Error("Every non-first attempt requires a parentAttemptId and edgeKind");if(e.retryKind&&!["same_method_retry","provider_fallback","durable_resume","reconciliation"].includes(e.edgeKind??""))throw new Error("retryKind requires a retry or reconciliation edgeKind");let r=e.id??m();return await o().execute({sql:`INSERT INTO operation_attempts
|
|
3
|
-
(id, run_id, parent_attempt_id, attempt_number, edge_kind, retry_kind, retry_reason, retry_owner,
|
|
4
|
-
method, provider, normalized_flags_json, started_at)
|
|
5
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,args:[r,e.runId,e.parentAttemptId??null,e.attemptNumber,e.edgeKind??null,e.retryKind??null,l(e.retryReason,500),l(e.retryOwner,100),a(e.method,"method"),e.provider??null,p(e.normalizedFlags),e.startedAt??new Date().toISOString()]}),r}async function C(e){let r=m();return await o().execute({sql:`INSERT INTO operation_attempts
|
|
6
|
-
(id, run_id, parent_attempt_id, attempt_number, edge_kind, retry_kind, retry_reason,
|
|
7
|
-
method, provider, normalized_flags_json, started_at)
|
|
8
|
-
SELECT ?, ?, ?, COALESCE(MAX(attempt_number), 0) + 1, ?, ?, ?, ?, ?, ?, ?
|
|
9
|
-
FROM operation_attempts WHERE run_id = ?`,args:[r,e.runId,e.parentAttemptId,e.edgeKind,e.retryKind??null,l(e.retryReason,500),a(e.method,"method"),e.provider??null,p(e.normalizedFlags),new Date().toISOString(),e.runId]}),r}async function T(e){if(!Number.isInteger(e.durationMs)||e.durationMs<0)throw new Error("durationMs must be a non-negative integer");let r=e.endedAt??new Date().toISOString();if((await o().execute({sql:`UPDATE operation_attempts SET
|
|
10
|
-
status = ?, error_code = ?, error_message = ?, ended_at = ?, duration_ms = ?, updated_at = ?
|
|
11
|
-
WHERE id = ? AND status = 'running'`,args:[e.status,l(e.errorCode,200),l(e.errorMessage),r,e.durationMs,r,e.attemptId]})).rowsAffected===1)return;let i=await o().execute({sql:"SELECT status, duration_ms FROM operation_attempts WHERE id = ?",args:[e.attemptId]});if(i.rows.length===0)throw new Error(`Unknown operation attempt: ${e.attemptId}`);if(String(i.rows[0]?.status)!==e.status||Number(i.rows[0]?.duration_ms)!==e.durationMs)throw new Error(`Operation attempt ${e.attemptId} is already terminal as ${String(i.rows[0]?.status)}`)}async function L(e){let r=a(e.provider,"provider"),t=a(e.method,"method"),i=c(a(e.accountScope,"accountScope")),s=e.providerSourceKey?.trim()||null,n=s?c(s):null,d=e.id??m(),u=await o().execute({sql:`INSERT OR IGNORE INTO provider_usage_receipts
|
|
12
|
-
(id, attempt_id, provider, account_scope_hash, method, provider_product, billing_tier,
|
|
13
|
-
provider_source_key, provider_source_key_hash, provider_status)
|
|
14
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,args:[d,e.attemptId,r,i,t,e.providerProduct??null,e.billingTier??null,s,n,e.providerStatus??null]});if(!n){if(u.rowsAffected===1)return{id:d,replayed:!1};let _=(await o().execute({sql:"SELECT attempt_id, provider, method FROM provider_usage_receipts WHERE id = ?",args:[d]})).rows[0];if(!_||String(_.attempt_id)!==e.attemptId||String(_.provider)!==r||String(_.method)!==t)throw new Error("Provider receipt ID is already used by a different receipt");return{id:d,replayed:!0}}let g=(await o().execute({sql:`SELECT id, attempt_id FROM provider_usage_receipts
|
|
15
|
-
WHERE provider = ? AND account_scope_hash = ? AND method = ? AND provider_source_key_hash = ?`,args:[r,i,t,n]})).rows[0];if(!g)throw new Error("Provider receipt insert did not produce a source receipt");if(String(g.attempt_id)!==e.attemptId)throw new Error("Provider source identity is already attached to a different attempt");return{id:String(g.id),replayed:String(g.id)!==d}}async function x(e,r){let t=a(r,"providerSourceKey"),i=c(t);if((await o().execute({sql:`UPDATE provider_usage_receipts
|
|
16
|
-
SET provider_source_key = ?, provider_source_key_hash = ?, updated_at = datetime('now')
|
|
17
|
-
WHERE id = ? AND provider_source_key IS NULL`,args:[t,i,e]})).rowsAffected===1)return;let n=await o().execute({sql:"SELECT provider_source_key_hash FROM provider_usage_receipts WHERE id = ?",args:[e]});if(!n.rows[0])throw new Error(`Unknown provider receipt: ${e}`);if(String(n.rows[0].provider_source_key_hash)!==i)throw new Error(`Provider receipt ${e} already has a different source identity`)}async function v(e){if(!Number.isSafeInteger(e.units)||e.units<0)throw new Error("Observed units must be a non-negative safe integer");if((await o().execute({sql:`UPDATE provider_usage_receipts SET units = ?, unit_type = ?,
|
|
18
|
-
provider_status = COALESCE(?, provider_status), checked_at = ?, updated_at = datetime('now')
|
|
19
|
-
WHERE id = ? AND cost_state = 'pending'`,args:[e.units,a(e.unitType,"unitType"),e.providerStatus??null,e.checkedAt??new Date().toISOString(),e.receiptId]})).rowsAffected!==1)throw new Error(`Unknown or terminal pending provider receipt: ${e.receiptId}`)}async function k(e){let r=e.checkedAt??new Date().toISOString();if((await o().execute({sql:`UPDATE provider_usage_receipts SET checked_at = ?, updated_at = ?,
|
|
20
|
-
error_code = ?, provider_status = COALESCE(?, provider_status)
|
|
21
|
-
WHERE id = ? AND cost_state IN ('pending', 'estimated')`,args:[r,r,l(e.errorCode,200),l(e.providerStatus,200),e.receiptId]})).rowsAffected===1)return;if(!(await o().execute({sql:"SELECT id FROM provider_usage_receipts WHERE id = ?",args:[e.receiptId]})).rows[0])throw new Error(`Unknown provider receipt: ${e.receiptId}`)}async function P(e){let t=(await o().execute({sql:`SELECT id FROM provider_usage_receipts
|
|
22
|
-
WHERE provider = ? AND account_scope_hash = ? AND method = ? AND provider_source_key_hash = ?`,args:[a(e.provider,"provider"),c(a(e.accountScope,"accountScope")),a(e.method,"method"),c(a(e.providerSourceKey,"providerSourceKey"))]})).rows[0];return t?(await v({receiptId:String(t.id),units:e.units,unitType:e.unitType,providerStatus:e.providerStatus,checkedAt:e.checkedAt}),!0):!1}async function S(e){if(e.units!=null&&(!Number.isFinite(e.units)||e.units<0))throw new Error("units must be non-negative");if(e.amountUsdNanos!=null&&(!Number.isSafeInteger(e.amountUsdNanos)||e.amountUsdNanos<0))throw new Error("amountUsdNanos must be a non-negative safe integer");if((e.costState==="actual"||e.costState==="measured")&&e.amountUsdNanos==null)throw new Error(`${e.costState} receipts require amountUsdNanos`);if((e.costState==="actual"||e.costState==="measured")&&e.amountUsdNanos===0&&!e.zeroCostReason?.trim())throw new Error(`${e.costState} zero-cost receipts require zeroCostReason`);if(e.costState==="measured"&&e.amountUsdNanos!==0&&(!e.providerProduct||!e.billingTier||!e.billableEvent||!e.measurementSource||!e.rateSource||e.rateNumerator==null||e.rateDenominator==null||!e.ratePolicyVersion||!e.rateEffectiveAt||e.units==null||!e.unitType))throw new Error("measured receipts require observed product, units, and an applied rate snapshot");if(e.rateNumerator!=null&&(!Number.isSafeInteger(e.rateNumerator)||e.rateNumerator<0))throw new Error("rateNumerator must be a non-negative safe integer");if(e.rateDenominator!=null&&(!Number.isSafeInteger(e.rateDenominator)||e.rateDenominator<1))throw new Error("rateDenominator must be a positive safe integer");let r=e.checkedAt??new Date().toISOString(),t=e.finalizedAt??r;if((await o().execute({sql:`UPDATE provider_usage_receipts SET
|
|
23
|
-
cost_state = ?,
|
|
24
|
-
units = CASE WHEN ? = 'actual' THEN ? ELSE COALESCE(?, units) END,
|
|
25
|
-
unit_type = CASE WHEN ? = 'actual' THEN ? ELSE COALESCE(?, unit_type) END,
|
|
26
|
-
amount_usd_nanos = ?, rate_source = COALESCE(?, rate_source), zero_cost_reason = ?,
|
|
27
|
-
provider_product = COALESCE(provider_product, ?), billing_tier = COALESCE(billing_tier, ?),
|
|
28
|
-
billable_event = CASE WHEN ? = 'actual' THEN ? ELSE COALESCE(?, billable_event) END,
|
|
29
|
-
measurement_source = COALESCE(?, measurement_source),
|
|
30
|
-
rate_numerator = CASE WHEN ? = 'actual' THEN ? ELSE COALESCE(?, rate_numerator) END,
|
|
31
|
-
rate_denominator = CASE WHEN ? = 'actual' THEN ? ELSE COALESCE(?, rate_denominator) END,
|
|
32
|
-
rate_policy_version = CASE WHEN ? = 'actual' THEN ? ELSE COALESCE(?, rate_policy_version) END,
|
|
33
|
-
rate_effective_at = CASE WHEN ? = 'actual' THEN ? ELSE COALESCE(?, rate_effective_at) END,
|
|
34
|
-
provider_status = ?, provider_duration_ms = ?, provider_captcha = ?, error_code = ?, error_message = ?,
|
|
35
|
-
checked_at = ?, finalized_at = ?, updated_at = ?
|
|
36
|
-
WHERE id = ? AND (cost_state = 'pending'
|
|
37
|
-
OR (cost_state = 'estimated' AND ? IN ('measured', 'actual'))
|
|
38
|
-
OR (cost_state = 'measured' AND ? = 'actual'))`,args:[e.costState,e.costState,e.units??null,e.units??null,e.costState,e.unitType??null,e.unitType??null,e.amountUsdNanos??null,e.rateSource??null,e.zeroCostReason??null,e.providerProduct??null,e.billingTier??null,e.costState,e.billableEvent??null,e.billableEvent??null,e.measurementSource??null,e.costState,e.rateNumerator??null,e.rateNumerator??null,e.costState,e.rateDenominator??null,e.rateDenominator??null,e.costState,e.ratePolicyVersion??null,e.ratePolicyVersion??null,e.costState,e.rateEffectiveAt??null,e.rateEffectiveAt??null,e.providerStatus??null,e.providerDurationMs??null,e.providerCaptcha==null?null:e.providerCaptcha?1:0,l(e.errorCode,200),l(e.errorMessage),r,t,t,e.receiptId,e.costState,e.costState]})).rowsAffected===1)return;let s=await o().execute({sql:"SELECT cost_state, units, unit_type, amount_usd_nanos FROM provider_usage_receipts WHERE id = ?",args:[e.receiptId]});if(s.rows.length===0)throw new Error(`Unknown provider receipt: ${e.receiptId}`);let n=s.rows[0],d=n?.units==null&&e.units==null||Number(n?.units)===e.units,u=n?.amount_usd_nanos==null&&e.amountUsdNanos==null||Number(n?.amount_usd_nanos)===e.amountUsdNanos,E=n?.unit_type==null&&e.unitType==null||String(n?.unit_type)===e.unitType;if(String(n?.cost_state)!==e.costState||!d||!u||!E)throw new Error(`Provider receipt ${e.receiptId} is already finalized as ${String(s.rows[0]?.cost_state)}`)}async function U(e){let t=(await o().execute({sql:`SELECT id FROM provider_usage_receipts
|
|
39
|
-
WHERE provider = ? AND account_scope_hash = ? AND method = ? AND provider_source_key_hash = ?`,args:[a(e.provider,"provider"),c(a(e.accountScope,"accountScope")),a(e.method,"method"),c(a(e.providerSourceKey,"providerSourceKey"))]})).rows[0];if(!t)return!1;let{provider:i,accountScope:s,method:n,providerSourceKey:d,...u}=e;return await S({...u,receiptId:String(t.id)}),!0}async function D(e=30){if(!Number.isInteger(e)||e<1||e>365)throw new Error("retentionDays must be an integer between 1 and 365");let r=`-${e} days`,t=o(),[i,s,n]=await Promise.all([t.execute({sql:`UPDATE operation_attempts
|
|
40
|
-
SET error_message = NULL, updated_at = datetime('now')
|
|
41
|
-
WHERE ended_at < datetime('now', ?) AND error_message IS NOT NULL`,args:[r]}),t.execute({sql:`UPDATE provider_usage_receipts
|
|
42
|
-
SET provider_source_key = NULL, error_message = NULL, updated_at = datetime('now')
|
|
43
|
-
WHERE finalized_at < datetime('now', ?)
|
|
44
|
-
AND (provider_source_key IS NOT NULL OR error_message IS NOT NULL)`,args:[r]}),t.execute({sql:`UPDATE harvest_attempts
|
|
45
|
-
SET provider_session_id = NULL, \u006b\u0065\u0072\u006e\u0065\u006c_session_id = NULL, error = NULL,
|
|
46
|
-
\u006b\u0065\u0072\u006e\u0065\u006c_delete_error = NULL, browser_close_error = NULL,
|
|
47
|
-
provider_error_message = NULL, provider_detail_json = NULL,
|
|
48
|
-
provider_disconnect_message = NULL, debug_json = NULL
|
|
49
|
-
WHERE completed_at < datetime('now', ?)
|
|
50
|
-
AND (provider_session_id IS NOT NULL OR \u006b\u0065\u0072\u006e\u0065\u006c_session_id IS NOT NULL OR error IS NOT NULL
|
|
51
|
-
OR \u006b\u0065\u0072\u006e\u0065\u006c_delete_error IS NOT NULL OR browser_close_error IS NOT NULL
|
|
52
|
-
OR provider_error_message IS NOT NULL OR provider_detail_json IS NOT NULL
|
|
53
|
-
OR provider_disconnect_message IS NOT NULL OR debug_json IS NOT NULL)`,args:[r]})]);return{operationAttempts:i.rowsAffected,providerReceipts:s.rowsAffected,legacyHarvestAttempts:n.rowsAffected}}async function H(e){let t={billing_authorizations:{column:"id"},billing_events:{column:"id"},billing_debits:{column:"idempotency_key"},billing_credits:{column:"idempotency_key"},ledger:{column:"id"}}[e.billingTable],i=a(e.billingKey,"billingKey"),s=await o().execute({sql:`SELECT b.user_id AS billing_user_id, r.user_id AS run_user_id
|
|
54
|
-
FROM operation_runs r
|
|
55
|
-
JOIN ${e.billingTable} b ON CAST(b.${t.column} AS TEXT) = ?
|
|
56
|
-
WHERE r.id = ?`,args:[i,e.runId]});if(!s.rows[0])throw new Error("Billing link target or operation run does not exist");let n=s.rows[0].billing_user_id,d=s.rows[0].run_user_id;if(d!=null&&n!=null&&String(d)!==String(n))throw new Error("Billing link owner does not match operation run owner");await o().execute({sql:`INSERT OR IGNORE INTO operation_billing_links
|
|
57
|
-
(run_id, billing_table, billing_key, relation, amount_mc) VALUES (?, ?, ?, ?, ?)`,args:[e.runId,e.billingTable,i,e.relation,e.amountMc??null]})}async function K(e,r=new Date().toISOString()){let t=m();return await o().execute({sql:"INSERT INTO provider_reconciliation_runs (id, provider, started_at) VALUES (?, ?, ?)",args:[t,a(e,"provider"),r]}),t}async function q(e){if([e.checkedCount,e.completedCount,e.pendingCount,e.unavailableCount,e.failedCount].some(s=>!Number.isInteger(s)||s<0))throw new Error("Reconciliation counts must be non-negative integers");if(e.completedCount+e.pendingCount+e.unavailableCount+e.failedCount>e.checkedCount)throw new Error("Reconciliation outcome counts cannot exceed checkedCount");let t=e.completedAt??new Date().toISOString();if((await o().execute({sql:`UPDATE provider_reconciliation_runs SET
|
|
58
|
-
status = ?, checked_count = ?, completed_count = ?, pending_count = ?, unavailable_count = ?,
|
|
59
|
-
failed_count = ?, error_code = ?, completed_at = ?
|
|
60
|
-
WHERE id = ? AND status = 'running'`,args:[e.status,e.checkedCount,e.completedCount,e.pendingCount,e.unavailableCount,e.failedCount,l(e.errorCode,200),t,e.id]})).rowsAffected!==1)throw new Error(`Unknown or terminal provider reconciliation run: ${e.id}`)}async function M(e){let r=o(),[t,i,s,n]=await Promise.all([r.execute({sql:"SELECT * FROM operation_runs WHERE id = ?",args:[e]}),r.execute({sql:"SELECT * FROM operation_attempts WHERE run_id = ? ORDER BY attempt_number",args:[e]}),r.execute({sql:`SELECT r.* FROM provider_usage_receipts r
|
|
61
|
-
JOIN operation_attempts a ON a.id = r.attempt_id
|
|
62
|
-
WHERE a.run_id = ? ORDER BY a.attempt_number, r.rowid`,args:[e]}),r.execute({sql:"SELECT * FROM operation_billing_links WHERE run_id = ? ORDER BY created_at, billing_table, billing_key",args:[e]})]);return t.rows[0]?{run:t.rows[0],attempts:[...i.rows],providerReceipts:[...s.rows],billingLinks:[...n.rows]}:null}export{O as a,I as b,C as c,T as d,L as e,x as f,v as g,k as h,P as i,S as j,U as k,D as l,H as m,K as n,q as o,M as p};
|
package/dist/chunk-ANQ4JJVI.js
DELETED
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
import{a as A}from"./chunk-PKQHHCO4.js";import{c as w}from"./chunk-4ZVO6GX4.js";import{a as u}from"./chunk-WNUXMPVX.js";import{b as E,c as f,d as S,e as m,f as l}from"./chunk-HNNYXMSI.js";import{randomUUID as D}from"crypto";var a="(CAST(strftime('%s', 'now') AS INTEGER) * 1000)",N=e=>{if(!Number.isSafeInteger(e)||e<1e3||e>36e5)throw Error("Execution lease must be between one second and one hour")};async function d(e,t,n){return(await e.execute({sql:`SELECT e.*, r.status AS run_status, r.tool, r.job_id, ${a} AS now_ms FROM operation_executions e
|
|
2
|
-
JOIN operation_runs r ON r.id = e.run_id WHERE e.run_id = ? AND r.user_id = ?`,args:[t,n]})).rows[0]}async function R(e,t,n,r,o=u(),s){N(r),s&&l({userId:t,tool:s.tool,jobId:s.jobId},s);let i=await d(o,e,t);return i?(i.phase==="claimed"&&Number(i.expires_at_ms)<=Number(i.now_ms)&&(await o.execute({sql:`UPDATE operation_executions SET claim_token = ?, expires_at_ms = ${a} + ?
|
|
3
|
-
WHERE run_id = ? AND phase = 'claimed' AND expires_at_ms <= ${a}
|
|
4
|
-
AND EXISTS (SELECT 1 FROM operation_runs WHERE id = ? AND user_id = ? AND status = 'running' AND (? = 1 OR json_extract(normalized_flags_json,'$._storeGateRequired') IS NOT 1)${s?" AND tool = ? AND job_id = ?":""})
|
|
5
|
-
${s?`AND (${s.sql})`:""}`,args:[n,r,e,e,t,s?1:0,...s?[s.tool,s.jobId,...s.args]:[]]}),i=await d(o,e,t)),i?.phase==="effects_started"&&Number(i.expires_at_ms)<=Number(i.now_ms)&&(await o.batch([{sql:`UPDATE operation_executions SET phase = 'unknown' WHERE run_id = ?
|
|
6
|
-
AND phase = 'effects_started' AND expires_at_ms <= ${a}
|
|
7
|
-
AND EXISTS (SELECT 1 FROM operation_runs WHERE id = ? AND user_id = ?)`,args:[e,e,t]},{sql:`UPDATE operation_runs SET status = 'unknown', failure_class = 'execution_expired_after_effects',
|
|
8
|
-
ended_at = datetime('now'), updated_at = datetime('now') WHERE id = ? AND user_id = ? AND status = 'running'
|
|
9
|
-
AND EXISTS (SELECT 1 FROM operation_executions WHERE run_id = ? AND phase = 'unknown')`,args:[e,t,e]}],"write"),i=await d(o,e,t)),i?.phase==="published"&&i.run_status===i.result_status?{kind:"replay",runId:e,result:{json:String(i.result_json),status:i.result_status}}:i?.phase==="unknown"||i?.run_status!=="running"?{kind:"unknown",runId:e}:i.phase==="claimed"&&i.claim_token===n&&Number(i.expires_at_ms)>Number(i.now_ms)?{kind:"claimed",claim:{runId:e,userId:t,token:n}}:{kind:"pending",runId:e}):{kind:"unknown",runId:e}}async function I(e,t){return t&&l({userId:e.userId,tool:t.tool,jobId:t.jobId},t),(await u().execute({sql:`UPDATE operation_executions SET phase = 'effects_started' WHERE run_id = ? AND claim_token = ?
|
|
10
|
-
AND phase = 'claimed' AND expires_at_ms > ${a}
|
|
11
|
-
AND EXISTS (SELECT 1 FROM operation_runs WHERE id = ? AND user_id = ? AND status = 'running' AND (? = 1 OR json_extract(normalized_flags_json,'$._storeGateRequired') IS NOT 1)${t?" AND tool = ? AND job_id = ?":""})
|
|
12
|
-
${t?`AND (${t.sql})`:""}`,args:[e.runId,e.token,e.runId,e.userId,t?1:0,...t?[t.tool,t.jobId,...t.args]:[]]})).rowsAffected===1}async function j(e,t){return N(t),(await u().execute({sql:`UPDATE operation_executions SET expires_at_ms = ${a} + ? WHERE run_id = ? AND claim_token = ?
|
|
13
|
-
AND phase IN ('claimed', 'effects_started') AND expires_at_ms > ${a}
|
|
14
|
-
AND EXISTS (SELECT 1 FROM operation_runs WHERE id = ? AND user_id = ? AND status = 'running')`,args:[t,e.runId,e.token,e.runId,e.userId]})).rowsAffected===1}async function q(e,t,n=3e5){if(N(n),!Number.isSafeInteger(t)||t<=0)throw Error("Authenticated recovery principal is required");let r=u(),o=D(),s;try{await r.batch([{sql:`UPDATE operation_executions SET phase = 'unknown', claim_token = ?, expires_at_ms = ${a} + ?
|
|
15
|
-
WHERE run_id = ? AND phase IN ('effects_started', 'unknown') AND expires_at_ms <= ${a}
|
|
16
|
-
AND EXISTS (SELECT 1 FROM operation_runs WHERE id = ? AND user_id = ? AND status IN ('running', 'unknown'))`,args:[o,n,e,e,t]},{sql:`UPDATE operation_runs SET status = 'unknown', failure_class = 'execution_expired_after_effects',
|
|
17
|
-
ended_at = datetime('now'), updated_at = datetime('now') WHERE id = ? AND user_id = ? AND status = 'running'
|
|
18
|
-
AND EXISTS (SELECT 1 FROM operation_executions WHERE run_id = ? AND phase = 'unknown' AND claim_token = ?)`,args:[e,t,e,o]}],"write")}catch(_){s=_}let i;try{i=await d(r,e,t)}catch(_){throw s??_}if(i?.phase==="unknown"&&i.run_status==="unknown"&&i.claim_token===o&&Number(i.expires_at_ms)>Number(i.now_ms))return{runId:e,userId:t,token:o};if(s)throw s;return null}async function x(e,t,n,r){r&&l({userId:e.userId,tool:r.tool,jobId:r.jobId},r);let o=n?"unknown":"effects_started",s=n?"unknown":"running";if(JSON.parse(t.json),Buffer.byteLength(t.json)>16*1024*1024)throw Error("Operation result exceeds 16 MiB");let i=u(),_;try{await i.batch([{sql:`UPDATE operation_executions SET phase = 'published', result_json = ?, result_status = ?
|
|
19
|
-
WHERE run_id = ? AND claim_token = ? AND phase = ? AND expires_at_ms > ${a}
|
|
20
|
-
AND EXISTS (SELECT 1 FROM operation_runs WHERE id = ? AND user_id = ? AND status = ?)
|
|
21
|
-
AND (? = 0 OR NOT EXISTS (
|
|
22
|
-
SELECT 1 FROM operation_debit_plans p JOIN billing_debits d ON d.idempotency_key = p.debit_key
|
|
23
|
-
WHERE p.run_id = operation_executions.run_id AND d.status IN ('applying', 'applied')
|
|
24
|
-
AND NOT EXISTS (SELECT 1 FROM billing_events b WHERE b.user_id = d.user_id
|
|
25
|
-
AND b.billing_class = 'wallet_hold_settlement' AND b.source_surface = p.source_surface
|
|
26
|
-
AND b.status = 'settled' AND (b.amount_mc = 0${r?" OR EXISTS(SELECT 1 FROM operation_final_settlements s WHERE s.run_id=p.run_id AND s.debit_key=p.debit_key AND s.user_id=d.user_id AND s.final_amount_mc=b.amount_mc AND s.refund_operation=p.refund_operation AND s.source_surface=p.source_surface)":""})
|
|
27
|
-
AND json_extract(b.metadata, '$.debitIdempotencyKey') = p.debit_key
|
|
28
|
-
AND json_extract(b.metadata, '$.refundOperation') = p.refund_operation)
|
|
29
|
-
))${r?` AND (${r.sql}) AND EXISTS(SELECT 1 FROM operation_runs g WHERE g.id=operation_executions.run_id AND g.tool=? AND g.job_id=?)`:""}`,args:[t.json,t.status,e.runId,e.token,o,e.runId,e.userId,s,n?1:0,...r?[...r.args,r.tool,r.jobId]:[]]},{sql:`UPDATE operation_runs SET status = ?, ended_at = datetime('now'), updated_at = datetime('now')
|
|
30
|
-
WHERE id = ? AND user_id = ? AND status = ?
|
|
31
|
-
AND EXISTS (SELECT 1 FROM operation_executions WHERE run_id = ? AND claim_token = ?
|
|
32
|
-
AND phase = 'published' AND result_json = ? AND result_status = ?)`,args:[t.status,e.runId,e.userId,s,e.runId,e.token,t.json,t.status]}],"write")}catch(c){_=c}let p=await d(i,e.runId,e.userId);if(p?.phase==="published"&&p.claim_token===e.token&&p.result_json===t.json&&p.result_status===t.status&&p.run_status===t.status)return!0;if(_)throw _;return!1}async function $(e,t){return x(e,t,!1)}async function H(e,t,n){if(t.status!=="unknown")throw Error("Recovery cannot publish a known execution outcome");return x(e,t,!0,n)}async function W(e){await u().execute({sql:`UPDATE operation_executions SET expires_at_ms = ${a}
|
|
33
|
-
WHERE run_id = ? AND claim_token = ? AND phase = 'claimed'
|
|
34
|
-
AND EXISTS (SELECT 1 FROM operation_runs WHERE id = ? AND user_id = ? AND status = 'running')`,args:[e.runId,e.token,e.runId,e.userId]})}async function F(e){let t=u();await A(t);let n;try{return(await t.execute({sql:`UPDATE operation_executions SET phase = 'claimed', expires_at_ms = ${a}
|
|
35
|
-
WHERE run_id = ? AND claim_token = ? AND phase = 'effects_started' AND expires_at_ms > ${a}
|
|
36
|
-
AND EXISTS (SELECT 1 FROM operation_runs root
|
|
37
|
-
WHERE root.id = operation_executions.run_id AND root.user_id = ? AND root.status = 'running'
|
|
38
|
-
AND root.job_id IS NOT NULL
|
|
39
|
-
AND NOT EXISTS (SELECT 1 FROM operation_runs child
|
|
40
|
-
LEFT JOIN operation_executions execution ON execution.run_id = child.id
|
|
41
|
-
WHERE child.user_id = root.user_id AND child.job_id = root.job_id AND child.id <> root.id
|
|
42
|
-
AND (child.status = 'unknown' OR execution.phase IN ('effects_started', 'unknown')
|
|
43
|
-
OR (child.status = 'running' AND execution.run_id IS NULL)))
|
|
44
|
-
AND NOT EXISTS (SELECT 1 FROM operation_physical_attempts physical
|
|
45
|
-
WHERE physical.user_id = root.user_id AND physical.state IN ('prepared', 'effects_started', 'unknown')
|
|
46
|
-
AND (physical.parent_run_id = root.id OR EXISTS (SELECT 1 FROM operation_runs parent
|
|
47
|
-
WHERE parent.id = physical.parent_run_id AND parent.user_id = root.user_id
|
|
48
|
-
AND parent.job_id = root.job_id))))`,args:[e.runId,e.token,e.userId]})).rowsAffected===1}catch(o){n=o}let r=await d(t,e.runId,e.userId).catch(()=>null);if(r?.phase==="claimed"&&r.run_status==="running"&&r.claim_token===e.token&&Number(r.expires_at_ms)<=Number(r.now_ms))return!0;throw n}async function L(e){await u().batch([{sql:`UPDATE operation_executions SET phase = 'unknown', expires_at_ms = ${a}
|
|
49
|
-
WHERE run_id = ? AND claim_token = ? AND phase IN ('effects_started', 'unknown') AND expires_at_ms > ${a}
|
|
50
|
-
AND EXISTS (SELECT 1 FROM operation_runs WHERE id = ? AND user_id = ? AND status IN ('running', 'unknown'))`,args:[e.runId,e.token,e.runId,e.userId]},{sql:`UPDATE operation_runs SET status = 'unknown', failure_class = 'execution_outcome_unavailable',
|
|
51
|
-
ended_at = datetime('now'), updated_at = datetime('now') WHERE id = ? AND user_id = ? AND status IN ('running', 'unknown')
|
|
52
|
-
AND EXISTS (SELECT 1 FROM operation_executions WHERE run_id = ? AND phase = 'unknown' AND claim_token = ?)`,args:[e.runId,e.userId,e.runId,e.token]}],"write")}async function P(e){let t=await d(u(),e.runId,e.userId);return t?.phase==="effects_started"&&t.run_status==="running"&&t.claim_token===e.token&&Number(t.expires_at_ms)>Number(t.now_ms)}function h(e){let t=m(e.tool,"tool"),n=m(e.ownerScope,"ownerScope"),r=e.idempotencyKey?.trim()||null,o=e.requestFingerprint?.trim()||null;if(r==null!=(o==null))throw Error("idempotencyKey and requestFingerprint must be supplied together");let s=r?f(`${n}\0${t}\0${r}`):null,i=e.id??D(),_=[i,e.userId??null,f(n),t,s,o,e.jobId??null,e.requestId??w()?.requestId??null,e.deploymentCommit??null,S(e.normalizedFlags),e.startedAt??new Date().toISOString()];return{id:i,scopeHash:s,requestFingerprint:o,statement:{sql:`INSERT${s?" OR IGNORE":""} INTO operation_runs
|
|
53
|
-
(id, user_id, owner_scope_hash, tool, idempotency_scope_hash, request_fingerprint,
|
|
54
|
-
job_id, request_id, deployment_commit, normalized_flags_json, started_at)
|
|
55
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,args:_}}}async function O(e,t){let n=(await e.execute({sql:t.scopeHash?"SELECT id, request_fingerprint FROM operation_runs WHERE idempotency_scope_hash = ?":"SELECT id, request_fingerprint FROM operation_runs WHERE id = ?",args:[t.scopeHash??t.id]})).rows[0];if(!n)throw Error("Operation run insert did not produce an idempotency receipt");if(t.scopeHash&&String(n.request_fingerprint)!==t.requestFingerprint)throw new E;return{id:String(n.id),replayed:String(n.id)!==t.id}}async function M(e){let t=u(),n=h(e);return await t.execute(n.statement),n.scopeHash?O(t,n):{id:n.id,replayed:!1}}async function U(e,t,n,r){N(n),r&&l(e,r);let o=u(),s=h(r?{...e,normalizedFlags:{...e.normalizedFlags,_storeGateRequired:!0}}:e),i=r?{sql:s.statement.sql.replace("VALUES (","SELECT ").replace(/\)$/,"")+` WHERE (${r.sql})`,args:[...s.statement.args,...r.args]}:s.statement,_;try{await o.batch([i,{sql:`INSERT INTO operation_executions (run_id, claim_token, expires_at_ms, phase)
|
|
56
|
-
SELECT id, ?, ${a} + ?, 'claimed' FROM operation_runs
|
|
57
|
-
WHERE id = ? AND user_id = ? AND status = 'running' AND changes() = 1`,args:[t,n,s.id,e.userId]}],"write")}catch(c){_=c}let p;try{p=await O(o,s)}catch(c){if(c instanceof E)throw c;if(r&&!_)return{kind:"unknown",runId:s.id};throw _??c}return R(p.id,e.userId,t,n,o,r)}async function X(e){let t=u(),n=e.endedAt??new Date().toISOString(),r=e.failureClass==null?null:e.failureClass.slice(0,200);if((await t.execute({sql:`UPDATE operation_runs SET status = ?, failure_class = ?, ended_at = ?, updated_at = ?
|
|
58
|
-
WHERE id = ? AND status = 'running'
|
|
59
|
-
AND NOT EXISTS (SELECT 1 FROM operation_executions WHERE run_id = ?)`,args:[e.status,r,n,n,e.runId,e.runId]})).rowsAffected===1)return;let s=(await t.execute({sql:"SELECT status, failure_class FROM operation_runs WHERE id = ?",args:[e.runId]})).rows[0];if(!s)throw Error(`Unknown operation run: ${e.runId}`);if(s.status==="running")throw Error("Claimed operation runs require fenced result publication");let i=s.failure_class==null?null:String(s.failure_class);if(String(s.status)!==e.status||i!==r)throw Error(`Operation run ${e.runId} is already terminal as ${String(s.status)}`)}function v(e,t){if(!Number.isSafeInteger(e.userId)||e.userId<=0||!e.runId||!e.token||!t.tool||!t.jobId)throw Error("Invalid operation write fence");let n=t.recovery?"unknown":"effects_started",r=t.recovery?"unknown":"running";return{sql:`EXISTS (SELECT 1 FROM operation_executions x JOIN operation_runs r ON r.id=x.run_id
|
|
60
|
-
WHERE x.run_id=? AND x.claim_token=? AND x.phase=? AND x.expires_at_ms > ${a}
|
|
61
|
-
AND r.user_id=? AND r.status=? AND r.tool=? AND r.job_id=?)`,args:[e.runId,e.token,n,e.userId,r,t.tool,t.jobId]}}async function G(e,t,n){let o=(await u().execute({sql:`SELECT r.id,r.request_fingerprint,r.status,x.phase,x.result_json,x.result_status
|
|
62
|
-
FROM operation_runs r LEFT JOIN operation_executions x ON x.run_id=r.id
|
|
63
|
-
WHERE r.user_id=? AND r.idempotency_scope_hash=?`,args:[e,t]})).rows[0];if(!o)return null;if(String(o.request_fingerprint)!==n)throw new E;return o.phase!=="published"||o.status!==o.result_status?null:{runId:String(o.id),result:{json:String(o.result_json),status:o.result_status}}}async function z(e,t){return!!await d(u(),e,t)}async function J(e,t,n){return(await u().execute({sql:`SELECT 1 FROM operation_runs r JOIN operation_executions x ON x.run_id=r.id
|
|
64
|
-
WHERE r.job_id=? AND r.user_id=? AND r.tool=? AND (x.phase='unknown' OR r.status='unknown') LIMIT 1`,args:[e,t,n]})).rows.length>0}function V(e,t,n,r){if(![e,t].every(s=>/^[a-z_.]+$/.test(s))||!/^[a-z_]+$/.test(n))throw Error("Invalid operation group fence");if(r!=null&&(!r.trim()||r.length>512))throw Error("Invalid operation group exclusion");let o=r==null?"":`AND x.run_id <> '${r.replace(/'/g,"''")}'`;return`NOT EXISTS (SELECT 1 FROM operation_runs r JOIN operation_executions x ON x.run_id=r.id
|
|
65
|
-
WHERE r.job_id=${e} AND r.user_id=${t} AND r.tool='${n}'
|
|
66
|
-
AND x.phase IN ('claimed','effects_started') AND x.expires_at_ms > ${a} AND r.status='running' ${o})`}async function K(e,t){l({userId:e.userId,tool:t.tool,jobId:t.jobId},t);try{return await I(e,t)}catch(n){let r=await d(u(),e.runId,e.userId).catch(()=>null);if(r?.phase==="effects_started"&&r.claim_token===e.token&&r.run_status==="running"&&r.tool===t.tool&&r.job_id===t.jobId&&Number(r.expires_at_ms)>Number(r.now_ms))return!0;throw n}}async function B(e,t,n,r){if(!Number.isSafeInteger(t)||t<=0||!e||!n||!r)return null;let o=(await u().execute({sql:`SELECT r.id,r.status,r.normalized_flags_json,r.request_fingerprint,r.started_at,
|
|
67
|
-
e.phase,e.expires_at_ms,${a} AS now_ms FROM operation_runs r JOIN operation_executions e ON e.run_id=r.id
|
|
68
|
-
WHERE r.id=? AND r.user_id=? AND r.tool=? AND r.job_id=?
|
|
69
|
-
AND json_extract(r.normalized_flags_json,'$._storeGateRequired') IS 1`,args:[e,t,n,r]})).rows[0];return o?{runId:String(o.id),status:String(o.status),phase:String(o.phase),flags:JSON.parse(String(o.normalized_flags_json)),fingerprint:String(o.request_fingerprint),startedAt:String(o.started_at),expiresAtMs:Number(o.expires_at_ms),nowMs:Number(o.now_ms)}:null}function Q(e,t,n){if(![e,t].every(r=>/^[a-z_.]+$/.test(r))||!/^[a-z_]+$/.test(n))throw Error("Invalid unresolved operation fence");return`NOT EXISTS (SELECT 1 FROM operation_runs r JOIN operation_executions e ON e.run_id=r.id
|
|
70
|
-
WHERE r.job_id=${e} AND r.user_id=${t} AND r.tool='${n}'
|
|
71
|
-
AND (e.phase IN ('effects_started','unknown') OR r.status='unknown'))`}export{R as a,I as b,j as c,q as d,$ as e,H as f,W as g,F as h,L as i,P as j,M as k,U as l,X as m,v as n,G as o,z as p,J as q,V as r,K as s,B as t,Q as u};
|
package/dist/chunk-B3JRL45T.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{isIP as c}from"net";import{lookup as d}from"dns/promises";import o from"ipaddr.js";function a(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function i(e){let r=a(e);if(!c(r))return!1;try{let t=o.parse(r),s=n=>[["192.0.0.0",24],["192.0.2.0",24],["198.18.0.0",15],["198.51.100.0",24],["203.0.113.0",24]].some(([l,u])=>n.match(o.parse(l),u));if(t instanceof o.IPv6&&t.isIPv4MappedAddress()){let n=t.toIPv4Address();return n.range()!=="unicast"||s(n)}return t instanceof o.IPv4&&s(t)?!0:t.range()!=="unicast"}catch{return!0}}async function p(e){let r=a(e.toLowerCase());if(r==="localhost"||r.endsWith(".localhost")||r.endsWith(".local")||i(r))return!0;try{let t=await d(r,{all:!0,verbatim:!0});return t.length===0||t.some(s=>i(s.address))}catch{return!0}}async function I(e,r){let t;try{t=new URL(e.trim())}catch{return{error:`Invalid ${r.field}`}}return(r.requireHttps?["https:"]:["http:","https:"]).includes(t.protocol)?await p(t.hostname)?{error:`${r.field} must resolve to a public internet host`}:{parsed:t}:{error:r.requireHttps?`${r.field} must use https`:`${r.field} must use http or https`}}export{i as a,I as b};
|
package/dist/chunk-B4ZKPLSP.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function S(){return(process.env.BROWSER_SERVICE_API_KEY??process.env.\u004b\u0045\u0052\u004e\u0045\u004c_API_KEY)?.trim()||void 0}function i(){return(process.env.BROWSER_AGENT_PROFILE_NAME??process.env.BROWSER_SERVICE_PROFILE_NAME??process.env.\u004b\u0045\u0052\u004e\u0045\u004c_BROWSER_PROFILE_NAME??process.env.\u004b\u0045\u0052\u004e\u0045\u004c_PROFILE_NAME)?.trim()||void 0}function u(){let e=(process.env.BROWSER_AGENT_PROFILE_SAVE_CHANGES??process.env.BROWSER_SERVICE_PROFILE_SAVE_CHANGES??process.env.\u004b\u0045\u0052\u004e\u0045\u004c_BROWSER_PROFILE_SAVE_CHANGES??process.env.\u004b\u0045\u0052\u004e\u0045\u004c_PROFILE_SAVE_CHANGES)?.trim().toLowerCase();if(e){if(["1","true","yes","on"].includes(e))return!0;if(["0","false","no","off"].includes(e))return!1}}var A="none";function a(e){switch(e){case"day":return"qdr:d";case"week":return"qdr:w";case"month":return"qdr:m";case"year":return"qdr:y";default:return}}function M(e,r=!1,n="light",t=1,_=!1,E=!1){let o=r&&(_||E)?24e4:r&&n==="full"?t>=2?75e3:45e3:r?4e4:4e5,R=Math.min(o+5e3,795e3);return{serverMs:o,clientMs:R}}function s(e){return e.reason??new DOMException("The operation was aborted.","AbortError")}async function f(e,r){if(!r)return e;if(r.aborted)throw s(r);let n,t=new Promise((_,E)=>{n=()=>E(s(r)),r.addEventListener("abort",n,{once:!0})});e.catch(()=>{});try{return await Promise.race([e,t])}finally{n&&r.removeEventListener("abort",n)}}function O(e,r){let n=AbortSignal.timeout(e);return r?AbortSignal.any([r,n]):n}export{A as a,a as b,M as c,S as d,i as e,u as f,s as g,f as h,O as i};
|
package/dist/chunk-B5Y26E3A.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{z as e}from"zod";import{z as t}from"zod";var o=t.enum(["hubspot","salesforce","highlevel","zoho","pipedrive","keap"]),m=t.object({provider:o,sourceRecordId:t.string().trim().min(1).max(240),occurredAt:t.string().datetime(),updatedAt:t.string().datetime(),contact:t.object({kind:t.enum(["provider_contact_id","verified_email_hmac","verified_phone_hmac"]),reference:t.string().trim().min(1).max(240)}).strict(),event:t.object({name:t.string().regex(/^[a-z][a-z0-9_]{1,79}$/),pipelineId:t.string().trim().min(1).max(240).nullable(),stageId:t.string().trim().min(1).max(240).nullable(),stageLabel:t.string().trim().min(1).max(240).nullable()}).strict(),revenue:t.object({minor:t.number().int().nonnegative(),currency:t.string().regex(/^[A-Z]{3}$/),provenance:t.enum(["provider_verified","mapped_provider_field"])}).strict().nullable(),tombstone:t.boolean()}).strict(),s=t.object({contractVersion:t.literal(1),provider:o,outcomes:t.array(m).max(500),cursor:t.string().max(2e3).nullable(),hasMore:t.boolean(),warnings:t.array(t.enum(["contact_association_missing","currency_missing","deleted_records_unavailable","effective_scope_narrowed","rate_limit_near","schema_drift"])).max(50)}).strict().superRefine((i,a)=>{i.outcomes.some(c=>c.provider!==i.provider)&&a.addIssue({code:t.ZodIssueCode.custom,message:"provider_mismatch"}),i.hasMore&&!i.cursor&&a.addIssue({code:t.ZodIssueCode.custom,message:"cursor_required_when_more"})});function _(i){return s.parse(i)}var r=e.enum(["hubspot","salesforce","highlevel","zoho","pipedrive","keap"]),n=e.enum(["hubspot","highlevel","zoho","keap"]),l=e.enum(["incremental_and_webhook","incremental_only","webhook_only","manual_backfill","unavailable"]),p=e.object({documented:e.boolean(),normalizedAdapter:e.boolean(),advertisedTools:e.array(e.string().trim().min(1).max(120)).max(100),grantedScopes:e.array(e.string().trim().min(1).max(160)).max(200),missingRequirements:e.array(e.string().trim().min(1).max(240)).max(100),tenantSchemaFingerprint:e.string().regex(/^[a-f0-9]{64}$/).nullable(),evaluatedAt:e.string().datetime()}).strict(),d=e.object({provider:r,mode:l,canSyncNow:e.boolean(),canProvisionFields:e.boolean(),canUpsertPerson:e.boolean(),canApplyPipelineEvent:e.boolean(),supportedObjects:e.array(e.string().trim().min(1).max(100)).max(100),evidence:p,caveats:e.array(e.string().trim().min(1).max(500)).max(100)}).strict(),P=d.extend({provider:n}).strict(),g=e.object({object:e.string().trim().min(1).max(100),internalName:e.string().trim().min(1).max(160),label:e.string().trim().min(1).max(160),type:e.enum(["string","number","datetime","url","boolean"]),writable:e.boolean(),required:e.boolean().optional()}).strict(),u=e.object({planId:e.string().regex(/^crmplan_[a-f0-9]{24}$/),provider:r,connectionId:e.string().trim().min(1).max(240),personObject:e.string().trim().min(1).max(100),existingMappings:e.record(e.string().max(160),e.string().max(160)),proposedFields:e.array(g).max(50),fallback:e.enum(["note","activity"]),permissionRequirements:e.array(e.string().trim().min(1).max(160)).max(50),schemaFingerprint:e.string().regex(/^[a-f0-9]{64}$/),requestFingerprint:e.string().regex(/^[a-f0-9]{64}$/),createdAt:e.string().datetime()}).strict(),I=u.extend({provider:n}).strict(),x=e.object({receiptId:e.string().regex(/^crmreceipt_[a-f0-9]{24}$/),planId:e.string().regex(/^crmplan_[a-f0-9]{24}$/),provider:r,connectionId:e.string().trim().min(1).max(240),status:e.enum(["approved","tested","failed"]),createdFields:e.array(e.object({object:e.string().trim().min(1).max(100),internalName:e.string().trim().min(1).max(160),providerFieldId:e.string().trim().min(1).max(240).optional()}).strict()).max(50),existingMappings:e.record(e.string().max(160),e.string().max(160)),cleanup:e.object({supported:e.boolean(),instructions:e.string().max(1e3)}).strict(),planFingerprint:e.string().regex(/^[a-f0-9]{64}$/),occurredAt:e.string().datetime(),errorCode:e.string().regex(/^[a-zA-Z0-9_:-]{1,120}$/).optional()}).strict(),j=x.extend({provider:n}).strict(),z=e.object({identityTier:e.literal("confirmed"),personId:e.string().trim().min(1).max(240),deterministicIdentity:e.object({kind:e.enum(["email","phone","crm_id","customer_id"]),value:e.string().trim().min(1).max(500)}).strict(),contact:e.object({email:e.string().email().max(320).optional(),phone:e.string().trim().min(3).max(50).optional(),firstName:e.string().trim().max(160).optional(),lastName:e.string().trim().max(160).optional()}).strict().optional(),firstTouch:e.string().max(1e3).optional(),lastNonDirectTouch:e.string().max(1e3).optional(),convertingTouch:e.string().max(1e3).optional(),landingPage:e.string().url().max(2e3).optional(),conversionPage:e.string().url().max(2e3).optional(),sessionCount:e.number().int().nonnegative(),eventCount:e.number().int().nonnegative(),campaignClickCoverage:e.string().max(240).optional(),consentReceiptRef:e.string().trim().min(1).max(240),detailedJourneyUrl:e.string().url().max(2e3)}).strict(),y=e.object({version:e.number().int().positive(),eventName:e.string().regex(/^[a-z][a-z0-9_]{1,79}$/),pipelineId:e.string().trim().min(1).max(240),stageId:e.string().trim().min(1).max(240),operation:e.enum(["create_or_update_deal","update_stage"]),valueSource:e.enum(["none","verified_revenue"]),activationEligible:e.boolean()}).strict(),$=e.object({eventId:e.string().trim().min(1).max(240),eventName:e.string().regex(/^[a-z][a-z0-9_]{1,79}$/),occurredAt:e.string().datetime(),verifiedRevenueMinor:e.number().int().nonnegative().optional(),currency:e.string().regex(/^[A-Z]{3}$/).optional()}).strict(),O=e.object({object:e.string().trim().min(1).max(100),sourceEventIdField:e.string().trim().min(1).max(160),occurredAtField:e.string().trim().min(1).max(160),personIdField:e.string().trim().max(160).optional(),dealIdField:e.string().trim().max(160).optional(),stageField:e.string().trim().max(160).optional(),valueField:e.string().trim().max(160).optional(),currencyField:e.string().trim().max(160).optional(),eventName:e.string().trim().min(2).max(80)}).strict(),b=e.object({syncId:e.string().regex(/^crmsync_[a-f0-9]{24}$/),siteId:e.string().uuid(),connectionId:e.string().trim().min(1).max(240),provider:r,state:e.enum(["queued","running","completed","degraded","cancelled","webhook_only"]),mode:e.enum(["initial","incremental","webhook"]),cursor:e.string().max(2e3).nullable(),lastStartedAt:e.string().datetime().nullable(),lastSuccessAt:e.string().datetime().nullable(),nextRunAt:e.string().datetime().nullable(),imported:e.number().int().nonnegative(),deduplicated:e.number().int().nonnegative(),rejected:e.number().int().nonnegative(),lastErrorCode:e.string().regex(/^[a-zA-Z0-9_:-]{1,120}$/).nullable(),requestFingerprint:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),F=b.extend({provider:n}).strict(),R=e.object({code:e.string().regex(/^[a-zA-Z0-9_:-]{1,120}$/),retryable:e.boolean(),message:e.string().max(500)}).strict(),v=e.enum(["contact.email","contact.phone","contact.firstName","contact.lastName","attribution.firstTouch","attribution.lastNonDirectTouch","attribution.convertingTouch","attribution.landingPage","attribution.conversionPage","clickIds.gclid","clickIds.gbraid","clickIds.wbraid","events.selected","revenue.verified"]),f=e.object({policyId:e.string().regex(/^crmpolicy_[a-f0-9]{24}$/),siteId:e.string().uuid(),provider:r,connectionId:e.string().trim().min(1).max(240),kind:e.enum(["person_summary","pipeline_event"]),enabled:e.boolean(),version:e.number().int().positive(),provisioningReceiptId:e.string().regex(/^crmreceipt_[a-f0-9]{24}$/),schemaFingerprint:e.string().regex(/^[a-f0-9]{64}$/),mappingVersion:e.number().int().positive().nullable(),mapping:y.nullable(),allowedFields:e.array(v).max(20),selectedEvents:e.array(e.string().regex(/^[a-z][a-z0-9_]{1,79}$/)).max(100),purpose:e.enum(["necessary_form_fulfillment","site_analytics","advertising_measurement"]),updatedAt:e.string().datetime()}).strict(),k=f.extend({provider:n}).strict(),w=e.object({jobId:e.string().regex(/^crmjob_[a-f0-9]{24}$/),policyId:e.string().regex(/^crmpolicy_[a-f0-9]{24}$/),siteId:e.string().uuid(),personId:e.string().uuid(),kind:e.enum(["person_summary","pipeline_event"]),state:e.enum(["pending","running","retrying","delivered","dead_letter","cancelled"]),policyVersion:e.number().int().positive(),mappingVersion:e.number().int().positive().nullable(),attempts:e.number().int().nonnegative(),nextAttemptAt:e.string().datetime().nullable(),safeErrorCode:e.string().regex(/^[a-zA-Z0-9_:-]{1,120}$/).nullable(),requestFingerprint:e.string().regex(/^[a-f0-9]{64}$/)}).strict(),E=e.object({receiptId:e.string().trim().min(1).max(240),jobId:e.string().trim().min(1).max(240),status:e.enum(["accepted","rejected","failed","retrying"]),externalReceiptId:e.string().trim().min(1).max(240).optional(),safeErrorCode:e.string().regex(/^[a-zA-Z0-9_:-]{1,120}$/).optional(),occurredAt:e.string().datetime()}).strict();export{s as a,_ as b,n as c,d,P as e,g as f,u as g,I as h,x as i,j,z as k,y as l,$ as m,O as n,b as o,F as p,v as q,f as r,k as s,w as t,E as u};
|
package/dist/chunk-C3JWX6KM.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
function S(r,e,t,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!o:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(r,t):o?o.value=t:e.set(r,t),t}function _(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}var ct=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return ct=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};function Ue(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var ve=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};var x=class extends Error{},I=class r extends x{constructor(e,t,n,o){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=o,this.error=t}static makeMessage(e,t,n){let o=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,t,n,o){if(!e||!o)return new D({message:n,cause:ve(t)});let s=t;return e===400?new he(e,s,n,o):e===401?new W(e,s,n,o):e===403?new X(e,s,n,o):e===404?new me(e,s,n,o):e===409?new ye(e,s,n,o):e===422?new ge(e,s,n,o):e===429?new we(e,s,n,o):e>=500?new V(e,s,n,o):new r(e,s,n,o)}},T=class extends I{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},D=class extends I{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},U=class extends D{constructor({message:e}={}){super({message:e??"Request timed out."})}},he=class extends I{},W=class extends I{},X=class extends I{},me=class extends I{},ye=class extends I{},ge=class extends I{},we=class extends I{},V=class extends I{};var Er=/^[a-z][a-z0-9+.-]*:/i,vt=r=>Er.test(r),$=r=>($=Array.isArray,$(r)),lt=$;function ut(r){return typeof r!="object"?{}:r??{}}function ft(r){if(!r)return!0;for(let e in r)return!1;return!0}function Dt(r,e){return Object.prototype.hasOwnProperty.call(r,e)}var Nt=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new x(`${r} must be an integer`);if(e<0)throw new x(`${r} must be a positive integer`);return e},Sr=r=>{if(typeof r=="number")return Math.round(r);if(typeof r=="string")return parseInt(r,10);throw new x(`Could not coerce ${r} (type: ${typeof r}) into a number`)};var Ir=r=>typeof r=="boolean"?r:typeof r=="string"?r==="true":!!r,Ht=r=>{if(r!=null)return Sr(r)};var dt=r=>{if(r!=null)return Ir(r)},Bt=r=>{try{return JSON.parse(r)}catch{return}};var Mt=r=>new Promise(e=>setTimeout(e,r));var z="0.93.0";function $r(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var Lr=()=>{let r=$r();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":qt(Deno.build.os),"X-Stainless-Arch":Kt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":qt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Kt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Tr();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Tr(){if(typeof navigator>"u"||!navigator)return null;let r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${s}.${a}`}}}return null}var Kt=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",qt=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),Wt,Xt=()=>Wt??(Wt=Lr());function Vt(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new \u004b\u0065\u0072\u006e\u0065\u006c({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function pt(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function Ve(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return pt({start(){},async pull(t){let{done:n,value:o}=await e.next();n?t.close():t.enqueue(o)},async cancel(){await e.return?.()}})}function ht(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function zt(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}var Jt=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var mt="RFC3986",yt=r=>String(r),gt={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:yt},Gt="RFC1738";var ze=(r,e)=>(ze=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),ze(r,e)),N=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var wt=1024,Qt=(r,e,t,n,o)=>{if(r.length===0)return r;let s=r;if(typeof r=="symbol"?s=Symbol.prototype.toString.call(r):typeof r!="string"&&(s=String(r)),t==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let a="";for(let c=0;c<s.length;c+=wt){let f=s.length>=wt?s.slice(c,c+wt):s,d=[];for(let m=0;m<f.length;++m){let l=f.charCodeAt(m);if(l===45||l===46||l===95||l===126||l>=48&&l<=57||l>=65&&l<=90||l>=97&&l<=122||o===Gt&&(l===40||l===41)){d[d.length]=f.charAt(m);continue}if(l<128){d[d.length]=N[l];continue}if(l<2048){d[d.length]=N[192|l>>6]+N[128|l&63];continue}if(l<55296||l>=57344){d[d.length]=N[224|l>>12]+N[128|l>>6&63]+N[128|l&63];continue}m+=1,l=65536+((l&1023)<<10|f.charCodeAt(m)&1023),d[d.length]=N[240|l>>18]+N[128|l>>12&63]+N[128|l>>6&63]+N[128|l&63]}a+=d.join("")}return a};function Yt(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function bt(r,e){if($(r)){let t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}var er={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},tr=function(r,e){Array.prototype.push.apply(r,$(e)?e:[e])},Zt,R={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Qt,encodeValuesOnly:!1,format:mt,formatter:yt,indices:!1,serializeDate(r){return(Zt??(Zt=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function Cr(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var xt={};function rr(r,e,t,n,o,s,a,c,f,d,m,l,g,h,A,E,v,k){let b=r,Y=k,Z=0,it=!1;for(;(Y=Y.get(xt))!==void 0&&!it;){let L=Y.get(r);if(Z+=1,typeof L<"u"){if(L===Z)throw new RangeError("Cyclic object value");it=!0}typeof Y.get(xt)>"u"&&(Z=0)}if(typeof d=="function"?b=d(e,b):b instanceof Date?b=g?.(b):t==="comma"&&$(b)&&(b=bt(b,function(L){return L instanceof Date?g?.(L):L})),b===null){if(s)return f&&!E?f(e,R.encoder,v,"key",h):e;b=""}if(Cr(b)||Yt(b)){if(f){let L=E?e:f(e,R.encoder,v,"key",h);return[A?.(L)+"="+A?.(f(b,R.encoder,v,"value",h))]}return[A?.(e)+"="+A?.(String(b))]}let q=[];if(typeof b>"u")return q;let Fe;if(t==="comma"&&$(b))E&&f&&(b=bt(b,f)),Fe=[{value:b.length>0?b.join(",")||null:void 0}];else if($(d))Fe=d;else{let L=Object.keys(b);Fe=m?L.sort(m):L}let kt=c?String(e).replace(/\./g,"%2E"):String(e),Xe=n&&$(b)&&b.length===1?kt+"[]":kt;if(o&&$(b)&&b.length===0)return Xe+"[]";for(let L=0;L<Fe.length;++L){let pe=Fe[L],Ft=typeof pe=="object"&&typeof pe.value<"u"?pe.value:b[pe];if(a&&Ft===null)continue;let at=l&&c?pe.replace(/\./g,"%2E"):pe,Rr=$(b)?typeof t=="function"?t(Xe,at):Xe:Xe+(l?"."+at:"["+at+"]");k.set(r,Z);let Ut=new WeakMap;Ut.set(xt,k),tr(q,rr(Ft,Rr,t,n,o,s,a,c,t==="comma"&&E&&$(b)?null:f,d,m,l,g,h,A,E,v,Ut))}return q}function kr(r=R){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||R.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=mt;if(typeof r.format<"u"){if(!ze(gt,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=gt[t],o=R.filter;(typeof r.filter=="function"||$(r.filter))&&(o=r.filter);let s;if(r.arrayFormat&&r.arrayFormat in er?s=r.arrayFormat:"indices"in r?s=r.indices?"indices":"repeat":s=R.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:R.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:R.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:R.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:R.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?R.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:R.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:R.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:R.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:R.encodeValuesOnly,filter:o,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:R.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:R.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:R.strictNullHandling}}function nr(r,e={}){let t=r,n=kr(e),o,s;typeof n.filter=="function"?(s=n.filter,t=s("",t)):$(n.filter)&&(s=n.filter,o=s);let a=[];if(typeof t!="object"||t===null)return"";let c=er[n.arrayFormat],f=c==="comma"&&n.commaRoundTrip;o||(o=Object.keys(t)),n.sort&&o.sort(n.sort);let d=new WeakMap;for(let g=0;g<o.length;++g){let h=o[g];n.skipNulls&&t[h]===null||tr(a,rr(t[h],h,c,f,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,d))}let m=a.join(n.delimiter),l=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?l+="utf8=%26%2310003%3B&":l+="utf8=%E2%9C%93&"),m.length>0?l+m:""}function or(r){return nr(r,{arrayFormat:"comma"})}function ar(r){let e=0;for(let o of r)e+=o.length;let t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var sr;function De(r){let e;return(sr??(e=new globalThis.TextEncoder,sr=e.encode.bind(e)))(r)}var ir;function _t(r){let e;return(ir??(e=new globalThis.TextDecoder,ir=e.decode.bind(e)))(r)}var j,C,ee=class{constructor(){j.set(this,void 0),C.set(this,void 0),S(this,j,new Uint8Array,"f"),S(this,C,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?De(e):e;S(this,j,ar([_(this,j,"f"),t]),"f");let n=[],o;for(;(o=Ur(_(this,j,"f"),_(this,C,"f")))!=null;){if(o.carriage&&_(this,C,"f")==null){S(this,C,o.index,"f");continue}if(_(this,C,"f")!=null&&(o.index!==_(this,C,"f")+1||o.carriage)){n.push(_t(_(this,j,"f").subarray(0,_(this,C,"f")-1))),S(this,j,_(this,j,"f").subarray(_(this,C,"f")),"f"),S(this,C,null,"f");continue}let s=_(this,C,"f")!==null?o.preceding-1:o.preceding,a=_t(_(this,j,"f").subarray(0,s));n.push(a),S(this,j,_(this,j,"f").subarray(o.index),"f"),S(this,C,null,"f")}return n}flush(){return _(this,j,"f").length?this.decode(`
|
|
2
|
-
`):[]}};j=new WeakMap,C=new WeakMap;ee.NEWLINE_CHARS=new Set([`
|
|
3
|
-
`,"\r"]);ee.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ur(r,e){for(let o=e??0;o<r.length;o++){if(r[o]===10)return{preceding:o,index:o+1,carriage:!1};if(r[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function cr(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}var Ge={off:0,error:200,warn:300,info:400,debug:500},At=(r,e,t)=>{if(r){if(Dt(Ge,r))return r;P(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(Ge))}`)}};function Ne(){}function Je(r,e,t){return!e||Ge[r]>Ge[t]?Ne:e[r].bind(e)}var vr={error:Ne,warn:Ne,info:Ne,debug:Ne},lr=new WeakMap;function P(r){let e=r.logger,t=r.logLevel??"off";if(!e)return vr;let n=lr.get(e);if(n&&n[0]===t)return n[1];let o={error:Je("error",e,t),warn:Je("warn",e,t),info:Je("info",e,t),debug:Je("debug",e,t)};return lr.set(e,[t,o]),o}var H=r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r);var He,Qe=class r{constructor(e,t,n){this.iterator=e,He.set(this,void 0),this.controller=t,S(this,He,n,"f")}static fromSSEResponse(e,t,n){let o=!1,s=n?P(n):console;async function*a(){if(o)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let c=!1;try{for await(let f of Dr(e,t))try{yield JSON.parse(f.data)}catch(d){throw s.error("Could not parse message into JSON:",f.data),s.error("From chunk:",f.raw),d}c=!0}catch(f){if(Ue(f))return;throw f}finally{c||t.abort()}}return new r(a,t,n)}static fromReadableStream(e,t,n){let o=!1;async function*s(){let c=new ee,f=ht(e);for await(let d of f)for(let m of c.decode(d))yield m;for(let d of c.flush())yield d}async function*a(){if(o)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let c=!1;try{for await(let f of s())c||f&&(yield JSON.parse(f));c=!0}catch(f){if(Ue(f))return;throw f}finally{c||t.abort()}}return new r(a,t,n)}[(He=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),o=s=>({next:()=>{if(s.length===0){let a=n.next();e.push(a),t.push(a)}return s.shift()}});return[new r(()=>o(e),this.controller,_(this,He,"f")),new r(()=>o(t),this.controller,_(this,He,"f"))]}toReadableStream(){let e=this,t;return pt({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:s}=await t.next();if(s)return n.close();let a=De(JSON.stringify(o)+`
|
|
4
|
-
`);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await t.return?.()}})}};async function*Dr(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new x("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new x("Attempted to iterate over a response with no body");let t=new Rt,n=new ee,o=ht(r.body);for await(let s of Nr(o))for(let a of n.decode(s)){let c=t.decode(a);c&&(yield c)}for(let s of n.flush()){let a=t.decode(s);a&&(yield a)}}async function*Nr(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?De(t):t,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=cr(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var Rt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
|
|
5
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,o]=Hr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),t==="event"?this.event=o:t==="data"&&this.data.push(o),null}};function Hr(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}async function Ye(r,e){let{response:t,requestLogID:n,retryOfRequestLogID:o,startTime:s}=e,a=await(async()=>{if(e.options.stream)return P(r).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,r):Qe.fromSSEResponse(t,e.controller,r);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let f=t.headers.get("content-type")?.split(";")[0]?.trim();return f?.includes("application/json")||f?.endsWith("+json")?t.headers.get("content-length")==="0"?void 0:await t.json():await t.text()})();return P(r).debug(`[${n}] response parsed`,H({retryOfRequestLogID:o,url:t.url,status:t.status,body:a,durationMs:Date.now()-s})),a}var Be,te=class r extends Promise{constructor(e,t,n=Ye){super(o=>{o(null)}),this.responsePromise=t,this.parseResponse=n,Be.set(this,void 0),S(this,Be,e,"f")}_thenUnwrap(e){return new r(_(this,Be,"f"),this.responsePromise,async(t,n)=>e(await this.parseResponse(t,n),n))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(_(this,Be,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Be=new WeakMap;var Ze,et=class{constructor(e,t,n,o){Ze.set(this,void 0),S(this,Ze,e,"f"),this.options=o,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new x("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await _(this,Ze,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ze=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Me=class extends te{constructor(e,t,n){super(e,t,async(o,s)=>new n(o,s.response,await Ye(o,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},tt=class extends et{constructor(e,t,n,o){super(e,t,n,o),this.items=n||[],this.next_page_token=this.response.headers.get("x-next-page-token")??null,this.has_more=dt(this.response.headers.get("x-has-more"))??null}getPaginatedItems(){return this.items??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next_page_token;return e?{...this.options,query:{...ut(this.options.query),page_token:e}}:null}},w=class extends et{constructor(e,t,n,o){super(e,t,n,o),this.items=n||[],this.has_more=dt(this.response.headers.get("x-has-more"))??null,this.next_offset=Ht(this.response.headers.get("x-next-offset"))??null}getPaginatedItems(){return this.items??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next_offset;if(e==null){if(this.has_more)throw new x("Server reported X-Has-More: true without an X-Next-Offset header; refusing to silently truncate pagination");return null}return e===0?null:{...this.options,query:{...ut(this.options.query),offset:e}}}};var St=()=>{if(typeof File>"u"){let{process:r}=globalThis,e=typeof r?.versions?.node=="string"&&parseInt(r.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function be(r,e,t){return St(),new File(r,e??"unknown_file",t)}function Ke(r){return(typeof r=="object"&&r!==null&&("name"in r&&r.name&&String(r.name)||"url"in r&&r.url&&String(r.url)||"filename"in r&&r.filename&&String(r.filename)||"path"in r&&r.path&&String(r.path))||"").split(/[\\/]/).pop()||void 0}var rt=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function";var B=async(r,e)=>({...r,body:await Kr(r.body,e)}),ur=new WeakMap;function Mr(r){let e=typeof r=="function"?r:r.fetch,t=ur.get(e);if(t)return t;let n=(async()=>{try{let o="Response"in e?e.Response:(await e("data:,")).constructor,s=new FormData;return s.toString()!==await new o(s).text()}catch{return!0}})();return ur.set(e,n),n}var Kr=async(r,e)=>{if(!await Mr(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let t=new FormData;return await Promise.all(Object.entries(r||{}).map(([n,o])=>Et(t,n,o))),t},fr=r=>r instanceof Blob&&"name"in r,qr=r=>typeof r=="object"&&r!==null&&(r instanceof Response||rt(r)||fr(r)),Pt=r=>{if(qr(r))return!0;if(Array.isArray(r))return r.some(Pt);if(r&&typeof r=="object"){for(let e in r)if(Pt(r[e]))return!0}return!1},Et=async(r,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")r.append(e,String(t));else if(t instanceof Response)r.append(e,be([await t.blob()],Ke(t)));else if(rt(t))r.append(e,be([await new Response(Ve(t)).blob()],Ke(t)));else if(fr(t))r.append(e,t,Ke(t));else if(Array.isArray(t))await Promise.all(t.map((n,o)=>Et(r,`${e}[${o}]`,n)));else if(typeof t=="object")!(e==="env_vars")&&!Pt(t)?Object.entries(t).filter(([s,a])=>a!==void 0).length>0&&r.append(e,JSON.stringify(t)):await Promise.all(Object.entries(t).map(([o,s])=>Et(r,`${e}[${o}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var dr=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function",Wr=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&dr(r),Xr=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function";async function nt(r,e,t){if(St(),r=await r,Wr(r))return r instanceof File?r:be([await r.arrayBuffer()],r.name);if(Xr(r)){let o=await r.blob();return e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()),be(await It(o),e,t)}let n=await It(r);if(e||(e=Ke(r)),!t?.type){let o=n.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof o=="string"&&(t={...t,type:o})}return be(n,e,t)}async function It(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(dr(r))e.push(r instanceof Blob?r:await r.arrayBuffer());else if(rt(r))for await(let t of r)e.push(...await It(t));else{let t=r?.constructor?.name;throw new Error(`Unexpected data type: ${typeof r}${t?`; constructor: ${t}`:""}${Vr(r)}`)}return e}function Vr(r){return typeof r!="object"||r===null?"":`; props: [${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}var p=class{constructor(e){this._client=e}};var pr=Symbol("brand.privateNullableHeaders");function*Jr(r){if(!r)return;if(pr in r){let{values:n,nulls:o}=r;yield*n.entries();for(let s of o)yield[s,null];return}let e=!1,t;r instanceof Headers?t=r.entries():lt(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let n of t){let o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let s=lt(n[1])?n[1]:[n[1]],a=!1;for(let c of s)c!==void 0&&(e&&!a&&(a=!0,yield[o,null]),yield[o,c])}}var u=r=>{let e=new Headers,t=new Set;for(let n of r){let o=new Set;for(let[s,a]of Jr(n)){let c=s.toLowerCase();o.has(c)||(e.delete(s),o.add(c)),a===null?(e.delete(s),t.add(c)):(e.append(s,a),t.delete(c))}}return{[pr]:!0,values:e,nulls:t}};function mr(r){return r.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var hr=Object.freeze(Object.create(null)),Gr=(r=mr)=>function(t,...n){if(t.length===1)return t[0];let o=!1,s=[],a=t.reduce((m,l,g)=>{/[?#]/.test(l)&&(o=!0);let h=n[g],A=(o?encodeURIComponent:r)(""+h);return g!==n.length&&(h==null||typeof h=="object"&&h.toString===Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??hr)??hr)?.toString)&&(A=h+"",s.push({start:m.length+l.length,length:A.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),m+l+(g===n.length?"":A)},""),c=a.split(/[?#]/,1)[0],f=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,d;for(;(d=f.exec(c))!==null;)s.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(s.sort((m,l)=>m.start-l.start),s.length>0){let m=0,l=s.reduce((g,h)=>{let A=" ".repeat(h.start-m),E="^".repeat(h.length);return m=h.start+h.length,g+A+E},"");throw new x(`Path parameters result in path with invalid segments:
|
|
6
|
-
${s.map(g=>g.error).join(`
|
|
7
|
-
`)}
|
|
8
|
-
${a}
|
|
9
|
-
${l}`)}return a},i=Gr(mr);var re=class extends p{create(e,t){return this._client.post("/org/api_keys",{body:e,...t})}retrieve(e,t={},n){return this._client.get(i`/org/api_keys/${e}`,{query:t,...n})}update(e,t,n){return this._client.patch(i`/org/api_keys/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/org/api_keys",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/org/api_keys/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}rotate(e,t={},n){return this._client.post(i`/org/api_keys/${e}/rotate`,{body:t,...n})}};var ne=class extends p{list(e={},t){return this._client.getAPIList("/apps",w,{query:e,...t})}};var xe=class extends p{create(e,t){return this._client.post("/audit-logs/export/destinations",{body:e,...t})}retrieve(e,t){return this._client.get(i`/audit-logs/export/destinations/${e}`,t)}update(e,t,n){return this._client.patch(i`/audit-logs/export/destinations/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/audit-logs/export/destinations",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/audit-logs/export/destinations/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}test(e,t){return this._client.post(i`/audit-logs/export/destinations/${e}/test`,t)}};var Yr=6,Zr=5e4,en=8e3,F=class extends x{};async function gr(r,e,t,n,o={}){if(!t||typeof t.write!="function")throw new TypeError("audit log download destination must provide write()");let{onProgress:s,maxTransferRetries:a=Yr,...c}=o;if(!Number.isInteger(a)||a<0)throw new TypeError("maxTransferRetries must be a non-negative integer");let f=c.timeout??n,d,m={bytesWritten:0,chunks:0,rows:0},l=new Set;for(;;){let g=await tn(r,d?{...e,cursor:d}:e,c,a,f),{nextCursor:h,hasMore:A,rows:E}=rn(g.headers,d);if(A&&h){if(l.has(h))throw new F("response repeated X-Next-Cursor header");l.add(h)}if(await sn(t,g.body),d=h,m.bytesWritten+=g.body.byteLength,m.chunks+=1,m.rows+=E,s&&await s({...m,chunkRows:E}),!A)return m}}async function tn(r,e,t,n,o){for(let s=0;;s+=1){let a=new AbortController,c=()=>a.abort();t.signal?.aborted?a.abort():t.signal?.addEventListener("abort",c,{once:!0});let f;try{f=await r(e,{...t,signal:a.signal})}catch(l){throw t.signal?.removeEventListener("abort",c),l}let d=!1,m=setTimeout(()=>{d=!0,a.abort()},o);try{let l=new Uint8Array(await f.arrayBuffer());if(clearTimeout(m),t.signal?.aborted)throw new T;if(d)throw new U;let g=f.headers.get("x-content-sha256");if(!g)throw new F("response missing X-Content-Sha256 header");let h=await nn(l);if(t.signal?.aborted)throw new T;if(h!==g)throw new F(`audit log chunk checksum mismatch (got ${h}, want ${g})`);return{body:l,headers:f.headers}}catch(l){if(t.signal?.aborted&&!(l instanceof T)?l=new T:d&&(l=new U),s===n||l instanceof T)throw l;await on(s+1,t.signal)}finally{clearTimeout(m),t.signal?.removeEventListener("abort",c)}}}function rn(r,e){let t=r.get("x-has-more");if(t!=="true"&&t!=="false")throw new F("response missing or invalid X-Has-More header");let n=t==="true",o=r.get("x-row-count");if(o===null||!/^[0-9]+$/.test(o))throw new F("response missing or invalid X-Row-Count header");let s=Number(o);if(!Number.isSafeInteger(s)||s>Zr)throw new F("response missing or invalid X-Row-Count header");let a=r.get("x-next-cursor")||void 0;if(n&&(!a||a===e))throw new F("response has invalid X-Next-Cursor header");if(!n&&a)throw new F("response returned a cursor after the final chunk");return{rows:s,nextCursor:a,hasMore:n}}async function nn(r){let e=await globalThis.crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(e),t=>t.toString(16).padStart(2,"0")).join("")}async function on(r,e){let t=Math.min(1e3*2**(r-1),en);await new Promise((n,o)=>{if(e?.aborted){o(new T);return}let s=()=>{clearTimeout(a),o(new T)},a=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t);e?.addEventListener("abort",s,{once:!0})})}async function sn(r,e){let t=0;for(;t<e.byteLength;){let n=await r.write(t===0?e:e.subarray(t));if(typeof n=="number"){t+=yr(n,e.byteLength-t);continue}if(n&&typeof n=="object"&&"bytesWritten"in n){let o=n.bytesWritten;t+=yr(o,e.byteLength-t);continue}return}}function yr(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new F("audit log download destination performed a short write");return r}var J=class extends p{constructor(){super(...arguments),this.exportDestinations=new xe(this._client)}list(e,t){return this._client.getAPIList("/audit-logs",tt,{query:e,...t})}exportChunk(e,t){return this._client.get("/audit-logs/export/chunk",{query:e,...t,headers:u([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}download(e,t,n){return gr((o,s)=>this.exportChunk(o,s),e,t,this._client.timeout,n)}};J.ExportDestinations=xe;var _e=class extends p{create(e,t){return this._client.post("/auth/connections",{body:e,...t})}retrieve(e,t){return this._client.get(i`/auth/connections/${e}`,t)}update(e,t,n){return this._client.patch(i`/auth/connections/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/auth/connections",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/auth/connections/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}follow(e,t){return this._client.get(i`/auth/connections/${e}/events`,{...t,headers:u([{Accept:"text/event-stream"},t?.headers]),stream:!0})}login(e,t={},n){return this._client.post(i`/auth/connections/${e}/login`,{body:t,...n})}submit(e,t,n){return this._client.post(i`/auth/connections/${e}/submit`,{body:t,...n})}timeline(e,t={},n){return this._client.getAPIList(i`/auth/connections/${e}/timeline`,w,{query:t,...n})}};var Ae=class extends p{retrieve(e){return this._client.get("/auth/context",e)}};var M=class extends p{constructor(){super(...arguments),this.context=new Ae(this._client),this.connections=new _e(this._client)}};M.Context=Ae;M.Connections=_e;var oe=class extends p{create(e,t){return this._client.post("/browser_pools",{body:e,...t})}retrieve(e,t){return this._client.get(i`/browser_pools/${e}`,t)}update(e,t,n){return this._client.patch(i`/browser_pools/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/browser_pools",w,{query:e,...t})}delete(e,t={},n){return this._client.delete(i`/browser_pools/${e}`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}acquire(e,t,n){return this._client.post(i`/browser_pools/${e}/acquire`,{body:t,...n})}flush(e,t){return this._client.post(i`/browser_pools/${e}/flush`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}release(e,t,n){return this._client.post(i`/browser_pools/${e}/release`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}};var Re=class extends p{batch(e,t,n){return this._client.post(i`/browsers/${e}/computer/batch`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}captureScreenshot(e,t={},n){return this._client.post(i`/browsers/${e}/computer/screenshot`,{body:t,...n,headers:u([{Accept:"image/png"},n?.headers]),__binaryResponse:!0})}clickMouse(e,t,n){return this._client.post(i`/browsers/${e}/computer/click_mouse`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}dragMouse(e,t,n){return this._client.post(i`/browsers/${e}/computer/drag_mouse`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}getMousePosition(e,t){return this._client.post(i`/browsers/${e}/computer/get_mouse_position`,t)}moveMouse(e,t,n){return this._client.post(i`/browsers/${e}/computer/move_mouse`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}pressKey(e,t,n){return this._client.post(i`/browsers/${e}/computer/press_key`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}readClipboard(e,t){return this._client.post(i`/browsers/${e}/computer/clipboard/read`,t)}scroll(e,t,n){return this._client.post(i`/browsers/${e}/computer/scroll`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}setCursorVisibility(e,t,n){return this._client.post(i`/browsers/${e}/computer/cursor`,{body:t,...n})}typeText(e,t,n){return this._client.post(i`/browsers/${e}/computer/type`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}writeClipboard(e,t,n){return this._client.post(i`/browsers/${e}/computer/clipboard/write`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}};var Pe=class extends p{stream(e,t,n){return this._client.get(i`/browsers/${e}/logs/stream`,{query:t,...n,headers:u([{Accept:"text/event-stream"},n?.headers]),stream:!0})}};var Ee=class extends p{execute(e,t,n){return this._client.post(i`/browsers/${e}/playwright/execute`,{body:t,...n})}};var Se=class extends p{exec(e,t,n){return this._client.post(i`/browsers/${e}/process/exec`,{body:t,...n})}kill(e,t,n){let{id:o,...s}=t;return this._client.post(i`/browsers/${o}/process/${e}/kill`,{body:s,...n})}resize(e,t,n){let{id:o,...s}=t;return this._client.post(i`/browsers/${o}/process/${e}/resize`,{body:s,...n})}spawn(e,t,n){return this._client.post(i`/browsers/${e}/process/spawn`,{body:t,...n})}status(e,t,n){let{id:o}=t;return this._client.get(i`/browsers/${o}/process/${e}/status`,n)}stdin(e,t,n){let{id:o,...s}=t;return this._client.post(i`/browsers/${o}/process/${e}/stdin`,{body:s,...n})}stdoutStream(e,t,n){let{id:o}=t;return this._client.get(i`/browsers/${o}/process/${e}/stdout/stream`,{...n,headers:u([{Accept:"text/event-stream"},n?.headers]),stream:!0})}};var Ie=class extends p{list(e,t){return this._client.get(i`/browsers/${e}/replays`,t)}download(e,t,n){let{id:o}=t;return this._client.get(i`/browsers/${o}/replays/${e}`,{...n,headers:u([{Accept:"video/mp4"},n?.headers]),__binaryResponse:!0})}start(e,t={},n){return this._client.post(i`/browsers/${e}/replays`,{body:t,...n})}stop(e,t,n){let{id:o}=t;return this._client.post(i`/browsers/${o}/replays/${e}/stop`,{...n,headers:u([{Accept:"*/*"},n?.headers])})}};var $e=class extends p{events(e,t={},n){return this._client.getAPIList(i`/browsers/${e}/telemetry/events`,w,{query:t,...n})}stream(e,t={},n){let{"Last-Event-ID":o,...s}=t??{};return this._client.get(i`/browsers/${e}/telemetry/stream`,{query:s,...n,headers:u([{Accept:"text/event-stream",...o!=null?{"Last-Event-ID":o}:void 0},n?.headers]),stream:!0})}};var Le=class extends p{events(e,t,n){let{id:o}=t;return this._client.get(i`/browsers/${o}/fs/watch/${e}/events`,{...n,headers:u([{Accept:"text/event-stream"},n?.headers]),stream:!0})}start(e,t,n){return this._client.post(i`/browsers/${e}/fs/watch`,{body:t,...n})}stop(e,t,n){let{id:o}=t;return this._client.delete(i`/browsers/${o}/fs/watch/${e}`,{...n,headers:u([{Accept:"*/*"},n?.headers])})}};var se=class extends p{constructor(){super(...arguments),this.watch=new Le(this._client)}createDirectory(e,t,n){return this._client.put(i`/browsers/${e}/fs/create_directory`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}deleteDirectory(e,t,n){return this._client.put(i`/browsers/${e}/fs/delete_directory`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}deleteFile(e,t,n){return this._client.put(i`/browsers/${e}/fs/delete_file`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}downloadDirZip(e,t,n){return this._client.get(i`/browsers/${e}/fs/download_dir_zip`,{query:t,...n,headers:u([{Accept:"application/zip"},n?.headers]),__binaryResponse:!0})}fileInfo(e,t,n){return this._client.get(i`/browsers/${e}/fs/file_info`,{query:t,...n})}listFiles(e,t,n){return this._client.get(i`/browsers/${e}/fs/list_files`,{query:t,...n})}move(e,t,n){return this._client.put(i`/browsers/${e}/fs/move`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}readFile(e,t,n){return this._client.get(i`/browsers/${e}/fs/read_file`,{query:t,...n,headers:u([{Accept:"application/octet-stream"},n?.headers]),__binaryResponse:!0})}setFilePermissions(e,t,n){return this._client.put(i`/browsers/${e}/fs/set_file_permissions`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}upload(e,t,n){return this._client.post(i`/browsers/${e}/fs/upload`,B({body:t,...n,headers:u([{Accept:"*/*"},n?.headers])},this._client))}uploadZip(e,t,n){return this._client.post(i`/browsers/${e}/fs/upload_zip`,B({body:t,...n,headers:u([{Accept:"*/*"},n?.headers])},this._client))}writeFile(e,t,n,o){let{path:s,mode:a}=n;return this._client.put(i`/browsers/${e}/fs/write_file`,{body:t,query:{path:s,mode:a},...o,headers:u([{"Content-Type":"application/octet-stream",Accept:"*/*"},o?.headers])})}};se.Watch=Le;function ot(r,e){return`${r.replace(/\/+$/,"")}${e.startsWith("/")?e:`/${e}`}`}async function wr(r,e,t,n){let o=r.browserRouteCache.get(e);if(!o)throw new x(`browser route cache does not contain session ${e}; create, retrieve, or list the browser before calling browser.fetch`);let{url:s,method:a,headers:c,body:f,signal:d,duplex:m,timeout_ms:l}=wn(t,n);bn(s);let g={url:s,jwt:o.jwt};l!==void 0&&(g.timeout_ms=l);let h=c.get("accept"),A={method:gn(a),path:ot(o.baseURL,"/curl/raw"),query:g,body:f,headers:u([{Authorization:null},h?{Accept:h}:{Accept:"*/*"},xn(c)]),signal:d??null,__binaryResponse:!0};return m&&(A.fetchOptions={duplex:m}),r.request(A).asResponse()}function gn(r){let e=r.toLowerCase();if(!new Set(["get","post","put","patch","delete"]).has(e))throw new x(`browser.fetch unsupported HTTP method: ${r}`);return e}function wn(r,e){let t=e&&"timeout_ms"in e?e.timeout_ms:void 0;if(r instanceof Request){let o=new Headers(r.headers);e?.headers&&new Headers(e.headers).forEach((d,m)=>{o.set(m,d)});let s={url:r.url,method:(e?.method??r.method)?.toUpperCase()||"GET",headers:o},a=e?.body??r.body;a!=null&&(s.body=a);let c=e?.signal??r.signal;return c!==void 0&&(s.signal=c),e?.duplex!==void 0&&(s.duplex=e.duplex),t!==void 0&&(s.timeout_ms=t),s}let n={url:r instanceof URL?r.href:String(r),method:(e?.method??"GET").toUpperCase(),headers:new Headers(e?.headers)};return e?.body!==void 0&&(n.body=e.body),e?.signal!==void 0&&(n.signal=e.signal),e?.duplex!==void 0&&(n.duplex=e.duplex),t!==void 0&&(n.timeout_ms=t),n}function bn(r){let e;try{e=new URL(r)}catch{throw new x(`browser.fetch target must be an absolute URL; received: ${r}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new x(`browser.fetch only supports http(s) URLs; received: ${e.protocol}`)}function xn(r){let e={};return r.forEach((t,n)=>{switch(n.toLowerCase()){case"accept":case"content-length":case"connection":case"keep-alive":case"proxy-authenticate":case"proxy-authorization":case"te":case"trailers":case"transfer-encoding":case"upgrade":return;default:e[n]=t}}),e}var O=class extends p{constructor(){super(...arguments),this.telemetry=new $e(this._client),this.replays=new Ie(this._client),this.fs=new se(this._client),this.process=new Se(this._client),this.logs=new Pe(this._client),this.computer=new Re(this._client),this.playwright=new Ee(this._client)}create(e={},t){return this._client.post("/browsers",{body:e,...t})}retrieve(e,t={},n){return this._client.get(i`/browsers/${e}`,{query:t,...n})}update(e,t,n){return this._client.patch(i`/browsers/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/browsers",w,{query:e,...t})}curl(e,t,n){return this._client.post(i`/browsers/${e}/curl`,{body:t,...n})}fetch(e,t,n){return wr(this._client,e,t,n)}deleteByID(e,t){return this._client.delete(i`/browsers/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}loadExtensions(e,t,n){return this._client.post(i`/browsers/${e}/extensions`,B({body:t,...n,headers:u([{Accept:"*/*"},n?.headers])},this._client))}};O.Telemetry=$e;O.Replays=Ie;O.Fs=se;O.Process=Se;O.Logs=Pe;O.Computer=Re;O.Playwright=Ee;var ie=class extends p{create(e,t){return this._client.post("/org/credential_providers",{body:e,...t})}retrieve(e,t){return this._client.get(i`/org/credential_providers/${e}`,t)}update(e,t,n){return this._client.patch(i`/org/credential_providers/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/org/credential_providers",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/org/credential_providers/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}listItems(e,t){return this._client.get(i`/org/credential_providers/${e}/items`,t)}test(e,t){return this._client.post(i`/org/credential_providers/${e}/test`,t)}};var ae=class extends p{create(e,t){return this._client.post("/credentials",{body:e,...t})}retrieve(e,t){return this._client.get(i`/credentials/${e}`,t)}update(e,t,n){return this._client.patch(i`/credentials/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/credentials",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/credentials/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}totpCode(e,t){return this._client.get(i`/credentials/${e}/totp-code`,t)}};var ce=class extends p{create(e,t){return this._client.post("/deployments",B({body:e,...t},this._client))}retrieve(e,t){return this._client.get(i`/deployments/${e}`,t)}list(e={},t){return this._client.getAPIList("/deployments",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/deployments/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}follow(e,t={},n){return this._client.get(i`/deployments/${e}/events`,{query:t,...n,headers:u([{Accept:"text/event-stream"},n?.headers]),stream:!0})}};var le=class extends p{list(e={},t){return this._client.getAPIList("/extensions",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/extensions/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}download(e,t){return this._client.get(i`/extensions/${e}`,{...t,headers:u([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}downloadFromChromeStore(e,t){return this._client.get("/extensions/from_chrome_store",{query:e,...t,headers:u([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}get(e,t){return this._client.get(i`/extensions/${e}/metadata`,t)}upload(e,t){return this._client.post("/extensions",B({body:e,...t},this._client))}};var ue=class extends p{create(e,t){return this._client.post("/invocations",{body:e,...t})}retrieve(e,t){return this._client.get(i`/invocations/${e}`,t)}update(e,t,n){return this._client.patch(i`/invocations/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/invocations",w,{query:e,...t})}deleteBrowsers(e,t){return this._client.delete(i`/invocations/${e}/browsers`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}follow(e,t={},n){return this._client.get(i`/invocations/${e}/events`,{query:t,...n,headers:u([{Accept:"text/event-stream"},n?.headers]),stream:!0})}listBrowsers(e,t){return this._client.get(i`/invocations/${e}/browsers`,t)}};var Te=class extends p{retrieve(e){return this._client.get("/org/entitlements",e)}};var Oe=class extends p{retrieve(e){return this._client.get("/org/limits",e)}update(e,t){return this._client.patch("/org/limits",{body:e,...t})}};var K=class extends p{constructor(){super(...arguments),this.entitlements=new Te(this._client),this.limits=new Oe(this._client)}};K.Entitlements=Te;K.Limits=Oe;var fe=class extends p{create(e,t){return this._client.post("/profiles",{body:e,...t})}retrieve(e,t){return this._client.get(i`/profiles/${e}`,t)}update(e,t,n){return this._client.patch(i`/profiles/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/profiles",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/profiles/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}download(e,t={},n){return this._client.get(i`/profiles/${e}/download`,{query:t,...n,headers:u([{Accept:"application/octet-stream"},n?.headers]),__binaryResponse:!0})}};var je=class extends p{retrieve(e,t){return this._client.get(i`/org/projects/${e}/limits`,t)}update(e,t,n){return this._client.patch(i`/org/projects/${e}/limits`,{body:t,...n})}};var G=class extends p{constructor(){super(...arguments),this.limits=new je(this._client)}create(e,t){return this._client.post("/org/projects",{body:e,...t})}retrieve(e,t){return this._client.get(i`/org/projects/${e}`,t)}update(e,t,n){return this._client.patch(i`/org/projects/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/org/projects",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/org/projects/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}};G.Limits=je;var de=class extends p{create(e,t){return this._client.post("/proxies",{body:e,...t})}retrieve(e,t){return this._client.get(i`/proxies/${e}`,t)}update(e,t,n){return this._client.patch(i`/proxies/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/proxies",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/proxies/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}check(e,t={},n){return this._client.post(i`/proxies/${e}/check`,{body:t,...n})}};var Ce=class extends p{create(e,t){return this._client.post("/telemetry/destinations",{body:e,...t})}retrieve(e,t){return this._client.get(i`/telemetry/destinations/${e}`,t)}update(e,t,n){return this._client.patch(i`/telemetry/destinations/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/telemetry/destinations",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/telemetry/destinations/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}};var Q=class extends p{constructor(){super(...arguments),this.destinations=new Ce(this._client)}};Q.Destinations=Ce;var qe=class{constructor(){this.entries=new Map}get(e){return this.entries.get(e)}set(e){this.entries.set(e.sessionId,e)}delete(e){this.entries.delete(e)}clear(){this.entries.clear()}},br="\u004b\u0045\u0052\u004e\u0045\u004c_BROWSER_ROUTING_SUBRESOURCES",Sn=["curl","telemetry/stream"],In=/^\/(?:v\d+\/)?browsers(?:\/[^/]+)?\/?$/,$n=/^\/(?:v\d+\/)?browser_pools\/[^/]+\/acquire\/?$/,Ln=/^\/(?:v\d+\/)?browsers\/([^/]+)\/?$/,Tn=/^\/(?:v\d+\/)?browser_pools\/[^/]+\/release\/?$/;function Lt(){let r=Kn();return r===void 0?[...Sn]:r.trim()===""?[]:r.split(",").map(e=>e.trim()).filter(Boolean)}function Tt(r,{apiBaseURL:e,subresources:t,cache:n}){let o=[...t].map(a=>a.trim().replace(/^\/+|\/+$/g,"")).filter(Boolean),s=new URL(e).origin;return async(a,c)=>{let f=new Request(a,c),d=On(f,s),m=await Dn(r,{input:a,init:c,request:f},s,o,n);return d&&await Un(m,n),await jn(f,m,s,n),m}}function On(r,e){let t=new URL(r.url);return t.origin===e&&(In.test(t.pathname)||$n.test(t.pathname))}async function jn(r,e,t,n){if(!e.ok)return;let o=new URL(r.url);if(o.origin!==t)return;let s=Cn(r,o.pathname)??await kn(r,o.pathname);s&&n.delete(s)}function Cn(r,e){if(r.method.toUpperCase()!=="DELETE")return;let t=e.match(Ln);return t&&decodeURIComponent(t[1]??"")||void 0}async function kn(r,e){if(!(r.method.toUpperCase()!=="POST"||!Tn.test(e)))try{let t=await r.clone().json();if(!t||typeof t!="object")return;let n=t.session_id;return typeof n=="string"&&n.trim()?n.trim():void 0}catch{return}}function Fn(r){if(!r||typeof r!="object")return;let e=r,t=typeof e.session_id=="string"?e.session_id.trim():"",n=typeof e.base_url=="string"?e.base_url.trim():"";if(!t||!n)return;let o=typeof e.jwt=="string"?e.jwt.trim():"",s=typeof e.cdp_ws_url=="string"?e.cdp_ws_url:void 0,a=o||Mn(s)||"";if(a)return{sessionId:t,baseURL:n,jwt:a}}async function Un(r,e){if((r.headers.get("content-type")?.toLowerCase()??"").includes("application/json"))try{$t(await r.clone().json(),e)}catch{}}function $t(r,e){let t=Fn(r);if(t&&e.set(t),Array.isArray(r)){for(let n of r)$t(n,e);return}if(!(!r||typeof r!="object"))for(let n of Object.values(r))typeof n=="object"&&n!==null&&$t(n,e)}function vn(r,e){let t=r.replace(/^\/+|\/+$/g,"");return e.some(n=>t===n||t.startsWith(n+"/"))}async function Dn(r,{input:e,init:t,request:n},o,s,a){let c=new URL(n.url);if(c.origin!==o)return r(e,t);let f=c.pathname.match(/^\/(?:v\d+\/)?browsers\/([^/]+)\/([^/]+)(\/.*)?$/);if(!f)return r(e,t);let d=decodeURIComponent(f[1]??""),m=f[2]??"";if(!d||!vn(m+(f[3]??""),s))return r(e,t);let l=a.get(d);if(l===void 0)return r(e,t);let g=new URL(ot(l.baseURL,`/${m}${f[3]??""}`));c.searchParams.forEach((A,E)=>{E!=="jwt"&&g.searchParams.append(E,A)}),g.searchParams.get("jwt")||g.searchParams.set("jwt",l.jwt);let h=new Headers(n.headers);return h.delete("authorization"),r(g.toString(),Nn(e,n,t,h))}function Nn(r,e,t,n){let o=e.method.toUpperCase(),s={...t??{},method:o,headers:n,redirect:e.redirect,signal:t?.signal??(r instanceof Request?r.signal:void 0)};if(delete s.body,delete s.duplex,o!=="GET"&&o!=="HEAD"){let a=Hn(e,t);a!==void 0&&(s.body=a),t?.duplex!==void 0?s.duplex=t.duplex:Bn(a)&&(s.duplex="half")}return s}function Hn(r,e){return e?.body!==void 0&&e.body!==null?e.body:r.body??void 0}function Bn(r){return globalThis.ReadableStream&&r instanceof globalThis.ReadableStream||typeof r=="object"&&r!==null&&Symbol.asyncIterator in r}function Mn(r){if(r)try{return new URL(r).searchParams.get("jwt")??void 0}catch{return}}function Kn(){if(typeof globalThis.process<"u"){let r=globalThis.process.env?.[br];return typeof r=="string"?r:void 0}if(typeof globalThis.Deno<"u"){let r=globalThis.Deno.env?.get?.(br);return typeof r=="string"?r:void 0}}var st=class{constructor(e){this.actions=new Map,this.name=e,xr.registerApp(this)}action(e,t){let n;if(t.length===0)throw new Error("Action handlers must accept at least the context parameter");if(t.length===1){let o=t;n=async(s,a)=>o(s)}else n=t;return this.actions.set(e,{name:e,handler:n}),n}getActions(){return Array.from(this.actions.values())}getAction(e){return this.actions.get(e)}toJSON(){return{name:this.name,actions:this.getActions().map(e=>({name:e.name}))}}},Ot=class{constructor(){this.apps=new Map}registerApp(e){this.apps.set(e.name,e)}getApps(){return Array.from(this.apps.values())}getAppByName(e){return this.apps.get(e)}export(){return{apps:this.getApps().map(e=>e.toJSON())}}exportJSON(){return JSON.stringify(this.export(),null,2)}},xr=new Ot;var ke=r=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()||void 0};var jt,Ct,We,_r,Ar={production:"https://api.on\u006b\u0065\u0072\u006e\u0065\u006c.com/",development:"https://localhost:3001/"},y=class{constructor({baseURL:e=ke("\u004b\u0045\u0052\u004e\u0045\u004c_BASE_URL"),apiKey:t=ke("\u004b\u0045\u0052\u004e\u0045\u004c_API_KEY"),projectID:n=null,project:o=null,...s}={}){if(jt.add(this),We.set(this,void 0),this.deployments=new ce(this),this.apps=new ne(this),this.invocations=new ue(this),this.browsers=new O(this),this.profiles=new fe(this),this.auth=new M(this),this.telemetry=new Q(this),this.proxies=new de(this),this.extensions=new le(this),this.browserPools=new oe(this),this.credentials=new ae(this),this.projects=new G(this),this.organization=new K(this),this.auditLogs=new J(this),this.apiKeys=new re(this),this.credentialProviders=new ie(this),typeof globalThis<"u"&&typeof globalThis.Bun<"u"&&globalThis.Bun.version&&!ke("\u004b\u0045\u0052\u004e\u0045\u004c_SUPPRESS_BUN_WARNING")&&P(this).warn("The Bun runtime was detected. Playwright may have CDP connection issues, proceed with caution. Suppress this warning by setting the \u004b\u0045\u0052\u004e\u0045\u004c_SUPPRESS_BUN_WARNING environment variable to true"),t===void 0)throw new x("The \u004b\u0045\u0052\u004e\u0045\u004c_API_KEY environment variable is missing or empty; either provide it, or instantiate the \u004b\u0065\u0072\u006e\u0065\u006c client with an apiKey option, like new \u004b\u0065\u0072\u006e\u0065\u006c({ apiKey: 'My API Key' }).");let a={apiKey:t,projectID:n,project:o,...s,baseURL:e,environment:s.environment??"production"};if(e&&s.environment)throw new x("Ambiguous URL; The `baseURL` option (or \u004b\u0045\u0052\u004e\u0045\u004c_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null");this.baseURL=a.baseURL||Ar[a.environment||"production"],this.timeout=a.timeout??Ct.DEFAULT_TIMEOUT,this.logger=a.logger??console;let c="warn";this.logLevel=c,this.logLevel=At(a.logLevel,"ClientOptions.logLevel",this)??At(ke("\u004b\u0045\u0052\u004e\u0045\u004c_LOG"),"process.env['\u004b\u0045\u0052\u004e\u0045\u004c_LOG']",this)??c,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.rawFetch=a.fetch??Vt(),this.browserRouteCache=new qe,this.fetch=Tt(this.rawFetch,{apiBaseURL:this.baseURL,subresources:Lt(),cache:this.browserRouteCache}),S(this,We,Jt,"f");let f=ke("\u004b\u0045\u0052\u004e\u0045\u004c_CUSTOM_HEADERS");if(f){let d={};for(let m of f.split(`
|
|
10
|
-
`)){let l=m.indexOf(":");l>=0&&(d[m.substring(0,l).trim()]=m.substring(l+1).trim())}a.defaultHeaders={...d,...a.defaultHeaders}}this._options=a,this.apiKey=t,this.projectID=n,this.project=o}withOptions(e){let t=new this.constructor({...this._options,environment:e.environment?e.environment:void 0,baseURL:e.environment?void 0:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.rawFetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,projectID:this.projectID,project:this.project,...e});return t.browserRouteCache=this.browserRouteCache,t.fetch=Tt(t.rawFetch,{apiBaseURL:t.baseURL,subresources:Lt(),cache:t.browserRouteCache}),t}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return u([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return or(e)}getUserAgent(){return`${this.constructor.name}/JS ${z}`}defaultIdempotencyKey(){return`stainless-node-retry-${ct()}`}makeStatusError(e,t,n,o){return I.generate(e,t,n,o)}buildURL(e,t,n){let o=!_(this,jt,"m",_r).call(this)&&n||this.baseURL,s=vt(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),c=Object.fromEntries(s.searchParams);return(!ft(a)||!ft(c))&&(t={...c,...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(s.search=this.stringifyQuery(t)),s.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(o=>({method:e,path:t,...o})))}request(e,t=null){return new te(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let o=await e,s=o.maxRetries??this.maxRetries;t==null&&(t=s),await this.prepareOptions(o);let{req:a,url:c,timeout:f}=await this.buildRequest(o,{retryCount:s-t});await this.prepareRequest(a,{url:c,options:o});let d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=n===void 0?"":`, retryOf: ${n}`,l=Date.now();if(P(this).debug(`[${d}] sending request`,H({retryOfRequestLogID:n,method:o.method,url:c,options:o,headers:a.headers})),o.signal?.aborted)throw new T;let g=new AbortController,h=await this.fetchWithTimeout(c,a,f,g).catch(ve),A=Date.now();if(h instanceof globalThis.Error){let v=`retrying, ${t} attempts remaining`;if(o.signal?.aborted)throw new T;let k=Ue(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return P(this).info(`[${d}] connection ${k?"timed out":"failed"} - ${v}`),P(this).debug(`[${d}] connection ${k?"timed out":"failed"} (${v})`,H({retryOfRequestLogID:n,url:c,durationMs:A-l,message:h.message})),this.retryRequest(o,t,n??d);throw P(this).info(`[${d}] connection ${k?"timed out":"failed"} - error; no more retries left`),P(this).debug(`[${d}] connection ${k?"timed out":"failed"} (error; no more retries left)`,H({retryOfRequestLogID:n,url:c,durationMs:A-l,message:h.message})),k?new U:new D({cause:h})}let E=`[${d}${m}] ${a.method} ${c} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${A-l}ms`;if(!h.ok){let v=await this.shouldRetry(h);if(t&&v){let q=`retrying, ${t} attempts remaining`;return await zt(h.body),P(this).info(`${E} - ${q}`),P(this).debug(`[${d}] response error (${q})`,H({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:A-l})),this.retryRequest(o,t,n??d,h.headers)}let k=v?"error; no more retries left":"error; not retryable";P(this).info(`${E} - ${k}`);let b=await h.text().catch(q=>ve(q).message),Y=Bt(b),Z=Y?void 0:b;throw P(this).debug(`[${d}] response error (${k})`,H({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,message:Z,durationMs:Date.now()-l})),this.makeStatusError(h.status,Y,Z,h.headers)}return P(this).info(E),P(this).debug(`[${d}] response start`,H({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:A-l})),{response:h,options:o,controller:g,requestLogID:d,retryOfRequestLogID:n,startTime:l}}getAPIList(e,t,n){return this.requestAPIList(t,n&&"then"in n?n.then(o=>({method:"get",path:e,...o})):{method:"get",path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new Me(this,n,e)}async fetchWithTimeout(e,t,n,o){let{signal:s,method:a,...c}=t||{},f=this._makeAbort(o);s&&s.addEventListener("abort",f,{once:!0});let d=setTimeout(f,n),m=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,l={signal:o.signal,...m?{duplex:"half"}:{},method:"GET",...c};a&&(l.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,l)}finally{clearTimeout(d)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,o){let s,a=o?.get("retry-after-ms");if(a){let f=parseFloat(a);Number.isNaN(f)||(s=f)}let c=o?.get("retry-after");if(c&&!s){let f=parseFloat(c);Number.isNaN(f)?s=Date.parse(c)-Date.now():s=f*1e3}if(s===void 0){let f=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,f)}return await Mt(s),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let s=t-e,a=Math.min(.5*Math.pow(2,s),8),c=1-Math.random()*.25;return a*c*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:o,path:s,query:a,defaultBaseURL:c}=n,f=this.buildURL(s,a,c);"timeout"in n&&Nt("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:d,body:m}=this.buildBody({options:n}),l=await this.buildHeaders({options:e,method:o,bodyHeaders:d,retryCount:t});return{req:{method:o,headers:l,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"},...m&&{body:m},...this.fetchOptions??{},...n.fetchOptions??{}},url:f,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:o}){let s={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let a=u([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Xt(),"X-\u004b\u0065\u0072\u006e\u0065\u006c-Project-Id":this.projectID,"X-\u004b\u0065\u0072\u006e\u0065\u006c-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:n}=e;if(!t)return t==null&&"body"in e?_(this,We,"f").call(this,{body:t,headers:u([n])}):{bodyHeaders:void 0,body:void 0};let o=u([n]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&o.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:Ve(t)}:typeof t=="object"&&o.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(t)}:_(this,We,"f").call(this,{body:t,headers:o})}app(e){return new st(e)}};Ct=y,We=new WeakMap,jt=new WeakSet,_r=function(){return this.baseURL!==Ar[this._options.environment||"production"]};y.\u004b\u0065\u0072\u006e\u0065\u006c=Ct;y.DEFAULT_TIMEOUT=6e4;y.\u004b\u0065\u0072\u006e\u0065\u006cError=x;y.APIError=I;y.APIConnectionError=D;y.APIConnectionTimeoutError=U;y.APIUserAbortError=T;y.NotFoundError=me;y.ConflictError=ye;y.RateLimitError=we;y.BadRequestError=he;y.AuthenticationError=W;y.InternalServerError=V;y.PermissionDeniedError=X;y.UnprocessableEntityError=ge;y.toFile=nt;y.Deployments=ce;y.Apps=ne;y.Invocations=ue;y.Browsers=O;y.Profiles=fe;y.Auth=M;y.Telemetry=Q;y.Proxies=de;y.Extensions=le;y.BrowserPools=oe;y.Credentials=ae;y.Projects=G;y.Organization=K;y.AuditLogs=J;y.APIKeys=re;y.CredentialProviders=ie;var qn="SERP browser service is not configured";function Cc(r,e){return Wn(e)||r instanceof W||r instanceof X||r instanceof D||r instanceof U||r instanceof V||/^401\s+Invalid or disabled API key\s*$/i.test(e.trim())||e===qn}function Wn(r){return/(?:401|403)\s+Auth Failed\s*\((?:customer_suspended|customer_inactive|invalid_auth|auth_failed)\)/i.test(r)}export{y as a,Cc as b,Wn as c};
|
package/dist/chunk-C7MGJUTU.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var k="Google returned a CAPTCHA. Run with --headless=false to re-warm the browser profile, then retry.",m="This operation is temporarily unavailable. Please retry later.",b=["request_aborted","captcha_exhausted","captcha_or_blocked","location_mismatch","proxy_tunnel_failed","proxy_unavailable","harvest_timeout","mcp_request_timeout","mcp_http_error","extraction_failed","concurrency_limit_exceeded","unauthorized","forbidden","invalid_request","rate_limited","upstream_rate_limited","insufficient_balance","service_unavailable","response_lost","vendor_unavailable","page_not_found","page_forbidden","page_rate_limited","page_server_error","page_http_error","bot_check_unresolved","page_too_large","page_unreachable","browser_session_interrupted","site_export_not_found","directory_job_not_found","site_export_format_unavailable","site_export_read_failed","site_export_image_not_found","image_url_invalid","image_url_not_https","image_host_unresolvable","image_host_blocked","image_redirect_invalid","image_source_unavailable","image_too_large","image_redirect_limit","image_base64_invalid","image_source_missing","image_source_ambiguous","image_source_type_invalid","image_artifact_not_found","image_page_too_large","page_image_not_found","page_image_candidates_unusable","image_format_unsupported","image_storage_unconfigured","featured_image_unhostable"],h=["request_aborted","captcha","location_mismatch","connection","timeout","extraction","concurrency_limit","unauthorized","forbidden","invalid_request","not_found","rate_limit","billing","service_unavailable"];function S(e){return e?JSON.stringify(e):null}function R(e){if(e==null)return null;try{let r=typeof e=="string"?JSON.parse(e):e;if(!r||typeof r!="object"||Array.isArray(r))return null;let t=r;if(typeof t.error_code!="string"||!p.has(t.error_code))return null;let a=C({errorCode:t.error_code,errorType:t.error_type,retryable:t.retryable,retryAfterSeconds:t.retry_after_seconds,chargeStatus:t.charge_status,details:t.details});if(typeof t.message=="string"){let n=g(t.message).trim().slice(0,1e3);n&&!/https?:\/\//i.test(n)&&(a.message=n)}return a}catch{return null}}var p=new Set(b),f=new Set(h),y=new Set(["active","limit","operation","upgrade_url","topup_url","upgrade_command","slots_per_pack","pack_price_usd","balance_credits","required_credits","retry_guidance","http_status"]),v=12,T=500;function o(e){return typeof e=="string"&&p.has(e)?e:"service_unavailable"}function x(e){if(!e||typeof e!="object"||Array.isArray(e))return;let r={};for(let[t,a]of Object.entries(e)){if(Object.keys(r).length>=v)break;if(y.has(t))if(typeof a=="string"){if((t==="upgrade_url"||t==="topup_url")&&!E(a))continue;let n=g(a).slice(0,T);n&&(r[t]=n)}else(typeof a=="number"&&Number.isFinite(a)||typeof a=="boolean"||a===null)&&(r[t]=a)}return Object.keys(r).length>0?r:void 0}function E(e){if(e.startsWith("/")&&!e.startsWith("//"))return!0;try{let r=new URL(e);return r.protocol==="https:"&&(r.hostname==="mcpscraper.dev"||r.hostname.endsWith(".mcpscraper.dev"))}catch{return!1}}function P(e){let r=o(e);switch(r){case"captcha_exhausted":case"captcha_or_blocked":return"captcha";case"proxy_tunnel_failed":case"proxy_unavailable":case"response_lost":return"connection";case"harvest_timeout":case"mcp_request_timeout":return"timeout";case"concurrency_limit_exceeded":return"concurrency_limit";case"rate_limited":case"upstream_rate_limited":return"rate_limit";case"extraction_failed":case"page_not_found":case"page_forbidden":case"page_rate_limited":case"page_server_error":case"page_http_error":case"bot_check_unresolved":case"page_too_large":case"page_unreachable":case"browser_session_interrupted":case"site_export_not_found":case"site_export_format_unavailable":case"site_export_read_failed":case"site_export_image_not_found":return"extraction";case"image_url_invalid":case"image_url_not_https":case"image_host_unresolvable":case"image_host_blocked":case"image_redirect_invalid":case"image_source_unavailable":case"image_too_large":case"image_redirect_limit":case"image_base64_invalid":case"image_source_missing":case"image_source_ambiguous":case"image_source_type_invalid":case"image_artifact_not_found":case"image_page_too_large":case"page_image_not_found":case"page_image_candidates_unusable":case"image_format_unsupported":case"image_storage_unconfigured":case"featured_image_unhostable":return"invalid_request";case"insufficient_balance":return"billing";case"vendor_unavailable":case"mcp_http_error":return"service_unavailable";case"directory_job_not_found":return"not_found";default:return r}}function w(e){switch(o(e)){case"request_aborted":return"The request was cancelled before it completed.";case"captcha_exhausted":case"captcha_or_blocked":return"The target site returned a verification challenge. Heavy traffic can temporarily increase these challenges; retry in a few minutes.";case"location_mismatch":return"The target site returned results for a different location. Please retry.";case"proxy_tunnel_failed":case"proxy_unavailable":return"The web request could not establish a working connection. Please retry later.";case"harvest_timeout":return"The request timed out before it completed. Please retry with a smaller request.";case"mcp_request_timeout":return"The MCP caller stopped waiting before a final response arrived. Durable work may still be running; continue with the returned Task or job handle instead of restarting it.";case"concurrency_limit_exceeded":return"The service is available, but this account has reached its parallel-operation limit. Wait for an active operation to finish or add capacity.";case"unauthorized":return"Authentication is required to perform this operation.";case"forbidden":return"This account does not have permission to perform this operation.";case"invalid_request":return"The request is invalid. Check the supplied inputs and try again.";case"rate_limited":return"This account is sending requests too quickly. Wait briefly and retry.";case"upstream_rate_limited":return"The connected provider is temporarily rate-limiting requests. Wait briefly and retry.";case"mcp_http_error":return"The API returned an unexpected HTTP response.";case"insufficient_balance":return"This account does not have enough Credits for the operation.";case"extraction_failed":return"The target could not be extracted. Check retryable before attempting it again.";case"directory_job_not_found":return"This directory job was not found for the current account.";case"response_lost":return"The connection was lost before the response arrived. The operation may have already completed and been billed on our side \u2014 check credits_info before retrying blind.";case"vendor_unavailable":return"MCP Scraper's internal browser services require MCP Scraper team attention. Servers or IPs are down until this is fixed \u2014 this is not caused by your request. Please retry in a few minutes.";case"page_not_found":return"The page could not be found. It may have been moved or deleted.";case"page_forbidden":return"The site refused the request.";case"page_rate_limited":return"The site is rate-limiting requests right now. Retrying after a short wait usually works.";case"page_server_error":return"The page's own server returned an error. This is on the target site's side, not something a retry here can fix.";case"page_http_error":return"The page returned an unexpected HTTP response.";case"bot_check_unresolved":return"This site has automated-traffic protection (a bot/CAPTCHA check) that could not be resolved in time. Some sites are simply not extractable this way.";case"page_too_large":return"The page is larger than we can safely process.";case"page_unreachable":return"The page did not respond in time, or the connection could not be completed.";case"browser_session_interrupted":return"The browser session closed before extraction completed. MCP Scraper will retry once with a fresh session; retry the request if this persists.";case"site_export_not_found":return"The site export or requested page was not found, expired, or does not belong to this account.";case"site_export_format_unavailable":return"That representation was not retained for this export page. Read the export manifest and request one of the formats marked available.";case"site_export_read_failed":return"The stored site export could not be read or did not pass its integrity check.";case"site_export_image_not_found":return"The requested site-export image was not found, expired, or does not belong to this account.";case"image_url_invalid":return"The image source is not a valid URL. Use a stable public HTTPS URL or inline image bytes.";case"image_url_not_https":return"Commons image sources must use a public HTTPS URL or inline image bytes.";case"image_host_unresolvable":return"The image host could not be resolved. Use a different stable public URL or inline image bytes.";case"image_host_blocked":return"The image source resolves to a network address Commons cannot fetch safely.";case"image_redirect_invalid":return"The image source redirected to an invalid or unsafe destination.";case"image_source_unavailable":return"The image source could not be fetched. Host a different stable public URL or provide inline image bytes.";case"image_too_large":return"The image exceeds the Commons image size limit.";case"image_redirect_limit":return"The image source exceeded the Commons redirect limit.";case"image_base64_invalid":return"The supplied inline image bytes are invalid.";case"image_source_missing":return"Provide exactly one of a public image or webpage URL, inline image bytes, or an owner-scoped image artifact.";case"image_source_ambiguous":return"Provide only one image source: sourceUrl, imageBase64, or artifactId.";case"image_source_type_invalid":return"Use sourceType only with inline image bytes or an owner-scoped image artifact.";case"image_artifact_not_found":return"The image artifact was not found, expired, or does not belong to this account.";case"image_page_too_large":return"The webpage is too large for bounded Commons image discovery.";case"page_image_not_found":return"The webpage did not expose a usable featured or content image.";case"page_image_candidates_unusable":return"The webpage exposed image candidates, but none returned supported public image bytes.";case"image_format_unsupported":return"Commons accepts JPEG, PNG, GIF, or WebP image bytes.";case"image_storage_unconfigured":return"Commons image storage is temporarily unavailable.";case"featured_image_unhostable":return"The required featured image could not be hosted for Commons publication.";default:return m}}function C(e){let r=o(e.errorCode),t=typeof e.retryAfterSeconds=="number"&&Number.isFinite(e.retryAfterSeconds)?Math.max(1,Math.min(86400,Math.trunc(e.retryAfterSeconds))):void 0,a=e.chargeStatus==="not_charged"||e.chargeStatus==="refund_pending"||e.chargeStatus==="refunded"||e.chargeStatus==="charged"?e.chargeStatus:void 0,n=typeof e.errorType=="string"&&f.has(e.errorType)?e.errorType:void 0,s=x(e.details);return{error_code:r,error_type:n??P(r),message:w(r),retryable:e.retryable===!0,...t?{retry_after_seconds:t}:{},...a?{charge_status:a}:{},...s?{details:s}:{}}}function g(e){return e.replace((new RegExp("https?:\\/\\/[^\\s]*(?:\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061|on\u006b\u0065\u0072\u006e\u0065\u006c|\u006b\u0065\u0072\u006e\u0065\u006c\\.sh)[^\\s]*", "gi")),"the service").replace(/bright\s*data/gi,"the service").replace((new RegExp("\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061", "gi")),"the service").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\.sh\\s+sessions?", "gi")),"sessions").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\.sh\\s+session", "gi")),"this session").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\.sh", "gi")),"the service").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\s+sessions?", "gi")),"sessions").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\s+session", "gi")),"this session").replace(/\b(?:sub|cus|sess|proxy)_[A-Za-z0-9_-]+\b/g,"[redacted]").replace((new RegExp("\\b(?:\u004b\u0045\u0052\u004e\u0045\u004c|\u0042\u0052\u0049\u0047\u0048\u0054\u0044\u0041\u0054\u0041|\u0042\u0052\u0049\u0047\u0048\u0054_\u0044\u0041\u0054\u0041)_[A-Z0-9_]*API_KEY\\b", "g")),"BROWSER_SERVICE_API_KEY").replace((new RegExp("\\b\u006b\u0065\u0072\u006e\u0065\u006c\\b", "gi")),"the service").replace(/ +/g," ").trim()}var i=class extends Error{constructor(t){super(`CAPTCHA detected. ${t}`);this.instructions=t}instructions;name="CaptchaError"},c=class extends Error{constructor(t,a){super(t);this.cause=a}cause;name="ExtractionError"},u=class extends Error{constructor(t){super(`Google Maps search did not reach a complete result state (${t})`);this.pageState=t}pageState;name="MapsSearchIncompletePageError"},l=class extends Error{name="RequestAbortedError";constructor(r="Request aborted before harvest completed"){super(r)}},_=class extends Error{name="PaaInteractionInterruptedError"},d=class extends Error{name="LocationMismatchError";constructor(r="Google returned results for a different location than requested"){super(r)}};export{k as a,m as b,b as c,S as d,R as e,o as f,w as g,C as h,g as i,i as j,c as k,u as l,l as m,_ as n,d as o};
|
package/dist/chunk-CNSVZTTT.js
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import{b as y}from"./chunk-B3JRL45T.js";var $=100*1024,L=new Set(["webp","avif","svg","svg+xml"]);function x(s){return s==null?null:s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(1)} KB`:`${(s/(1024*1024)).toFixed(2)} MB`}var R=s=>s.replace(/&/g,"&").replace(/�?38;/g,"&").replace(/&/gi,"&").trim(),M=s=>s.replace(/^https?:\/\//i,"//").replace(/\/$/,""),E=(s,r)=>{if(s){let c=s.split(";")[0].trim().toLowerCase();if(c.startsWith("image/"))return c.replace("image/","")}return(r.split("?")[0].match(/\.([a-z0-9]+)$/i)?.[1]||"unknown").toLowerCase()};function T(s){let r=new Map;for(let c of s)for(let n of c.imageLinks||[]){let e=R(n);if(!/^https?:\/\//i.test(e)||/[{}]|%7[bd]/i.test(e))continue;let a=M(e),o=r.get(a);(!o||/^https:/i.test(e)&&/^http:/i.test(o))&&r.set(a,e)}return[...r.values()]}async function D(s,r){let c=new AbortController,n=setTimeout(()=>c.abort(),r),e=o=>({len:o.headers.get("content-length"),cr:o.headers.get("content-range"),ct:o.headers.get("content-type"),status:o.status}),a=async o=>{let g=s;for(let p=0;p<=5;p++){let m=await y(g,{field:"image URL"});if(m.error||!m.parsed)throw new Error(m.error??"Image URL was rejected");let u=await fetch(m.parsed.href,{method:o,...o==="GET"?{headers:{Range:"bytes=0-0"}}:{},redirect:"manual",signal:c.signal});if(u.status>=300&&u.status<400){let t=u.headers.get("location");if(!t)throw new Error(`HTTP ${u.status} redirect did not include Location`);g=new URL(t,m.parsed.href).href;continue}return u}throw new Error("Image request exceeded five redirects")};try{let o=null,g=null,p=null;try{let m=e(await a("HEAD"));p=m.status,g=m.ct,m.len&&(o=Number(m.len))}catch{}if(o==null){let m=await a("GET"),u=e(m);if(p=p??u.status,g=g??u.ct,u.cr&&u.cr.includes("/")){let t=u.cr.split("/")[1];t&&t!=="*"&&(o=Number(t))}else u.len&&(o=Number(u.len));try{await m.body?.cancel()}catch{}}return{url:s,status:p,bytes:Number.isFinite(o)?o:null,contentType:g}}catch(o){return{url:s,status:null,bytes:null,contentType:null,error:String(o.message||o)}}finally{clearTimeout(n)}}async function v(s,r,c){let n=new Array(s.length),e=0;return await Promise.all(Array.from({length:Math.min(r,s.length)},async()=>{for(;e<s.length;){let a=e++;n[a]=await c(s[a])}})),n}async function S(s,r={}){return A(T(s),r)}async function A(s,r={}){let c=r.concurrency??12,n=r.timeoutMs??12e3,e=r.max??5e3,a=T([{imageLinks:s}]).slice(0,e),g=(await v(a,c,t=>D(t,n))).map(t=>{let f=E(t.contentType,t.url);return{...t,size:x(t.bytes),format:f,over100kb:t.bytes!=null&&t.bytes>$,legacyFormat:f!=="unknown"&&!L.has(f)}}),p=g.filter(t=>t.bytes!=null),m=p.reduce((t,f)=>t+f.bytes,0),u={};for(let t of g)u[t.format]=(u[t.format]||0)+1;return{rows:g.sort((t,f)=>(f.bytes??0)-(t.bytes??0)),summary:{unique:g.length,sized:p.length,totalBytes:m,totalSize:x(m)??"0 B",avgSize:x(Math.round(m/(p.length||1)))??"0 B",over100kb:g.filter(t=>t.over100kb).length,legacyFormat:g.filter(t=>t.legacyFormat).length,formatCounts:u,...r.sampleTruncated?{sampleTruncated:!0,sampleCap:e}:{}}}}function _(s){let r=s.summary,c=Object.entries(r.formatCounts).sort((a,o)=>o[1]-a[1]).map(([a,o])=>`${a}:${o}`).join(" "),n=s.rows.filter(a=>a.over100kb).slice(0,15),e=["## Images",`**${r.unique} unique images** \xB7 ${r.totalSize} total \xB7 ${r.avgSize} avg \xB7 ${r.over100kb} over 100 KB \xB7 ${r.legacyFormat} legacy format`,`Formats: ${c}`];if(n.length){e.push("","| Size | Format | URL |","|------|--------|-----|");for(let a of n)e.push(`| ${a.size} | ${a.format} | ${a.url} |`)}return e.join(`
|
|
2
|
-
`)}function I(s){let r=s.replace(/^www\./,"").toLowerCase(),c=r.split(".");return c.length<=2?r:c.slice(-2).join(".")}function U(s,r,c){let n="";try{n=I(new URL(c).hostname)}catch{n=""}let e=s.filter(l=>l.internal),a=r.length,o=r.filter(l=>l.orphan).length,g=e.filter(l=>l.targetStatus!=null&&l.targetStatus>=400).length,p=r.reduce((l,h)=>l+h.inlinks,0),m=r.reduce((l,h)=>l+h.outlinksInternal+h.outlinksExternal,0),u={zero:0,oneToTwo:0,threeToTen:0,elevenPlus:0};for(let l of r)l.inlinks===0?u.zero++:l.inlinks<=2?u.oneToTwo++:l.inlinks<=10?u.threeToTen++:u.elevenPlus++;let t=[...r].sort((l,h)=>h.inlinks-l.inlinks).slice(0,20).map(l=>({url:l.url,inlinks:l.inlinks,outlinksInternal:l.outlinksInternal,outlinksExternal:l.outlinksExternal})),f=new Map,d=0;for(let l of s){let h;try{h=I(new URL(l.to).hostname)}catch{continue}if(!h||h===n)continue;d++;let k=f.get(h)??{links:0,nofollow:0,pages:new Set};k.links++,l.nofollow&&k.nofollow++,k.pages.add(l.from),f.set(h,k)}let i=[...f.entries()].map(([l,h])=>({domain:l,links:h.links,nofollow:h.nofollow,pages:h.pages.size})).sort((l,h)=>h.links-l.links),b=l=>Math.round(l*10)/10;return{summary:{internal:{totalLinks:e.length,pages:a,orphans:o,brokenInternal:g,avgInlinks:a?b(p/a):0,avgOutlinks:a?b(m/a):0,distribution:u,topByInlinks:t},external:{totalLinks:d,uniqueDomains:i.length,topDomains:i.slice(0,20)}},externalDomains:i}}function X(s){let r=s.summary;return["## Link analysis",`**Internal:** ${r.internal.totalLinks} links \xB7 ${r.internal.pages} pages \xB7 avg ${r.internal.avgInlinks} inlinks/page \xB7 ${r.internal.orphans} orphans \xB7 ${r.internal.brokenInternal} broken`,`**External:** ${r.external.totalLinks} links to ${r.external.uniqueDomains} domains`,"","### Inlink distribution",`- 0 inlinks (orphans): ${r.internal.distribution.zero}`,`- 1\u20132: ${r.internal.distribution.oneToTwo}`,`- 3\u201310: ${r.internal.distribution.threeToTen}`,`- 11+: ${r.internal.distribution.elevenPlus}`,"","### Top 20 internal pages by inlinks","| inlinks | out (int/ext) | URL |","|---|---|---|",...r.internal.topByInlinks.map(n=>`| ${n.inlinks} | ${n.outlinksInternal}/${n.outlinksExternal} | ${n.url} |`),"","### Top 20 external domains by links","| links | nofollow | from pages | domain |","|---|---|---|---|",...r.external.topDomains.map(n=>`| ${n.links} | ${n.nofollow} | ${n.pages} | ${n.domain} |`)].join(`
|
|
3
|
-
`)}function w(s,r){let c=new Map;for(let n of s){let e=r(n);if(e==null||e==="")continue;let a=String(e);c.has(a)||c.set(a,[]),c.get(a).push(n.url)}return[...c.values()].filter(n=>n.length>1).flat()}function B(s,r,c){let n=t=>({count:t.length,urls:t.slice(0,200)}),e=t=>s.filter(t).map(f=>f.url),a=t=>t.extractionStatus!=="failed",o=t=>a(t)&&t.status===200,g=new Set(s.filter(a).map(t=>t.url)),p=t=>{try{return new URL(t).pathname}catch{return""}},m={"title.missing":n(e(t=>o(t)&&!t.title)),"title.duplicate":n(w(s.filter(o),t=>t.title)),"title.tooLong":n(e(t=>(t.titleLength??0)>60||(t.titlePixels??0)>561)),"title.tooShort":n(e(t=>t.title!=null&&(t.titleLength??0)<30)),"title.sameAsH1":n(e(t=>!!t.title&&!!t.h1&&t.title.trim()===t.h1.trim())),"meta.missing":n(e(t=>o(t)&&!t.metaDescription)),"meta.duplicate":n(w(s.filter(o),t=>t.metaDescription)),"meta.tooLong":n(e(t=>(t.metaDescLength??0)>155)),"meta.tooShort":n(e(t=>t.metaDescription!=null&&(t.metaDescLength??0)<70)),"h1.missing":n(e(t=>o(t)&&!t.h1)),"h1.multiple":n(e(t=>!!t.h1_2)),"h1.duplicate":n(w(s.filter(o),t=>t.h1)),"h1.tooLong":n(e(t=>(t.h1?.length??0)>70)),"h2.missing":n(e(t=>o(t)&&t.h2Count===0)),"crawl.extractionFailed":n(e(t=>!a(t))),"indexability.nonIndexable":n(e(t=>a(t)&&!t.indexable)),"indexability.noindex":n(e(t=>t.indexabilityReason==="noindex")),"canonical.missing":n(e(t=>o(t)&&!t.canonicalUrl)),"canonical.canonicalised":n(e(t=>t.indexabilityReason==="canonicalised")),"response.broken4xx":n(e(t=>(t.status??0)>=400&&(t.status??0)<500)),"response.error5xx":n(e(t=>(t.status??0)>=500)),"response.redirect3xx":n(e(t=>(t.status??0)>=300&&(t.status??0)<400)),"response.noResponse":n(e(t=>t.status===null)),"content.thin":n(e(t=>o(t)&&t.wordCount>0&&t.wordCount<200)),"content.exactDuplicate":n(w(s.filter(t=>o(t)&&t.contentHash),t=>t.contentHash)),"images.missingAlt":n(e(t=>a(t)&&t.imagesMissingAlt>0)),"schema.missing":n(e(t=>o(t)&&t.schemaTypes.length===0)),"url.tooLong":n(e(t=>t.url.length>115)),"url.uppercase":n(e(t=>/[A-Z]/.test(p(t.url)))),"url.underscores":n(e(t=>p(t.url).includes("_"))),"links.orphan":n([...r.values()].filter(t=>t.orphan&&g.has(t.url)).map(t=>t.url))},u=c;if(!u){let t=d=>{try{let i=new URL(d);return i.hash="",(i.origin+i.pathname).replace(/\/+$/,"")+i.search}catch{return d.replace(/#.*$/,"").replace(/\/+$/,"")}},f=new Map(s.map(d=>[t(d.url),d.status]));u=new Set;for(let d of s)for(let i of d.outlinks??[]){if(!i.internal)continue;let b=f.get(t(i.href));b!=null&&b>=400&&u.add(d.url)}}return m["links.brokenInternal"]=n([...u]),m}function C(s,r,c,n){let e=r.length,a=r.filter(i=>i.extractionStatus!=="failed").length,o=e-a,g=i=>i.startsWith("response.broken")||i.startsWith("response.error")||i.startsWith("links.broken")?"\u{1F534}":i.startsWith("title.missing")||i.startsWith("h1.missing")||i.startsWith("indexability")||i.startsWith("canonical.missing")?"\u{1F7E0}":"\u{1F7E1}",p=Object.entries(c).filter(([,i])=>i.count>0).sort((i,b)=>b[1].count-i[1].count).map(([i,b])=>`| ${g(i)} | \`${i}\` | ${b.count} | ${b.urls.slice(0,3).join(" \xB7 ")}${b.urls.length>3?" \u2026":""} |`),m=[...n.values()].map(i=>i.crawlDepth).filter(i=>i!=null),u=m.length?Math.max(...m):0,t=new Set(r.filter(i=>i.extractionStatus!=="failed").map(i=>i.url)),f=[...n.values()].filter(i=>i.orphan&&t.has(i.url)).length,d=[...n.values()].sort((i,b)=>b.inlinks-i.inlinks).slice(0,5);return[`# SEO Crawl Report: ${s}`,`**${e} pages attempted** \xB7 ${a} extracted \xB7 ${o} failed \xB7 max crawl depth ${u} \xB7 ${f} orphan page(s)`,`
|
|
4
|
-
## Issues
|
|
5
|
-
| | Issue | Count | Examples |
|
|
6
|
-
|---|-------|-------|----------|
|
|
7
|
-
${p.join(`
|
|
8
|
-
`)||"| \u2705 | none | 0 | \u2014 |"}`,`
|
|
9
|
-
## Most-linked pages
|
|
10
|
-
${d.map(i=>`- ${i.inlinks} inlinks \xB7 depth ${i.crawlDepth??"\u2014"} \xB7 ${i.url}`).join(`
|
|
11
|
-
`)}`,`
|
|
12
|
-
_Thresholds: title 60ch/561px, meta 155ch, H1 70ch, thin <200 words, URL 115ch. Pixel widths are estimates._`].join(`
|
|
13
|
-
`)}export{S as a,A as b,_ as c,U as d,X as e,B as f,C as g};
|
package/dist/chunk-EYGA6LOU.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var e={schemaVersion:1,ratePolicy:{version:"serp-page-2026-09-24",effectiveDate:"2026-09-24T00:00:00.000Z"},costEvidence:{id:"serp-page-rate-basis-2026-09",status:"owner-approved"},operationCosts:{serp:{credits:20,unit:"per page (ordinary search)",label:"SERP 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 20 credits per delivered page, or 35 credits per delivered page if the backup supplies the result. One-page full searches cost 35 credits. Setting recency to week or month applies Google's date filter through a managed browser and returns organic results only. It costs 35 credits for one page; filtered pages:2 follows Google's page-two control and costs 70 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 40 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 35-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 60-credit base price; optional page snapshots add 1 credit per attempted URL."},paa:{credits:10,unit:"per question (+400 credit base)",label:"PAA harvest",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 400 credit base + 10 per question actually returned (unused estimate refunded)."},page_scrape:{credits:1,unit:"per page",label:"Page crawl / extract",notes:"Applies to both single-URL extraction and per-page site crawls."},listing_create:{credits:10,unit:"per new listing",label:"Directory or wiki listing creation",notes:"Fixed total price for a new Local Sourcebook directory listing or Transparent Commons wiki entity. Sourcebook acquisition is included."},listing_edit:{credits:2,unit:"per existing listing revision",label:"Directory or wiki listing edit",notes:"Fixed total price for refreshing an existing Local Sourcebook listing or revising an existing Transparent Commons entity."},url_map:{credits:5,unit:"per mapping operation",label:"Site URL mapping",notes:"Flat rate for the full /map-urls call regardless of URL count discovered."},yt_channel:{credits:2,unit:"per call",label:"YouTube search / channel harvest"},yt_transcription:{credits:200,unit:"base + 2/min of video",label:"YouTube transcription",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)."},fb_ad:{credits:7,unit:"per call",label:"Facebook search / ad lookup"},maps_search:{credits:5,unit:"per search",label:"Maps business search",notes:"Returns up to 50 Google Maps business/profile candidates. Use maps_place_intel to hydrate selected businesses."},maps_place:{credits:60,unit:"per business",label:"Maps business lookup",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."},maps_review:{credits:1,unit:"per review card",label:"Maps review",notes:"One credit per unique saved review on a completed Maps place run. The declared maximum is held before browsing; unused credits are refunded."},fb_search:{credits:8,unit:"per search",label:"Facebook ad library search",notes:"Browser automation to search Facebook Ads Library by keyword."},google_ads_search:{credits:6,unit:"per search",label:"Google Ads Transparency search",notes:"Browser automation to find advertisers in Google Ads Transparency Center by domain or name."},google_ads_intel:{credits:2,unit:"per call",label:"Google Ads Transparency advertiser intel",notes:"Lists and hydrates an advertiser's creatives with image URLs and video references."},google_ads_transcribe:{credits:200,unit:"base + 2/min of video",label:"Google ad video transcription",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)."},fb_transcribe:{credits:200,unit:"base + 2/min of video",label:"Facebook video / ad transcription",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)."},fb_reels_inventory:{credits:4,unit:"per profile scan",label:"Facebook Reel URL inventory",notes:"Collects canonical Reel URLs from a Facebook profile. Logged-out scans are capped at 60 URLs; saved browser profiles can request larger inventories."},tiktok_transcribe:{credits:200,unit:"base + 2/min of video",label:"TikTok video transcription",notes:"Transcribes a public TikTok video from its playback media. Flat 200-credit base plus 2 credits per minute, reconciled after transcription."},instagram_profile:{credits:4,unit:"per profile scan",label:"Instagram profile content discovery",notes:"Browser extraction of public Instagram profile grid links. Complete history may require a logged-in profile."},instagram_media:{credits:4,unit:"per post or reel",label:"Instagram media download",notes:"Extracts post text, image URLs, and reel audio/video tracks, with local downloads when the server can write files."},instagram_transcribe:{credits:200,unit:"base + 2/min of video",label:"Instagram media transcription",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)."},browser_minute:{credits:120,unit:"per minute of use",label:"Interactive browser session",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."},reddit_thread:{credits:30,unit:"per thread",label:"Reddit thread base lookup",notes:"Base lookup for the post itself. Comments billed separately per comment at reddit_comment rate. Refunded if the thread cannot be retrieved."},reddit_comment:{credits:2,unit:"per comment",label:"Reddit comment",notes:"Charged per comment actually extracted, billed down automatically if the balance runs out mid-thread."},video_analysis:{credits:6667,unit:"per 120 frames (max 480)",label:"Video breakdown (frame-by-frame + transcript)",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 6667 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."},trustpilot_reviews:{credits:5,unit:"per call",label:"Trustpilot review harvest",notes:"Base lookup. Reviews billed separately per card at trustpilot_review rate. Refunded if no reviews are found."},trustpilot_review:{credits:1,unit:"per review card",label:"Trustpilot review card",notes:"Charged per review actually extracted, billed down automatically if the balance runs out mid-page."},g2_reviews:{credits:5,unit:"per call",label:"G2 review harvest",notes:"Base lookup. Reviews billed separately per card at g2_review rate. Refunded if no reviews are found."},g2_review:{credits:2,unit:"per review card",label:"G2 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."},diff_page:{credits:1,unit:"per check",label:"Page change 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."}},publicTiers:[{tier:"starter",label:"Starter",monthlyUsd:12,credits:8e4,concurrency:3},{tier:"growth",label:"Growth",monthlyUsd:40,credits:266667,concurrency:10},{tier:"scale",label:"Scale",monthlyUsd:100,credits:8e5,concurrency:20}],credits:{mcPerCredit:100,freeSignupCredits:0},inventory:{totalTools:347,scraperTools:233,memoryTools:114},concurrencyPack:{ratePolicyVersion:"2026-08-14.concurrency-pack-v1",monthlyUsd:5,currency:"usd",interval:"month",billingUnit:"pack",slotsPerPack:2},scaleCreditPack:{ratePolicyVersion:"2026-09-21.scale-credit-pack-v1",eligibleTier:"scale",incrementUsd:10,creditsPerIncrement:8e4,maxQuantity:100,currency:"usd",expiryMonths:3},addons:{memory:{monthlyUsd:19,quotaGb:5,freeQuotaGb:.01},connectedAccounts:{schemaVersion:2,ratePolicyVersion:"2026-08-03.connected-usage-v3",effectiveAt:"2026-08-03T00:00:00.000Z",entitlement:"paid_plan_add_on",connection:{billingMode:"flat_recurring_credits",amountCredits:15e3,interval:"month",unit:"active_connection",proration:"none"},usage:{billingMode:"credits",settlementMode:"authoritative_receipt",rounding:"aggregate_then_ceil_to_mc",functionRun:{credits:2,mc:200,unit:"per_function_run"},proxyRequest:{credits:2,mc:200,unit:"per_proxy_request"},compute:{creditsPerSecond:5,mcPerSecond:500,sourceUnit:"millisecond",unit:"per_compute_second",formula:"ceil(computeMilliseconds * mcPerSecond / 1000)"}}}}};export{e as a};
|