@crawlee/http 4.0.0-beta.14 → 4.0.0-beta.141

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
@@ -1,23 +1,23 @@
1
1
  <h1 align="center">
2
2
  <a href="https://crawlee.dev">
3
3
  <picture>
4
- <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-dark.svg?sanitize=true">
5
- <img alt="Crawlee" src="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-light.svg?sanitize=true" width="500">
4
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-dark.svg?sanitize=true" />
5
+ <img alt="Crawlee" src="https://raw.githubusercontent.com/apify/crawlee/master/website/static/img/crawlee-light.svg?sanitize=true" width="500" />
6
6
  </picture>
7
7
  </a>
8
- <br>
8
+ <br />
9
9
  <small>A web scraping and browser automation library</small>
10
10
  </h1>
11
11
 
12
- <p align=center>
13
- <a href="https://trendshift.io/repositories/5179" target="_blank"><img src="https://trendshift.io/api/badge/repositories/5179" alt="apify%2Fcrawlee | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
12
+ <p align="center">
13
+ <a href="https://trendshift.io/repositories/5179" target="_blank"><img src="https://trendshift.io/api/badge/repositories/5179" alt="apify%2Fcrawlee | Trendshift" width="250" height="55"/></a>
14
14
  </p>
15
15
 
16
- <p align=center>
17
- <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/v/@crawlee/core.svg" alt="NPM latest version" data-canonical-src="https://img.shields.io/npm/v/@crawlee/core/next.svg" style="max-width: 100%;"></a>
18
- <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/dm/@crawlee/core.svg" alt="Downloads" data-canonical-src="https://img.shields.io/npm/dm/@crawlee/core.svg" style="max-width: 100%;"></a>
19
- <a href="https://discord.gg/jyEM2PRvMU" rel="nofollow"><img src="https://img.shields.io/discord/801163717915574323?label=discord" alt="Chat on discord" data-canonical-src="https://img.shields.io/discord/801163717915574323?label=discord" style="max-width: 100%;"></a>
20
- <a href="https://github.com/apify/crawlee/actions/workflows/test-ci.yml"><img src="https://github.com/apify/crawlee/actions/workflows/test-ci.yml/badge.svg?branch=master" alt="Build Status" style="max-width: 100%;"></a>
16
+ <p align="center">
17
+ <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/v/@crawlee/core.svg" alt="NPM latest version" data-canonical-src="https://img.shields.io/npm/v/@crawlee/core/next.svg" /></a>
18
+ <a href="https://www.npmjs.com/package/@crawlee/core" rel="nofollow"><img src="https://img.shields.io/npm/dm/@crawlee/core.svg" alt="Downloads" data-canonical-src="https://img.shields.io/npm/dm/@crawlee/core.svg" /></a>
19
+ <a href="https://discord.gg/jyEM2PRvMU" rel="nofollow"><img src="https://img.shields.io/discord/801163717915574323?label=discord" alt="Chat on discord" data-canonical-src="https://img.shields.io/discord/801163717915574323?label=discord" /></a>
20
+ <a href="https://github.com/apify/crawlee/actions/workflows/test-ci.yml"><img src="https://github.com/apify/crawlee/actions/workflows/test-ci.yml/badge.svg?branch=master" alt="Build Status" /></a>
21
21
  </p>
22
22
 
23
23
  Crawlee covers your crawling and scraping end-to-end and **helps you build reliable scrapers. Fast.**
@@ -89,7 +89,7 @@ By default, Crawlee stores data to `./storage` in the current working directory.
89
89
  We provide automated beta builds for every merged code change in Crawlee. You can find them in the npm [list of releases](https://www.npmjs.com/package/crawlee?activeTab=versions). If you want to test new features or bug fixes before we release them, feel free to install a beta build like this:
90
90
 
91
91
  ```bash
92
- npm install crawlee@3.12.3-beta.13
92
+ npm install crawlee@next
93
93
  ```
94
94
 
95
95
  If you also use the [Apify SDK](https://github.com/apify/apify-sdk-js), you need to specify dependency overrides in your `package.json` file so that you don't end up with multiple versions of Crawlee installed:
@@ -98,9 +98,9 @@ If you also use the [Apify SDK](https://github.com/apify/apify-sdk-js), you need
98
98
  {
99
99
  "overrides": {
100
100
  "apify": {
101
- "@crawlee/core": "3.12.3-beta.13",
102
- "@crawlee/types": "3.12.3-beta.13",
103
- "@crawlee/utils": "3.12.3-beta.13"
101
+ "@crawlee/core": "$crawlee",
102
+ "@crawlee/types": "$crawlee",
103
+ "@crawlee/utils": "$crawlee"
104
104
  }
105
105
  }
106
106
  }
package/index.d.ts CHANGED
@@ -1,4 +1,3 @@
1
1
  export * from '@crawlee/basic';
2
2
  export * from './internals/http-crawler.js';
3
3
  export * from './internals/file-download.js';
4
- //# sourceMappingURL=index.d.ts.map
package/index.js CHANGED
@@ -1,4 +1,3 @@
1
1
  export * from '@crawlee/basic';
2
2
  export * from './internals/http-crawler.js';
3
3
  export * from './internals/file-download.js';
4
- //# sourceMappingURL=index.js.map
@@ -1,10 +1,11 @@
1
1
  import { Transform } from 'node:stream';
2
2
  import type { BasicCrawlerOptions } from '@crawlee/basic';
3
3
  import { BasicCrawler } from '@crawlee/basic';
4
- import type { CrawlingContext, LoadedRequest, Request } from '@crawlee/core';
4
+ import type { ContextPipeline, CrawlingContext, LoadedRequest, Request } from '@crawlee/core';
5
5
  import type { Dictionary } from '@crawlee/types';
6
- import type { ErrorHandler, GetUserDataFromRequest, InternalHttpHook, RequestHandler, RouterRoutes } from '../index.js';
7
- export type FileDownloadErrorHandler<UserData extends Dictionary = any> = ErrorHandler<FileDownloadCrawlingContext<UserData>>;
6
+ import type { ErrorHandler, GetUserDataFromRequest, InternalHttpHook, RequestHandler, RouterHandler, RouterRoutes, RouteSchemas, RoutesFromSchemas } from '../index.js';
7
+ export type FileDownloadErrorHandler<UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
8
+ ContextExtension = Dictionary<never>> = ErrorHandler<CrawlingContext, FileDownloadCrawlingContext<UserData> & ContextExtension>;
8
9
  export type FileDownloadHook<UserData extends Dictionary = any> = InternalHttpHook<FileDownloadCrawlingContext<UserData>>;
9
10
  export interface FileDownloadCrawlingContext<UserData extends Dictionary = any> extends CrawlingContext<UserData> {
10
11
  request: LoadedRequest<Request<UserData>>;
@@ -49,23 +50,23 @@ export declare function ByteCounterStream({ logTransferredBytes, loggingInterval
49
50
  *
50
51
  * `FileCrawler` downloads each URL using a plain HTTP request and then invokes the user-provided {@link FileDownloadOptions.requestHandler} where the user can specify what to do with the downloaded data.
51
52
  *
52
- * The source URLs are represented using {@link Request} objects that are fed from {@link RequestList} or {@link RequestQueue} instances provided by the {@link FileDownloadOptions.requestList} or {@link FileDownloadOptions.requestQueue} constructor options, respectively.
53
+ * The source URLs are represented using {@link Request} objects that are fed from the {@link IRequestManager|request manager} provided via the {@link FileDownloadOptions.requestManager|`requestManager`} constructor option (a {@link RequestQueue} is itself a request manager). To read from a read-only source such as a {@link RequestList} while still being able to enqueue new requests, combine it with a queue into a {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the result as `requestManager`.
53
54
  *
54
- * If both {@link FileDownloadOptions.requestList} and {@link FileDownloadOptions.requestQueue} are used, the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them to {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
55
+ * > The {@link FileDownloadOptions.requestList|`requestList`} and {@link FileDownloadOptions.requestQueue|`requestQueue`} options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
55
56
  *
56
57
  * The crawler finishes when there are no more {@link Request} objects to crawl.
57
58
  *
58
- * We can use the `preNavigationHooks` to adjust `gotOptions`:
59
+ * We can use the `preNavigationHooks` to adjust the crawling context before the request is made:
59
60
  *
60
61
  * ```
61
62
  * preNavigationHooks: [
62
- * (crawlingContext, gotOptions) => {
63
+ * (crawlingContext) => {
63
64
  * // ...
64
65
  * },
65
66
  * ]
66
67
  * ```
67
68
  *
68
- * New requests are only dispatched when there is enough free CPU and memory available, using the functionality provided by the {@link AutoscaledPool} class. All {@link AutoscaledPool} configuration options can be passed to the `autoscaledPoolOptions` parameter of the `FileCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency` {@link AutoscaledPool} options are available directly in the `FileCrawler` constructor.
69
+ * New requests are only dispatched when there is enough free CPU and memory available, as judged by the crawler's {@link ConcurrencySystem}. Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the `FileCrawler` constructor, or, for finer control, by injecting a pre-configured {@link ConcurrencySystem|`concurrencySystem`}.
69
70
  *
70
71
  * ## Example usage
71
72
  *
@@ -85,6 +86,7 @@ export declare function ByteCounterStream({ logTransferredBytes, loggingInterval
85
86
  */
86
87
  export declare class FileDownload extends BasicCrawler<FileDownloadCrawlingContext> {
87
88
  constructor(options?: BasicCrawlerOptions<FileDownloadCrawlingContext>);
89
+ protected buildContextPipeline(): ContextPipeline<CrawlingContext, FileDownloadCrawlingContext>;
88
90
  private initiateDownload;
89
91
  }
90
92
  /**
@@ -111,6 +113,6 @@ export declare class FileDownload extends BasicCrawler<FileDownloadCrawlingConte
111
113
  * await crawler.run();
112
114
  * ```
113
115
  */
114
- // @ts-ignore optional peer dependency or compatibility with es2022
115
- export declare function createFileRouter<Context extends FileDownloadCrawlingContext = FileDownloadCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, UserData>): import("@crawlee/basic").RouterHandler<Context>;
116
- //# sourceMappingURL=file-download.d.ts.map
116
+ export declare function createFileRouter<Context extends FileDownloadCrawlingContext = FileDownloadCrawlingContext, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<Context['request']>>>(routes?: RouterRoutes<Context, Routes>): RouterHandler<Context, Routes>;
117
+ export declare function createFileRouter<Context extends FileDownloadCrawlingContext = FileDownloadCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, Record<string, UserData>>): RouterHandler<Context, Record<string, UserData>>;
118
+ export declare function createFileRouter<Context extends FileDownloadCrawlingContext = FileDownloadCrawlingContext, const Schemas extends RouteSchemas = RouteSchemas>(schemas: Schemas): RouterHandler<Context, RoutesFromSchemas<Schemas>>;
@@ -1,8 +1,9 @@
1
1
  import { Transform } from 'node:stream';
2
- import { finished } from 'node:stream/promises';
3
- import { BasicCrawler, ContextPipeline } from '@crawlee/basic';
2
+ import { BasicCrawler } from '@crawlee/basic';
3
+ import { ResponseWithUrl } from '@crawlee/http-client';
4
4
  import { Router } from '../index.js';
5
5
  import { parseContentTypeFromResponse } from './utils.js';
6
+ const kBodyDrained = Symbol('bodyDrained');
6
7
  /**
7
8
  * Creates a transform stream that throws an error if the source data speed is below the specified minimum speed.
8
9
  * This `Transform` checks the amount of data every `checkProgressInterval` milliseconds.
@@ -70,23 +71,23 @@ export function ByteCounterStream({ logTransferredBytes, loggingInterval = 5000,
70
71
  *
71
72
  * `FileCrawler` downloads each URL using a plain HTTP request and then invokes the user-provided {@link FileDownloadOptions.requestHandler} where the user can specify what to do with the downloaded data.
72
73
  *
73
- * The source URLs are represented using {@link Request} objects that are fed from {@link RequestList} or {@link RequestQueue} instances provided by the {@link FileDownloadOptions.requestList} or {@link FileDownloadOptions.requestQueue} constructor options, respectively.
74
+ * The source URLs are represented using {@link Request} objects that are fed from the {@link IRequestManager|request manager} provided via the {@link FileDownloadOptions.requestManager|`requestManager`} constructor option (a {@link RequestQueue} is itself a request manager). To read from a read-only source such as a {@link RequestList} while still being able to enqueue new requests, combine it with a queue into a {@link RequestManagerTandem} via {@link IRequestLoader.toTandem|`requestLoader.toTandem()`} and pass the result as `requestManager`.
74
75
  *
75
- * If both {@link FileDownloadOptions.requestList} and {@link FileDownloadOptions.requestQueue} are used, the instance first processes URLs from the {@link RequestList} and automatically enqueues all of them to {@link RequestQueue} before it starts their processing. This ensures that a single URL is not crawled multiple times.
76
+ * > The {@link FileDownloadOptions.requestList|`requestList`} and {@link FileDownloadOptions.requestQueue|`requestQueue`} options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
76
77
  *
77
78
  * The crawler finishes when there are no more {@link Request} objects to crawl.
78
79
  *
79
- * We can use the `preNavigationHooks` to adjust `gotOptions`:
80
+ * We can use the `preNavigationHooks` to adjust the crawling context before the request is made:
80
81
  *
81
82
  * ```
82
83
  * preNavigationHooks: [
83
- * (crawlingContext, gotOptions) => {
84
+ * (crawlingContext) => {
84
85
  * // ...
85
86
  * },
86
87
  * ]
87
88
  * ```
88
89
  *
89
- * New requests are only dispatched when there is enough free CPU and memory available, using the functionality provided by the {@link AutoscaledPool} class. All {@link AutoscaledPool} configuration options can be passed to the `autoscaledPoolOptions` parameter of the `FileCrawler` constructor. For user convenience, the `minConcurrency` and `maxConcurrency` {@link AutoscaledPool} options are available directly in the `FileCrawler` constructor.
90
+ * New requests are only dispatched when there is enough free CPU and memory available, as judged by the crawler's {@link ConcurrencySystem}. Concurrency is tuned via the `minConcurrency`, `maxConcurrency` and `maxRequestsPerMinute` options of the `FileCrawler` constructor, or, for finer control, by injecting a pre-configured {@link ConcurrencySystem|`concurrencySystem`}.
90
91
  *
91
92
  * ## Example usage
92
93
  *
@@ -109,55 +110,58 @@ export class FileDownload extends BasicCrawler {
109
110
  constructor(options = {}) {
110
111
  super({
111
112
  ...options,
112
- contextPipelineBuilder: () => ContextPipeline.create().compose({
113
- action: async (context) => this.initiateDownload(context),
114
- cleanup: async (context) => {
115
- await (context.response.body ? finished(context.response.body) : Promise.resolve());
116
- },
117
- }),
113
+ contextPipelineBuilder: () => this.buildContextPipeline(),
114
+ });
115
+ }
116
+ buildContextPipeline() {
117
+ return super.buildContextPipeline().compose({
118
+ action: async (context) => this.initiateDownload(context),
119
+ cleanup: async (context) => {
120
+ if (!context.response.bodyUsed) {
121
+ // Nobody consumed the body — cancel it so the
122
+ // underlying connection can be released.
123
+ await context.response.body?.cancel();
124
+ }
125
+ await context[kBodyDrained];
126
+ },
118
127
  });
119
128
  }
120
129
  async initiateDownload(context) {
121
- const response = await this.httpClient.stream({
122
- url: context.request.url,
123
- timeout: { request: undefined },
124
- proxyUrl: context.proxyInfo?.url,
130
+ const response = await this.httpClient.sendRequest(context.request.intoFetchAPIRequest(), {
131
+ session: context.session,
125
132
  });
126
133
  const { type, charset: encoding } = parseContentTypeFromResponse(response);
127
134
  context.request.url = response.url;
135
+ const { response: trackedResponse, bodyDrained } = trackBodyConsumption(response);
128
136
  const contextExtension = {
129
137
  request: context.request,
130
- response,
138
+ response: trackedResponse,
131
139
  contentType: { type, encoding },
140
+ [kBodyDrained]: bodyDrained,
132
141
  };
133
142
  return contextExtension;
134
143
  }
135
144
  }
136
145
  /**
137
- * Creates new {@link Router} instance that works based on request labels.
138
- * This instance can then serve as a `requestHandler` of your {@link FileDownload}.
139
- * Defaults to the {@link FileDownloadCrawlingContext}.
140
- *
141
- * > Serves as a shortcut for using `Router.create<FileDownloadCrawlingContext>()`.
142
- *
143
- * ```ts
144
- * import { FileDownload, createFileRouter } from 'crawlee';
145
- *
146
- * const router = createFileRouter();
147
- * router.addHandler('label-a', async (ctx) => {
148
- * ctx.log.info('...');
149
- * });
150
- * router.addDefaultHandler(async (ctx) => {
151
- * ctx.log.info('...');
152
- * });
153
- *
154
- * const crawler = new FileDownload({
155
- * requestHandler: router,
156
- * });
157
- * await crawler.run();
158
- * ```
146
+ * Wraps a Response so that we can track when the body stream has been fully
147
+ * consumed (or errored). Pipes the original body through a TransformStream;
148
+ * the readable side becomes the new Response body, and `pipeTo` gives us a
149
+ * promise that resolves once the body is fully read or cancelled.
159
150
  */
160
- export function createFileRouter(routes) {
161
- return Router.create(routes);
151
+ function trackBodyConsumption(response) {
152
+ if (!response.body) {
153
+ return { response, bodyDrained: Promise.resolve() };
154
+ }
155
+ const passthrough = new TransformStream();
156
+ const bodyDrained = response.body.pipeTo(passthrough.writable).catch(() => { });
157
+ const trackedResponse = new ResponseWithUrl(passthrough.readable, {
158
+ headers: response.headers,
159
+ status: response.status,
160
+ statusText: response.statusText,
161
+ url: response.url,
162
+ });
163
+ return { response: trackedResponse, bodyDrained };
164
+ }
165
+ export function createFileRouter(routesOrSchemas) {
166
+ return Router.create(routesOrSchemas);
162
167
  }
163
- //# sourceMappingURL=file-download.js.map