scrapfly-sdk 0.10.3 → 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.
- package/package.json +1 -1
- package/src/_dnt.shims.ts +64 -0
- package/src/batch.ts +272 -0
- package/src/browserconfig.ts +118 -0
- package/src/client.ts +1609 -0
- package/src/crawl.ts +251 -0
- package/src/crawlerconfig.ts +363 -0
- package/src/crawlerresult.ts +471 -0
- package/src/deps/jsr.io/@std/path/1.0.1/_common/assert_path.ts +10 -0
- package/src/deps/jsr.io/@std/path/1.0.1/_common/basename.ts +53 -0
- package/src/deps/jsr.io/@std/path/1.0.1/_common/common.ts +26 -0
- package/src/deps/jsr.io/@std/path/1.0.1/_common/constants.ts +49 -0
- package/src/deps/jsr.io/@std/path/1.0.1/_common/dirname.ts +9 -0
- package/src/deps/jsr.io/@std/path/1.0.1/_common/format.ts +25 -0
- package/src/deps/jsr.io/@std/path/1.0.1/_common/from_file_url.ts +10 -0
- package/src/deps/jsr.io/@std/path/1.0.1/_common/glob_to_reg_exp.ts +290 -0
- package/src/deps/jsr.io/@std/path/1.0.1/_common/normalize.ts +9 -0
- package/src/deps/jsr.io/@std/path/1.0.1/_common/normalize_string.ts +74 -0
- package/src/deps/jsr.io/@std/path/1.0.1/_common/relative.ts +10 -0
- package/src/deps/jsr.io/@std/path/1.0.1/_common/strip_trailing_separators.ts +25 -0
- package/src/deps/jsr.io/@std/path/1.0.1/_common/to_file_url.ts +17 -0
- package/src/deps/jsr.io/@std/path/1.0.1/_os.ts +31 -0
- package/src/deps/jsr.io/@std/path/1.0.1/basename.ts +35 -0
- package/src/deps/jsr.io/@std/path/1.0.1/common.ts +35 -0
- package/src/deps/jsr.io/@std/path/1.0.1/constants.ts +18 -0
- package/src/deps/jsr.io/@std/path/1.0.1/dirname.ts +28 -0
- package/src/deps/jsr.io/@std/path/1.0.1/extname.ts +27 -0
- package/src/deps/jsr.io/@std/path/1.0.1/format.ts +30 -0
- package/src/deps/jsr.io/@std/path/1.0.1/from_file_url.ts +30 -0
- package/src/deps/jsr.io/@std/path/1.0.1/glob_to_regexp.ts +94 -0
- package/src/deps/jsr.io/@std/path/1.0.1/is_absolute.ts +30 -0
- package/src/deps/jsr.io/@std/path/1.0.1/is_glob.ts +49 -0
- package/src/deps/jsr.io/@std/path/1.0.1/join.ts +28 -0
- package/src/deps/jsr.io/@std/path/1.0.1/join_globs.ts +42 -0
- package/src/deps/jsr.io/@std/path/1.0.1/mod.ts +55 -0
- package/src/deps/jsr.io/@std/path/1.0.1/normalize.ts +31 -0
- package/src/deps/jsr.io/@std/path/1.0.1/normalize_glob.ts +45 -0
- package/src/deps/jsr.io/@std/path/1.0.1/parse.ts +44 -0
- package/src/deps/jsr.io/@std/path/1.0.1/posix/_util.ts +10 -0
- package/src/deps/jsr.io/@std/path/1.0.1/posix/basename.ts +39 -0
- package/src/deps/jsr.io/@std/path/1.0.1/posix/constants.ts +15 -0
- package/src/deps/jsr.io/@std/path/1.0.1/posix/dirname.ts +55 -0
- package/src/deps/jsr.io/@std/path/1.0.1/posix/extname.ts +73 -0
- package/src/deps/jsr.io/@std/path/1.0.1/posix/format.ts +31 -0
- package/src/deps/jsr.io/@std/path/1.0.1/posix/from_file_url.ts +25 -0
- package/src/deps/jsr.io/@std/path/1.0.1/posix/glob_to_regexp.ts +94 -0
- package/src/deps/jsr.io/@std/path/1.0.1/posix/is_absolute.ts +25 -0
- package/src/deps/jsr.io/@std/path/1.0.1/posix/join.ts +27 -0
- package/src/deps/jsr.io/@std/path/1.0.1/posix/join_globs.ts +44 -0
- package/src/deps/jsr.io/@std/path/1.0.1/posix/normalize.ts +41 -0
- package/src/deps/jsr.io/@std/path/1.0.1/posix/normalize_glob.ts +42 -0
- package/src/deps/jsr.io/@std/path/1.0.1/posix/parse.ts +121 -0
- package/src/deps/jsr.io/@std/path/1.0.1/posix/relative.ts +103 -0
- package/src/deps/jsr.io/@std/path/1.0.1/posix/resolve.ts +69 -0
- package/src/deps/jsr.io/@std/path/1.0.1/posix/to_file_url.ts +32 -0
- package/src/deps/jsr.io/@std/path/1.0.1/posix/to_namespaced_path.ts +21 -0
- package/src/deps/jsr.io/@std/path/1.0.1/relative.ts +32 -0
- package/src/deps/jsr.io/@std/path/1.0.1/resolve.ts +32 -0
- package/src/deps/jsr.io/@std/path/1.0.1/to_file_url.ts +30 -0
- package/src/deps/jsr.io/@std/path/1.0.1/to_namespaced_path.ts +31 -0
- package/src/deps/jsr.io/@std/path/1.0.1/types.ts +40 -0
- package/src/deps/jsr.io/@std/path/1.0.1/windows/_util.ts +28 -0
- package/src/deps/jsr.io/@std/path/1.0.1/windows/basename.ts +48 -0
- package/src/deps/jsr.io/@std/path/1.0.1/windows/constants.ts +15 -0
- package/src/deps/jsr.io/@std/path/1.0.1/windows/dirname.ts +114 -0
- package/src/deps/jsr.io/@std/path/1.0.1/windows/extname.ts +86 -0
- package/src/deps/jsr.io/@std/path/1.0.1/windows/format.ts +31 -0
- package/src/deps/jsr.io/@std/path/1.0.1/windows/from_file_url.ts +34 -0
- package/src/deps/jsr.io/@std/path/1.0.1/windows/glob_to_regexp.ts +92 -0
- package/src/deps/jsr.io/@std/path/1.0.1/windows/is_absolute.ts +40 -0
- package/src/deps/jsr.io/@std/path/1.0.1/windows/join.ts +72 -0
- package/src/deps/jsr.io/@std/path/1.0.1/windows/join_globs.ts +45 -0
- package/src/deps/jsr.io/@std/path/1.0.1/windows/normalize.ts +132 -0
- package/src/deps/jsr.io/@std/path/1.0.1/windows/normalize_glob.ts +42 -0
- package/src/deps/jsr.io/@std/path/1.0.1/windows/parse.ts +184 -0
- package/src/deps/jsr.io/@std/path/1.0.1/windows/relative.ts +128 -0
- package/src/deps/jsr.io/@std/path/1.0.1/windows/resolve.ts +174 -0
- package/src/deps/jsr.io/@std/path/1.0.1/windows/to_file_url.ts +38 -0
- package/src/deps/jsr.io/@std/path/1.0.1/windows/to_namespaced_path.ts +60 -0
- package/src/deps.ts +4 -0
- package/src/errors.ts +55 -0
- package/src/extractionconfig.ts +175 -0
- package/src/logger.ts +51 -0
- package/src/main.ts +61 -0
- package/src/monitoringconfig.ts +50 -0
- package/src/polyfill.ts +37 -0
- package/src/result.ts +338 -0
- package/src/scrapeconfig.ts +448 -0
- package/src/screenshotconfig.ts +204 -0
- package/src/types.ts +2 -0
- package/src/utils.ts +86 -0
- package/src/webhookserver.ts +66 -0
|
@@ -0,0 +1,471 @@
|
|
|
1
|
+
import { writeFile } from './polyfill.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Pull a required field out of an API response body and fail loud if it's
|
|
5
|
+
* missing or the wrong type. Using this consistently across the response
|
|
6
|
+
* classes means a server-side contract change surfaces as a clear error at
|
|
7
|
+
* parse time instead of a silent fallback to 0/null/empty later.
|
|
8
|
+
*/
|
|
9
|
+
function requireField<T>(
|
|
10
|
+
data: Record<string, any>,
|
|
11
|
+
key: string,
|
|
12
|
+
typeName: 'string' | 'number' | 'boolean' | 'object' | 'array',
|
|
13
|
+
contextClass: string,
|
|
14
|
+
): T {
|
|
15
|
+
if (!(key in data)) {
|
|
16
|
+
throw new Error(`${contextClass}: required field '${key}' is missing from API response`);
|
|
17
|
+
}
|
|
18
|
+
const value = data[key];
|
|
19
|
+
if (value === null || value === undefined) {
|
|
20
|
+
throw new Error(`${contextClass}: required field '${key}' is null/undefined`);
|
|
21
|
+
}
|
|
22
|
+
const actual = Array.isArray(value) ? 'array' : typeof value;
|
|
23
|
+
if (typeName === 'array' ? actual !== 'array' : actual !== typeName) {
|
|
24
|
+
throw new Error(
|
|
25
|
+
`${contextClass}: field '${key}' must be ${typeName}, got ${actual} (${JSON.stringify(value).slice(0, 100)})`,
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
return value as T;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Like `requireField` but for optional fields that the server may legitimately
|
|
33
|
+
* omit or send as `null`. Returns `null` when absent; validates type otherwise.
|
|
34
|
+
*/
|
|
35
|
+
function optionalField<T>(
|
|
36
|
+
data: Record<string, any>,
|
|
37
|
+
key: string,
|
|
38
|
+
typeName: 'string' | 'number' | 'boolean' | 'object' | 'array',
|
|
39
|
+
contextClass: string,
|
|
40
|
+
): T | null {
|
|
41
|
+
if (!(key in data)) return null;
|
|
42
|
+
const value = data[key];
|
|
43
|
+
if (value === null || value === undefined) return null;
|
|
44
|
+
const actual = Array.isArray(value) ? 'array' : typeof value;
|
|
45
|
+
if (typeName === 'array' ? actual !== 'array' : actual !== typeName) {
|
|
46
|
+
throw new Error(
|
|
47
|
+
`${contextClass}: field '${key}' must be ${typeName} or null, got ${actual}`,
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
return value as T;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Crawler job status values returned by the API.
|
|
55
|
+
*
|
|
56
|
+
* Note: there is **no** `COMPLETED` or `FAILED` value. A finished crawl always
|
|
57
|
+
* has `status === 'DONE'`; success vs. failure is signaled by `is_success`.
|
|
58
|
+
* `CANCELLED` is a separate terminal state set when the user cancels the job.
|
|
59
|
+
*/
|
|
60
|
+
export type CrawlerStatusValue = 'PENDING' | 'RUNNING' | 'DONE' | 'CANCELLED';
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Reasons documented for why a crawler stopped.
|
|
64
|
+
*/
|
|
65
|
+
export type CrawlerStopReason =
|
|
66
|
+
| 'no_more_urls'
|
|
67
|
+
| 'page_limit'
|
|
68
|
+
| 'max_duration'
|
|
69
|
+
| 'max_api_credit'
|
|
70
|
+
| 'seed_url_failed'
|
|
71
|
+
| 'user_cancelled'
|
|
72
|
+
| 'crawler_error'
|
|
73
|
+
| 'no_api_credit_left'
|
|
74
|
+
| 'storage_error';
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Per-job state metrics returned in the status response and webhook payloads.
|
|
78
|
+
*
|
|
79
|
+
* Note on nullable fields: while the crawler is in `PENDING` (before any
|
|
80
|
+
* worker has picked up the job), `start_time`, `stop_time`, and `stop_reason`
|
|
81
|
+
* are all `null`. They become populated once the crawl starts progressing.
|
|
82
|
+
* `duration` is always a number (0 when nothing has happened yet).
|
|
83
|
+
*/
|
|
84
|
+
export interface CrawlerState {
|
|
85
|
+
urls_visited: number;
|
|
86
|
+
urls_extracted: number;
|
|
87
|
+
urls_failed: number;
|
|
88
|
+
urls_skipped: number;
|
|
89
|
+
urls_to_crawl: number;
|
|
90
|
+
api_credit_used: number;
|
|
91
|
+
duration: number;
|
|
92
|
+
/** `null` until the crawler stops. */
|
|
93
|
+
stop_reason: CrawlerStopReason | null;
|
|
94
|
+
/** `null` until the crawler actually starts processing (still PENDING). */
|
|
95
|
+
start_time: number | null;
|
|
96
|
+
/** `null` until the crawler stops. */
|
|
97
|
+
stop_time: number | null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Wraps the JSON response of `GET /crawl/{uuid}/status`.
|
|
102
|
+
*
|
|
103
|
+
* Strict parsing: every field documented in the public API contract is
|
|
104
|
+
* required. A missing or wrong-typed field throws a clear error at parse
|
|
105
|
+
* time so API contract drift surfaces loud and early instead of silently
|
|
106
|
+
* producing zero-valued metrics.
|
|
107
|
+
*/
|
|
108
|
+
export class CrawlerStatus {
|
|
109
|
+
crawler_uuid: string;
|
|
110
|
+
status: CrawlerStatusValue;
|
|
111
|
+
is_finished: boolean;
|
|
112
|
+
/** `null` while the crawler is still running; bool once terminal. */
|
|
113
|
+
is_success: boolean | null;
|
|
114
|
+
state: CrawlerState;
|
|
115
|
+
|
|
116
|
+
constructor(data: Record<string, any>) {
|
|
117
|
+
// Canonical API field name is `crawler_uuid`; accept short `uuid` as a
|
|
118
|
+
// legacy fallback but throw if neither is present.
|
|
119
|
+
if ('crawler_uuid' in data && typeof data.crawler_uuid === 'string' && data.crawler_uuid) {
|
|
120
|
+
this.crawler_uuid = data.crawler_uuid;
|
|
121
|
+
} else if ('uuid' in data && typeof data.uuid === 'string' && data.uuid) {
|
|
122
|
+
this.crawler_uuid = data.uuid;
|
|
123
|
+
} else {
|
|
124
|
+
throw new Error(
|
|
125
|
+
"CrawlerStatus: required field 'crawler_uuid' (or legacy 'uuid') is missing from API response",
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
this.status = requireField<CrawlerStatusValue>(data, 'status', 'string', 'CrawlerStatus');
|
|
129
|
+
this.is_finished = requireField<boolean>(data, 'is_finished', 'boolean', 'CrawlerStatus');
|
|
130
|
+
// `is_success` is documented as nullable while the crawler is running.
|
|
131
|
+
const isSuccessRaw = 'is_success' in data ? data.is_success : null;
|
|
132
|
+
if (isSuccessRaw !== null && typeof isSuccessRaw !== 'boolean') {
|
|
133
|
+
throw new Error(
|
|
134
|
+
`CrawlerStatus: field 'is_success' must be bool or null, got ${typeof isSuccessRaw}`,
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
this.is_success = isSuccessRaw;
|
|
138
|
+
|
|
139
|
+
const state = requireField<Record<string, any>>(data, 'state', 'object', 'CrawlerStatus');
|
|
140
|
+
this.state = {
|
|
141
|
+
// URL counters and `duration` are always present and numeric (0 during PENDING).
|
|
142
|
+
urls_visited: requireField<number>(state, 'urls_visited', 'number', 'CrawlerStatus.state'),
|
|
143
|
+
urls_extracted: requireField<number>(state, 'urls_extracted', 'number', 'CrawlerStatus.state'),
|
|
144
|
+
urls_failed: requireField<number>(state, 'urls_failed', 'number', 'CrawlerStatus.state'),
|
|
145
|
+
urls_skipped: requireField<number>(state, 'urls_skipped', 'number', 'CrawlerStatus.state'),
|
|
146
|
+
urls_to_crawl: requireField<number>(state, 'urls_to_crawl', 'number', 'CrawlerStatus.state'),
|
|
147
|
+
api_credit_used: requireField<number>(state, 'api_credit_used', 'number', 'CrawlerStatus.state'),
|
|
148
|
+
duration: requireField<number>(state, 'duration', 'number', 'CrawlerStatus.state'),
|
|
149
|
+
// `start_time` / `stop_time` / `stop_reason` are null until the crawler
|
|
150
|
+
// actually starts / stops — verified against the live server behavior.
|
|
151
|
+
start_time: optionalField<number>(state, 'start_time', 'number', 'CrawlerStatus.state'),
|
|
152
|
+
stop_time: optionalField<number>(state, 'stop_time', 'number', 'CrawlerStatus.state'),
|
|
153
|
+
stop_reason: optionalField<CrawlerStopReason>(state, 'stop_reason', 'string', 'CrawlerStatus.state'),
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** True while the crawler is still working (PENDING or RUNNING). */
|
|
158
|
+
get isRunning(): boolean {
|
|
159
|
+
return this.status === 'PENDING' || this.status === 'RUNNING';
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** True if the crawler reached a terminal state successfully. */
|
|
163
|
+
get isComplete(): boolean {
|
|
164
|
+
return this.status === 'DONE' && this.is_success === true;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** True if the crawler reached a terminal state but failed. */
|
|
168
|
+
get isFailed(): boolean {
|
|
169
|
+
return this.status === 'DONE' && this.is_success === false;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** True if the crawler was cancelled by the user. */
|
|
173
|
+
get isCancelled(): boolean {
|
|
174
|
+
return this.status === 'CANCELLED';
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Rough progress estimate based on visited vs. extracted URLs (0–100).
|
|
179
|
+
* Returns 0 when nothing has been extracted yet.
|
|
180
|
+
*/
|
|
181
|
+
get progressPct(): number {
|
|
182
|
+
return this.state.urls_extracted > 0 ? (this.state.urls_visited / this.state.urls_extracted) * 100 : 0;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Single URL entry from `GET /crawl/{uuid}/urls`.
|
|
188
|
+
*
|
|
189
|
+
* The endpoint streams one record per line as `text/plain`. For `visited`
|
|
190
|
+
* URLs each line is just the URL; for `failed` or `skipped` URLs the line is
|
|
191
|
+
* `url,reason` (reason is the first token after the first comma — URLs never
|
|
192
|
+
* contain a comma once percent-encoded, so this is unambiguous).
|
|
193
|
+
*
|
|
194
|
+
* Streaming text is used because the endpoint is expected to scale to
|
|
195
|
+
* millions of URLs per job; JSON is not a suitable wire format at that
|
|
196
|
+
* volume.
|
|
197
|
+
*/
|
|
198
|
+
export interface CrawlerUrlEntry {
|
|
199
|
+
url: string;
|
|
200
|
+
/** Only populated when the caller passed an explicit `status` filter. */
|
|
201
|
+
status?: 'visited' | 'pending' | 'failed' | 'skipped';
|
|
202
|
+
/** Only present for `failed` or `skipped` URLs. */
|
|
203
|
+
reason?: string;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Wraps the streaming text response of `GET /crawl/{uuid}/urls`.
|
|
208
|
+
*
|
|
209
|
+
* The server returns one record per line with `Content-Type: text/plain`;
|
|
210
|
+
* this class parses that stream into a materialised list for caller
|
|
211
|
+
* convenience. For very large jobs, prefer {@link ScrapflyClient.crawlUrlsStream}
|
|
212
|
+
* (if provided) or call the endpoint via `client.fetch` directly and iterate
|
|
213
|
+
* the body as a stream.
|
|
214
|
+
*
|
|
215
|
+
* Pagination metadata fields (`page`, `per_page`) are echoes of the caller's
|
|
216
|
+
* request parameters — the wire protocol carries no global `total`, only the
|
|
217
|
+
* records in the current page. Use `urls.length` for the page size and
|
|
218
|
+
* request further pages by incrementing `page` until an empty response.
|
|
219
|
+
*/
|
|
220
|
+
export class CrawlerUrls {
|
|
221
|
+
urls: CrawlerUrlEntry[];
|
|
222
|
+
page: number;
|
|
223
|
+
per_page: number;
|
|
224
|
+
|
|
225
|
+
constructor(
|
|
226
|
+
urls: CrawlerUrlEntry[],
|
|
227
|
+
page: number,
|
|
228
|
+
perPage: number,
|
|
229
|
+
) {
|
|
230
|
+
this.urls = urls;
|
|
231
|
+
this.page = page;
|
|
232
|
+
this.per_page = perPage;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Parse the raw text body returned by `GET /crawl/{uuid}/urls`.
|
|
237
|
+
*
|
|
238
|
+
* - Empty lines are ignored (trailing newlines, blank records).
|
|
239
|
+
* - `visited` status → one URL per line, record has `{url, status: 'visited'}`.
|
|
240
|
+
* - `failed`/`skipped` status → `url,reason`, record includes `reason`.
|
|
241
|
+
* - When the caller didn't pass a `status` filter, the server defaults to
|
|
242
|
+
* `visited`; we pass that as the `statusHint` so every parsed record gets
|
|
243
|
+
* the right status tag.
|
|
244
|
+
*
|
|
245
|
+
* @param body Raw text body of the response.
|
|
246
|
+
* @param statusHint The status filter passed on the request (for tagging).
|
|
247
|
+
* @param page Caller-provided page (echoed on the response object).
|
|
248
|
+
* @param perPage Caller-provided per_page (echoed on the response object).
|
|
249
|
+
*/
|
|
250
|
+
static fromText(
|
|
251
|
+
body: string,
|
|
252
|
+
statusHint: 'visited' | 'pending' | 'failed' | 'skipped',
|
|
253
|
+
page: number,
|
|
254
|
+
perPage: number,
|
|
255
|
+
): CrawlerUrls {
|
|
256
|
+
const urls: CrawlerUrlEntry[] = [];
|
|
257
|
+
for (const rawLine of body.split(/\r?\n/)) {
|
|
258
|
+
const line = rawLine.trim();
|
|
259
|
+
if (!line) continue;
|
|
260
|
+
if (statusHint === 'visited' || statusHint === 'pending') {
|
|
261
|
+
// Plain URL per line.
|
|
262
|
+
urls.push({ url: line, status: statusHint });
|
|
263
|
+
} else {
|
|
264
|
+
// `url,reason` — split on the first comma.
|
|
265
|
+
const commaIdx = line.indexOf(',');
|
|
266
|
+
if (commaIdx === -1) {
|
|
267
|
+
urls.push({ url: line, status: statusHint });
|
|
268
|
+
} else {
|
|
269
|
+
urls.push({
|
|
270
|
+
url: line.slice(0, commaIdx),
|
|
271
|
+
status: statusHint,
|
|
272
|
+
reason: line.slice(commaIdx + 1),
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return new CrawlerUrls(urls, page, perPage);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Wraps the JSON-mode response of `GET /crawl/{uuid}/contents` (i.e. `plain=false`).
|
|
283
|
+
*
|
|
284
|
+
* The `contents` field maps each URL to a map of format → content. When
|
|
285
|
+
* `plain=true` is used instead, {@link ScrapflyClient.crawlContents} returns
|
|
286
|
+
* a raw `string` directly rather than this class.
|
|
287
|
+
*
|
|
288
|
+
* Strict parsing: `contents` and `links` are both required per the documented
|
|
289
|
+
* contract. A response missing either field indicates an API contract change
|
|
290
|
+
* and throws at parse time rather than producing an empty envelope that looks
|
|
291
|
+
* valid.
|
|
292
|
+
*/
|
|
293
|
+
export class CrawlerContents {
|
|
294
|
+
contents: Record<string, Record<string, string>>;
|
|
295
|
+
links: { crawled_urls?: string; next?: string | null; prev?: string | null };
|
|
296
|
+
|
|
297
|
+
constructor(data: Record<string, any>) {
|
|
298
|
+
this.contents = requireField<Record<string, Record<string, string>>>(
|
|
299
|
+
data,
|
|
300
|
+
'contents',
|
|
301
|
+
'object',
|
|
302
|
+
'CrawlerContents',
|
|
303
|
+
);
|
|
304
|
+
this.links = requireField<typeof this.links>(data, 'links', 'object', 'CrawlerContents');
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Artifact type accepted by `GET /crawl/{uuid}/artifact?type=...`.
|
|
310
|
+
*/
|
|
311
|
+
export type CrawlerArtifactType = 'warc' | 'har';
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Holds the raw bytes of a downloaded WARC or HAR artifact.
|
|
315
|
+
*
|
|
316
|
+
* **Note on parsing:** the SDK does NOT bundle WARC or HAR parsers. Use a dedicated
|
|
317
|
+
* library (e.g. `warcio` on npm for WARC) if you need to walk the records. The
|
|
318
|
+
* `save()` method is provided for the common case of writing the artifact to disk.
|
|
319
|
+
*/
|
|
320
|
+
export class CrawlerArtifact {
|
|
321
|
+
type: CrawlerArtifactType;
|
|
322
|
+
data: Uint8Array;
|
|
323
|
+
|
|
324
|
+
constructor(type: CrawlerArtifactType, data: Uint8Array) {
|
|
325
|
+
this.type = type;
|
|
326
|
+
this.data = data;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** Write the artifact to a file on disk. */
|
|
330
|
+
async save(filepath: string): Promise<void> {
|
|
331
|
+
await writeFile(filepath, this.data);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// ---------------------------------------------------------------------------
|
|
336
|
+
// Webhook payloads
|
|
337
|
+
// ---------------------------------------------------------------------------
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Fields common to every crawler webhook payload.
|
|
341
|
+
*/
|
|
342
|
+
export interface CrawlerWebhookCommon {
|
|
343
|
+
crawler_uuid: string;
|
|
344
|
+
project: string;
|
|
345
|
+
env: string;
|
|
346
|
+
action: string;
|
|
347
|
+
state: CrawlerState;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Webhook for the four "lifecycle" events that share an identical payload shape:
|
|
352
|
+
* `crawler_started`, `crawler_stopped`, `crawler_cancelled`, `crawler_finished`.
|
|
353
|
+
*
|
|
354
|
+
* Verified against `apps/scrapfly/web-app/src/Template/Docs/crawler-api/webhooks_example/`.
|
|
355
|
+
*/
|
|
356
|
+
export interface CrawlerLifecycleWebhook {
|
|
357
|
+
event: 'crawler_started' | 'crawler_stopped' | 'crawler_cancelled' | 'crawler_finished';
|
|
358
|
+
payload: CrawlerWebhookCommon & {
|
|
359
|
+
seed_url: string;
|
|
360
|
+
links: { status: string };
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** Payload for `crawler_url_visited` events. */
|
|
365
|
+
export interface CrawlerUrlVisitedWebhook {
|
|
366
|
+
event: 'crawler_url_visited';
|
|
367
|
+
payload: CrawlerWebhookCommon & {
|
|
368
|
+
url: string;
|
|
369
|
+
scrape: {
|
|
370
|
+
status_code: number;
|
|
371
|
+
country?: string;
|
|
372
|
+
log_uuid?: string;
|
|
373
|
+
log_url?: string;
|
|
374
|
+
content: Record<string, string>;
|
|
375
|
+
};
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** Payload for `crawler_url_skipped` events. */
|
|
380
|
+
export interface CrawlerUrlSkippedWebhook {
|
|
381
|
+
event: 'crawler_url_skipped';
|
|
382
|
+
payload: CrawlerWebhookCommon & {
|
|
383
|
+
/** Map of skipped URL → reason (e.g. `"page_limit"`). */
|
|
384
|
+
urls: Record<string, string>;
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** Payload for `crawler_url_discovered` events. */
|
|
389
|
+
export interface CrawlerUrlDiscoveredWebhook {
|
|
390
|
+
event: 'crawler_url_discovered';
|
|
391
|
+
payload: CrawlerWebhookCommon & {
|
|
392
|
+
origin: string;
|
|
393
|
+
discovered_urls: string[];
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** Payload for `crawler_url_failed` events. */
|
|
398
|
+
export interface CrawlerUrlFailedWebhook {
|
|
399
|
+
event: 'crawler_url_failed';
|
|
400
|
+
payload: CrawlerWebhookCommon & {
|
|
401
|
+
url: string;
|
|
402
|
+
error: string;
|
|
403
|
+
scrape_config: Record<string, any>;
|
|
404
|
+
links: { log: string | null };
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Discriminated union of every crawler webhook payload type.
|
|
410
|
+
*
|
|
411
|
+
* Use {@link parseCrawlerWebhook} to safely turn an `unknown` body into one of these.
|
|
412
|
+
*/
|
|
413
|
+
export type CrawlerWebhookPayload =
|
|
414
|
+
| CrawlerLifecycleWebhook
|
|
415
|
+
| CrawlerUrlVisitedWebhook
|
|
416
|
+
| CrawlerUrlSkippedWebhook
|
|
417
|
+
| CrawlerUrlDiscoveredWebhook
|
|
418
|
+
| CrawlerUrlFailedWebhook;
|
|
419
|
+
|
|
420
|
+
const LIFECYCLE_EVENTS = new Set([
|
|
421
|
+
'crawler_started',
|
|
422
|
+
'crawler_stopped',
|
|
423
|
+
'crawler_cancelled',
|
|
424
|
+
'crawler_finished',
|
|
425
|
+
]);
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Parse a raw webhook body (JSON-decoded object) into a typed crawler webhook payload.
|
|
429
|
+
*
|
|
430
|
+
* Throws `Error` if the body is not an object, has no `event` field, or carries an
|
|
431
|
+
* unknown event name. Use this in your webhook handler after `JSON.parse()`.
|
|
432
|
+
*
|
|
433
|
+
* @example
|
|
434
|
+
* ```ts
|
|
435
|
+
* import { parseCrawlerWebhook } from '@scrapfly/scrapfly-sdk';
|
|
436
|
+
*
|
|
437
|
+
* app.post('/webhook', async (req, res) => {
|
|
438
|
+
* const body = await req.json();
|
|
439
|
+
* const webhook = parseCrawlerWebhook(body);
|
|
440
|
+
* if (webhook.event === 'crawler_finished') {
|
|
441
|
+
* console.log('done', webhook.payload.state.urls_visited);
|
|
442
|
+
* }
|
|
443
|
+
* });
|
|
444
|
+
* ```
|
|
445
|
+
*/
|
|
446
|
+
export function parseCrawlerWebhook(body: unknown): CrawlerWebhookPayload {
|
|
447
|
+
if (typeof body !== 'object' || body === null) {
|
|
448
|
+
throw new Error('Crawler webhook body must be a JSON object');
|
|
449
|
+
}
|
|
450
|
+
const obj = body as Record<string, any>;
|
|
451
|
+
const event = obj.event;
|
|
452
|
+
if (typeof event !== 'string') {
|
|
453
|
+
throw new Error('Crawler webhook body is missing required `event` string field');
|
|
454
|
+
}
|
|
455
|
+
if (typeof obj.payload !== 'object' || obj.payload === null) {
|
|
456
|
+
throw new Error('Crawler webhook body is missing required `payload` object field');
|
|
457
|
+
}
|
|
458
|
+
if (
|
|
459
|
+
LIFECYCLE_EVENTS.has(event) ||
|
|
460
|
+
event === 'crawler_url_visited' ||
|
|
461
|
+
event === 'crawler_url_skipped' ||
|
|
462
|
+
event === 'crawler_url_discovered' ||
|
|
463
|
+
event === 'crawler_url_failed'
|
|
464
|
+
) {
|
|
465
|
+
// The body has already been validated to have an `event` and `payload`. The
|
|
466
|
+
// narrower per-event field shapes are runtime-checked by the discriminated union
|
|
467
|
+
// — TypeScript users get the typed view; runtime users get a permissive bag.
|
|
468
|
+
return obj as unknown as CrawlerWebhookPayload;
|
|
469
|
+
}
|
|
470
|
+
throw new Error(`Unknown crawler webhook event: ${event}`);
|
|
471
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
|
2
|
+
// Copyright the Browserify authors. MIT License.
|
|
3
|
+
|
|
4
|
+
export function assertPath(path?: string) {
|
|
5
|
+
if (typeof path !== "string") {
|
|
6
|
+
throw new TypeError(
|
|
7
|
+
`Path must be a string. Received ${JSON.stringify(path)}`,
|
|
8
|
+
);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
|
2
|
+
// This module is browser compatible.
|
|
3
|
+
|
|
4
|
+
import { assertPath } from "./assert_path.js";
|
|
5
|
+
|
|
6
|
+
export function stripSuffix(name: string, suffix: string): string {
|
|
7
|
+
if (suffix.length >= name.length) {
|
|
8
|
+
return name;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const lenDiff = name.length - suffix.length;
|
|
12
|
+
|
|
13
|
+
for (let i = suffix.length - 1; i >= 0; --i) {
|
|
14
|
+
if (name.charCodeAt(lenDiff + i) !== suffix.charCodeAt(i)) {
|
|
15
|
+
return name;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
return name.slice(0, -suffix.length);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function lastPathSegment(
|
|
23
|
+
path: string,
|
|
24
|
+
isSep: (char: number) => boolean,
|
|
25
|
+
start = 0,
|
|
26
|
+
): string {
|
|
27
|
+
let matchedNonSeparator = false;
|
|
28
|
+
let end = path.length;
|
|
29
|
+
|
|
30
|
+
for (let i = path.length - 1; i >= start; --i) {
|
|
31
|
+
if (isSep(path.charCodeAt(i))) {
|
|
32
|
+
if (matchedNonSeparator) {
|
|
33
|
+
start = i + 1;
|
|
34
|
+
break;
|
|
35
|
+
}
|
|
36
|
+
} else if (!matchedNonSeparator) {
|
|
37
|
+
matchedNonSeparator = true;
|
|
38
|
+
end = i + 1;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return path.slice(start, end);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function assertArgs(path: string, suffix: string) {
|
|
46
|
+
assertPath(path);
|
|
47
|
+
if (path.length === 0) return path;
|
|
48
|
+
if (typeof suffix !== "string") {
|
|
49
|
+
throw new TypeError(
|
|
50
|
+
`Suffix must be a string. Received ${JSON.stringify(suffix)}`,
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
|
2
|
+
// This module is browser compatible.
|
|
3
|
+
|
|
4
|
+
export function common(paths: string[], sep: string): string {
|
|
5
|
+
const [first = "", ...remaining] = paths;
|
|
6
|
+
const parts = first.split(sep);
|
|
7
|
+
|
|
8
|
+
let endOfPrefix = parts.length;
|
|
9
|
+
let append = "";
|
|
10
|
+
for (const path of remaining) {
|
|
11
|
+
const compare = path.split(sep);
|
|
12
|
+
if (compare.length <= endOfPrefix) {
|
|
13
|
+
endOfPrefix = compare.length;
|
|
14
|
+
append = "";
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
for (let i = 0; i < endOfPrefix; i++) {
|
|
18
|
+
if (compare[i] !== parts[i]) {
|
|
19
|
+
endOfPrefix = i;
|
|
20
|
+
append = i === 0 ? "" : sep;
|
|
21
|
+
break;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return parts.slice(0, endOfPrefix).join(sep) + append;
|
|
26
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
|
2
|
+
// Copyright the Browserify authors. MIT License.
|
|
3
|
+
// Ported from https://github.com/browserify/path-browserify/
|
|
4
|
+
// This module is browser compatible.
|
|
5
|
+
|
|
6
|
+
// Alphabet chars.
|
|
7
|
+
export const CHAR_UPPERCASE_A = 65; /* A */
|
|
8
|
+
export const CHAR_LOWERCASE_A = 97; /* a */
|
|
9
|
+
export const CHAR_UPPERCASE_Z = 90; /* Z */
|
|
10
|
+
export const CHAR_LOWERCASE_Z = 122; /* z */
|
|
11
|
+
|
|
12
|
+
// Non-alphabetic chars.
|
|
13
|
+
export const CHAR_DOT = 46; /* . */
|
|
14
|
+
export const CHAR_FORWARD_SLASH = 47; /* / */
|
|
15
|
+
export const CHAR_BACKWARD_SLASH = 92; /* \ */
|
|
16
|
+
export const CHAR_VERTICAL_LINE = 124; /* | */
|
|
17
|
+
export const CHAR_COLON = 58; /* : */
|
|
18
|
+
export const CHAR_QUESTION_MARK = 63; /* ? */
|
|
19
|
+
export const CHAR_UNDERSCORE = 95; /* _ */
|
|
20
|
+
export const CHAR_LINE_FEED = 10; /* \n */
|
|
21
|
+
export const CHAR_CARRIAGE_RETURN = 13; /* \r */
|
|
22
|
+
export const CHAR_TAB = 9; /* \t */
|
|
23
|
+
export const CHAR_FORM_FEED = 12; /* \f */
|
|
24
|
+
export const CHAR_EXCLAMATION_MARK = 33; /* ! */
|
|
25
|
+
export const CHAR_HASH = 35; /* # */
|
|
26
|
+
export const CHAR_SPACE = 32; /* */
|
|
27
|
+
export const CHAR_NO_BREAK_SPACE = 160; /* \u00A0 */
|
|
28
|
+
export const CHAR_ZERO_WIDTH_NOBREAK_SPACE = 65279; /* \uFEFF */
|
|
29
|
+
export const CHAR_LEFT_SQUARE_BRACKET = 91; /* [ */
|
|
30
|
+
export const CHAR_RIGHT_SQUARE_BRACKET = 93; /* ] */
|
|
31
|
+
export const CHAR_LEFT_ANGLE_BRACKET = 60; /* < */
|
|
32
|
+
export const CHAR_RIGHT_ANGLE_BRACKET = 62; /* > */
|
|
33
|
+
export const CHAR_LEFT_CURLY_BRACKET = 123; /* { */
|
|
34
|
+
export const CHAR_RIGHT_CURLY_BRACKET = 125; /* } */
|
|
35
|
+
export const CHAR_HYPHEN_MINUS = 45; /* - */
|
|
36
|
+
export const CHAR_PLUS = 43; /* + */
|
|
37
|
+
export const CHAR_DOUBLE_QUOTE = 34; /* " */
|
|
38
|
+
export const CHAR_SINGLE_QUOTE = 39; /* ' */
|
|
39
|
+
export const CHAR_PERCENT = 37; /* % */
|
|
40
|
+
export const CHAR_SEMICOLON = 59; /* ; */
|
|
41
|
+
export const CHAR_CIRCUMFLEX_ACCENT = 94; /* ^ */
|
|
42
|
+
export const CHAR_GRAVE_ACCENT = 96; /* ` */
|
|
43
|
+
export const CHAR_AT = 64; /* @ */
|
|
44
|
+
export const CHAR_AMPERSAND = 38; /* & */
|
|
45
|
+
export const CHAR_EQUAL = 61; /* = */
|
|
46
|
+
|
|
47
|
+
// Digits
|
|
48
|
+
export const CHAR_0 = 48; /* 0 */
|
|
49
|
+
export const CHAR_9 = 57; /* 9 */
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
|
2
|
+
// This module is browser compatible.
|
|
3
|
+
|
|
4
|
+
import { assertPath } from "./assert_path.js";
|
|
5
|
+
|
|
6
|
+
export function assertArg(path: string) {
|
|
7
|
+
assertPath(path);
|
|
8
|
+
if (path.length === 0) return ".";
|
|
9
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
|
2
|
+
// This module is browser compatible.
|
|
3
|
+
|
|
4
|
+
import type { ParsedPath } from "../types.js";
|
|
5
|
+
|
|
6
|
+
export function _format(
|
|
7
|
+
sep: string,
|
|
8
|
+
pathObject: Partial<ParsedPath>,
|
|
9
|
+
): string {
|
|
10
|
+
const dir: string | undefined = pathObject.dir || pathObject.root;
|
|
11
|
+
const base: string = pathObject.base ||
|
|
12
|
+
(pathObject.name || "") + (pathObject.ext || "");
|
|
13
|
+
if (!dir) return base;
|
|
14
|
+
if (base === sep) return dir;
|
|
15
|
+
if (dir === pathObject.root) return dir + base;
|
|
16
|
+
return dir + sep + base;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function assertArg(pathObject: Partial<ParsedPath>) {
|
|
20
|
+
if (pathObject === null || typeof pathObject !== "object") {
|
|
21
|
+
throw new TypeError(
|
|
22
|
+
`The "pathObject" argument must be of type Object. Received type ${typeof pathObject}`,
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
|
2
|
+
// This module is browser compatible.
|
|
3
|
+
|
|
4
|
+
export function assertArg(url: URL | string) {
|
|
5
|
+
url = url instanceof URL ? url : new URL(url);
|
|
6
|
+
if (url.protocol !== "file:") {
|
|
7
|
+
throw new TypeError("Must be a file URL.");
|
|
8
|
+
}
|
|
9
|
+
return url;
|
|
10
|
+
}
|