@crawlee/cli 4.0.0-beta.33 → 4.0.0-beta.330

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 (33) hide show
  1. package/README.md +15 -11
  2. package/commands/{CreateProjectCommand.d.ts → create-project-command.d.ts} +0 -1
  3. package/commands/{CreateProjectCommand.js → create-project-command.js} +4 -6
  4. package/commands/{InstallPlaywrightBrowsersCommand.d.ts → install-playwright-browsers-command.d.ts} +0 -1
  5. package/commands/{InstallPlaywrightBrowsersCommand.js → install-playwright-browsers-command.js} +0 -1
  6. package/commands/{RunProjectCommand.d.ts → run-project-command.d.ts} +0 -1
  7. package/commands/{RunProjectCommand.js → run-project-command.js} +0 -1
  8. package/commands/upgrade-command.d.ts +19 -0
  9. package/commands/upgrade-command.js +150 -0
  10. package/index.d.ts +0 -1
  11. package/index.js +16 -5
  12. package/package.json +10 -10
  13. package/skills/crawlee-upgrade/SKILL.md +20 -0
  14. package/skills/crawlee-upgrade-v4/SKILL.md +45 -0
  15. package/skills/crawlee-upgrade-v4/guide/autoscaling.md +256 -0
  16. package/skills/crawlee-upgrade-v4/guide/browser-management.md +174 -0
  17. package/skills/crawlee-upgrade-v4/guide/http-clients.md +108 -0
  18. package/skills/crawlee-upgrade-v4/guide/internals.md +130 -0
  19. package/skills/crawlee-upgrade-v4/guide/removed-symbols.md +63 -0
  20. package/skills/crawlee-upgrade-v4/guide/request-loaders.md +241 -0
  21. package/skills/crawlee-upgrade-v4/guide/sessions-and-proxies.md +164 -0
  22. package/skills/crawlee-upgrade-v4/guide/statistics.md +56 -0
  23. package/skills/crawlee-upgrade-v4/guide/storage-backends.md +170 -0
  24. package/skills/crawlee-upgrade-v4/guide/upgrading-v4.md +1310 -0
  25. package/skills/crawlee-upgrade-v4/guide/utils-and-types.md +52 -0
  26. package/commands/CreateProjectCommand.d.ts.map +0 -1
  27. package/commands/CreateProjectCommand.js.map +0 -1
  28. package/commands/InstallPlaywrightBrowsersCommand.d.ts.map +0 -1
  29. package/commands/InstallPlaywrightBrowsersCommand.js.map +0 -1
  30. package/commands/RunProjectCommand.d.ts.map +0 -1
  31. package/commands/RunProjectCommand.js.map +0 -1
  32. package/index.d.ts.map +0 -1
  33. package/index.js.map +0 -1
@@ -0,0 +1,56 @@
1
+ ---
2
+ id: statistics
3
+ title: 'Upgrading to v4: crawler statistics'
4
+ sidebar_label: Crawler statistics
5
+ sidebar_position: 4
6
+ slug: /upgrading/upgrading-to-v4/statistics
7
+ ---
8
+
9
+ Applies when you passed `statisticsOptions` to a crawler, subclassed `Statistics`, or passed type arguments to `BrowserCrawler`/`BrowserCrawlerOptions`. This page is part of the [Upgrading to v4](./upgrading-v4.md) guide.
10
+
11
+ ## `statisticsOptions` is replaced by a `statistics` instance
12
+
13
+ The `statisticsOptions` option has been removed from the crawler constructor. Instead of passing options for the crawler to build its `Statistics` from, construct a `Statistics` instance yourself and pass it via the new `statistics` option — the same inject-or-default idiom as `sessionPool` and `browserPool`.
14
+
15
+ ```typescript
16
+ import { BasicCrawler, Statistics } from '@crawlee/basic';
17
+
18
+ const crawler = new BasicCrawler({
19
+ // The old parameter won't work anymore
20
+ // statisticsOptions: { saveErrorSnapshots: true },
21
+ statistics: new Statistics({ saveErrorSnapshots: true }),
22
+ });
23
+ ```
24
+
25
+ Omit the option and the crawler builds its own default, exactly as before. A supplied instance is treated as borrowed: the crawler records into it and drives its capture lifecycle for the run, but never `reset()`s it between `run()` calls — so a preconfigured instance keeps whatever state it was handed.
26
+
27
+ The option accepts the built-in `Statistics` or any object implementing the new `IStatistics` interface, so a fully custom statistics backend can be plugged in without subclassing. The crawler exposes it as `crawler.statistics` (renamed from `crawler.stats`) typed as `IStatistics`.
28
+
29
+ ## The request-recording methods are renamed
30
+
31
+ A crawler processes requests, not jobs, so the three methods for recording them dropped the borrowed vocabulary. Signatures are unchanged, so a custom implementation only needs renaming:
32
+
33
+ - `startJob()` -> `recordRequestStart()`
34
+ - `finishJob()` -> `recordRequestSuccess()`
35
+ - `failJob()` -> `recordRequestFailure()`
36
+
37
+ `IStatistics` also requires a fourth method that v3 did not have, `discardRequestRecord(id)`.
38
+
39
+ ## The `Statistics` persistence lifecycle is stricter
40
+
41
+ `persistState()` and `resetStore()` no longer take `PersistenceOptions` — persistence is enabled or disabled once, in the constructor. `resetStore()` throws while the instance is capturing, where the next `PERSIST_STATE` event would write the record straight back; call it before `startCapturing()` or after `stopCapturing()`. And `reset()` only resets the counters — it no longer stops an ongoing capture, which `stopCapturing()` does.
42
+
43
+ A persisted record is also validated on load now. One that does not match the expected shape is discarded whole, with a warning, and the statistics start from scratch — where v3 would copy the malformed values into the live state and let them corrupt every later increment. Custom fields are scoped the same way: when `stateExtension.deserialize` throws, only those fields restart and the built-in counters are kept.
44
+
45
+ ## Subclassing `Statistics` to track extra fields is replaced by the `stateExtension` option
46
+
47
+ `persistStateKey` and `_maybeLoadStatistics()` were `protected` and are now private (`toJSON()` stays public). Declare extra fields via the new `stateExtension` option instead — `{ defaultState, deserialize, serialize }`, the same trio `RecoverableState` takes, scoped to the custom fields. See the [Custom statistics fields](https://crawlee.dev/js/docs/next/guides/custom-statistics) guide.
48
+
49
+ The persisted record is now validated strictly, and keys that are neither built-in nor declared in `stateExtension` are dropped rather than written back. `calculate()` is still public and still an override point.
50
+
51
+ The custom field types reach `crawler.statistics.state` through a new trailing `StatisticStateExtension` type parameter on the crawler classes and their options. It defaults to `{}`, so existing type arguments keep working — except on `BrowserCrawler`, where it was inserted after `Routes`, ahead of the trailing `GoToOptions` parameter. Adjust any explicit type arguments you passed there.
52
+
53
+ `AdaptivePlaywrightCrawler` now uses this mechanism for its own extra fields, with two consequences:
54
+
55
+ - `httpOnlyRequestHandlerRuns`, `browserRequestHandlerRuns` and `renderingTypeMispredictions` were typed as optional and are now always present. Reading them no longer needs a `?? 0`.
56
+ - The `statistics` option accepts any `IStatistics<AdaptivePlaywrightCrawlerStatisticState>`. Build one by extending the exported `adaptivePlaywrightCrawlerStatisticState`.
@@ -0,0 +1,170 @@
1
+ ---
2
+ id: storage-backends
3
+ title: 'Upgrading to v4: storage backends'
4
+ sidebar_label: Storage backends
5
+ sidebar_position: 7
6
+ slug: /upgrading/upgrading-to-v4/storage-backends
7
+ ---
8
+
9
+ Applies when you implement your own storage backend, or reach below the `Dataset`, `KeyValueStore` and `RequestQueue` frontends. This page is part of the [Upgrading to v4](./upgrading-v4.md) guide.
10
+
11
+ ## `StorageBackend` interface simplified
12
+
13
+ The `StorageBackend` interface (from `@crawlee/types`, formerly named `StorageClient`) has been redesigned and simplified. A new storage backend now needs **4 classes** instead of the previous 7.
14
+
15
+ ### What changed
16
+
17
+ The three **collection client** interfaces have been removed:
18
+
19
+ - `DatasetCollectionClient`
20
+ - `KeyValueStoreCollectionClient`
21
+ - `RequestQueueCollectionClient`
22
+
23
+ Along with their associated types (`DatasetCollectionData`, `DatasetCollectionClientOptions`, and the `Dataset` interface from `@crawlee/types`).
24
+
25
+ The `StorageBackend` interface changed from synchronous sub-client getters to **async factory methods**:
26
+
27
+ | Before (v3) | After (v4) |
28
+ |---|---|
29
+ | `client.dataset(id)` | `backend.createDatasetBackend({ id?, name? })` |
30
+ | `client.datasets().getOrCreate(name)` | _(absorbed into `createDatasetBackend`)_ |
31
+ | `client.keyValueStore(id)` | `backend.createKeyValueStoreBackend({ id?, name? })` |
32
+ | `client.keyValueStores().getOrCreate(name)` | _(absorbed into `createKeyValueStoreBackend`)_ |
33
+ | `client.requestQueue(id, opts)` | `backend.createRequestQueueBackend({ id?, name? })` |
34
+ | `client.requestQueues().getOrCreate(name)` | _(absorbed into `createRequestQueueBackend`)_ |
35
+
36
+ The sub-backend interfaces (`DatasetBackend`, `KeyValueStoreBackend`, `RequestQueueBackend`, formerly `DatasetClient` / `KeyValueStoreClient` / `RequestQueueClient`) have been simplified:
37
+
38
+ | Before (v3) | After (v4) |
39
+ |---|---|
40
+ | `get()` | `getMetadata()` |
41
+ | `update()` | Removed |
42
+ | `delete()` | `drop()` |
43
+ | _(n/a)_ | `purge()` (new — clears data, keeps storage) |
44
+
45
+ **`DatasetBackend`:**
46
+
47
+ | Before (v3) | After (v4) |
48
+ |---|---|
49
+ | `pushItems(items: Data \| Data[] \| string \| string[])` | `pushData(items: Data[])` |
50
+ | `listItems(options?)` (dual iterable) | `getData(options?)` (returns a single `PaginatedList` page) |
51
+ | `listEntries(options?)` | Removed (handled by `Dataset` frontend) |
52
+ | `downloadItems()` | Removed |
53
+
54
+ **`KeyValueStoreBackend`:**
55
+
56
+ | Before (v3) | After (v4) |
57
+ |---|---|
58
+ | `getRecord(key, options?)` | `getValue(key)` |
59
+ | `setRecord(record, options?)` | `setValue(record)` |
60
+ | `deleteRecord(key)` | `deleteValue(key)` |
61
+ | `getRecordPublicUrl(key)` | `getPublicUrl(key)` |
62
+ | `listKeys(options?)` → `KeyValueStoreClientListData` | `listKeys(options?)` → `KeyValueStoreListKeysResult` (a single self-describing page) |
63
+ | `keys()`, `values()`, `entries()` | Removed (handled by `KeyValueStore` frontend) |
64
+
65
+ **`RequestQueueBackend`:**
66
+
67
+ The request queue backend's surface was reshaped. The frontend-owned distributed-locking protocol (`listAndLockHead` → `prolongRequestLock` → `deleteRequestLock`) was removed. Queue-head and consistency bookkeeping are now internal concerns of the backend implementation.
68
+
69
+ | Before (v3) | After (v4) |
70
+ |---|---|
71
+ | `addRequest(request, opts?)` | `addBatchOfRequests([request], opts?)` |
72
+ | `batchAddRequests(requests, opts?)` | `addBatchOfRequests(requests, opts?)` |
73
+ | `getRequest(id)` | `getRequest(uniqueKey)` |
74
+ | `updateRequest(request, opts?)` | `markRequestAsHandled(request)` / `reclaimRequest(request, opts?)` |
75
+ | `listHead(opts?)` | `fetchNextRequest()` (returns a single request, marks it in progress) |
76
+ | `listAndLockHead(opts)` | Removed (locking is internal to the client) |
77
+ | `prolongRequestLock(id, opts)` | `extendRequestProcessingTime(requestId, extensionSecs)` (optional — per-request lock extension for locking backends; wired to `context.extendTimeout`) |
78
+ | `deleteRequestLock(id, opts?)` | Removed |
79
+ | `deleteRequest(id)` | Removed |
80
+ | _(n/a)_ | `isEmpty()` (new — `true` when no pending requests are left to fetch) |
81
+ | _(n/a)_ | `isFinished()` (new — `true` when no pending **and** no in-progress requests remain) |
82
+
83
+ The lifecycle is now: `fetchNextRequest()` hands out a pending request and marks it in progress; once processed, call `markRequestAsHandled(request)`; on failure call `reclaimRequest(request, { forefront? })` to return it to the queue.
84
+
85
+ Methods that may have "nothing" to return now consistently resolve to `undefined` rather than `null`. `fetchNextRequest()` resolves to `undefined` when there is nothing to fetch, and `markRequestAsHandled()` / `reclaimRequest()` resolve to `undefined` when the request is not something the backend is currently processing (not an error; a backend may still apply the operation, as the memory backend does, but the result stays `undefined`). This matches the `undefined` already returned by `getRequest()`, `KeyValueStoreBackend.getValue()`, and `getPublicUrl()`, so the whole backend family uses a single "absent" sentinel. If you implemented a custom backend that returned `null` from these methods, return `undefined` instead.
86
+
87
+ `RequestQueueBackend.isEmpty()` and `RequestQueueBackend.isFinished()` answer two different questions:
88
+
89
+ - `isEmpty()` is the weak check — `true` when the next `fetchNextRequest()` would return `undefined`, i.e. there is nothing left to fetch right now. Requests that are currently in progress (fetched but not yet handled or reclaimed) are **not** counted, because they are not fetchable. This is what drives the crawler's task scheduling.
90
+ - `isFinished()` is the strong check — `true` only when there are no pending requests **and** no requests currently in progress (including those locked by other clients sharing the queue). This is what determines whether crawling is actually done. An in-progress request keeps the queue *empty but not finished*, which is what stops a crawler from shutting down while a request is still being processed.
91
+
92
+ The loader and manager frontends do **not** draw that distinction — `IRequestLoader` and `IRequestManager` answer both questions with one [`checkReadiness()`](./request-loaders.md#isempty--isfinished-replaced-by-checkreadiness) call. The split lives at the backend boundary because that is the layer where the two questions really are two separate storage lookups; a frontend that split them too would either probe twice per scheduling decision or lose the distinction, whereas a backend that answers one at a time costs its caller nothing.
93
+
94
+ The separate `RequestQueueV1`/`RequestQueueV2` classes (and the `RequestProvider` base class) have been removed. They no longer differ in behavior — request coordination is now internal to the storage backend — so they are merged into a single `RequestQueue` class. Replace any `RequestQueueV1`, `RequestQueueV2`, or `RequestProvider` imports with `RequestQueue`.
95
+
96
+ The `requestLocking` crawler experiment has been removed, along with the `experiments` crawler option and the `CrawlerExperiments` type that contained it. Request locking has been the default since v3.10 and there is no longer an alternative implementation to opt out to, so the flag did nothing. Delete any `experiments: { requestLocking: ... }` from your crawler options:
97
+
98
+ ```diff
99
+ const crawler = new CheerioCrawler({
100
+ async requestHandler({ $, request }) {
101
+ // ...
102
+ },
103
+ - experiments: {
104
+ - requestLocking: true,
105
+ - },
106
+ });
107
+ ```
108
+
109
+ The `RequestQueue.requestLockSecs` property has been removed. Because request locking is now internal to the storage backend, the lock duration is no longer configured on the queue. When you run a crawler, it automatically tells the queue how long it expects to hold a request (based on `requestHandlerTimeoutMillis`), so a long-running request handler will not have its request handed out a second time — you usually don't need to configure anything.
110
+
111
+ If you use a `RequestQueue` outside of a crawler and your processing may exceed the 3-minute default lock, call `setExpectedRequestProcessingTime(processingTimeSecs)` on the queue to raise it:
112
+
113
+ ```typescript
114
+ import { RequestQueue } from 'crawlee';
115
+
116
+ const queue = await RequestQueue.open();
117
+ await queue.setExpectedRequestProcessingTime(600);
118
+ ```
119
+
120
+ The `RequestQueue.internalTimeoutMillis` property and the associated "stuck queue" self-recovery have been removed. In v3 the `RequestQueue` frontend kept its own copy of the queue head and in-progress set, which could drift out of sync with the backing storage (an eventual-consistency hazard on the Apify platform); `isFinished()` watched for inactivity exceeding `internalTimeoutMillis` and reset that frontend state to recover. In v4 the frontend no longer holds any such bookkeeping — the storage backend is the single source of truth — so there is nothing for a reset to fix, and stuck request locks now self-heal on expiry. Any consistency-recovery logic that is genuinely specific to the Apify platform's distributed storage belongs in the Apify SDK's client implementation instead, and is tracked in [apify/crawlee#3328](https://github.com/apify/crawlee/issues/3328).
121
+
122
+ **Apify-specific fields removed from storage metadata.** The metadata returned by `getMetadata()` (`DatasetInfo`, `KeyValueStoreInfo`, `RequestQueueInfo`) has been trimmed to what is meaningful for any storage backend. The following platform-specific fields were dropped: `actId`, `actRunId`, `userId`, and — on `RequestQueueInfo` — `expireAt` and `hadMultipleClients`. The per-storage `stats` field (and its `DatasetStats` / `KeyValueStoreStats` / `RequestQueueStats` types) was removed as well. If you consumed any of these, read them from the Apify API client directly; a custom `StorageBackend` should simply stop returning them.
123
+
124
+ **Removed types** from `@crawlee/types`: `DatasetClientUpdateOptions`, `KeyValueStoreClientUpdateOptions`, `KeyValueStoreRecordOptions`, `KeyValueStoreClientListData`, `KeyValueStoreClientGetRecordOptions`, `QueueHead`, `RequestQueueHeadItem`, `ListOptions`, `ListAndLockOptions`, `ListAndLockHeadResult`, `ProlongRequestLockOptions`, `ProlongRequestLockResult`, `DeleteRequestLockOptions`, `DatasetStats`, `KeyValueStoreStats`, `RequestQueueStats`. `KeyValueStoreClientListOptions` was renamed to `KeyValueStoreListKeysOptions`.
125
+
126
+ The high-level storage classes (`Dataset`, `KeyValueStore`, `RequestQueue`) are now thin wrappers over a single sub-backend, which they receive directly in the constructor options. The constructor takes `{ metadata, backend }`, where `backend` is the sub-backend and `metadata` is the resolved storage info (as returned by the backend's `getMetadata()`) that the storage derives its `id` and `name` from — instead of receiving separate `id` / `name` arguments (or a `StorageBackend` and calling its methods). In practice you never call these constructors yourself; use `Dataset.open()` / `KeyValueStore.open()` / `RequestQueue.open()`, which resolve the metadata and open the backend for you.
127
+
128
+ `RequestQueue` no longer accepts (or stores) `clientKey` / `timeoutSecs`. These are request-locking concerns that are now internal to the storage backend implementation (see [apify/crawlee#3328](https://github.com/apify/crawlee/issues/3328)); the `create*Backend` methods take a plain `StorageIdentifier` (`{ id?, name?, alias? }`).
129
+
130
+ ### `RecordOptions` simplified
131
+
132
+ `timeoutSecs` and `doNotRetryTimeouts` were removed from `RecordOptions` (used by `KeyValueStore.setValue`). Only `contentType` remains.
133
+
134
+ ### `maybeStringify` is removed
135
+
136
+ The `maybeStringify` helper exported from `@crawlee/core` has been removed. Value (de)serialization now lives entirely in the `KeyValueStore` frontend: writing serializes the value (and infers its content type), reading parses it back, and the storage backend is a plain byte transport. If you imported `maybeStringify` directly, use the `serializeValue` / `parseValue` functions exported from `@crawlee/core` instead.
137
+
138
+ ### `KeyValueStoreIteratorOptions` simplified
139
+
140
+ `exclusiveStartKey` and `collection` were removed. Only `prefix` remains.
141
+
142
+ ### `Dataset.listItems` replaced by `Dataset.getData` and `Dataset.values`
143
+
144
+ `Dataset.listItems()` is replaced by two methods:
145
+ - `Dataset.getData(options?)` — returns a single `PaginatedList<Data>` page.
146
+ - `Dataset.values(options?)` — dual iterable: `for await...of` iterates all items; `await` returns all items as `Data[]`.
147
+
148
+ `Dataset.entries()` works the same way as `values()` but yields `[index, Data]` tuples. `KeyValueStore.keys()`, `.values()`, `.entries()` follow the same dual-iterable pattern.
149
+
150
+ ### Removed `list()` method
151
+
152
+ The `list()` method on collection clients (e.g. `client.datasets().list()`) has no replacement. If you were using it to enumerate all storages, you will need to use the Apify API client directly.
153
+
154
+ ### Migration guide
155
+
156
+ If you implemented a custom `StorageBackend`, you need to:
157
+
158
+ 1. Remove your `*CollectionClient` classes.
159
+ 2. Replace the six getter methods (`dataset`, `datasets`, `keyValueStore`, `keyValueStores`, `requestQueue`, `requestQueues`) with three async factory methods (`createDatasetBackend`, `createKeyValueStoreBackend`, `createRequestQueueBackend`). Each factory should handle both opening an existing storage and creating a new one.
160
+ 3. Apply the sub-backend renames listed above (`get` → `getMetadata`, `delete` → `drop`, etc.) and implement the new `purge()` method.
161
+
162
+ ## Storage internals are no longer part of the public API
163
+
164
+ `DatasetOptions`, `KeyValueStoreOptions` and `RequestQueueOptions` are internal. They only described the arguments of the storage constructors, which were already internal — always open storages through the static `open()` methods.
165
+
166
+ ## `Dataset` field visibility now matches its siblings
167
+
168
+ - `Dataset.client` is now `Dataset.backend`, matching `KeyValueStore.backend` and `RequestQueue.backend`. Prefer the `Dataset` methods (`pushData`, `getData`, `getInfo`, `drop`, ...) over reaching for the backend.
169
+ - `Dataset.id` and `Dataset.name` are `readonly`, matching `KeyValueStore` and `RequestQueue`.
170
+ - `Dataset.log` has been removed. It was never read by Crawlee and `KeyValueStore` never had it; use your own logger, or `crawler.log` inside a request handler.