scrapfly-sdk 0.10.2 → 0.10.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/esm/batch.d.ts.map +1 -1
  2. package/esm/batch.js +4 -0
  3. package/esm/client.d.ts.map +1 -1
  4. package/esm/client.js +17 -8
  5. package/package.json +1 -1
  6. package/script/batch.d.ts.map +1 -1
  7. package/script/batch.js +4 -0
  8. package/script/client.d.ts.map +1 -1
  9. package/script/client.js +17 -8
  10. package/src/_dnt.shims.ts +64 -0
  11. package/src/batch.ts +272 -0
  12. package/src/browserconfig.ts +118 -0
  13. package/src/client.ts +1609 -0
  14. package/src/crawl.ts +251 -0
  15. package/src/crawlerconfig.ts +363 -0
  16. package/src/crawlerresult.ts +471 -0
  17. package/src/deps/jsr.io/@std/path/1.0.1/_common/assert_path.ts +10 -0
  18. package/src/deps/jsr.io/@std/path/1.0.1/_common/basename.ts +53 -0
  19. package/src/deps/jsr.io/@std/path/1.0.1/_common/common.ts +26 -0
  20. package/src/deps/jsr.io/@std/path/1.0.1/_common/constants.ts +49 -0
  21. package/src/deps/jsr.io/@std/path/1.0.1/_common/dirname.ts +9 -0
  22. package/src/deps/jsr.io/@std/path/1.0.1/_common/format.ts +25 -0
  23. package/src/deps/jsr.io/@std/path/1.0.1/_common/from_file_url.ts +10 -0
  24. package/src/deps/jsr.io/@std/path/1.0.1/_common/glob_to_reg_exp.ts +290 -0
  25. package/src/deps/jsr.io/@std/path/1.0.1/_common/normalize.ts +9 -0
  26. package/src/deps/jsr.io/@std/path/1.0.1/_common/normalize_string.ts +74 -0
  27. package/src/deps/jsr.io/@std/path/1.0.1/_common/relative.ts +10 -0
  28. package/src/deps/jsr.io/@std/path/1.0.1/_common/strip_trailing_separators.ts +25 -0
  29. package/src/deps/jsr.io/@std/path/1.0.1/_common/to_file_url.ts +17 -0
  30. package/src/deps/jsr.io/@std/path/1.0.1/_os.ts +31 -0
  31. package/src/deps/jsr.io/@std/path/1.0.1/basename.ts +35 -0
  32. package/src/deps/jsr.io/@std/path/1.0.1/common.ts +35 -0
  33. package/src/deps/jsr.io/@std/path/1.0.1/constants.ts +18 -0
  34. package/src/deps/jsr.io/@std/path/1.0.1/dirname.ts +28 -0
  35. package/src/deps/jsr.io/@std/path/1.0.1/extname.ts +27 -0
  36. package/src/deps/jsr.io/@std/path/1.0.1/format.ts +30 -0
  37. package/src/deps/jsr.io/@std/path/1.0.1/from_file_url.ts +30 -0
  38. package/src/deps/jsr.io/@std/path/1.0.1/glob_to_regexp.ts +94 -0
  39. package/src/deps/jsr.io/@std/path/1.0.1/is_absolute.ts +30 -0
  40. package/src/deps/jsr.io/@std/path/1.0.1/is_glob.ts +49 -0
  41. package/src/deps/jsr.io/@std/path/1.0.1/join.ts +28 -0
  42. package/src/deps/jsr.io/@std/path/1.0.1/join_globs.ts +42 -0
  43. package/src/deps/jsr.io/@std/path/1.0.1/mod.ts +55 -0
  44. package/src/deps/jsr.io/@std/path/1.0.1/normalize.ts +31 -0
  45. package/src/deps/jsr.io/@std/path/1.0.1/normalize_glob.ts +45 -0
  46. package/src/deps/jsr.io/@std/path/1.0.1/parse.ts +44 -0
  47. package/src/deps/jsr.io/@std/path/1.0.1/posix/_util.ts +10 -0
  48. package/src/deps/jsr.io/@std/path/1.0.1/posix/basename.ts +39 -0
  49. package/src/deps/jsr.io/@std/path/1.0.1/posix/constants.ts +15 -0
  50. package/src/deps/jsr.io/@std/path/1.0.1/posix/dirname.ts +55 -0
  51. package/src/deps/jsr.io/@std/path/1.0.1/posix/extname.ts +73 -0
  52. package/src/deps/jsr.io/@std/path/1.0.1/posix/format.ts +31 -0
  53. package/src/deps/jsr.io/@std/path/1.0.1/posix/from_file_url.ts +25 -0
  54. package/src/deps/jsr.io/@std/path/1.0.1/posix/glob_to_regexp.ts +94 -0
  55. package/src/deps/jsr.io/@std/path/1.0.1/posix/is_absolute.ts +25 -0
  56. package/src/deps/jsr.io/@std/path/1.0.1/posix/join.ts +27 -0
  57. package/src/deps/jsr.io/@std/path/1.0.1/posix/join_globs.ts +44 -0
  58. package/src/deps/jsr.io/@std/path/1.0.1/posix/normalize.ts +41 -0
  59. package/src/deps/jsr.io/@std/path/1.0.1/posix/normalize_glob.ts +42 -0
  60. package/src/deps/jsr.io/@std/path/1.0.1/posix/parse.ts +121 -0
  61. package/src/deps/jsr.io/@std/path/1.0.1/posix/relative.ts +103 -0
  62. package/src/deps/jsr.io/@std/path/1.0.1/posix/resolve.ts +69 -0
  63. package/src/deps/jsr.io/@std/path/1.0.1/posix/to_file_url.ts +32 -0
  64. package/src/deps/jsr.io/@std/path/1.0.1/posix/to_namespaced_path.ts +21 -0
  65. package/src/deps/jsr.io/@std/path/1.0.1/relative.ts +32 -0
  66. package/src/deps/jsr.io/@std/path/1.0.1/resolve.ts +32 -0
  67. package/src/deps/jsr.io/@std/path/1.0.1/to_file_url.ts +30 -0
  68. package/src/deps/jsr.io/@std/path/1.0.1/to_namespaced_path.ts +31 -0
  69. package/src/deps/jsr.io/@std/path/1.0.1/types.ts +40 -0
  70. package/src/deps/jsr.io/@std/path/1.0.1/windows/_util.ts +28 -0
  71. package/src/deps/jsr.io/@std/path/1.0.1/windows/basename.ts +48 -0
  72. package/src/deps/jsr.io/@std/path/1.0.1/windows/constants.ts +15 -0
  73. package/src/deps/jsr.io/@std/path/1.0.1/windows/dirname.ts +114 -0
  74. package/src/deps/jsr.io/@std/path/1.0.1/windows/extname.ts +86 -0
  75. package/src/deps/jsr.io/@std/path/1.0.1/windows/format.ts +31 -0
  76. package/src/deps/jsr.io/@std/path/1.0.1/windows/from_file_url.ts +34 -0
  77. package/src/deps/jsr.io/@std/path/1.0.1/windows/glob_to_regexp.ts +92 -0
  78. package/src/deps/jsr.io/@std/path/1.0.1/windows/is_absolute.ts +40 -0
  79. package/src/deps/jsr.io/@std/path/1.0.1/windows/join.ts +72 -0
  80. package/src/deps/jsr.io/@std/path/1.0.1/windows/join_globs.ts +45 -0
  81. package/src/deps/jsr.io/@std/path/1.0.1/windows/normalize.ts +132 -0
  82. package/src/deps/jsr.io/@std/path/1.0.1/windows/normalize_glob.ts +42 -0
  83. package/src/deps/jsr.io/@std/path/1.0.1/windows/parse.ts +184 -0
  84. package/src/deps/jsr.io/@std/path/1.0.1/windows/relative.ts +128 -0
  85. package/src/deps/jsr.io/@std/path/1.0.1/windows/resolve.ts +174 -0
  86. package/src/deps/jsr.io/@std/path/1.0.1/windows/to_file_url.ts +38 -0
  87. package/src/deps/jsr.io/@std/path/1.0.1/windows/to_namespaced_path.ts +60 -0
  88. package/src/deps.ts +4 -0
  89. package/src/errors.ts +55 -0
  90. package/src/extractionconfig.ts +175 -0
  91. package/src/logger.ts +51 -0
  92. package/src/main.ts +61 -0
  93. package/src/monitoringconfig.ts +50 -0
  94. package/src/polyfill.ts +37 -0
  95. package/src/result.ts +338 -0
  96. package/src/scrapeconfig.ts +448 -0
  97. package/src/screenshotconfig.ts +204 -0
  98. package/src/types.ts +2 -0
  99. package/src/utils.ts +86 -0
  100. package/src/webhookserver.ts +66 -0
@@ -0,0 +1,174 @@
1
+ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
2
+ // This module is browser compatible.
3
+ import * as dntShim from "../../../../../../_dnt.shims.js";
4
+
5
+
6
+ import { CHAR_COLON } from "../_common/constants.js";
7
+ import { normalizeString } from "../_common/normalize_string.js";
8
+ import { assertPath } from "../_common/assert_path.js";
9
+ import { isPathSeparator, isWindowsDeviceRoot } from "./_util.js";
10
+
11
+ /**
12
+ * Resolves path segments into a `path`.
13
+ *
14
+ * @example Usage
15
+ * ```ts
16
+ * import { resolve } from "@std/path/windows/resolve";
17
+ * import { assertEquals } from "@std/assert";
18
+ *
19
+ * const resolved = resolve("C:\\foo\\bar", "..\\baz");
20
+ * assertEquals(resolved, "C:\\foo\\baz");
21
+ * ```
22
+ *
23
+ * @param pathSegments The path segments to process to path
24
+ * @returns The resolved path
25
+ */
26
+ export function resolve(...pathSegments: string[]): string {
27
+ let resolvedDevice = "";
28
+ let resolvedTail = "";
29
+ let resolvedAbsolute = false;
30
+
31
+ for (let i = pathSegments.length - 1; i >= -1; i--) {
32
+ let path: string;
33
+ // deno-lint-ignore no-explicit-any
34
+ const { Deno } = dntShim.dntGlobalThis as any;
35
+ if (i >= 0) {
36
+ path = pathSegments[i]!;
37
+ } else if (!resolvedDevice) {
38
+ if (typeof Deno?.cwd !== "function") {
39
+ throw new TypeError("Resolved a drive-letter-less path without a CWD.");
40
+ }
41
+ path = Deno.cwd();
42
+ } else {
43
+ if (
44
+ typeof Deno?.env?.get !== "function" || typeof Deno?.cwd !== "function"
45
+ ) {
46
+ throw new TypeError("Resolved a relative path without a CWD.");
47
+ }
48
+ path = Deno.cwd();
49
+
50
+ // Verify that a cwd was found and that it actually points
51
+ // to our drive. If not, default to the drive's root.
52
+ if (
53
+ path === undefined ||
54
+ path.slice(0, 3).toLowerCase() !== `${resolvedDevice.toLowerCase()}\\`
55
+ ) {
56
+ path = `${resolvedDevice}\\`;
57
+ }
58
+ }
59
+
60
+ assertPath(path);
61
+
62
+ const len = path.length;
63
+
64
+ // Skip empty entries
65
+ if (len === 0) continue;
66
+
67
+ let rootEnd = 0;
68
+ let device = "";
69
+ let isAbsolute = false;
70
+ const code = path.charCodeAt(0);
71
+
72
+ // Try to match a root
73
+ if (len > 1) {
74
+ if (isPathSeparator(code)) {
75
+ // Possible UNC root
76
+
77
+ // If we started with a separator, we know we at least have an
78
+ // absolute path of some kind (UNC or otherwise)
79
+ isAbsolute = true;
80
+
81
+ if (isPathSeparator(path.charCodeAt(1))) {
82
+ // Matched double path separator at beginning
83
+ let j = 2;
84
+ let last = j;
85
+ // Match 1 or more non-path separators
86
+ for (; j < len; ++j) {
87
+ if (isPathSeparator(path.charCodeAt(j))) break;
88
+ }
89
+ if (j < len && j !== last) {
90
+ const firstPart = path.slice(last, j);
91
+ // Matched!
92
+ last = j;
93
+ // Match 1 or more path separators
94
+ for (; j < len; ++j) {
95
+ if (!isPathSeparator(path.charCodeAt(j))) break;
96
+ }
97
+ if (j < len && j !== last) {
98
+ // Matched!
99
+ last = j;
100
+ // Match 1 or more non-path separators
101
+ for (; j < len; ++j) {
102
+ if (isPathSeparator(path.charCodeAt(j))) break;
103
+ }
104
+ if (j === len) {
105
+ // We matched a UNC root only
106
+ device = `\\\\${firstPart}\\${path.slice(last)}`;
107
+ rootEnd = j;
108
+ } else if (j !== last) {
109
+ // We matched a UNC root with leftovers
110
+
111
+ device = `\\\\${firstPart}\\${path.slice(last, j)}`;
112
+ rootEnd = j;
113
+ }
114
+ }
115
+ }
116
+ } else {
117
+ rootEnd = 1;
118
+ }
119
+ } else if (isWindowsDeviceRoot(code)) {
120
+ // Possible device root
121
+
122
+ if (path.charCodeAt(1) === CHAR_COLON) {
123
+ device = path.slice(0, 2);
124
+ rootEnd = 2;
125
+ if (len > 2) {
126
+ if (isPathSeparator(path.charCodeAt(2))) {
127
+ // Treat separator following drive name as an absolute path
128
+ // indicator
129
+ isAbsolute = true;
130
+ rootEnd = 3;
131
+ }
132
+ }
133
+ }
134
+ }
135
+ } else if (isPathSeparator(code)) {
136
+ // `path` contains just a path separator
137
+ rootEnd = 1;
138
+ isAbsolute = true;
139
+ }
140
+
141
+ if (
142
+ device.length > 0 &&
143
+ resolvedDevice.length > 0 &&
144
+ device.toLowerCase() !== resolvedDevice.toLowerCase()
145
+ ) {
146
+ // This path points to another device so it is not applicable
147
+ continue;
148
+ }
149
+
150
+ if (resolvedDevice.length === 0 && device.length > 0) {
151
+ resolvedDevice = device;
152
+ }
153
+ if (!resolvedAbsolute) {
154
+ resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`;
155
+ resolvedAbsolute = isAbsolute;
156
+ }
157
+
158
+ if (resolvedAbsolute && resolvedDevice.length > 0) break;
159
+ }
160
+
161
+ // At this point the path should be resolved to a full absolute path,
162
+ // but handle relative paths to be safe (might happen when Deno.cwd()
163
+ // fails)
164
+
165
+ // Normalize the tail path
166
+ resolvedTail = normalizeString(
167
+ resolvedTail,
168
+ !resolvedAbsolute,
169
+ "\\",
170
+ isPathSeparator,
171
+ );
172
+
173
+ return resolvedDevice + (resolvedAbsolute ? "\\" : "") + resolvedTail || ".";
174
+ }
@@ -0,0 +1,38 @@
1
+ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
2
+ // This module is browser compatible.
3
+
4
+ import { encodeWhitespace } from "../_common/to_file_url.js";
5
+ import { isAbsolute } from "./is_absolute.js";
6
+
7
+ /**
8
+ * Converts a path string to a file URL.
9
+ *
10
+ * @example Usage
11
+ * ```ts
12
+ * import { toFileUrl } from "@std/path/windows/to-file-url";
13
+ * import { assertEquals } from "@std/assert";
14
+ *
15
+ * assertEquals(toFileUrl("\\home\\foo"), new URL("file:///home/foo"));
16
+ * assertEquals(toFileUrl("C:\\Users\\foo"), new URL("file:///C:/Users/foo"));
17
+ * assertEquals(toFileUrl("\\\\127.0.0.1\\home\\foo"), new URL("file://127.0.0.1/home/foo"));
18
+ * ```
19
+ * @param path The path to convert.
20
+ * @returns The file URL.
21
+ */
22
+ export function toFileUrl(path: string): URL {
23
+ if (!isAbsolute(path)) {
24
+ throw new TypeError("Must be an absolute path.");
25
+ }
26
+ const [, hostname, pathname] = path.match(
27
+ /^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/,
28
+ )!;
29
+ const url = new URL("file:///");
30
+ url.pathname = encodeWhitespace(pathname!.replace(/%/g, "%25"));
31
+ if (hostname !== undefined && hostname !== "localhost") {
32
+ url.hostname = hostname;
33
+ if (!url.hostname) {
34
+ throw new TypeError("Invalid hostname.");
35
+ }
36
+ }
37
+ return url;
38
+ }
@@ -0,0 +1,60 @@
1
+ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
2
+ // This module is browser compatible.
3
+
4
+ import {
5
+ CHAR_BACKWARD_SLASH,
6
+ CHAR_COLON,
7
+ CHAR_DOT,
8
+ CHAR_QUESTION_MARK,
9
+ } from "../_common/constants.js";
10
+ import { isWindowsDeviceRoot } from "./_util.js";
11
+ import { resolve } from "./resolve.js";
12
+
13
+ /**
14
+ * Resolves path to a namespace path
15
+ *
16
+ * @example Usage
17
+ * ```ts
18
+ * import { toNamespacedPath } from "@std/path/windows/to-namespaced-path";
19
+ * import { assertEquals } from "@std/assert";
20
+ *
21
+ * const namespaced = toNamespacedPath("C:\\foo\\bar");
22
+ * assertEquals(namespaced, "\\\\?\\C:\\foo\\bar");
23
+ * ```
24
+ *
25
+ * @param path The path to resolve to namespaced path
26
+ * @returns The resolved namespaced path
27
+ */
28
+ export function toNamespacedPath(path: string): string {
29
+ // Note: this will *probably* throw somewhere.
30
+ if (typeof path !== "string") return path;
31
+ if (path.length === 0) return "";
32
+
33
+ const resolvedPath = resolve(path);
34
+
35
+ if (resolvedPath.length >= 3) {
36
+ if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
37
+ // Possible UNC root
38
+
39
+ if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
40
+ const code = resolvedPath.charCodeAt(2);
41
+ if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
42
+ // Matched non-long UNC root, convert the path to a long UNC path
43
+ return `\\\\?\\UNC\\${resolvedPath.slice(2)}`;
44
+ }
45
+ }
46
+ } else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0))) {
47
+ // Possible device root
48
+
49
+ if (
50
+ resolvedPath.charCodeAt(1) === CHAR_COLON &&
51
+ resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
52
+ ) {
53
+ // Matched device root, convert the path to a long UNC path
54
+ return `\\\\?\\${resolvedPath}`;
55
+ }
56
+ }
57
+ }
58
+
59
+ return path;
60
+ }
package/src/deps.ts ADDED
@@ -0,0 +1,4 @@
1
+ import * as cheerio from 'cheerio';
2
+ import * as path from './deps/jsr.io/@std/path/1.0.1/mod.js';
3
+
4
+ export { cheerio, path };
package/src/errors.ts ADDED
@@ -0,0 +1,55 @@
1
+ export class ScrapflyError extends Error {
2
+ args: Record<string, any>;
3
+
4
+ constructor(message: string, args: Record<string, any> = {}) {
5
+ super(message);
6
+ this.args = args;
7
+ }
8
+ }
9
+
10
+ // raised when scrape config is invalid
11
+ export class ScrapeConfigError extends ScrapflyError {}
12
+ // raised when screenshot config is invalid
13
+ export class ScreenshotConfigError extends ScrapflyError {}
14
+ // raised when extraction config is invalid
15
+ export class ExtractionConfigError extends ScrapflyError {}
16
+ // raised when crawler config is invalid
17
+ export class CrawlerConfigError extends ScrapflyError {}
18
+
19
+ // raised when scrape parameters cannot be encoded
20
+ export class EncodeError extends ScrapflyError {}
21
+ export class ContentTypeError extends ScrapflyError {}
22
+
23
+ // Base error for all http related operations
24
+ export class HttpError extends ScrapflyError {}
25
+ export class UpstreamHttpError extends HttpError {}
26
+ export class UpstreamHttpClientError extends UpstreamHttpError {}
27
+ export class UpstreamHttpServerError extends UpstreamHttpClientError {}
28
+
29
+ export class ApiHttpClientError extends HttpError {}
30
+ // raised when API key provided to client is not valid or not existant
31
+ export class BadApiKeyError extends ApiHttpClientError {}
32
+
33
+ export class TooManyRequests extends HttpError {}
34
+ export class ApiHttpServerError extends HttpError {}
35
+ export class ScrapflyScrapeError extends HttpError {}
36
+ // raised when proxy settings don't match available proxies (e.g. invalid proxy pool, country setting)
37
+ export class ScrapflyProxyError extends HttpError {}
38
+ export class ScrapflyThrottleError extends HttpError {}
39
+ // raised when ScrapFly fails to bypass anti-scraping protection
40
+ export class ScrapflyAspError extends HttpError {}
41
+ export class ScrapflyScheduleError extends HttpError {}
42
+ // raised when Webhook is invalid or cannot be fulfilled (i.e. full queue)
43
+ export class ScrapflyWebhookError extends HttpError {}
44
+ // raised when session is access concurrently
45
+ export class ScrapflySessionError extends HttpError {}
46
+ // raised when concurrent requests exceed account limits
47
+ export class TooManyConcurrentRequests extends HttpError {}
48
+ // raised when account is out of scrape credits
49
+ export class QuotaLimitReached extends HttpError {}
50
+ // raised with Scrapfly screenshot API related errors
51
+ export class ScreenshotApiError extends ApiHttpClientError {}
52
+ // raised with Scrapfly extraction API related errors
53
+ export class ExtractionApiError extends ApiHttpClientError {}
54
+ // raised with Scrapfly crawler API related errors (job lifecycle: ALREADY_STARTED, NOT_STARTED, FAILED, CANCELLED, TIMEOUT, etc.)
55
+ export class ScrapflyCrawlerError extends HttpError {}
@@ -0,0 +1,175 @@
1
+ import * as errors from './errors.js';
2
+ import { urlsafe_b64encode } from './utils.js';
3
+ import { ExtractionConfigError } from './errors.js';
4
+
5
+ export enum CompressionFormat {
6
+ /**
7
+ Document compression format.
8
+
9
+ Attributes:
10
+ GZIP: gzip format.
11
+ ZSTD: zstd format.
12
+ DEFLATE: deflate.
13
+ """
14
+ */
15
+ GZIP = 'gzip',
16
+ ZSTD = 'zstd',
17
+ DEFLATE = 'deflate',
18
+ }
19
+
20
+ type ExtractionConfigOptions = {
21
+ body: string;
22
+ content_type: string;
23
+ url?: string;
24
+ charset?: string;
25
+ extraction_template?: string; // saved template name
26
+ extraction_ephemeral_template?: object; // ephemeraly declared json template
27
+ extraction_prompt?: string;
28
+ extraction_model?: string;
29
+ is_document_compressed?: boolean;
30
+ document_compression_format?: 'gzip' | 'zstd' | 'deflate' | CompressionFormat;
31
+ webhook?: string;
32
+ timeout?: number;
33
+
34
+ // deprecated options
35
+ template?: string;
36
+ ephemeral_template?: object;
37
+ };
38
+
39
+ export class ExtractionConfig {
40
+ body: string | Uint8Array;
41
+ content_type: string;
42
+ url?: string;
43
+ charset?: string;
44
+ extraction_template?: string; // saved template name
45
+ extraction_ephemeral_template?: object; // ephemeraly declared json template
46
+ extraction_prompt?: string;
47
+ extraction_model?: string;
48
+ is_document_compressed?: boolean;
49
+ document_compression_format?: 'gzip' | 'zstd' | 'deflate' | CompressionFormat;
50
+ webhook?: string;
51
+ timeout?: number;
52
+
53
+ // // deprecated options
54
+ template?: string;
55
+ ephemeral_template?: object;
56
+
57
+ constructor(options: ExtractionConfigOptions) {
58
+ this.validateOptions(options);
59
+ if (options.template) {
60
+ console.warn(
61
+ `Deprecation warning: 'template' is deprecated. Use 'extraction_template' instead.`
62
+ );
63
+ this.extraction_template = options.template;
64
+ } else {
65
+ this.extraction_template = options.extraction_template;
66
+ }
67
+ if (options.ephemeral_template) {
68
+ console.warn(
69
+ `Deprecation warning: 'ephemeral_template' is deprecated. Use 'extraction_ephemeral_template' instead.`
70
+ );
71
+ this.extraction_ephemeral_template = options.ephemeral_template;
72
+ } else {
73
+ this.extraction_ephemeral_template = options.extraction_ephemeral_template;
74
+ }
75
+
76
+ if (
77
+ options.document_compression_format &&
78
+ !Object.values(CompressionFormat).includes(options.document_compression_format as CompressionFormat)
79
+ ) {
80
+ throw new errors.ExtractionConfigError(
81
+ `Invalid CompressionFormat param value: ${options.document_compression_format}`,
82
+ );
83
+ }
84
+ this.body = options.body;
85
+ this.content_type = options.content_type;
86
+ this.url = options.url ?? this.url;
87
+ this.charset = options.charset ?? this.charset;
88
+ this.extraction_template = options.extraction_template ?? this.extraction_template;
89
+ this.extraction_ephemeral_template = options.extraction_ephemeral_template ?? this.extraction_ephemeral_template;
90
+ this.extraction_prompt = options.extraction_prompt ?? this.extraction_prompt;
91
+ this.extraction_model = options.extraction_model ?? this.extraction_model;
92
+ this.is_document_compressed = options.is_document_compressed ?? this.is_document_compressed;
93
+ this.document_compression_format = options.document_compression_format ?? this.document_compression_format;
94
+ this.webhook = options.webhook ?? this.webhook;
95
+ this.timeout = options.timeout ?? this.timeout;
96
+ }
97
+
98
+ private validateOptions(options: Partial<ExtractionConfigOptions>) {
99
+ const validKeys = new Set(Object.keys(this) as Array<keyof ExtractionConfig>);
100
+ for (const key in options) {
101
+ if (!validKeys.has(key as keyof ExtractionConfig)) {
102
+ throw new errors.ExtractionConfigError(`Invalid option provided: ${key}`);
103
+ }
104
+ }
105
+ }
106
+
107
+ toApiParams(options: { key: string }): Record<string, any> {
108
+ const params: Record<string, any> = {
109
+ key: options.key,
110
+ };
111
+ // params.body = this.body;
112
+ params.content_type = this.content_type;
113
+
114
+ if (this.url) {
115
+ params.url = encodeURI(this.url);
116
+ }
117
+
118
+ if (this.charset) {
119
+ params.charset = this.charset;
120
+ }
121
+
122
+ if (this.extraction_template && this.extraction_ephemeral_template) {
123
+ throw new ExtractionConfigError(
124
+ 'You cannot pass both parameters extraction_template and extraction_ephemeral_template. You must choose',
125
+ );
126
+ }
127
+
128
+ if (this.extraction_template) {
129
+ params.extraction_template = this.extraction_template;
130
+ }
131
+
132
+ if (this.extraction_ephemeral_template) {
133
+ params.extraction_template = 'ephemeral:' + urlsafe_b64encode(JSON.stringify(this.extraction_ephemeral_template));
134
+ }
135
+
136
+ if (this.extraction_prompt) {
137
+ params.extraction_prompt = this.extraction_prompt;
138
+ }
139
+
140
+ if (this.extraction_model) {
141
+ params.extraction_model = this.extraction_model;
142
+ }
143
+
144
+ if (this.document_compression_format) {
145
+ if (this.is_document_compressed === undefined) {
146
+ throw new errors.ExtractionConfigError(
147
+ `When declaring compression format, your must declare the ` +
148
+ `is_document_compressed parameter to compress the document or skip it.`,
149
+ );
150
+ }
151
+ if (this.is_document_compressed === false) {
152
+ // if (this.document_compression_format === CompressionFormat.GZIP) {
153
+ // XXX: This breaks cloudflare workers for some reason
154
+ // const compressed = gzip(new TextEncoder().encode(this.body as string));
155
+ // this.body = new Uint8Array(compressed);
156
+ // throw new Error("automatic gzip is not supported yet, pass gzipped ");
157
+ // } else {
158
+ throw new errors.ExtractionConfigError(
159
+ `Auto compression for ${this.document_compression_format} format isn't available. ` +
160
+ `You can manually compress to ${this.document_compression_format}.`,
161
+ );
162
+ // }
163
+ }
164
+ }
165
+
166
+ if (this.webhook) {
167
+ params.webhook_name = this.webhook;
168
+ }
169
+ if (this.timeout) {
170
+ params.timeout = this.timeout;
171
+ }
172
+
173
+ return params;
174
+ }
175
+ }
package/src/logger.ts ADDED
@@ -0,0 +1,51 @@
1
+ enum LogLevel {
2
+ DEBUG = 'DEBUG',
3
+ INFO = 'INFO',
4
+ WARN = 'WARN',
5
+ ERROR = 'ERROR',
6
+ }
7
+
8
+ class Logger {
9
+ private level: LogLevel;
10
+ public name: string;
11
+
12
+ constructor(name: string, level: LogLevel = LogLevel.INFO) {
13
+ this.name = name;
14
+ this.level = level;
15
+ }
16
+
17
+ debug(...args: any[]): void {
18
+ if (this.level <= LogLevel.DEBUG) {
19
+ console.log(...args);
20
+ }
21
+ }
22
+
23
+ info(...args: any[]): void {
24
+ if (this.level <= LogLevel.INFO) {
25
+ console.info(...args);
26
+ }
27
+ }
28
+
29
+ warn(...args: any[]): void {
30
+ if (this.level <= LogLevel.WARN) {
31
+ console.warn(...args);
32
+ }
33
+ }
34
+
35
+ error(...args: any[]): void {
36
+ if (this.level <= LogLevel.ERROR) {
37
+ console.error(...args);
38
+ }
39
+ }
40
+
41
+ setLevel(level: string): void {
42
+ if (Object.values(LogLevel).includes(level as LogLevel)) {
43
+ this.level = level as LogLevel;
44
+ } else {
45
+ console.error(`Invalid log level: ${level}`);
46
+ }
47
+ }
48
+ }
49
+
50
+ export default Logger;
51
+ export const log: Logger = new Logger('scrapfly');
package/src/main.ts ADDED
@@ -0,0 +1,61 @@
1
+ export { ScrapflyClient } from './client.js';
2
+ export {
3
+ Format as ScrapeFormat,
4
+ FormatOption as ScrapeFormatOptions,
5
+ ScrapeConfig,
6
+ ScreenshotFlags,
7
+ } from './scrapeconfig.js';
8
+ export {
9
+ Format as ScreenshotFormat,
10
+ Options as ScreenshotOptions,
11
+ ScreenshotConfig,
12
+ VisionDeficiency,
13
+ } from './screenshotconfig.js';
14
+ export { ExtractionConfig } from './extractionconfig.js';
15
+ export { BrowserConfig, ProxyPool, OperatingSystem } from './browserconfig.js';
16
+ export type { BrowserConfigOptions } from './browserconfig.js';
17
+ export * as errors from './errors.js';
18
+
19
+ export { ExtractionResult, ScrapeResult, ScreenshotResult } from './result.js';
20
+
21
+ export type { AccountData, ClassifyOptions, ClassifyResult, ConfigData, ContextData, ResultData, ScreenshotMetadata } from './result.js';
22
+
23
+ // Crawler API
24
+ export { CrawlerConfig } from './crawlerconfig.js';
25
+ export type { CrawlerConfigOptions, CrawlerContentFormat, CrawlerWebhookEventName } from './crawlerconfig.js';
26
+ export { Crawl } from './crawl.js';
27
+ export {
28
+ CrawlerArtifact,
29
+ CrawlerContents,
30
+ CrawlerStatus,
31
+ CrawlerUrls,
32
+ parseCrawlerWebhook,
33
+ } from './crawlerresult.js';
34
+ export type {
35
+ CrawlerArtifactType,
36
+ CrawlerLifecycleWebhook,
37
+ CrawlerState,
38
+ CrawlerStatusValue,
39
+ CrawlerStopReason,
40
+ CrawlerUrlDiscoveredWebhook,
41
+ CrawlerUrlEntry,
42
+ CrawlerUrlFailedWebhook,
43
+ CrawlerUrlSkippedWebhook,
44
+ CrawlerUrlVisitedWebhook,
45
+ CrawlerWebhookCommon,
46
+ CrawlerWebhookPayload,
47
+ } from './crawlerresult.js';
48
+
49
+ // Monitoring API
50
+ export type {
51
+ CloudBrowserMonitoringOptions,
52
+ MonitoringAggregation,
53
+ MonitoringDataFormat,
54
+ MonitoringMetricsOptions,
55
+ MonitoringPeriod,
56
+ MonitoringTargetMetricsOptions,
57
+ } from './monitoringconfig.js';
58
+
59
+ export { log } from './logger.js';
60
+
61
+ export { createServer, verifySignature } from './webhookserver.js';
@@ -0,0 +1,50 @@
1
+ export type MonitoringDataFormat = 'structured' | 'prometheus';
2
+
3
+ export type MonitoringPeriod = 'subscription' | 'last7d' | 'last24h' | 'last1h' | 'last5m';
4
+
5
+ export type MonitoringAggregation = 'account' | 'project' | 'target';
6
+
7
+ export interface MonitoringMetricsOptions {
8
+ format?: MonitoringDataFormat;
9
+ period?: MonitoringPeriod;
10
+ aggregation?: MonitoringAggregation[];
11
+ /** Fold WEBHOOK origin events (callbacks executed by the webhook
12
+ * worker) into this product's totals. Defaults to false to match
13
+ * the dashboard's default view. */
14
+ includeWebhook?: boolean;
15
+ }
16
+
17
+ export interface MonitoringTargetMetricsOptions {
18
+ domain: string;
19
+ groupSubdomain?: boolean;
20
+ period?: MonitoringPeriod;
21
+ start?: Date;
22
+ end?: Date;
23
+ /** Fold WEBHOOK origin events into this product's totals. */
24
+ includeWebhook?: boolean;
25
+ }
26
+
27
+ /** Options for the Cloud Browser monitoring endpoints. Cloud Browser
28
+ * is session-based (one allocation = one long-lived browser, billed
29
+ * by runtime + bandwidth) and exposes a distinct shape from the
30
+ * request-based products. There is no `domain`/`target` and no
31
+ * `includeWebhook`. */
32
+ export interface CloudBrowserMonitoringOptions {
33
+ period?: MonitoringPeriod;
34
+ /** Optional filter to a single proxy pool
35
+ * (e.g. `public_datacenter_pool`, `public_residential_pool`, `byop`). */
36
+ proxyPool?: string;
37
+ start?: Date;
38
+ end?: Date;
39
+ }
40
+
41
+ export function formatMonitoringDate(d: Date): string {
42
+ const pad = (n: number): string => n.toString().padStart(2, '0');
43
+ const y = d.getUTCFullYear();
44
+ const mo = pad(d.getUTCMonth() + 1);
45
+ const da = pad(d.getUTCDate());
46
+ const h = pad(d.getUTCHours());
47
+ const mi = pad(d.getUTCMinutes());
48
+ const s = pad(d.getUTCSeconds());
49
+ return `${y}-${mo}-${da} ${h}:${mi}:${s}`;
50
+ }