UNPKG

screenshotone-api-sdk

Version:

Use ScreenshotOne.com API to generate screenshots of any website.

1,454 lines (1,453 loc) 46.3 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.AnimateOptions = exports.TakeOptions = exports.Client = exports.APIError = void 0; const big_js_1 = __importDefault(require("big.js")); const cross_fetch_1 = __importDefault(require("cross-fetch")); const signature_1 = require("./signature"); const errors_1 = __importDefault(require("./errors")); exports.APIError = errors_1.default; const API_BASE_URL = "https://api.screenshotone.com"; const API_TAKE_PATH = "/take"; const API_ANIMATE_PATH = "/animate"; /** * Represents an API client for the ScreenshotOne.com API. */ class Client { constructor(accessKey, secretKey, apiBaseUrl) { if (!accessKey || !secretKey) { throw new Error("Both non-empty access and secret keys are required"); } this.accessKey = accessKey; this.secretKey = secretKey; this.apiBaseUrl = apiBaseUrl ? apiBaseUrl : API_BASE_URL; } /** * Generates an URL that can be used to send GET requests for taking screenshots. * * Warning! Don't share the link publicly generated by this method publicly. * * @param options Options for taking the screenshot. * @returns An URL that will generate the screenshot if requested. */ async generateTakeURL(options) { const query = options.toQuery(); query.append("access_key", this.accessKey); let queryString = query.toString(); return `${this.apiBaseUrl}${API_TAKE_PATH}?${queryString}`; } /** * Generates the link that can be publicly available, but make sure * you read the documentation before at https://screenshotone.com/docs/signed-requests/. * * @param options * @returns A signed URL that will generate the screenshot if requested. */ async generateSignedTakeURL(options) { const query = options.toQuery(); query.append("access_key", this.accessKey); let queryString = query.toString(); const signature = await (0, signature_1.signQueryString)(queryString, this.secretKey); queryString += "&signature=" + signature; return `${this.apiBaseUrl}${API_TAKE_PATH}?${queryString}`; } /** * Generates the link that can be publicly available, but make sure * you read the documentation before at https://screenshotone.com/docs/signed-requests/. * * @param options * @returns A signed URL that will generate the animated screenshot if requested. */ async generateSignedAnimateURL(options) { const query = options.toQuery(); query.append("access_key", this.accessKey); let queryString = query.toString(); const signature = await (0, signature_1.signQueryString)(queryString, this.secretKey); queryString += "&signature=" + signature; return `${this.apiBaseUrl}${API_ANIMATE_PATH}?${queryString}`; } /** * Generates a screenshot and return the image blob. * * @param options * @returns */ async take(options) { const url = await this.generateSignedTakeURL(options); const response = await (0, cross_fetch_1.default)(url); if (response.ok) { return await response.blob(); } try { const data = await response.json(); throw new errors_1.default(`Failed to generate screenshot, response returned ${response.status} (${response.statusText}): ${data?.error_message}`, response.status, data?.error_code, data?.error_message, data?.documentation_url); } catch (e) { if (e instanceof errors_1.default) { throw e; } throw new Error(`failed to take screenshot, response returned ${response.status} ${response.statusText}`); } } /** * Generates an animated screenshot and return the image blob. * * @param options * @returns */ async animate(options) { const url = await this.generateSignedAnimateURL(options); const response = await (0, cross_fetch_1.default)(url); if (response.ok) { return await response.blob(); } try { const data = await response.json(); throw new errors_1.default(`Failed to generate animation, response returned ${response.status} (${response.statusText}): ${data?.error_message}`, response.status, data?.error_code, data?.error_message, data?.documentation_url); } catch (e) { if (e instanceof errors_1.default) { throw e; } throw new Error(`Failed to generate animation, response returned ${response.status} (${response.statusText})`); } } /** * Generates an animated screenshot and return the image blob. * * @param options * @returns */ async store(options, path, bucket, acl, storageClass, accessKeyId, secretAccessKey) { options.store(true).storagePath(path).responseType("empty"); if (bucket) { options.storageBucket(bucket); } if (acl) { options.storageACL(acl); } if (storageClass) { options.storageClass(storageClass); } if (accessKeyId) { options.storageAccessKeyId(accessKeyId); } if (secretAccessKey) { options.storageSecretAccessKey(secretAccessKey); } const url = options instanceof TakeOptions ? await this.generateSignedTakeURL(options) : await this.generateSignedAnimateURL(options); const response = await (0, cross_fetch_1.default)(url); if (response.ok) { return { key: response.headers.get("X-ScreenshotOne-Store-Key"), bucket: response.headers.get("X-ScreenshotOne-Store-Bucket"), }; } const data = await response.json(); throw new errors_1.default(`Failed to generate animation, response returned ${response.status} (${response.statusText}): ${data?.error_message}`, response.status, data?.error_code, data?.error_message, data?.documentation_url); } } exports.Client = Client; /** * Represents options for taking screenshots. */ class TakeOptions { constructor() { const query = new URLSearchParams(); this.query = query; } /** * Initializes take screenshot options with provided website URL. */ static url(url) { const options = new TakeOptions(); options.put("url", url); return options; } /** * Initializes take screenshot options with provided HTML. */ static html(html) { const options = new TakeOptions(); options.put("html", html); return options; } /** * Initializes take screenshot options with provided Markdown. */ static markdown(markdown) { const options = new TakeOptions(); options.put("markdown", markdown); return options; } put(key, ...values) { for (const value of values) { if (values.length == 1) { this.query.set(key, value); } else { this.query.append(key, value); } } } /** * Selector is a CSS-like selector of the element to take a screenshot of. */ selector(selector) { this.put("selector", selector); return this; } /** * Available response types: * by_format — return exactly the response defined in the format option. If format=png, the response will be the binary representation of the png with the content type header image/png; * empty — return only status or error. It is suitable when you want to upload the screenshot to storage and don't care about the results. It also speeds up the response since there are no networking costs involved. * json — A method returns the response in the JSON format, but it is only suitable if you use options that are effective for JSON. By default, the JSON response will be empty. But for example, when you use caching, the JSON will be populated with additional data. * The default value is by_format. */ responseType(responseType) { this.put("response_type", responseType); return this; } /** * It determines the behavior of what to do when selector is not found. */ errorOnSelectorNotFound(errorOn) { this.put("error_on_selector_not_found", errorOn ? "true" : "false"); return this; } /** * Capture beyond the viewport. */ captureBeyondViewport(beyond) { this.put("capture_beyond_viewport", beyond ? "true" : "false"); return this; } /** * When reduced_motion set to `true`, * the API will request the site to minimize the amount of non-essential motion it uses. * When the site supports it, it should use animations as least as possible. */ reducedMotion(reducedMotion) { this.put("reduced_motion", reducedMotion ? "true" : "false"); return this; } /** * If you want to request the page and it is supported to be rendered for printers, specify `print`. * If the page is by default rendered for printers and you want it to be rendered for screens, * use `screen`. */ mediaType(mediaType) { this.put("media_type", mediaType); return this; } /** * Set `true` to request site rendering, if supported, in the dark mode. * Set `false` to request site rendering in the light mode if supported. * If you don't set the parameter. The site is rendered in the default mode. */ darkMode(darkMode) { this.put("dark_mode", darkMode ? "true" : "false"); return this; } /** * The `hide_selectors` option allows hiding elements before taking a screenshot. * You can specify as many selectors as you wish. * All elements that match each selector will be hidden by * setting the `display` style property to none `!important`. */ hideSelectors(...selectors) { this.put("hide_selectors", ...selectors); return this; } /** * The scripts_wait_until option allows you to wait until a given * set of events after the scripts were executed. * It accepts the same values as wait_until and can have multiple values: * - `load`: the navigation is successful when the load even is fired; * - `domcontentloaded`: the navigation is finished when the DOMContentLoaded even is fired; * - `networkidle0`: the navigation is finished when there are no more than 0 network connections for at least 500 ms; * _ `networkidle2`: consider navigation to be finished when there are no more than 2 network connections for at least 500 ms. */ scriptsWaitUntil(...until) { this.put("scripts_wait_until", ...until); return this; } /** * Styles specifies custom CSS styles for the page. */ styles(styles) { this.put("styles", styles); return this; } /** * Scripts specifies custom scripts for the page. */ scripts(scripts) { this.put("scripts", scripts); return this; } /** * Renders the full page. */ fullPage(fullPage) { this.put("full_page", fullPage ? "true" : "false"); return this; } /** * Max height. */ fullPageMaxHeight(maxHeight) { this.put("full_page_max_height", maxHeight.toString()); return this; } /** * Sets the algorithm to use for full page screenshot—"by_sections" or ""/"default". */ fullPageAlgorithm(algorithm) { this.put("full_page_algorithm", algorithm); return this; } /** * Set `true` to scroll the page to the bottom. */ fullPageScroll(scroll) { this.put("full_page_scroll", scroll ? "true" : "false"); return this; } /** * Sets response format, one of: "png", "jpeg", "webp", "jpg", "gif", "jp2", "tiff", "avif", "heif", "pdf", "html". */ format(format) { this.put("format", format); return this; } /** * When the site responds within the range of 200-299 status code, * you can ignore errors and take a screenshot of the error page anyway. * To do that, set the option ignore_host_errors to true. * It is false by default. * * It is helpful when you want to create a gallery of error pages or, * for some reason, you need to render error pages. */ ignoreHostErrors(ignore) { this.put("ignore_host_errors", ignore ? "true" : "false"); return this; } /** * Use wait_until to wait until an event occurred before taking a screenshot or rendering HTML or PDF. * * The default value of wait_until is ['load']. Allowed values are: * - load: the navigation is successful when the load even is fired; * - domcontentloaded: the navigation is finished when the DOMContentLoaded even is fired; * - networkidle0: the navigation is finished when there are no more than 0 network connections for at least 500 ms; * - networkidle2: consider navigation to be finished when there are no more than 2 network connections for at least 500 ms. * * The parameter accepts many values. It means that screenshots will be taken after all events occur altogether. */ waitUntil(...until) { this.put("wait_until", ...until); return this; } /** * Sets IP country code. */ ipCountryCode(countryCode) { this.put("ip_country_code", countryCode); return this; } /** * Renders image with the specified quality. Available for the next formats: "jpeg" ("jpg"), "webp". */ imageQuality(imageQuality) { this.put("image_quality", imageQuality.toString()); return this; } /** * Renders a transparent background for the image. Works only if the site has not defined background color. * Available for the following response formats: "png", "webp". */ omitBackground(omitBackground) { this.put("omit_background", omitBackground ? "true" : "false"); return this; } /** * Instead of manually specifying viewport parameters like width and height, * you can specify a device to use for emulation. * In addition, other parameters of the viewport, including the user agent, * will be set automatically. */ viewportDevice(viewportDevice) { this.put("viewport_device", viewportDevice); return this; } /** * Sets the width of the browser viewport (pixels). */ viewportWidth(viewportWidth) { this.put("viewport_width", viewportWidth.toString()); return this; } /** * Sets the height of the browser viewport (pixels). */ viewportHeight(viewportHeight) { this.put("viewport_height", viewportHeight.toString()); return this; } /** * The clip_x option specifies only the top coordinate (x) of the area to clip. */ clipX(clipX) { this.put("clip_x", clipX.toString()); return this; } /** * The clip_y option specifies only the top coordinate (y) of the area to clip. */ clipY(clipY) { this.put("clip_y", clipY.toString()); return this; } /** * The clip_width option specifies only the width of the area to clip. */ clipWidth(clipWidth) { this.put("clip_width", clipWidth.toString()); return this; } /** * The clip_height option specifies only the width of the area to clip. */ clipHeight(clipHeight) { this.put("clip_height", clipHeight.toString()); return this; } /** * Sets the device scale factor. Acceptable value is one of: 1, 2 or 3. */ deviceScaleFactor(deviceScaleFactor) { this.put("device_scale_factor", deviceScaleFactor.toString()); return this; } /** * Whether the meta viewport tag is taken into account. Defaults to `false`. */ viewportMobile(isMobile) { this.put("viewport_mobile", isMobile ? "true" : "false"); return this; } /** * The default value is `false`. Set to `true` if the viewport supports touch events. */ viewportHasTouch(hasTouch) { this.put("viewport_has_touch", hasTouch ? "true" : "false"); return this; } /** * The default value is `false`. Set to `true` if the viewport is in landscape mode. */ viewportLandscape(landscape) { this.put("viewport_landscape", landscape ? "true" : "false"); return this; } /** * Sets geolocation latitude for the request. * Both latitude and longitude are required if one of them is set. */ geolocationLatitude(latitude) { this.put("geolocation_latitude", new big_js_1.default(latitude).toFixed(20).replace(/0+$/, "")); return this; } /** * Sets geolocation longitude for the request. Both latitude and longitude are required if one of them is set. */ geolocationLongitude(longitude) { this.put("geolocation_longitude", new big_js_1.default(longitude).toFixed(20).replace(/0+$/, "")); return this; } /** * Sets the geolocation accuracy in meters. */ geolocationAccuracy(accuracy) { this.put("geolocation_accuracy", accuracy.toString()); return this; } /** * Blocks ads. */ blockAds(blockAds) { this.put("block_ads", blockAds ? "true" : "false"); return this; } /** * Blocks banners by heuristics. */ blockBannersByHeuristics(block) { this.put("block_banners_by_heuristics", block ? "true" : "false"); return this; } /** * Blocks cookie banners. */ blockCookieBanners(block) { this.put("block_cookie_banners", block ? "true" : "false"); return this; } /** * Blocks chats. */ blockChats(block) { this.put("block_chats", block ? "true" : "false"); return this; } /** * Blocks trackers. */ blockTrackers(blockTrackers) { this.put("block_trackers", blockTrackers ? "true" : "false"); return this; } /** * Blocks requests by specifying URL, domain, or even a simple pattern. */ blockRequests(...blockRequests) { this.put("block_requests", ...blockRequests); return this; } /** * Blocks loading resources by type. Available resource types are: "document", "stylesheet", "image", "media", * "font", "script", "texttrack", "xhr", "fetch", "eventsource", "websocket", "manifest", "other". */ blockResources(...blockResources) { this.put("block_resources", ...blockResources); return this; } /** * Enables caching. */ cache(cache) { this.put("cache", cache ? "true" : "false"); return this; } /** * Sets cache TTL. */ cacheTtl(cacheTTL) { this.put("cache_ttl", cacheTTL.toString()); return this; } /** * Sets cache key. */ cacheKey(cacheKey) { this.put("cache_key", cacheKey); return this; } /** * Sets a user agent for the request. */ userAgent(userAgent) { this.put("user_agent", userAgent); return this; } /** * Sets an authorization header for the request. */ authorization(authorization) { this.put("authorization", authorization); return this; } /** * It scrolls the page if needed and ensures that the given * selector is present in the view when taking a screenshot. */ scrollIntoView(selector) { this.put("scroll_into_view", selector); return this; } /** * After the given element appears in the viewport and its top coordinate is aligned with the viewport's top, * you can adjust the position a bit before taking a screenshot. */ scrollIntoViewAdjustTop(adjustTop) { this.put("scroll_into_view_adjust_top", adjustTop.toString()); return this; } /** * You can use your custom proxy to take screenshots * or render HTML with the proxy option. * * The https, http, socks4 and socks5 proxies are supported. */ proxy(proxy) { this.put("proxy", proxy); return this; } /** * Set cookies for the request. */ cookies(...cookies) { this.put("cookies", ...cookies); return this; } /** * Sets extra headers for the request. */ headers(...headers) { this.put("headers", ...headers); return this; } /** * TimeZone sets time zone for the request. * Available time zones are: "America/Santiago", "Asia/Shanghai", "Europe/Berlin", "America/Guayaquil", * "Europe/Madrid", "Pacific/Majuro", "Asia/Kuala_Lumpur", "Pacific/Auckland", "Europe/Lisbon", "Europe/Kiev", * "Asia/Tashkent", "Europe/London". */ timeZone(timeZone) { this.put("time_zone", timeZone); return this; } /** * Sets delay. */ delay(delay) { this.put("delay", delay.toString()); return this; } /** * Sets timeout. */ timeout(timeout) { this.put("timeout", timeout.toString()); return this; } /** * Sets navigation timeout. */ navigationTimeout(timeout) { this.put("navigation_timeout", timeout.toString()); return this; } /** * Default value is false. Use store=true to trigger upload of the taken screenshot, * rendered HTML or PDF to the configured S3 bucket. * Make sure you configured access to S3. */ store(store) { this.put("store", store ? "true" : "false"); return this; } /** * The parameter is required if you set store=true. * You must specify the key for the file, but don't specify an extension, * it will be added automatically based on the format you specified. * You can also specify "subdirectories" in the path part. */ storagePath(path) { this.put("storage_path", path); return this; } storageACL(acl) { this.put("storage_acl", acl); return this; } /** * You can override the default bucket you configured with storage_bucket=<bucket name>. */ storageBucket(bucket) { this.put("storage_bucket", bucket); return this; } /** * Access key ID. It overrides the one specified in the dashboard configuration. */ storageAccessKeyId(accessKeyId) { this.put("storage_access_key_id", accessKeyId); return this; } /** * Secret access key. It overrides the one specified in the dashboard configuration. */ storageSecretAccessKey(secretAccessKey) { this.put("storage_secret_access_key", secretAccessKey); return this; } /** * Leave empty for Amazon S3, specify only when needed. Any S3-compatible storage is supported, * e.g. "https://<accountId>.r2.cloudflarestorage.com" for Cloudlfare R2 storage. */ storageEndpoint(endpoint) { this.put("storage_endpoint", endpoint); return this; } /** * Storage class allows you to specify the object storage class. */ storageClass(storageClass) { this.put("storage_class", storageClass); return this; } /** * Sets the image width for thumbnail creation. */ imageWidth(width) { this.put("image_width", width.toString()); return this; } /** * Sets the image height for thumbnail creation. */ imageHeight(height) { this.put("image_height", height.toString()); return this; } /** * Sets whether to request GPU rendering. */ requestGpuRendering(request) { this.put("request_gpu_rendering", request ? "true" : "false"); return this; } /** * Sets whether to print background for PDF. */ pdfPrintBackground(print) { this.put("pdf_print_background", print ? "true" : "false"); return this; } /** * Sets whether to fit PDF to one page. */ pdfFitOnePage(fit) { this.put("pdf_fit_one_page", fit ? "true" : "false"); return this; } /** * Sets the OpenAI API key for vision integration. */ openAiApiKey(key) { this.put("openai_api_key", key); return this; } /** * Sets the vision prompt for OpenAI integration. */ visionPrompt(prompt) { this.put("vision_prompt", prompt); return this; } /** * Sets the maximum tokens for OpenAI vision response. */ visionMaxTokens(tokens) { this.put("vision_max_tokens", tokens.toString()); return this; } /** * Sets whether to bypass Content Security Policy. */ bypassCsp(bypass) { this.put("bypass_csp", bypass ? "true" : "false"); return this; } /** * Sets whether to wait for a specific selector. */ waitForSelector(selector) { this.put("wait_for_selector", selector); return this; } /** * Sets whether to return the storage location. */ storageReturnLocation(return_location) { this.put("storage_return_location", return_location ? "true" : "false"); return this; } /** * Sets whether to include image size metadata. */ metadataImageSize(include) { this.put("metadata_image_size", include ? "true" : "false"); return this; } /** * Sets whether to include fonts metadata. */ metadataFonts(include) { this.put("metadata_fonts", include ? "true" : "false"); return this; } /** * Sets whether to include Open Graph metadata. */ metadataOpenGraph(include) { this.put("metadata_open_graph", include ? "true" : "false"); return this; } /** * Sets whether to include page title metadata. */ metadataPageTitle(include) { this.put("metadata_page_title", include ? "true" : "false"); return this; } /** * Sets whether to include content metadata. */ metadataContent(include) { this.put("metadata_content", include ? "true" : "false"); return this; } /** * Sets whether to include HTTP response status code metadata. */ metadataHttpResponseStatusCode(include) { this.put("metadata_http_response_status_code", include ? "true" : "false"); return this; } /** * Sets whether to include HTTP response headers metadata. */ metadataHttpResponseHeaders(include) { this.put("metadata_http_response_headers", include ? "true" : "false"); return this; } /** * Sets whether to execute the request asynchronously. */ async(isAsync) { this.put("async", isAsync ? "true" : "false"); return this; } /** * Sets the webhook URL for asynchronous requests. */ webhookUrl(url) { this.put("webhook_url", url); return this; } /** * Sets whether to sign the webhook request. */ webhookSign(sign) { this.put("webhook_sign", sign ? "true" : "false"); return this; } /** * Sets the text to check for in the content to force request failure. */ failIfContentContains(text) { this.put("fail_if_content_contains", text); return this; } /** * Sets whether to fail if GPU rendering fails. */ failIfGpuRenderingFails(fail) { this.put("fail_if_gpu_rendering_fails", fail ? "true" : "false"); return this; } toQuery() { return new URLSearchParams(this.query.toString()); } } exports.TakeOptions = TakeOptions; /** * Represents options for animating screenshots. */ class AnimateOptions { constructor() { const query = new URLSearchParams(); this.query = query; } /** * Initializes take screenshot options with provided website URL. */ static url(url) { const options = new AnimateOptions(); options.put("url", url); return options; } /** * Initializes take screenshot options with provided HTML. */ static html(html) { const options = new AnimateOptions(); options.put("html", html); return options; } /** * Initializes take screenshot options with provided Markdown. */ static markdown(markdown) { const options = new AnimateOptions(); options.put("markdown", markdown); return options; } put(key, ...values) { for (const value of values) { if (values.length == 1) { this.query.set(key, value); } else { this.query.append(key, value); } } } /** * Available response types: * by_format — return exactly the response defined in the format option. If format=png, the response will be the binary representation of the png with the content type header image/png; * empty — return only status or error. It is suitable when you want to upload the screenshot to storage and don't care about the results. It also speeds up the response since there are no networking costs involved. * The default value is by_format. */ responseType(responseType) { this.put("response_type", responseType); return this; } /** * When reduced_motion set to `true`, * the API will request the site to minimize the amount of non-essential motion it uses. * When the site supports it, it should use animations as least as possible. */ reducedMotion(darkMode) { this.put("reduced_motion", darkMode ? "true" : "false"); return this; } /** * If you want to request the page and it is supported to be rendered for printers, specify `print`. * If the page is by default rendered for printers and you want it to be rendered for screens, * use `screen`. */ mediaType(mediaType) { this.put("media_type", mediaType); return this; } /** * Set `true` to request site rendering, if supported, in the dark mode. * Set `false` to request site rendering in the light mode if supported. * If you don't set the parameter. The site is rendered in the default mode. */ darkMode(darkMode) { this.put("dark_mode", darkMode ? "true" : "false"); return this; } /** * The `hide_selectors` option allows hiding elements before taking a screenshot. * You can specify as many selectors as you wish. * All elements that match each selector will be hidden by * setting the `display` style property to none `!important`. */ hideSelectors(...selectors) { this.put("hide_selectors", ...selectors); return this; } /** * The scripts_wain_until option allows you to wait until a given * set of events after the scripts were executed. * It accepts the same values as wait_until and can have multiple values: * - `load`: the navigation is successful when the load even is fired; * - `domcontentloaded`: the navigation is finished when the DOMContentLoaded even is fired; * - `networkidle0`: the navigation is finished when there are no more than 0 network connections for at least 500 ms; * _ `networkidle2`: consider navigation to be finished when there are no more than 2 network connections for at least 500 ms. */ scriptsWaitUntil(...until) { this.put("scripts_wait_until", ...until); return this; } /** * Styles specifies custom CSS styles for the page. */ styles(styles) { this.put("styles", styles); return this; } /** * You can use your custom proxy to take screenshots * or render HTML with the proxy option. * * The https, http, socks4 and socks5 proxies are supported. */ proxy(proxy) { this.put("proxy", proxy); return this; } /** * Scripts specifies custom scripts for the page. */ scripts(scripts) { this.put("scripts", scripts); return this; } /** * Sets response format, one of: "mp4", "avi", "webm", "mov" or "gif". */ format(format) { this.put("format", format); return this; } /** * Renders a transparent background for the image. Works only if the site has not defined background color. * Available for the following response formats: "png", "webp". */ omitBackground(omitBackground) { this.put("omit_background", omitBackground ? "true" : "false"); return this; } /** * Instead of manually specifying viewport parameters like width and height, * you can specify a device to use for emulation. * In addition, other parameters of the viewport, including the user agent, * will be set automatically. */ viewportDevice(viewportDevice) { this.put("viewport_device", viewportDevice); return this; } /** * Sets the width of the browser viewport (pixels). */ viewportWidth(viewportWidth) { this.put("viewport_width", viewportWidth.toString()); return this; } /** * Sets the height of the browser viewport (pixels). */ viewportHeight(viewportHeight) { this.put("viewport_height", viewportHeight.toString()); return this; } /** * Sets the device scale factor. Acceptable value is one of: 1, 2 or 3. */ deviceScaleFactor(deviceScaleFactor) { this.put("device_scale_factor", deviceScaleFactor.toString()); return this; } /** * Whether the meta viewport tag is taken into account. Defaults to `false`. */ viewportMobile(isMobile) { this.put("viewport_mobile", isMobile ? "true" : "false"); return this; } /** * The default value is `false`. Set to `true` if the viewport supports touch events. */ viewportHasTouch(hasTouch) { this.put("viewport_has_touch", hasTouch ? "true" : "false"); return this; } /** * The default value is `false`. Set to `true` if the viewport is in landscape mode. */ viewportLandscape(landscape) { this.put("viewport_landscape", landscape ? "true" : "false"); return this; } /** * Sets geolocation latitude for the request. * Both latitude and longitude are required if one of them is set. */ geolocationLatitude(latitude) { this.put("geolocation_latitude", new big_js_1.default(latitude).toFixed(20).replace(/0+$/, "")); return this; } /** * Sets geolocation longitude for the request. Both latitude and longitude are required if one of them is set. */ geolocationLongitude(longitude) { this.put("geolocation_longitude", new big_js_1.default(longitude).toFixed(20).replace(/0+$/, "")); return this; } /** * Sets the geolocation accuracy in meters. */ geolocationAccuracy(accuracy) { this.put("geolocation_accuracy", accuracy.toString()); return this; } /** * Blocks ads. */ blockAds(blockAds) { this.put("block_ads", blockAds ? "true" : "false"); return this; } /** * Blocks cookie banners. */ blockCookieBanners(block) { this.put("block_cookie_banners", block ? "true" : "false"); return this; } /** * Blocks chats. */ blockChats(block) { this.put("block_chats", block ? "true" : "false"); return this; } /** * Blocks trackers. */ blockTrackers(blockTrackers) { this.put("block_trackers", blockTrackers ? "true" : "false"); return this; } /** * Blocks requests by specifying URL, domain, or even a simple pattern. */ blockRequests(...blockRequests) { this.put("block_requests", ...blockRequests); return this; } /** * Blocks loading resources by type. Available resource types are: "document", "stylesheet", "image", "media", * "font", "script", "texttrack", "xhr", "fetch", "eventsource", "websocket", "manifest", "other". */ blockResources(...blockResources) { this.put("block_resources", ...blockResources); return this; } /** * Blocks banners by heuristics. */ blockBannersByHeuristics(block) { this.put("block_banners_by_heuristics", block ? "true" : "false"); return this; } /** * Enables caching. */ cache(cache) { this.put("cache", cache ? "true" : "false"); return this; } /** * Sets cache TTL. */ cacheTtl(cacheTTL) { this.put("cache_ttl", cacheTTL.toString()); return this; } /** * Sets cache key. */ cacheKey(cacheKey) { this.put("cache_key", cacheKey); return this; } /** * Sets a user agent for the request. */ userAgent(userAgent) { this.put("user_agent", userAgent); return this; } /** * Sets an authorization header for the request. */ authorization(authorization) { this.put("authorization", authorization); return this; } /** * Set cookies for the request. */ cookies(...cookies) { this.put("cookies", ...cookies); return this; } /** * Sets extra headers for the request. */ headers(...headers) { this.put("headers", ...headers); return this; } /** * TimeZone sets time zone for the request. * Available time zones are: "America/Santiago", "Asia/Shanghai", "Europe/Berlin", "America/Guayaquil", * "Europe/Madrid", "Pacific/Majuro", "Asia/Kuala_Lumpur", "Pacific/Auckland", "Europe/Lisbon", "Europe/Kiev", * "Asia/Tashkent", "Europe/London". */ timeZone(timeZone) { this.put("time_zone", timeZone); return this; } /** * Sets delay. */ delay(delay) { this.put("delay", delay.toString()); return this; } /** * Sets timeout. */ timeout(timeout) { this.put("timeout", timeout.toString()); return this; } /** * Sets navigation timeout. */ navigationTimeout(timeout) { this.put("navigation_timeout", timeout.toString()); return this; } /** * Default value is false. Use store=true to trigger upload of the taken screenshot, * rendered HTML or PDF to the configured S3 bucket. * Make sure you configured access to S3. */ store(store) { this.put("store", store ? "true" : "false"); return this; } /** * Access key ID. It overrides the one specified in the dashboard configuration. */ storageAccessKeyId(accessKeyId) { this.put("storage_access_key_id", accessKeyId); return this; } /** * Secret access key. It overrides the one specified in the dashboard configuration. */ storageSecretAccessKey(secretAccessKey) { this.put("storage_secret_access_key", secretAccessKey); return this; } /** * The parameter is required if you set store=true. * You must specify the key for the file, but don't specify an extension, * it will be added automatically based on the format you specified. * You can also specify "subdirectories" in the path part. */ storagePath(path) { this.put("storage_path", path); return this; } /** * You can override the default bucket you configured with storage_bucket=<bucket name>. */ storageBucket(bucket) { this.put("storage_bucket", bucket); return this; } /** * Storage class allows you to specify the object storage class. */ storageClass(storageClass) { this.put("storage_class", storageClass); return this; } storageACL(acl) { this.put("storage_acl", acl); return this; } /** * Sets animation duration. */ duration(duration) { this.put("duration", duration.toString()); return this; } /** * Sets animation duration. */ scenario(scenario) { this.put("scenario", scenario); return this; } scrollDelay(delay) { this.put("scroll_delay", delay.toString()); return this; } scrollDuration(duration) { this.put("scroll_duration", duration.toString()); return this; } scrollStartImmediately(startImmediately) { this.put("scroll_start_immediately", startImmediately ? "true" : "false"); return this; } scrollBack(scrollBack) { this.put("scroll_back", scrollBack ? "true" : "false"); return this; } scrollBackAfterDuration(duration) { this.put("scroll_back_after_duration", duration.toString()); return this; } scrollStartDelay(delay) { this.put("scroll_start_delay", delay.toString()); return this; } scrollComplete(complete) { this.put("scroll_complete", complete ? "true" : "false"); return this; } scrollBy(pixels) { this.put("scroll_by", pixels.toString()); return this; } /** * When the site responds out of the range of 200-299 status code, * you can ignore errors and take a screenshot of the error page anyway. * To do that, set the option "ignore_host_errors" to true. * It is false by default. * * It is helpful when you want to create a gallery of error pages or, * for some reason, you need to render error pages. */ ignoreHostErrors(ignore) { this.put("ignore_host_errors", ignore ? "true" : "false"); return this; } /** * Sets whether to request GPU rendering. */ requestGpuRendering(request) { this.put("request_gpu_rendering", request ? "true" : "false"); return this; } /** * Sets whether to bypass Content Security Policy. */ bypassCsp(bypass) { this.put("bypass_csp", bypass ? "true" : "false"); return this; } /** * Sets whether to wait for a specific selector. */ waitForSelector(selector) { this.put("wait_for_selector", selector); return this; } /** * Sets whether to return the storage location. */ storageReturnLocation(return_location) { this.put("storage_return_location", return_location ? "true" : "false"); return this; } /** * Sets whether to execute the request asynchronously. */ async(isAsync) { this.put("async", isAsync ? "true" : "false"); return this; } /** * Sets the webhook URL for asynchronous requests. */ webhookUrl(url) { this.put("webhook_url", url); return this; } /** * Sets whether to sign the webhook request. */ webhookSign(sign) { this.put("webhook_sign", sign ? "true" : "false"); return this; } /** * Sets the text to check for in the content to force request failure. */ failIfContentContains(text) { this.put("fail_if_content_contains", text); return this; } /** * Sets whether to fail if GPU rendering fails. */ failIfGpuRenderingFails(fail) { this.put("fail_if_gpu_rendering_fails", fail ? "true" : "false"); return this; } /** * Sets the width of the animation. */ width(width) { this.put("width", width.toString()); return this; } /** * Sets the height of the animation. */ height(height) { this.put("height", height.toString()); return this; } /** * Sets the aspect ratio of the animation. */ aspectRatio(ratio) { this.put("aspect_ratio", ratio); return this; } /** * Sets the scroll easing effect. */ scrollEasing(easing) { this.put("scroll_easing", easing); return this; } /** * Sets whether to navigate while scrolling and record the new opened page. */ scrollTryNavigate(tryNavigate) { this.put("scroll_try_navigate", tryNavigate ? "true" : "false"); return this; } /** * Sets when to navigate after scrolling (in milliseconds). */ scrollNavigateAfter(duration) { this.put("scroll_navigate_after", duration.toString()); return this; } /** * Sets the URL to navigate to while scrolling. */ scrollNavigateToURL(url) { this.put("scroll_navigate_to_url", url); return this; } /** * Sets the link hints for navigation while scrolling. */ scrollNavigateLinkHints(...hints) { this.put("scroll_navigate_link_hints", ...hints); return this; } /** * Sets the scroll back algorithm. */ scrollBackAlgorithm(algorithm) { this.put("scroll_back_algorithm", algorithm); return this; } /** * Sets when to stop scrolling after the specified duration in milliseconds. */ scrollStopAfterDuration(duration) { this.put("scroll_stop_after_duration", duration.toString()); return this; } toQuery() { return new URLSearchParams(this.query.toString()); } } exports.AnimateOptions = AnimateOptions;