@crawlee/http 4.0.0-beta.2 → 4.0.0-beta.200

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,19 +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://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>
14
- <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>
15
- <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>
16
- <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>
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
+ </p>
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" /></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>
17
21
  </p>
18
22
 
19
23
  Crawlee covers your crawling and scraping end-to-end and **helps you build reliable scrapers. Fast.**
@@ -24,7 +28,7 @@ Crawlee is available as the [`crawlee`](https://www.npmjs.com/package/crawlee) N
24
28
 
25
29
  > 👉 **View full documentation, guides and examples on the [Crawlee project website](https://crawlee.dev)** 👈
26
30
 
27
- > Crawlee for Python is open for early adopters. 🐍 [👉 Checkout the source code 👈](https://github.com/apify/crawlee-python).
31
+ > Do you prefer 🐍 Python instead of JavaScript? [👉 Checkout Crawlee for Python 👈](https://github.com/apify/crawlee-python).
28
32
 
29
33
  ## Installation
30
34
 
@@ -85,7 +89,7 @@ By default, Crawlee stores data to `./storage` in the current working directory.
85
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:
86
90
 
87
91
  ```bash
88
- npm install crawlee@3.12.3-beta.13
92
+ npm install crawlee@next
89
93
  ```
90
94
 
91
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:
@@ -94,9 +98,9 @@ If you also use the [Apify SDK](https://github.com/apify/apify-sdk-js), you need
94
98
  {
95
99
  "overrides": {
96
100
  "apify": {
97
- "@crawlee/core": "3.12.3-beta.13",
98
- "@crawlee/types": "3.12.3-beta.13",
99
- "@crawlee/utils": "3.12.3-beta.13"
101
+ "@crawlee/core": "$crawlee",
102
+ "@crawlee/types": "$crawlee",
103
+ "@crawlee/utils": "$crawlee"
100
104
  }
101
105
  }
102
106
  }
package/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export * from '@crawlee/basic';
2
2
  export * from './internals/http-crawler.js';
3
+ export * from './internals/dom-crawler.js';
3
4
  export * from './internals/file-download.js';
4
- //# sourceMappingURL=index.d.ts.map
package/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  export * from '@crawlee/basic';
2
2
  export * from './internals/http-crawler.js';
3
+ export * from './internals/dom-crawler.js';
3
4
  export * from './internals/file-download.js';
4
- //# sourceMappingURL=index.js.map
@@ -0,0 +1,131 @@
1
+ import type { AddRequestsBatchedResult, ContextPipeline, CrawlingContext, EnqueueLinksOptions, ExtractLinksOptions, GetUserDataFromRequest } from '@crawlee/basic';
2
+ import type { Awaitable, Dictionary } from '@crawlee/types';
3
+ import type { CheerioAPI } from 'cheerio';
4
+ import type { HttpCrawlerOptions, InternalHttpCrawlingContext } from './http-crawler.js';
5
+ import { HttpCrawler } from './http-crawler.js';
6
+ /**
7
+ * The minimum a {@link DOMParser} has to contribute to the crawling context - the serialized document, used by
8
+ * the {@link DOMCrawlingContext.parseWithCheerio|`parseWithCheerio`} helper.
9
+ */
10
+ export interface DOMParseResult {
11
+ body: string;
12
+ }
13
+ /**
14
+ * Turns a response body into a DOM representation and knows how to query it. Passing one to {@link DOMCrawler}
15
+ * is what makes the crawler jsdom-based, linkedom-based, or based on a DOM implementation of your own.
16
+ *
17
+ * **Example usage:**
18
+ * ```ts
19
+ * import { DOMCrawler } from 'crawlee';
20
+ * import type { DOMParser } from 'crawlee';
21
+ *
22
+ * const myParser: DOMParser<{ body: string }> = {
23
+ * // ...
24
+ * };
25
+ *
26
+ * const crawler = new DOMCrawler({
27
+ * parser: myParser,
28
+ * async requestHandler({ body }) {
29
+ * // ...
30
+ * },
31
+ * });
32
+ * ```
33
+ */
34
+ export interface DOMParser<Parsed extends DOMParseResult> {
35
+ /**
36
+ * The context members {@link DOMParser.parse|`parse`} contributes, mapped to `true`. Used to build the
37
+ * placeholders that report a helpful error when the members are accessed after `skipNavigation` - the `Record`
38
+ * type forces every key of `Parsed` to be listed, so the compiler catches an omission that would otherwise
39
+ * yield `undefined` (rather than throwing) after `skipNavigation`.
40
+ */
41
+ readonly placeholderMembers: Record<keyof Parsed & string, true>;
42
+ parse(context: InternalHttpCrawlingContext): Awaitable<Parsed>;
43
+ /**
44
+ * Returns the URLs the `selector` matches, resolved against `baseUrl`.
45
+ */
46
+ extractLinks(parsed: Parsed, selector: string, baseUrl: string): Awaitable<string[]>;
47
+ /**
48
+ * Returns the current matches of `selector`. Only the count is used, by
49
+ * {@link DOMCrawlingContext.waitForSelector|`waitForSelector`}.
50
+ */
51
+ select(parsed: Parsed, selector: string): Awaitable<ArrayLike<unknown>>;
52
+ /**
53
+ * Whether the parse result can change after {@link DOMParser.parse|`parse`} returned - the case when the DOM
54
+ * implementation runs the page scripts. If it can, {@link DOMCrawlingContext.waitForSelector|`waitForSelector`}
55
+ * polls until the timeout elapses; otherwise it fails as soon as the selector does not match.
56
+ */
57
+ readonly mutable?: boolean;
58
+ /**
59
+ * Returns a Cheerio handle over the parse result, for parsers that are backed by Cheerio anyway. Without it,
60
+ * {@link DOMCrawlingContext.parseWithCheerio|`parseWithCheerio`} parses
61
+ * {@link DOMParseResult.body|`body`} again.
62
+ */
63
+ toCheerio?(parsed: Parsed): Awaitable<CheerioAPI>;
64
+ /**
65
+ * Releases whatever {@link DOMParser.parse|`parse`} allocated. Called after the request handler finishes or
66
+ * fails, and skipped entirely when navigation was skipped.
67
+ */
68
+ cleanup?(parsed: Parsed): Awaitable<void>;
69
+ }
70
+ export interface DOMCrawlingHelpers {
71
+ /**
72
+ * Extracts URLs from the parsed DOM, without adding them to the request queue.
73
+ */
74
+ extractLinks(options?: ExtractLinksOptions): Promise<string[]>;
75
+ /**
76
+ * Helper function for extracting URLs from the parsed DOM and adding them to the request queue.
77
+ */
78
+ enqueueLinks(options?: EnqueueLinksOptions): Promise<AddRequestsBatchedResult>;
79
+ /**
80
+ * Wait for an element matching the selector to appear. The `timeoutMs` only has an effect when the parser is
81
+ * {@link DOMParser.mutable|`mutable`} (e.g. {@link JSDOMCrawler} with `runScripts: true`); otherwise the
82
+ * selector is checked once and the call resolves or throws immediately.
83
+ * Timeout defaults to 5s.
84
+ *
85
+ * **Example usage:**
86
+ * ```ts
87
+ * async requestHandler({ waitForSelector, parseWithCheerio }) {
88
+ * await waitForSelector('article h1');
89
+ * const $ = await parseWithCheerio();
90
+ * const title = $('title').text();
91
+ * });
92
+ * ```
93
+ */
94
+ waitForSelector(selector: string, timeoutMs?: number): Promise<void>;
95
+ /**
96
+ * Returns Cheerio handle, allowing to work with the data same way as with {@link CheerioCrawler}.
97
+ * When provided with the `selector` argument, it will throw if it's not available.
98
+ *
99
+ * **Example usage:**
100
+ * ```javascript
101
+ * async requestHandler({ parseWithCheerio }) {
102
+ * const $ = await parseWithCheerio();
103
+ * const title = $('title').text();
104
+ * });
105
+ * ```
106
+ */
107
+ parseWithCheerio(selector?: string, timeoutMs?: number): Promise<CheerioAPI>;
108
+ }
109
+ export type DOMCrawlingContext<Parsed extends DOMParseResult = DOMParseResult, UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
110
+ JSONData extends Dictionary = any> = InternalHttpCrawlingContext<UserData, JSONData> & Parsed & DOMCrawlingHelpers;
111
+ export interface DOMCrawlerOptions<Parsed extends DOMParseResult = DOMParseResult, ContextExtension = Dictionary<never>, ExtendedContext extends DOMCrawlingContext<Parsed> = DOMCrawlingContext<Parsed> & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, any>, StatisticStateExtension extends object = {}> extends Omit<HttpCrawlerOptions<DOMCrawlingContext<Parsed>, ContextExtension, ExtendedContext, Routes, StatisticStateExtension>, 'contextPipelineBuilder'> {
112
+ /**
113
+ * The DOM implementation to parse the response bodies with. Its parse result becomes part of the crawling
114
+ * context, so the members the request handler receives follow from the parser you pass.
115
+ */
116
+ parser: DOMParser<Parsed>;
117
+ }
118
+ /**
119
+ * An {@link HttpCrawler} that parses each response into a DOM using the {@link DOMCrawlerOptions.parser|`parser`}
120
+ * it is given, and exposes the parse result plus the {@link DOMCrawlingContext.enqueueLinks|`enqueueLinks`} and
121
+ * {@link DOMCrawlingContext.extractLinks|`extractLinks`} helpers on the crawling context.
122
+ *
123
+ * {@link JSDOMCrawler} and {@link LinkeDOMCrawler} are this crawler with a parser already chosen.
124
+ *
125
+ * @category Crawlers
126
+ */
127
+ export declare class DOMCrawler<Parsed extends DOMParseResult = DOMParseResult, ContextExtension = Dictionary<never>, ExtendedContext extends DOMCrawlingContext<Parsed> = DOMCrawlingContext<Parsed> & ContextExtension, Routes extends Record<keyof Routes, Dictionary> = Record<string, GetUserDataFromRequest<DOMCrawlingContext<Parsed>['request']>>, StatisticStateExtension extends object = {}> extends HttpCrawler<DOMCrawlingContext<Parsed>, ContextExtension, ExtendedContext, Routes, StatisticStateExtension> {
128
+ #private;
129
+ constructor(options: DOMCrawlerOptions<Parsed, ContextExtension, ExtendedContext, Routes, StatisticStateExtension>);
130
+ protected buildContextPipeline(): ContextPipeline<CrawlingContext, DOMCrawlingContext<Parsed>>;
131
+ }
@@ -0,0 +1,93 @@
1
+ import { EnqueueStrategy, NavigationSkippedError, resolveBaseUrlForEnqueueLinksFiltering } from '@crawlee/basic';
2
+ import { sleep } from '@crawlee/utils';
3
+ import { HttpCrawler } from './http-crawler.js';
4
+ /**
5
+ * An {@link HttpCrawler} that parses each response into a DOM using the {@link DOMCrawlerOptions.parser|`parser`}
6
+ * it is given, and exposes the parse result plus the {@link DOMCrawlingContext.enqueueLinks|`enqueueLinks`} and
7
+ * {@link DOMCrawlingContext.extractLinks|`extractLinks`} helpers on the crawling context.
8
+ *
9
+ * {@link JSDOMCrawler} and {@link LinkeDOMCrawler} are this crawler with a parser already chosen.
10
+ *
11
+ * @category Crawlers
12
+ */
13
+ export class DOMCrawler extends HttpCrawler {
14
+ #parser;
15
+ constructor(options) {
16
+ const { parser, ...rest } = options;
17
+ super({ ...rest, contextPipelineBuilder: () => this.buildContextPipeline() });
18
+ this.#parser = parser;
19
+ }
20
+ buildContextPipeline() {
21
+ return super
22
+ .buildContextPipeline()
23
+ .compose(this.#parseContent.bind(this))
24
+ .compose(async (context) => this.#addHelpers(context));
25
+ }
26
+ async #parseContent(context, onCleanup) {
27
+ try {
28
+ const parsed = await this.#parser.parse(context);
29
+ onCleanup(() => this.#parser.cleanup?.(parsed));
30
+ return parsed;
31
+ }
32
+ catch (err) {
33
+ // The `skipNavigation` placeholders below throw on access, so there is nothing to clean up.
34
+ if (err instanceof NavigationSkippedError) {
35
+ return Object.defineProperties({}, Object.fromEntries(Object.keys(this.#parser.placeholderMembers).map((member) => [
36
+ member,
37
+ {
38
+ configurable: true,
39
+ enumerable: true,
40
+ get() {
41
+ throw new NavigationSkippedError(`The \`${member}\` property is not available - \`skipNavigation\` was used`, { cause: err });
42
+ },
43
+ },
44
+ ])));
45
+ }
46
+ throw err;
47
+ }
48
+ }
49
+ async #addHelpers(context) {
50
+ const { addRequests } = context;
51
+ const parser = this.#parser;
52
+ const extractLinks = async (options) => parser.extractLinks(context, options?.selector ?? 'a', options?.baseUrl ?? context.request.loadedUrl ?? context.request.url);
53
+ const waitForSelector = async (selector, timeoutMs = 5_000) => {
54
+ let remaining = parser.mutable ? timeoutMs : 0;
55
+ while ((await parser.select(context, selector)).length === 0) {
56
+ if (remaining <= 0) {
57
+ throw new Error(`Selector '${selector}' not found.`);
58
+ }
59
+ await sleep(50);
60
+ remaining -= 50;
61
+ }
62
+ };
63
+ return {
64
+ extractLinks,
65
+ waitForSelector,
66
+ enqueueLinks: async (options = {}) => {
67
+ const baseUrl = resolveBaseUrlForEnqueueLinksFiltering({
68
+ enqueueStrategy: options.strategy,
69
+ finalRequestUrl: context.request.loadedUrl,
70
+ originalRequestUrl: context.request.url,
71
+ userProvidedBaseUrl: options.baseUrl,
72
+ });
73
+ const urls = await extractLinks(options);
74
+ return addRequests(urls, {
75
+ ...options,
76
+ baseUrl,
77
+ strategy: options.strategy ?? EnqueueStrategy.SameHostname,
78
+ });
79
+ },
80
+ async parseWithCheerio(selector, _timeoutMs = 5_000) {
81
+ // Import full cheerio (not cheerio/slim) to be browser-compliant for DOM Crawlers (not CheerioCrawler).
82
+ const $ = (await parser.toCheerio?.(context)) ??
83
+ (await import('cheerio')).load(context.body, {
84
+ xmlMode: context.contentType.type.includes('xml'),
85
+ });
86
+ if (selector && $(selector).get().length === 0) {
87
+ throw new Error(`Selector '${selector}' not found.`);
88
+ }
89
+ return $;
90
+ },
91
+ };
92
+ }
93
+ }
@@ -1,29 +1,18 @@
1
+ import type { BasicCrawlerOptions, CrawlingContext, CrawlingRequest, LoadedRequest } from '@crawlee/basic';
2
+ import { BasicCrawler } from '@crawlee/basic';
1
3
  import type { Dictionary } from '@crawlee/types';
2
- // @ts-ignore optional peer dependency or compatibility with es2022
3
- import type { Request } from 'got-scraping';
4
- import type { ErrorHandler, GetUserDataFromRequest, HttpCrawlerOptions, InternalHttpCrawlingContext, InternalHttpHook, RequestHandler, RouterRoutes } from '../index.js';
5
- import { HttpCrawler } from '../index.js';
4
+ import type { ErrorHandler, GetUserDataFromRequest, RequestHandler, RouterHandler, RouterRoutes, RouteSchemas, RoutesFromSchemas } from '../index.js';
6
5
  export type FileDownloadErrorHandler<UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
7
- JSONData extends Dictionary = any> = ErrorHandler<FileDownloadCrawlingContext<UserData, JSONData>>;
8
- export type StreamHandlerContext = Omit<FileDownloadCrawlingContext, 'body' | 'parseWithCheerio' | 'json' | 'addRequests' | 'contentType'> & {
9
- stream: Request;
10
- };
11
- type StreamHandler = (context: StreamHandlerContext) => void | Promise<void>;
12
- export type FileDownloadOptions<UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
13
- JSONData extends Dictionary = any> = (Omit<HttpCrawlerOptions<FileDownloadCrawlingContext<UserData, JSONData>>, 'requestHandler'> & {
14
- requestHandler?: never;
15
- streamHandler?: StreamHandler;
16
- }) | (Omit<HttpCrawlerOptions<FileDownloadCrawlingContext<UserData, JSONData>>, 'requestHandler'> & {
17
- requestHandler: FileDownloadRequestHandler;
18
- streamHandler?: never;
19
- });
20
- export type FileDownloadHook<UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
21
- JSONData extends Dictionary = any> = InternalHttpHook<FileDownloadCrawlingContext<UserData, JSONData>>;
22
- export interface FileDownloadCrawlingContext<UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
23
- JSONData extends Dictionary = any> extends InternalHttpCrawlingContext<UserData, JSONData, FileDownload> {
6
+ ContextExtension = Dictionary<never>> = ErrorHandler<CrawlingContext, FileDownloadCrawlingContext<UserData> & ContextExtension>;
7
+ export interface FileDownloadCrawlingContext<UserData extends Dictionary = any> extends CrawlingContext<UserData> {
8
+ request: LoadedRequest<CrawlingRequest<UserData>>;
9
+ response: Response;
10
+ contentType: {
11
+ type: string;
12
+ encoding: BufferEncoding;
13
+ };
24
14
  }
25
- export type FileDownloadRequestHandler<UserData extends Dictionary = any, // with default to Dictionary we cant use a typed router in untyped crawler
26
- JSONData extends Dictionary = any> = RequestHandler<FileDownloadCrawlingContext<UserData, JSONData>>;
15
+ export type FileDownloadRequestHandler<UserData extends Dictionary = any> = RequestHandler<FileDownloadCrawlingContext<UserData>>;
27
16
  /**
28
17
  * Provides a framework for downloading files in parallel using plain HTTP requests. The URLs to download are fed either from a static list of URLs or they can be added on the fly from another crawler.
29
18
  *
@@ -31,25 +20,15 @@ JSONData extends Dictionary = any> = RequestHandler<FileDownloadCrawlingContext<
31
20
  * However, it doesn't parse the content - if you need to e.g. extract data from the downloaded files,
32
21
  * you might need to use {@link CheerioCrawler}, {@link PuppeteerCrawler} or {@link PlaywrightCrawler} instead.
33
22
  *
34
- * `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.
23
+ * `FileCrawler` downloads each URL using a plain HTTP request and then invokes the user-provided {@link BasicCrawlerOptions.requestHandler} where the user can specify what to do with the downloaded data.
35
24
  *
36
- * 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.
25
+ * The source URLs are represented using {@link Request} objects that are fed from the {@link IRequestManager|request manager} provided via the {@link BasicCrawlerOptions.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`.
37
26
  *
38
- * 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.
27
+ * > The {@link BasicCrawlerOptions.requestList|`requestList`} and {@link BasicCrawlerOptions.requestQueue|`requestQueue`} options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
39
28
  *
40
29
  * The crawler finishes when there are no more {@link Request} objects to crawl.
41
30
  *
42
- * We can use the `preNavigationHooks` to adjust `gotOptions`:
43
- *
44
- * ```
45
- * preNavigationHooks: [
46
- * (crawlingContext, gotOptions) => {
47
- * // ...
48
- * },
49
- * ]
50
- * ```
51
- *
52
- * 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.
31
+ * 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`}.
53
32
  *
54
33
  * ## Example usage
55
34
  *
@@ -67,11 +46,10 @@ JSONData extends Dictionary = any> = RequestHandler<FileDownloadCrawlingContext<
67
46
  * ]);
68
47
  * ```
69
48
  */
70
- export declare class FileDownload extends HttpCrawler<FileDownloadCrawlingContext> {
71
- private streamHandler?;
72
- constructor(options?: FileDownloadOptions);
73
- protected _runRequestHandler(context: FileDownloadCrawlingContext): Promise<void>;
74
- private streamRequestHandler;
49
+ export declare class FileDownload extends BasicCrawler<FileDownloadCrawlingContext> {
50
+ #private;
51
+ constructor(options?: Omit<BasicCrawlerOptions<FileDownloadCrawlingContext>, 'contextPipelineBuilder'>);
52
+ private initiateDownload;
75
53
  }
76
54
  /**
77
55
  * Creates new {@link Router} instance that works based on request labels.
@@ -97,7 +75,6 @@ export declare class FileDownload extends HttpCrawler<FileDownloadCrawlingContex
97
75
  * await crawler.run();
98
76
  * ```
99
77
  */
100
- // @ts-ignore optional peer dependency or compatibility with es2022
101
- export declare function createFileRouter<Context extends FileDownloadCrawlingContext = FileDownloadCrawlingContext, UserData extends Dictionary = GetUserDataFromRequest<Context['request']>>(routes?: RouterRoutes<Context, UserData>): import("packages/core/dist/router.js").RouterHandler<Context>;
102
- export {};
103
- //# sourceMappingURL=file-download.d.ts.map
78
+ 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>;
79
+ 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>>;
80
+ export declare function createFileRouter<Context extends FileDownloadCrawlingContext = FileDownloadCrawlingContext, const Schemas extends RouteSchemas = RouteSchemas>(schemas: Schemas): RouterHandler<Context, RoutesFromSchemas<Schemas>>;
@@ -1,6 +1,7 @@
1
- import { finished } from 'node:stream/promises';
2
- import { isPromise } from 'node:util/types';
3
- import { HttpCrawler, Router } from '../index.js';
1
+ import { BasicCrawler, ContextPipeline } from '@crawlee/basic';
2
+ import { ResponseWithUrl } from '@crawlee/http-client';
3
+ import { Router } from '../index.js';
4
+ import { parseContentTypeFromResponse } from './utils.js';
4
5
  /**
5
6
  * Provides a framework for downloading files in parallel using plain HTTP requests. The URLs to download are fed either from a static list of URLs or they can be added on the fly from another crawler.
6
7
  *
@@ -8,25 +9,15 @@ import { HttpCrawler, Router } from '../index.js';
8
9
  * However, it doesn't parse the content - if you need to e.g. extract data from the downloaded files,
9
10
  * you might need to use {@link CheerioCrawler}, {@link PuppeteerCrawler} or {@link PlaywrightCrawler} instead.
10
11
  *
11
- * `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.
12
+ * `FileCrawler` downloads each URL using a plain HTTP request and then invokes the user-provided {@link BasicCrawlerOptions.requestHandler} where the user can specify what to do with the downloaded data.
12
13
  *
13
- * 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.
14
+ * The source URLs are represented using {@link Request} objects that are fed from the {@link IRequestManager|request manager} provided via the {@link BasicCrawlerOptions.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`.
14
15
  *
15
- * 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.
16
+ * > The {@link BasicCrawlerOptions.requestList|`requestList`} and {@link BasicCrawlerOptions.requestQueue|`requestQueue`} options are deprecated; they are still accepted and folded into a single `requestManager` for back-compat.
16
17
  *
17
18
  * The crawler finishes when there are no more {@link Request} objects to crawl.
18
19
  *
19
- * We can use the `preNavigationHooks` to adjust `gotOptions`:
20
- *
21
- * ```
22
- * preNavigationHooks: [
23
- * (crawlingContext, gotOptions) => {
24
- * // ...
25
- * },
26
- * ]
27
- * ```
28
- *
29
- * 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.
20
+ * 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`}.
30
21
  *
31
22
  * ## Example usage
32
23
  *
@@ -44,106 +35,59 @@ import { HttpCrawler, Router } from '../index.js';
44
35
  * ]);
45
36
  * ```
46
37
  */
47
- export class FileDownload extends HttpCrawler {
48
- streamHandler;
38
+ export class FileDownload extends BasicCrawler {
39
+ // TODO hooks
49
40
  constructor(options = {}) {
50
- const { streamHandler } = options;
51
- delete options.streamHandler;
52
- if (streamHandler) {
53
- // For streams, the navigation is done in the request handler.
54
- options.requestHandlerTimeoutSecs = options.navigationTimeoutSecs ?? 120;
55
- }
56
- super(options);
57
- this.streamHandler = streamHandler;
58
- if (this.streamHandler) {
59
- this.requestHandler = this.streamRequestHandler;
60
- }
61
- // The base HttpCrawler class only supports a handful of text based mime types.
62
- // With the FileDownload crawler, we want to download any file type.
63
- this.supportedMimeTypes = new Set(['*/*']);
41
+ super({
42
+ ...options,
43
+ contextPipelineBuilder: () => this.#buildContextPipeline(),
44
+ });
64
45
  }
65
- async _runRequestHandler(context) {
66
- if (this.streamHandler) {
67
- context.request.skipNavigation = true;
68
- }
69
- await super._runRequestHandler(context);
46
+ #buildContextPipeline() {
47
+ return ContextPipeline.create().compose(this.initiateDownload.bind(this));
70
48
  }
71
- async streamRequestHandler(context) {
72
- const { log, request: { url }, } = context;
73
- const response = await this.httpClient.stream({
74
- url,
75
- timeout: { request: undefined },
76
- proxyUrl: context.proxyInfo?.url,
49
+ async initiateDownload(context, onCleanup) {
50
+ const response = await this.httpClient.sendRequest(context.request.intoFetchAPIRequest(), {
51
+ session: context.session,
77
52
  });
78
- let pollingInterval;
79
- const cleanUp = () => {
80
- clearInterval(pollingInterval);
81
- response.stream.destroy();
82
- };
83
- const downloadPromise = new Promise((resolve, reject) => {
84
- pollingInterval = setInterval(() => {
85
- const { total, transferred } = response.downloadProgress;
86
- if (transferred > 0) {
87
- log.debug(`Downloaded ${transferred} bytes of ${total ?? 0} bytes from ${url}.`);
88
- }
89
- }, 5000);
90
- response.stream.on('error', async (error) => {
91
- cleanUp();
92
- reject(error);
93
- });
94
- let streamHandlerResult;
95
- try {
96
- context.stream = response.stream;
97
- context.response = response;
98
- streamHandlerResult = this.streamHandler(context);
99
- }
100
- catch (e) {
101
- cleanUp();
102
- reject(e);
103
- }
104
- if (isPromise(streamHandlerResult)) {
105
- streamHandlerResult
106
- .then(() => {
107
- resolve();
108
- })
109
- .catch((e) => {
110
- cleanUp();
111
- reject(e);
112
- });
113
- }
114
- else {
115
- resolve();
53
+ const { type, charset: encoding } = parseContentTypeFromResponse(response);
54
+ context.request.url = response.url;
55
+ const { response: trackedResponse, bodyDrained } = trackBodyConsumption(response);
56
+ onCleanup(async () => {
57
+ if (!trackedResponse.bodyUsed) {
58
+ // Nobody consumed the body — cancel it so the
59
+ // underlying connection can be released.
60
+ await trackedResponse.body?.cancel();
116
61
  }
62
+ await bodyDrained;
117
63
  });
118
- await Promise.all([downloadPromise, finished(response.stream)]);
119
- cleanUp();
64
+ return {
65
+ request: context.request,
66
+ response: trackedResponse,
67
+ contentType: { type, encoding },
68
+ };
120
69
  }
121
70
  }
122
71
  /**
123
- * Creates new {@link Router} instance that works based on request labels.
124
- * This instance can then serve as a `requestHandler` of your {@link FileDownload}.
125
- * Defaults to the {@link FileDownloadCrawlingContext}.
126
- *
127
- * > Serves as a shortcut for using `Router.create<FileDownloadCrawlingContext>()`.
128
- *
129
- * ```ts
130
- * import { FileDownload, createFileRouter } from 'crawlee';
131
- *
132
- * const router = createFileRouter();
133
- * router.addHandler('label-a', async (ctx) => {
134
- * ctx.log.info('...');
135
- * });
136
- * router.addDefaultHandler(async (ctx) => {
137
- * ctx.log.info('...');
138
- * });
139
- *
140
- * const crawler = new FileDownload({
141
- * requestHandler: router,
142
- * });
143
- * await crawler.run();
144
- * ```
72
+ * Wraps a Response so that we can track when the body stream has been fully
73
+ * consumed (or errored). Pipes the original body through a TransformStream;
74
+ * the readable side becomes the new Response body, and `pipeTo` gives us a
75
+ * promise that resolves once the body is fully read or cancelled.
145
76
  */
146
- export function createFileRouter(routes) {
147
- return Router.create(routes);
77
+ function trackBodyConsumption(response) {
78
+ if (!response.body) {
79
+ return { response, bodyDrained: Promise.resolve() };
80
+ }
81
+ const passthrough = new TransformStream();
82
+ const bodyDrained = response.body.pipeTo(passthrough.writable).catch(() => { });
83
+ const trackedResponse = new ResponseWithUrl(passthrough.readable, {
84
+ headers: response.headers,
85
+ status: response.status,
86
+ statusText: response.statusText,
87
+ url: response.url,
88
+ });
89
+ return { response: trackedResponse, bodyDrained };
90
+ }
91
+ export function createFileRouter(routesOrSchemas) {
92
+ return Router.create(routesOrSchemas);
148
93
  }
149
- //# sourceMappingURL=file-download.js.map