@crawlbrulee/sdk 1.0.1 → 1.2.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
@@ -55,7 +55,8 @@ const page = await crawlbrulee.scrape({
55
55
  console.log(page.markdown)
56
56
  console.log(page.links?.length, 'links found')
57
57
  console.log(page.metadata?.title) // structured <head> metadata
58
- console.log(page.response_meta.usage.credits, 'credits charged') // usage accounting
58
+ console.log(page.page_status_code) // the site's own http status, e.g. 200 or 404
59
+ console.log(page.response_meta.usage.total_credit_cost, 'credits charged') // usage accounting
59
60
  ```
60
61
 
61
62
  ### authentication
@@ -135,15 +136,34 @@ the response carries the extracted content alongside structured `metadata` (the
135
136
 
136
137
  ```ts
137
138
  page.metadata?.title // structured <head> metadata (when extract.metadata, on by default)
138
-
139
- page.response_meta.usage.credits // credits charged
140
- page.response_meta.usage.engine // billed base: 'http' | 'browser' | 'screenshot' | 'cache'
141
- page.response_meta.usage.proxy // the resolved proxy tier actually used: 'basic' | 'advanced' (never 'auto')
142
- page.response_meta.usage.screenshot_slices // billed slice add-on: 0 or 1
139
+ page.page_status_code // the http status the site answered with for the final page, e.g. 200 or 404
140
+
141
+ const usage = page.response_meta.usage
142
+ usage.total_credit_cost // credits charged = engine_credit_cost × proxy_multiplier + screenshot_slicing_credit_cost
143
+ usage.engine_credit_cost // engine base: 1 http, 3 browser, 5 screenshot, 0 cache
144
+ usage.proxy_multiplier // 1 basic, 5 advanced
145
+ usage.screenshot_slicing_credit_cost // slicing add-on: 0 or 1
146
+ usage.engine // billed engine: 'http' | 'browser' | 'screenshot' | 'cache'
147
+ usage.proxy // the resolved proxy tier actually used: 'basic' | 'advanced' (never 'auto')
143
148
  ```
144
149
 
145
150
  notes:
146
151
 
152
+ - **`page_status_code`**: a page the site really served is a successful result, whatever its status. a 404, 410, 401
153
+ or 503 page comes back with its content and `page_status_code` set to the site's status — `scrape()` does not throw
154
+ for it. check the field when the status matters to you:
155
+
156
+ ```ts
157
+ const page = await crawlbrulee.scrape({ url: 'https://example.com/old-page' })
158
+ if (page.page_status_code === 404) {
159
+ // the site says the page does not exist — its 404 page is in page.markdown / page.cleaned_html
160
+ }
161
+ ```
162
+
163
+ billing follows the site's status: 2xx and 4xx pages are billed, except 403, 407, 408, 429 and 451; 5xx pages are
164
+ never billed. an unbilled page reports `total_credit_cost: 0`. errors are thrown when we could not return the page
165
+ — see [errors](#errors).
166
+
147
167
  - **`proxy`**: defaults to `auto` when omitted — it starts at the basic tier and escalates to advanced on failure,
148
168
  billed at the delivered tier. pass `'basic'` or `'advanced'` to pin a tier. on the response,
149
169
  `response_meta.usage.proxy` reports the tier we resolved and used — never `'auto'`. see
@@ -170,6 +190,17 @@ see [`ScrapeRequest`](src/types/scrape.ts) and [`ScrapeResponse`](src/types/scra
170
190
  documentation — and the [scrape endpoint](https://crawlbrulee.com/docs/scrape) reference for the api-side contract those
171
191
  types mirror.
172
192
 
193
+ #### zero data retention
194
+
195
+ pass `zero_data_retention: true` on `scrape`, `scrapeAsync` or `map` to keep the result out of the shared cache. anything stored to deliver it is kept for 24 hours, then deleted. it adds 1 credit and must be enabled for your organization. see [zero data retention](https://crawlbrulee.com/docs/zero-data-retention).
196
+
197
+ ```ts
198
+ const page = await crawlbrulee.scrape({ url: 'https://example.com', zero_data_retention: true })
199
+ console.log(page.response_meta.usage.zero_data_retention_credit_cost) // 1
200
+ ```
201
+
202
+ without it enabled, the call raises `ZeroDataRetentionNotEnabledError` (`403`, not billed).
203
+
173
204
  #### `crawlbrulee.scrapeAsync(request, options?)`
174
205
 
175
206
  submit a scrape job in the background. returns immediately with a `job_id`.
@@ -184,11 +215,13 @@ pass a `webhook` to be notified on completion instead of polling — see [webhoo
184
215
 
185
216
  look up the current state of an async job — `pending`, `running`, `done`, or `failed`. the response carries `job_id` and
186
217
  `created_at` (snake_case, straight off the wire). once the job is `done`, it also carries usage accounting on
187
- `response_meta.usage` (`credits`, `engine`, `proxy`, `screenshot_slices`).
218
+ `response_meta.usage` (`total_credit_cost`, `engine_credit_cost`, `proxy_multiplier`, `screenshot_slicing_credit_cost`,
219
+ `engine` and `proxy`).
188
220
 
189
221
  #### `crawlbrulee.getScrapeResult(jobId, options?)`
190
222
 
191
- fetch the result of a completed async job. throws if the job hasn't finished yet.
223
+ fetch the result of a completed async job. throws if the job hasn't finished yet. like `scrape()`, a job whose page came
224
+ back as a 404 (or any other status) is a completed job — the result carries `page_status_code`.
192
225
 
193
226
  #### `crawlbrulee.waitForScrape(jobId, options?)`
194
227
 
@@ -225,7 +258,7 @@ const result = await crawlbrulee.map({
225
258
  })
226
259
 
227
260
  console.log(result.links.length, 'urls on page 1 of', result.response_meta.pagination.total_pages)
228
- console.log(result.response_meta.usage.credits, 'credits charged') // usage accounting, alongside pagination + truncation
261
+ console.log(result.response_meta.usage.total_credit_cost, 'credits charged') // usage accounting, alongside pagination + truncation
229
262
  ```
230
263
 
231
264
  - **`max_urls`** defaults to `5_000` and maxes out at `100_000`. discovery _stops_ at this number, so a smaller value
@@ -233,8 +266,15 @@ console.log(result.response_meta.usage.credits, 'credits charged') // usage acco
233
266
  - **`limit`** (urls per page) defaults to `5_000` and maxes out at `10_000`.
234
267
  - the sdk sends only the fields you pass — omit `max_urls` or `limit` and the server applies its own default.
235
268
 
236
- `result.response_meta` carries `usage` (`credits` / billed `engine` / resolved `proxy`) alongside the map-specific `pagination`
237
- and `truncation` blocks. map operations do not produce screenshot slices.
269
+ `result.response_meta` carries `usage` alongside the map-specific `pagination` and `truncation` blocks. map usage has the
270
+ same fields as scrape usage minus slicing, since a map makes no screenshots: `total_credit_cost` (=
271
+ `engine_credit_cost × proxy_multiplier + zero_data_retention_credit_cost`), `engine_credit_cost` (1 `http`, 0 `cache`),
272
+ `proxy_multiplier`, `zero_data_retention_credit_cost` (0 or 1), the billed
273
+ `engine` and the resolved `proxy`. an empty map is free
274
+ when the site answered only with statuses we don't bill (a `5xx`, for example) or not at all.
275
+
276
+ a map has no `page_status_code`: it reads several pages (sitemaps and the home page), so one status would not describe
277
+ it.
238
278
 
239
279
  #### did the map miss pages?
240
280
 
@@ -323,8 +363,8 @@ const { job_id } = await crawlbrulee.scrapeAsync({
323
363
 
324
364
  configure the signing secret used for these deliveries in the dashboard (**account → webhooks**). there is no per-request
325
365
  secret - when the delivery arrives, verify it with [`verifyWebhookSignature`](#verifywebhooksignatureoptions) and read your `metadata` back from
326
- `webhook.data.metadata`. the delivery also carries usage accounting on `webhook.data.response_meta.usage` (`credits`,
327
- `engine`, `proxy`, `screenshot_slices`). see [`AsyncScrapeWebhook`](src/types/scrape.ts) for the full field documentation.
366
+ `webhook.data.metadata`. a `success` delivery also carries the site's status on `webhook.data.page_status_code` and usage
367
+ accounting on `webhook.data.response_meta.usage` (the same fields as on a scrape result). see [`AsyncScrapeWebhook`](src/types/scrape.ts) for the full field documentation.
328
368
 
329
369
  ### `verifyWebhookSignature(options)`
330
370
 
@@ -391,19 +431,21 @@ always verify the signature **before** parsing or trusting the body. the `X-Cwbl
391
431
  every failure raised by the sdk extends [`CrawlbruleeError`](src/errors.ts). typed subclasses are exported for the most actionable
392
432
  cases:
393
433
 
394
- | class | when it's raised |
395
- | ------------------------- | ---------------------------------------------------------------------------------------------------------- |
396
- | `AuthenticationError` | 401 / 403 responses (missing, invalid, or unauthorized api key). |
397
- | `AntibotBlockedError` | 403 `antibot_blocked` — the target site's bot protection blocked us. not a key problem. |
398
- | `TooManyRedirectsError` | 422 `too_many_redirects` — the target site redirected in a loop. not a bad request; retrying rarely helps. |
399
- | `PageTooLargeError` | 422 `page_too_large` — the page's html was too large to process. terminal; do not retry it. |
400
- | `RateLimitError` | 429 responses. exposes `retryAfterMs` and `limitedBy` when the server provided them. |
401
- | `UsageAllocationError` | the org's plan limit was hit. exposes `reason` (`credit_limit`, `concurrency_limit`, …) and `usage`. |
402
- | `ValidationError` | 4xx caused by a bad request (`invalid_url`, `url_too_long`, `blocked_url`, …). |
403
- | `NotFoundError` | 404 responses (e.g. unknown async `jobId`). |
404
- | `ServiceUnavailableError` | 503 responses (`service_unavailable`). the api is temporarily unavailable — transient, retry it. |
405
- | `TransportError` | network failures, aborts, non-json responses, request body read failures. |
406
- | `CrawlbruleeError` | base class — used for any other api error. always has `status`, `errorName`, `message`. |
434
+ | class | when it's raised |
435
+ | ---------------------------------- | --------------------------------------------------------------------------------------------------------------- |
436
+ | `AuthenticationError` | 401 / 403 responses (missing, invalid, or unauthorized api key). |
437
+ | `AntibotBlockedError` | 403 `antibot_blocked` — the target site's bot protection blocked us. not a key problem. |
438
+ | `TooManyRedirectsError` | 422 `too_many_redirects` — the target site redirected in a loop. not a bad request; retrying rarely helps. |
439
+ | `PageTooLargeError` | 422 `page_too_large` — the page's html was too large to process. terminal; do not retry it. |
440
+ | `ZeroDataRetentionNotEnabledError` | 403 `zero_data_retention_not_enabled` — `zero_data_retention` is not enabled for your organization. not billed. |
441
+ | `TargetUnreachableError` | 502 `target_unreachable` — we could not reach the target site at all. not billed; retrying later may help. |
442
+ | `RateLimitError` | 429 responses. exposes `retryAfterMs` and `limitedBy` when the server provided them. |
443
+ | `UsageAllocationError` | the org's plan limit was hit. exposes `reason` (`credit_limit`, `concurrency_limit`, …) and `usage`. |
444
+ | `ValidationError` | 4xx caused by a bad request (`invalid_url`, `url_too_long`, `blocked_url`, …). |
445
+ | `NotFoundError` | 404 from our api (e.g. unknown async `jobId`). never the target page — see below. |
446
+ | `ServiceUnavailableError` | 503 responses (`service_unavailable`). the api is temporarily unavailable — transient, retry it. |
447
+ | `TransportError` | network failures, aborts, non-json responses, request body read failures. |
448
+ | `CrawlbruleeError` | base class — used for any other api error. always has `status`, `errorName`, `message`. |
407
449
 
408
450
  ```ts
409
451
  import { Crawlbrulee, RateLimitError, UsageAllocationError } from '@crawlbrulee/sdk'
@@ -423,20 +465,32 @@ try {
423
465
  }
424
466
  ```
425
467
 
426
- `RateLimitError` (429) and `ServiceUnavailableError` (503) are the two transient ones — both are worth retrying with
427
- backoff, and a 429 carries a `retryAfterMs` hint when the server sent one. a 503 means our side couldn't serve the
468
+ `RateLimitError` (429), `ServiceUnavailableError` (503) and `TargetUnreachableError` (502) are the transient ones — all
469
+ are worth retrying with backoff, and a 429 carries a `retryAfterMs` hint when the server sent one. the sdk never retries
470
+ on its own; you choose when to try again. a 503 means our side couldn't serve the
428
471
  request for a moment; it says nothing about your credentials, so it is **not** a reason to rotate your api key. a key
429
472
  that is genuinely missing, invalid, or expired comes back as a 401 and raises `AuthenticationError` instead.
430
473
 
431
474
  **not every 403 is a key problem.** a 403 carrying `antibot_blocked` means the _target site_ blocked the request, not
432
475
  that your key was rejected — it raises `AntibotBlockedError`. retrying the same request rarely helps; use a higher
433
- proxy tier (`proxy: 'advanced'`) or skip the site. both `/scrape` and `/map` can return it. only a 403 with an
434
- unrecognized name still falls back to `AuthenticationError`.
476
+ proxy tier (`proxy: 'advanced'`) or skip the site. both `/scrape` and `/map` can return it. a 403 carrying
477
+ `zero_data_retention_not_enabled` raises `ZeroDataRetentionNotEnabledError`. only a 403 with an unrecognized name still
478
+ falls back to `AuthenticationError`.
435
479
 
436
480
  **a 422 `too_many_redirects` is the target's doing too.** the site redirected the request in a loop, or through more
437
481
  hops than the api follows — it raises `TooManyRedirectsError`, not `ValidationError`, because nothing about your
438
482
  request was wrong. retrying rarely helps. both `/scrape` and `/map` can return it.
439
483
 
484
+ **a target page with an error status is not an error.** when the site answers with a 404, 410, 401, 503 or any other
485
+ page, `scrape()` returns that page and puts the site's status in `page_status_code` — see the
486
+ [scrape notes](#crawlbruleescraperequest-options). `NotFoundError` only means something on our side was not found, like
487
+ an unknown async job id.
488
+
489
+ **a 502 `target_unreachable` means we never got a page.** we could not reach the site at all — for example it did not
490
+ answer in time, or its tls certificate was not valid. it raises `TargetUnreachableError` with the fixed message "Could
491
+ not reach the target site." and no `details`. you are not charged. the site may come back, so retrying later can help.
492
+ both `/scrape` and `/map` can return it.
493
+
440
494
  **a 422 `page_too_large` means the page, not the request.** the page's html was too large to process, so it raises
441
495
  `PageTooLargeError`, not `ValidationError`. it is terminal: the same url will fail the same way, so do not retry it —
442
496
  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.0.1 (node)";
15
+ const USER_AGENT = "@crawlbrulee/sdk/1.2.0 (node)";
16
16
 
17
17
  //#endregion
18
18
  //#region src/errors.ts
@@ -57,7 +57,9 @@ var CrawlbruleeError = class extends Error {
57
57
  *
58
58
  * Not every 403 is a key problem: a 403 carrying `antibot_blocked` is the
59
59
  * *target site* blocking us and raises {@link AntibotBlockedError} instead.
60
- * Only an unrecognized 403 name falls back to this class.
60
+ * A 403 carrying `zero_data_retention_not_enabled` raises
61
+ * {@link ZeroDataRetentionNotEnabledError}. Only an unrecognized 403 name falls
62
+ * back to this class.
61
63
  */
62
64
  var AuthenticationError = class extends CrawlbruleeError {
63
65
  constructor(message, options) {
@@ -103,6 +105,40 @@ var PageTooLargeError = class extends CrawlbruleeError {
103
105
  }
104
106
  };
105
107
  /**
108
+ * Raised when we could not reach the target site at all (HTTP 502,
109
+ * `target_unreachable`) — for example the site did not answer in time or its
110
+ * TLS certificate was not valid. We never got a page, so there is nothing to
111
+ * return and you are not charged. The message is always "Could not reach the
112
+ * target site." and there are no `details`.
113
+ *
114
+ * This is about the site, not your key or your request, so it is neither an
115
+ * `AuthenticationError` nor a `ValidationError`. It is also not our own
116
+ * outage ({@link ServiceUnavailableError}). Retrying later may help, since
117
+ * the site may come back. The SDK does not retry for you.
118
+ *
119
+ * Not the same as a page with an error status: when the site answers with a
120
+ * 404 or 503 page, the scrape succeeds and the site's status is in
121
+ * `page_status_code`. Returned by both `scrape` and `map`.
122
+ */
123
+ var TargetUnreachableError = class extends CrawlbruleeError {
124
+ constructor(message, options) {
125
+ super(message, options);
126
+ this.name = "TargetUnreachableError";
127
+ }
128
+ };
129
+ /**
130
+ * Raised when you send `zero_data_retention: true` but the option is not
131
+ * enabled for your organization (HTTP 403, `zero_data_retention_not_enabled`).
132
+ * The request is not billed. Not an API-key problem, so it is not an
133
+ * {@link AuthenticationError}. See https://crawlbrulee.com/docs/zero-data-retention.
134
+ */
135
+ var ZeroDataRetentionNotEnabledError = class extends CrawlbruleeError {
136
+ constructor(message, options) {
137
+ super(message, options);
138
+ this.name = "ZeroDataRetentionNotEnabledError";
139
+ }
140
+ };
141
+ /**
106
142
  * Raised for HTTP 429 responses. When the server included a `retry_after_ms`
107
143
  * hint in `details` it is surfaced directly on the instance.
108
144
  *
@@ -158,7 +194,14 @@ var ValidationError = class extends CrawlbruleeError {
158
194
  this.name = "ValidationError";
159
195
  }
160
196
  };
161
- /** Raised for 404 responses (e.g. unknown async job ID). */
197
+ /**
198
+ * Raised for 404 responses from the crawlbrulee api — something on our side
199
+ * was not found, for example an unknown or expired async job ID.
200
+ *
201
+ * It never means the target page was not found. When the site you scrape
202
+ * answers with a 404 page, the scrape succeeds and returns that page with
203
+ * `page_status_code: 404`.
204
+ */
162
205
  var NotFoundError = class extends CrawlbruleeError {
163
206
  constructor(message, options) {
164
207
  super(message, options);
@@ -247,6 +290,16 @@ function createApiError(body, status) {
247
290
  errorName: name,
248
291
  response
249
292
  });
293
+ case "target_unreachable": return new TargetUnreachableError(message, {
294
+ status,
295
+ errorName: name,
296
+ response
297
+ });
298
+ case "zero_data_retention_not_enabled": return new ZeroDataRetentionNotEnabledError(message, {
299
+ status,
300
+ errorName: name,
301
+ response
302
+ });
250
303
  case "invalid_credentials":
251
304
  case "access_denied": return new AuthenticationError(message, {
252
305
  status,
@@ -590,6 +643,13 @@ var Crawlbrulee = class Crawlbrulee {
590
643
  * (heavy JS rendering, screenshots of long pages) prefer
591
644
  * {@link Crawlbrulee.scrapeAsync} so the connection isn't held open.
592
645
  *
646
+ * Any page the site really served is returned, whatever its status: a 404,
647
+ * 410, 401 or 503 page resolves normally, with the site's status in
648
+ * `page_status_code` — it does not throw. Check that field when the page's
649
+ * status matters to you. The call throws when we could not return the page,
650
+ * for example `TargetUnreachableError` when the site could not be reached,
651
+ * `AntibotBlockedError`, or `PageTooLargeError`.
652
+ *
593
653
  * @param request — body for `POST /api/scrape`.
594
654
  * @param options — per-call timeout and abort signal.
595
655
  */
@@ -617,6 +677,10 @@ var Crawlbrulee = class Crawlbrulee {
617
677
  * Fetch the result of a completed async scrape job. Throws if the job is
618
678
  * still pending/running — call {@link Crawlbrulee.getScrapeStatus}
619
679
  * first, or use {@link Crawlbrulee.waitForScrape} to poll-then-fetch.
680
+ *
681
+ * Like {@link Crawlbrulee.scrape}, a 404 (or any other) page the site served
682
+ * is a completed job: the result carries the site's status in
683
+ * `page_status_code`.
620
684
  */
621
685
  getScrapeResult(jobId, options) {
622
686
  assertNonEmptyJobId(jobId);
@@ -943,6 +1007,7 @@ exports.NotFoundError = NotFoundError;
943
1007
  exports.PageTooLargeError = PageTooLargeError;
944
1008
  exports.RateLimitError = RateLimitError;
945
1009
  exports.ServiceUnavailableError = ServiceUnavailableError;
1010
+ exports.TargetUnreachableError = TargetUnreachableError;
946
1011
  exports.TooManyRedirectsError = TooManyRedirectsError;
947
1012
  exports.TransportError = TransportError;
948
1013
  exports.UsageAllocationError = UsageAllocationError;
@@ -950,6 +1015,7 @@ exports.ValidationError = ValidationError;
950
1015
  exports.WEBHOOK_EVENT_ID_HEADER = WEBHOOK_EVENT_ID_HEADER;
951
1016
  exports.WEBHOOK_SIGNATURE_HEADER = WEBHOOK_SIGNATURE_HEADER;
952
1017
  exports.WEBHOOK_SIGNATURE_ROTATED_HEADER = WEBHOOK_SIGNATURE_ROTATED_HEADER;
1018
+ exports.ZeroDataRetentionNotEnabledError = ZeroDataRetentionNotEnabledError;
953
1019
  exports.isCrawlbruleeError = isCrawlbruleeError;
954
1020
  exports.verifyWebhookSignature = verifyWebhookSignature;
955
1021
  //# sourceMappingURL=index.cjs.map