UNPKG

anil-brd-typescript-sdk

Version:

TypeScript SDK for Bright Data APIs - Web Unlocker, SERP, and Scraper APIs

82 lines (81 loc) 3.2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.WebUnlockerService = void 0; const index_1 = require("../index"); class WebUnlockerService { constructor(httpClient, zone) { this.httpClient = httpClient; this.zone = zone; } async unlock(url, options) { var _a, _b; if (!url || typeof url !== 'string') { throw new index_1.BrightDataError('URL is required and must be a string'); } // Clean and validate URL try { // Add https:// if protocol is missing if (!url.startsWith('http://') && !url.startsWith('https://')) { url = 'https://' + url; } // Validate URL format using our helper method if (!this.isValidUrl(url)) { throw new Error('Invalid URL format'); } } catch (error) { console.log('❌ URL validation failed:', error); throw new index_1.BrightDataError(`Invalid URL format: ${url}`); } // Prepare payload according to BrightData API specs const requestData = { url: url, zone: this.zone, format: options.format || 'raw', method: options.method || 'GET', ...(options.country && { country: options.country }), ...((options === null || options === void 0 ? void 0 : options.data_format) && { data_format: options.data_format }) }; try { // Make POST request to /request endpoint if (!requestData || Object.keys(requestData).length === 0) { throw new index_1.BrightDataError('Request data is empty or undefined'); } const response = await this.httpClient.post('/request', requestData); // Ensure we have valid content if (!response.data) { console.log('❌ No content in response'); throw new index_1.BrightDataError('No content received from the server'); } // Convert content to string if it's not already const content = typeof response.data === 'string' ? response.data : JSON.stringify(response.data); return { content, status: response.status || 200, headers: response.headers || {}, requestId: response.requestId, url: url }; } catch (error) { console.log('❌ Request failed:', error); if (error instanceof index_1.BrightDataError) { throw error; } const err = error; throw new index_1.BrightDataError(`Failed to unlock website: ${err.message || 'Unknown error'}`, (_a = err.response) === null || _a === void 0 ? void 0 : _a.status, (_b = err.response) === null || _b === void 0 ? void 0 : _b.data); } } isValidUrl(url) { try { new URL(url); return true; } catch (error) { return false; } } } exports.WebUnlockerService = WebUnlockerService;