@crawlbrulee/sdk 1.3.1 → 1.5.0

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/README.md CHANGED
@@ -170,19 +170,23 @@ notes:
170
170
  [proxies & location](https://crawlbrulee.com/docs/proxies) for what each tier does.
171
171
  - **`screenshot`**: custom `viewport.width`/`height` are integers in `[16, 10000]` and `device_scale_factor` is in
172
172
  `[1, 3]`; out-of-range values are rejected with a `400`. the `url` of the screenshot and of every slice is a signed
173
- link that expires 24 hours after the scrape, so download the image and keep the file, not the link. full capture
173
+ link that expires 24 hours after the scrape, so download the image and keep the file, not the link. set
174
+ `color_scheme: 'dark'` to ask the site for its dark theme (see [dark mode](#dark-mode)). full capture
174
175
  options: [screenshots](https://crawlbrulee.com/docs/scrape/screenshots).
175
176
  - **`extract.images`**: urls preserve their query string and resolve document-relative `src`s against the full page url
176
177
  (browser parity) — the same rules as `links`. every extract field is documented under
177
178
  [extraction](https://crawlbrulee.com/docs/scrape/extraction).
178
- - **`warnings`**: when we complete a scrape but something is worth flagging, the codes land on `page.warnings`, in two
179
- families. capped output: `screenshot_truncated` (a long page exceeded the scrolling-screenshot height cap),
179
+ - **`warnings`**: when we complete a scrape but something is worth flagging, the codes land on `page.warnings`, in three
180
+ groups. capped output: `screenshot_truncated` (a long page exceeded the scrolling-screenshot height cap),
180
181
  `links_truncated` (more than 30 000 links), `inline_images_truncated` (more than 10 000 inline images),
181
- `raw_html_truncated` (more than 10 000 000 characters of body html), and `elements_truncated` (an `elements` value
182
- hit a limit, see [elements](#elements)). failed extraction of one section: `links_unavailable`,
183
- `inline_images_unavailable`, `metadata_unavailable`, and `screenshot_unavailable` (a screenshot was asked for, but the
184
- page came back without one) — the field comes back omitted or empty while the rest of the scrape succeeds, which is
185
- how you tell "the page had none" from "we couldn't read them". they're stable, so you can switch on them — the union
182
+ `raw_html_truncated` (more than 10 000 000 characters of body html), `elements_truncated` (an `elements` value
183
+ hit a limit, see [elements](#elements)), and `pdf_single_page_overflow` (a `single_page` pdf was taller than
184
+ 15 000 px, so it goes on over more pages). failed extraction of one section: `links_unavailable`,
185
+ `inline_images_unavailable`, `metadata_unavailable`, `screenshot_unavailable` (a screenshot was asked for, but the
186
+ page came back without one) and `pdf_unavailable` (the same for a pdf, see [pdf](#pdf)). the field comes back
187
+ omitted or empty while the rest of the scrape succeeds, which is
188
+ how you tell "the page had none" from "we couldn't read them". and a request notice: `custom_user_agent` means the request set its own
189
+ `User-Agent` header, which can lower the success rate (see [headers and cookies](#headers-and-cookies)). they're stable, so you can switch on them — the union
186
190
  is exported as `ScrapeWarningCode`. `metadata_truncated` is retired and no longer sent; only results stored before
187
191
  that change can carry it. warnings are stored with the result, so cache hits and async result fetches report them
188
192
  too, filtered to the outputs you asked for.
@@ -197,33 +201,87 @@ types mirror.
197
201
 
198
202
  `extract.elements` reads named values from the page by CSS selector. each key is a name you pick. each value is a
199
203
  selector (the text of the first match) or a spec: `output` (`text`, `html` or `attribute`), `all: true` for every match
200
- as a list, and `fields` to read several values inside each match. the values come back on `page.elements` under the
204
+ as a list, and `fields` to read several values inside each match (`:scope` reads the match itself). the values come back on `page.elements` under the
201
205
  same names. a name with no match is `null`, or `[]` with `all: true`. it costs no extra credits.
202
206
 
203
207
  ```ts
204
208
  const page = await crawlbrulee.scrape({
205
- url: 'https://books.toscrape.com/',
209
+ url: 'https://shop.example.com/books/',
206
210
  extract: {
207
211
  elements: {
208
212
  heading: 'h1',
209
213
  books: {
210
- selector: 'article.product_pod',
214
+ selector: 'article.book',
211
215
  all: true,
212
216
  fields: {
213
217
  title: { selector: 'h3 a', output: 'attribute', attribute: 'title' },
214
- price: '.price_color',
218
+ price: '.price',
215
219
  },
216
220
  },
217
221
  },
218
222
  },
219
223
  })
220
224
 
221
- page.elements?.heading // 'All products'
222
- page.elements?.books // [{ title: 'A Light in the Attic', price: '£51.77' }, …]
225
+ page.elements?.heading // 'Books'
226
+ page.elements?.books // [{ title: 'The Night Garden', price: '€18.90' }, …]
223
227
  ```
224
228
 
225
229
  the request types are `ScrapeElements` and `ScrapeElementSpec`; each value on `page.elements` is a
226
- `ScrapeElementValue`. selector rules and limits: see [elements](https://crawlbrulee.com/docs/scrape/elements).
230
+ `ScrapeElementValue`. selector rules and limits: see [targeted extraction](https://crawlbrulee.com/docs/scrape/targeted-extraction).
231
+
232
+ #### pdf
233
+
234
+ `extract.pdf` saves the page as a pdf: a real document with selectable text and working links, backgrounds printed,
235
+ and no header or footer added. `{}` takes every default. it costs what a screenshot costs, and a pdf and a screenshot
236
+ in one request are billed once.
237
+
238
+ ```ts
239
+ const page = await crawlbrulee.scrape({
240
+ url: 'https://example.com/report',
241
+ extract: {
242
+ markdown: false,
243
+ metadata: false,
244
+ pdf: { paper: 'letter', landscape: true }, // or {} for every default
245
+ },
246
+ })
247
+
248
+ page.pdf?.url // signed link, expires 24 hours after the scrape
249
+ page.pdf?.bytes // size of the file
250
+ ```
251
+
252
+ the options are `layout` (`'pages'`, the default, on sheets of paper, or `'single_page'`, one tall page up to
253
+ 15 000 px), `paper` (`'a4'`, the default, or `'letter'`) and `landscape` (both only with `'pages'`), and `media`
254
+ (`'screen'`, the default, or `'print'`, the site's own print style). the request type is `PdfRequest`; the result is
255
+ `PdfResult`.
256
+
257
+ - the `url` is a signed link that expires 24 hours after the scrape, like a screenshot link. download the file and
258
+ keep it, not the link.
259
+ - when the pdf can't be made, `page.pdf` is left out, `warnings` carries `pdf_unavailable`, and the rest of the scrape
260
+ still comes back. the request then costs what it costs without the pdf.
261
+ - a pdf-only request, like the one above, turns every other format off. if its content type can't be made into a
262
+ pdf, it raises `ValidationError` (`422` `unsupported_pdf_output`), not billed. an async pdf-only job in that case,
263
+ or one that got no pdf, ends `failed` and is not billed (see
264
+ [`getScrapeResult`](#crawlbruleegetscraperesultjobid-options)).
265
+ - a cached copy of the page answers only when it has a pdf made with the same settings. `cache: { max_age: 0 }` always
266
+ makes a new one.
267
+
268
+ #### dark mode
269
+
270
+ set `color_scheme: 'dark'` on `extract.screenshot` to ask the site for its dark theme. a site without one looks the
271
+ same as with `'light'`, the default. it costs no extra credits.
272
+
273
+ ```ts
274
+ const page = await crawlbrulee.scrape({
275
+ url: 'https://example.com',
276
+ extract: {
277
+ screenshot: { type: 'full_page', color_scheme: 'dark' },
278
+ pdf: {}, // the pdf shows the dark theme too
279
+ },
280
+ })
281
+ ```
282
+
283
+ a pdf in the same request is made from the same page, so it is dark too. a pdf on its own is made with the light theme: the pdf
284
+ has no color setting of its own.
227
285
 
228
286
  #### zero data retention
229
287
 
@@ -236,6 +294,27 @@ console.log(page.response_meta.usage.zero_data_retention_credit_cost) // 1
236
294
 
237
295
  without it enabled, the call raises `ZeroDataRetentionNotEnabledError` (`403`, not billed).
238
296
 
297
+ #### headers and cookies
298
+
299
+ pass `headers` and `cookies` on `scrape` or `scrapeAsync` to send your own http headers and cookies to the site, for
300
+ example an api key or a fixed `User-Agent` that a site has on its allowlist. headers go only to the origin
301
+ of `url` (same scheme, host and port), or to its https version when `url` is http, and cookies only to its host.
302
+
303
+ ```ts
304
+ const page = await crawlbrulee.scrape({
305
+ url: 'https://app.example.com/orders',
306
+ headers: { Authorization: `Bearer ${process.env.APP_TOKEN}`, 'X-Tenant-Id': 'acme' },
307
+ cookies: [{ name: 'session_id', value: process.env.APP_SESSION! }],
308
+ extract: { markdown: true },
309
+ })
310
+ ```
311
+
312
+ a request with headers or cookies is never cached: it never reads from or writes to the cache, and is billed as a
313
+ normal fresh scrape. use `cookies` for cookies and `location.locale` for the language; a header the api doesn't accept
314
+ raises `ValidationError` (`400`) with a message that names it. your own `User-Agent` can lower the success rate and
315
+ adds the `custom_user_agent` warning. on a plain `http://` url, headers and cookies travel unencrypted. limits and
316
+ rules: see [headers and cookies](https://crawlbrulee.com/docs/scrape/custom-headers-and-cookies).
317
+
239
318
  #### `crawlbrulee.scrapeAsync(request, options?)`
240
319
 
241
320
  submit a scrape job in the background. returns immediately with a `job_id`.
@@ -258,6 +337,11 @@ look up the current state of an async job — `pending`, `running`, `done`, or `
258
337
  fetch the result of a completed async job. throws if the job hasn't finished yet. like `scrape()`, a job whose page came
259
338
  back as a 404 (or any other status) is a completed job — the result carries `page_status_code`.
260
339
 
340
+ a job that asked only for a screenshot, only for a pdf, or for both and nothing else, and got no capture, ends `failed`
341
+ and is not billed. its status says `failed`, and `getScrapeResult()` throws: `ValidationError` (`422`
342
+ `unsupported_screenshot_output` or `unsupported_pdf_output`) when the page's content type can't be captured, or a
343
+ `CrawlbruleeError` with `errorName: 'job_failed'` (`400`) otherwise. a job that got its capture completes as usual.
344
+
261
345
  a job's status and result are available for 24 hours after you submit it. after that, `getScrapeStatus()` and
262
346
  `getScrapeResult()` throw `NotFoundError`, the same as for an unknown `jobId`. screenshot links in the result expire at
263
347
  the same moment, however late you fetch it.
@@ -283,75 +367,119 @@ under [async scrape](https://crawlbrulee.com/docs/scrape/async).
283
367
 
284
368
  #### `crawlbrulee.map(request, options?)`
285
369
 
286
- build (or return a cached) link map for a website. combines sitemap discovery with the freshest cached homepage scrape
287
- when available.
370
+ build (or return a cached) link map of a site from its sitemaps, plus the links on its home page. a plain map reads
371
+ the site's top sitemap files and two levels of nested ones, and returns its pages.
288
372
 
289
373
  ```ts
290
374
  const result = await crawlbrulee.map({
291
375
  url: 'https://example.com',
292
376
  sitemap_only: false,
293
377
  types: { internal: true, internal_subdomains: false, external: false },
294
- max_urls: 5_000,
378
+ max_results: 5_000,
295
379
  page: 1,
296
380
  limit: 1_000,
297
381
  })
298
382
 
299
- console.log(result.links.length, 'urls on page 1 of', result.response_meta.pagination.total_pages)
383
+ for (const link of result.links) {
384
+ console.log(link.url, link.type, link.lastmod) // 'page' or 'sitemap'; lastmod is a UTC date and time, or null
385
+ }
386
+ console.log(result.response_meta.pagination.total_pages, 'pages of results')
300
387
  console.log(result.response_meta.usage.total_credit_cost, 'credits charged') // usage accounting, alongside pagination + truncation
301
388
  ```
302
389
 
303
- - **`max_urls`** defaults to `5_000` and maxes out at `100_000`. discovery _stops_ at this number, so a smaller value
304
- is a cheaper and faster crawl, not just a shorter answer.
390
+ - **`max_results`** defaults to `5_000` and maxes out at `100_000`. it counts only the kind you ask for in `entries`.
391
+ discovery _stops_ at this number, so a smaller value is a faster and lighter map, not just a shorter answer.
305
392
  - **`limit`** (urls per page) defaults to `5_000` and maxes out at `10_000`.
306
- - the sdk sends only the fields you pass — omit `max_urls` or `limit` and the server applies its own default.
393
+ - **`entries`**: `'pages'` (the default), `'sitemaps'` (sitemap files) or `'all'` (both).
394
+ - **`sitemap_url`**: start from this sitemap file instead of the site's own top sitemap files. it must be on the same
395
+ site as `url`, or on a host the site's robots.txt names, such as a CDN.
396
+ - **`depth`**: how many levels of nested sitemaps to follow: `0` to `3`, default `3`. the sdk passes the number
397
+ through; a higher value raises `ValidationError`.
398
+ - **`modified_since`**: a date such as `'2026-11-01'` (the start of that day in UTC), or an ISO 8601 date and time
399
+ with a zone, such as `'2026-11-01T08:00:00+01:00'`. only entries whose
400
+ `lastmod` is at or after it come back, so an entry with no `lastmod` is left out. such a map is always fresh, so
401
+ `cache.max_age` does nothing. see
402
+ [find what changed since a date](https://crawlbrulee.com/docs/map/sitemaps#find-what-changed-since-a-date).
403
+ - the sdk sends only the fields you pass: omit `max_results` or `limit` and the server applies its own default.
404
+ - `max_urls` and `truncation.total_before_max_urls` are the old names of `max_results` and
405
+ `truncation.total_before_max_results`. they still work and always match the new ones, and the api removes them on
406
+ 2027-02-01. when you send both, only `max_results` is used.
407
+
408
+ every link is `{ url, type, lastmod }`. `type` is `'page'` or `'sitemap'`; a sitemap link is a file you can read with
409
+ `sitemap_url` in another call (on another site, only when the site's robots.txt names its host). a link found on the home page is a `'page'` with `lastmod: null`. the site root is
410
+ listed only when a sitemap lists it. a map with `modified_since` or `sitemap_url` never adds home page links.
307
411
 
308
412
  `result.response_meta` carries `usage` alongside the map-specific `pagination` and `truncation` blocks. map usage has the
309
413
  same fields as scrape usage minus slicing, since a map makes no screenshots: `total_credit_cost` (=
310
414
  `engine_credit_cost × proxy_multiplier + zero_data_retention_credit_cost`), `engine_credit_cost` (1 `http`, 0 `cache`),
311
415
  `proxy_multiplier`, `zero_data_retention_credit_cost` (0 or 1), the billed
312
416
  `engine` and the resolved `proxy`. an empty map is free
313
- when the site answered only with statuses we don't bill (a `5xx`, for example) or not at all.
417
+ when the site answered only with statuses we don't bill (a `5xx`, for example) or not at all. when the site answers
418
+ `429` for the file in `sitemap_url`, for its robots.txt or for one of its top sitemap files, the map raises
419
+ `RateLimitError` and is not billed.
314
420
 
315
421
  a map has no `page_status_code`: it reads several pages (sitemaps and the home page), so one status would not describe
316
422
  it.
317
423
 
318
424
  #### did the map miss pages?
319
425
 
320
- a map that stopped at your own `max_urls` comes back with exactly `max_urls` links and `response_capped: false` — the
321
- signal that more exists is `discovery_cap_reason`, not the capped flags:
426
+ a map that stopped at your own `max_results` has `response_capped: false`. the signal that more exists is
427
+ `discovery_cap_reason`, not the capped flags:
322
428
 
323
429
  ```ts
324
430
  const { truncation } = result.response_meta
325
431
 
326
432
  if (truncation.discovery_capped) {
327
433
  // the site has more pages than this map lists
328
- // 'max_urls' | 'time' | 'file_budget' | 'depth' | 'file_size' | 'unread_files'
434
+ // 'max_results' | 'depth' | 'time' | 'file_budget' | 'file_size' | 'unread_files'
329
435
  console.log('stopped by:', truncation.discovery_cap_reason)
330
436
  console.log(truncation.sitemaps_skipped, 'sitemap files skipped or partly read')
437
+ console.log(truncation.unread_sitemaps) // sitemap files this call did not read whole
331
438
  }
332
439
 
333
- if (truncation.discovery_cap_reason === 'max_urls') {
334
- // the only reason you can fix from the request — ask again with a higher max_urls
440
+ if (truncation.discovery_cap_reason === 'max_results') {
441
+ // ask again with a higher max_results
335
442
  }
336
443
 
337
444
  if (truncation.discovery_cap_reason === 'unread_files') {
338
- // a sitemap file could not be read this time — try the same request again later
445
+ // a sitemap file could not be read whole this time; try the same request again later
339
446
  }
340
447
  ```
341
448
 
342
- `unread_files` means a sitemap file the site publishes could not be read at all this time: the request for it failed or
343
- was rate limited, or the file was not a readable sitemap. that is often temporary, so asking again later can return a
344
- fuller map.
449
+ - `max_results`: your own `max_results` was reached. ask again with a higher one.
450
+ - `depth`: there are sitemap files past the `depth` you asked for. that is the answer to your `depth`, not a fault.
451
+ - `time`, `file_budget`: the site is big or slow. map it in several calls (below).
452
+ - `file_size`: a sitemap file was too large. a file of pages that turns out too large while it is read gives the
453
+ links in its first part. a file that says up front that it is over the size limit, or any other file that turns
454
+ out too large (such as a sitemap index), gives nothing and is listed in `unread_sitemaps`.
455
+ - `unread_files`: a sitemap file could not be read whole this time. when its download broke off, the links received
456
+ before the break are returned, and the file is listed in `unread_sitemaps`. asking again later can return more.
457
+
458
+ `truncation.unread_sitemaps` lists the sitemap files the map knew about but did not read whole (up to 1 000). read
459
+ each one with `sitemap_url` in another call, except a file that says it is over the size limit: no call reads that
460
+ one. it is empty when every file was read.
461
+
462
+ #### a large site, in several calls
463
+
464
+ a very large or deep site is mapped in several calls: list its sitemap files with `depth: 0` and
465
+ `entries: 'sitemaps'`, then read each one with `sitemap_url`. `truncation.unread_sitemaps` names the files a call did
466
+ not read whole, to read next. the full walk-through is in
467
+ [map a very large or deep site in several calls](https://crawlbrulee.com/docs/map/sitemaps#map-a-very-large-or-deep-site-in-several-calls).
345
468
 
346
- every other reason (`time`, `file_budget`, `depth`, `file_size`) means the site itself is big, slow or deeply nested;
347
- re-asking with a higher `max_urls` will not return more, and neither will trying again later.
469
+ ```ts
470
+ const top = await crawlbrulee.map({ url: 'https://example.com', depth: 0, entries: 'sitemaps' })
471
+
472
+ for (const file of top.links) {
473
+ const part = await crawlbrulee.map({ url: 'https://example.com', sitemap_url: file.url })
474
+ console.log(part.links.length, part.response_meta.truncation.unread_sitemaps)
475
+ }
476
+ ```
348
477
 
349
478
  #### url shape and ordering
350
479
 
351
480
  returned urls come back normalised, the same way `/scrape` normalises the `url` it returns.
352
481
 
353
- ordering is stable, with the most useful links first,
354
- so a link item is always just `{ url }`.
482
+ ordering is stable, with the most useful links first.
355
483
 
356
484
  see the [map endpoint](https://crawlbrulee.com/docs/map) for discovery rules and pagination semantics.
357
485
 
@@ -530,6 +658,11 @@ answer in time, or its tls certificate was not valid. it raises `TargetUnreachab
530
658
  not reach the target site." and no `details`. you are not charged. the site may come back, so retrying later can help.
531
659
  both `/scrape` and `/map` can return it.
532
660
 
661
+ **a 422 `unsupported_screenshot_output` or `unsupported_pdf_output` is a `ValidationError`.** the request asked only for
662
+ a screenshot, or only for a pdf, and the content type can't be made into one. a request with only a screenshot and a pdf gets
663
+ `unsupported_screenshot_output`. ask for another format too to get the rest of the page. not billed. an async job
664
+ like that ends `failed`, and reading its result throws the same `422`.
665
+
533
666
  **a 422 `page_too_large` means the page, not the request.** the page's html was too large to process, so it raises
534
667
  `PageTooLargeError`, not `ValidationError`. it is terminal: the same url will fail the same way, so do not retry it —
535
668
  scrape a smaller page instead. `/scrape` returns it; `/map` does not.
package/dist/index.cjs CHANGED
@@ -12,7 +12,7 @@ const DEFAULT_REQUEST_TIMEOUT_MS = 0;
12
12
  /** Environment variable read by `Crawlbrulee.fromEnv()` to source the API key. */
13
13
  const ENV_API_KEY = "CRAWLBRULEE_API_KEY";
14
14
  /** Identifies the SDK in the `User-Agent` header. Kept in one place for easy bumping. */
15
- const USER_AGENT = "@crawlbrulee/sdk/1.3.1 (node)";
15
+ const USER_AGENT = "@crawlbrulee/sdk/1.5.0 (node)";
16
16
 
17
17
  //#endregion
18
18
  //#region src/errors.ts
@@ -323,7 +323,8 @@ function createApiError(body, status) {
323
323
  case "url_credentials_not_supported":
324
324
  case "blocked_url":
325
325
  case "unsupported_content":
326
- case "unsupported_screenshot_output": return new ValidationError(message, {
326
+ case "unsupported_screenshot_output":
327
+ case "unsupported_pdf_output": return new ValidationError(message, {
327
328
  status,
328
329
  errorName: name,
329
330
  response
@@ -765,8 +766,17 @@ var Crawlbrulee = class Crawlbrulee {
765
766
  }
766
767
  }
767
768
  /**
768
- * Build (or return a cached) site link-map for a domain. Combines sitemap
769
- * discovery with the freshest cached homepage scrape when available.
769
+ * Build (or return a cached) link map of a site from its sitemaps, plus the
770
+ * links on its home page. Every link is `{ url, type, lastmod }`.
771
+ *
772
+ * By default the map reads the site's top sitemap files and two levels of
773
+ * nested ones, and returns pages. Use `sitemap_url` to read one sitemap file,
774
+ * so a very large site can be mapped in several calls. When the site answers
775
+ * `429` for the file in `sitemap_url`, for its robots.txt or for one of its
776
+ * top sitemap files, the map raises
777
+ * {@link RateLimitError} and is not billed.
778
+ *
779
+ * See https://crawlbrulee.com/docs/map/sitemaps#map-a-very-large-or-deep-site-in-several-calls.
770
780
  */
771
781
  map(request, options) {
772
782
  return this.http.post("/api/map", request, options);