
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d6b6583b-6fe0-5d38-8816-ac2c7b550f19")}catch(e){}}();
import { ApifyApiError } from 'apify-client';
import log from '@apify/log';
import { HTTP_PAYMENT_REQUIRED } from '../const.js';
import { buildMCPResponse } from './mcp.js';
const PAYMENT_REQUIRED_HEADER = 'payment-required';
/**
 * Symbol used to attach captured payment-required header data to errors.
 * The axios response interceptor stores the header value here so it can be
 * forwarded as x402 payment data without modifying the apify-client SDK.
 */
const PAYMENT_REQUIRED_DATA = Symbol.for('paymentRequiredData');
function getAxiosInstance(apifyClient) {
    var _a;
    return (_a = apifyClient.httpClient) === null || _a === void 0 ? void 0 : _a.axios;
}
function decodePaymentRequiredHeader(headerValue) {
    if (typeof headerValue !== 'string' || headerValue.length === 0)
        return undefined;
    try {
        return JSON.parse(Buffer.from(headerValue, 'base64').toString('utf-8'));
    }
    catch {
        return undefined;
    }
}
/**
 * Registers an axios response error interceptor on the ApifyClient's internal
 * HTTP client. When a 402 response is received, the interceptor captures the
 * base64-encoded `payment-required` header, decodes it, and attaches the parsed
 * object to the error via a Symbol property.
 *
 * This is intentionally "hacky" — apify-client does not expose response headers
 * on errors, so we reach into the internal axios instance.
 */
export function registerPaymentRequiredInterceptor(apifyClient) {
    var _a, _b;
    const axiosInstance = getAxiosInstance(apifyClient);
    if (!((_b = (_a = axiosInstance === null || axiosInstance === void 0 ? void 0 : axiosInstance.interceptors) === null || _a === void 0 ? void 0 : _a.response) === null || _b === void 0 ? void 0 : _b.use)) {
        log.warning('[x402] Failed to access apify-client axios internals — payment header capture disabled');
        return;
    }
    // eslint-disable-next-line @typescript-eslint/promise-function-async -- axios interceptors must return a rejected promise, not throw
    axiosInstance.interceptors.response.use(null, (error) => {
        var _a;
        const response = error === null || error === void 0 ? void 0 : error.response;
        const paymentData = (response === null || response === void 0 ? void 0 : response.status) === HTTP_PAYMENT_REQUIRED
            ? decodePaymentRequiredHeader((_a = response.headers) === null || _a === void 0 ? void 0 : _a[PAYMENT_REQUIRED_HEADER])
            : undefined;
        if (paymentData) {
            Object.defineProperty(error, PAYMENT_REQUIRED_DATA, { value: paymentData, enumerable: false });
        }
        return Promise.reject(error);
    });
}
/**
 * Extracts payment-required data from an error thrown by the ApifyClient.
 *
 * Checks two sources in priority order:
 * 1. The captured `payment-required` response header (via axios interceptor)
 * 2. The `data` field on ApifyApiError (from the API response body)
 */
function extractPaymentRequiredData(error) {
    if (typeof error !== 'object' || error === null)
        return undefined;
    // Source 1: Captured payment-required header (set by our interceptor)
    const captured = error[PAYMENT_REQUIRED_DATA];
    if (captured && typeof captured === 'object')
        return captured;
    // Source 2: ApifyApiError.data (API response body) — only trust genuine Apify API errors
    if (error instanceof ApifyApiError) {
        const { data } = error;
        if (typeof data === 'object' && data !== null)
            return data;
    }
    return undefined;
}
/**
 * Builds an MCP response for a 402 Payment Required error.
 * Formats the response as a tool result containing the PaymentRequired JSON
 * per the x402 MCP transport spec, which allows clients to automatically handle the payment flow.
 */
export function buildPaymentRequiredResponse(errorOrMessage, precomputedPaymentData) {
    const paymentData = precomputedPaymentData !== null && precomputedPaymentData !== void 0 ? precomputedPaymentData : extractPaymentRequiredData(errorOrMessage);
    const message = errorOrMessage instanceof Error ? errorOrMessage.message : String(errorOrMessage);
    // When paymentData exists, return two text entries: JSON payload first (backward-compatible
    // position for x402 clients that parse content[0].text), then a human-readable explanation.
    const texts = paymentData
        ? [
            JSON.stringify(paymentData),
            'Payment required to run this Actor or access this resource.',
        ]
        : [message];
    return buildMCPResponse({ texts, isError: true });
}
//# sourceMappingURL=payment_errors.js.map
//# debugId=d6b6583b-6fe0-5d38-8816-ac2c7b550f19
