@crawlee/http-client 4.0.0-beta.100

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/LICENSE.md ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2018 Apify Technologies s.r.o.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,153 @@
1
+ <h1 align="center">
2
+ <a href="https://crawlee.dev">
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" />
6
+ </picture>
7
+ </a>
8
+ <br />
9
+ <small>A web scraping and browser automation library</small>
10
+ </h1>
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" 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>
21
+ </p>
22
+
23
+ Crawlee covers your crawling and scraping end-to-end and **helps you build reliable scrapers. Fast.**
24
+
25
+ Your crawlers will appear human-like and fly under the radar of modern bot protections even with the default configuration. Crawlee gives you the tools to crawl the web for links, scrape data, and store it to disk or cloud while staying configurable to suit your project's needs.
26
+
27
+ Crawlee is available as the [`crawlee`](https://www.npmjs.com/package/crawlee) NPM package.
28
+
29
+ > 👉 **View full documentation, guides and examples on the [Crawlee project website](https://crawlee.dev)** 👈
30
+
31
+ > Do you prefer 🐍 Python instead of JavaScript? [👉 Checkout Crawlee for Python 👈](https://github.com/apify/crawlee-python).
32
+
33
+ ## Installation
34
+
35
+ We recommend visiting the [Introduction tutorial](https://crawlee.dev/js/docs/introduction) in Crawlee documentation for more information.
36
+
37
+ > Crawlee requires **Node.js 16 or higher**.
38
+
39
+ ### With Crawlee CLI
40
+
41
+ The fastest way to try Crawlee out is to use the **Crawlee CLI** and choose the **Getting started example**. The CLI will install all the necessary dependencies and add boilerplate code for you to play with.
42
+
43
+ ```bash
44
+ npx crawlee create my-crawler
45
+ ```
46
+
47
+ ```bash
48
+ cd my-crawler
49
+ npm start
50
+ ```
51
+
52
+ ### Manual installation
53
+ If you prefer adding Crawlee **into your own project**, try the example below. Because it uses `PlaywrightCrawler` we also need to install [Playwright](https://playwright.dev). It's not bundled with Crawlee to reduce install size.
54
+
55
+ ```bash
56
+ npm install crawlee playwright
57
+ ```
58
+
59
+ ```js
60
+ import { PlaywrightCrawler, Dataset } from 'crawlee';
61
+
62
+ // PlaywrightCrawler crawls the web using a headless
63
+ // browser controlled by the Playwright library.
64
+ const crawler = new PlaywrightCrawler({
65
+ // Use the requestHandler to process each of the crawled pages.
66
+ async requestHandler({ request, page, enqueueLinks, log }) {
67
+ const title = await page.title();
68
+ log.info(`Title of ${request.loadedUrl} is '${title}'`);
69
+
70
+ // Save results as JSON to ./storage/datasets/default
71
+ await Dataset.pushData({ title, url: request.loadedUrl });
72
+
73
+ // Extract links from the current page
74
+ // and add them to the crawling queue.
75
+ await enqueueLinks();
76
+ },
77
+ // Uncomment this option to see the browser window.
78
+ // headless: false,
79
+ });
80
+
81
+ // Add first URL to the queue and start the crawl.
82
+ await crawler.run(['https://crawlee.dev']);
83
+ ```
84
+
85
+ By default, Crawlee stores data to `./storage` in the current working directory. You can override this directory via Crawlee configuration. For details, see [Configuration guide](https://crawlee.dev/js/docs/guides/configuration), [Request storage](https://crawlee.dev/js/docs/guides/request-storage) and [Result storage](https://crawlee.dev/js/docs/guides/result-storage).
86
+
87
+ ### Installing pre-release versions
88
+
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
+
91
+ ```bash
92
+ npm install crawlee@next
93
+ ```
94
+
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:
96
+
97
+ ```json
98
+ {
99
+ "overrides": {
100
+ "apify": {
101
+ "@crawlee/core": "$crawlee",
102
+ "@crawlee/types": "$crawlee",
103
+ "@crawlee/utils": "$crawlee"
104
+ }
105
+ }
106
+ }
107
+ ```
108
+
109
+ ## 🛠 Features
110
+
111
+ - Single interface for **HTTP and headless browser** crawling
112
+ - Persistent **queue** for URLs to crawl (breadth & depth first)
113
+ - Pluggable **storage** of both tabular data and files
114
+ - Automatic **scaling** with available system resources
115
+ - Integrated **proxy rotation** and session management
116
+ - Lifecycles customizable with **hooks**
117
+ - **CLI** to bootstrap your projects
118
+ - Configurable **routing**, **error handling** and **retries**
119
+ - **Dockerfiles** ready to deploy
120
+ - Written in **TypeScript** with generics
121
+
122
+ ### 👾 HTTP crawling
123
+
124
+ - Zero config **HTTP2 support**, even for proxies
125
+ - Automatic generation of **browser-like headers**
126
+ - Replication of browser **TLS fingerprints**
127
+ - Integrated fast **HTML parsers**. Cheerio and JSDOM
128
+ - Yes, you can scrape **JSON APIs** as well
129
+
130
+ ### 💻 Real browser crawling
131
+
132
+ - JavaScript **rendering** and **screenshots**
133
+ - **Headless** and **headful** support
134
+ - Zero-config generation of **human-like fingerprints**
135
+ - Automatic **browser management**
136
+ - Use **Playwright** and **Puppeteer** with the same interface
137
+ - **Chrome**, **Firefox**, **Webkit** and many others
138
+
139
+ ## Usage on the Apify platform
140
+
141
+ Crawlee is open-source and runs anywhere, but since it's developed by [Apify](https://apify.com), it's easy to set up on the Apify platform and run in the cloud. Visit the [Apify SDK website](https://sdk.apify.com) to learn more about deploying Crawlee to the Apify platform.
142
+
143
+ ## Support
144
+
145
+ If you find any bug or issue with Crawlee, please [submit an issue on GitHub](https://github.com/apify/crawlee/issues). For questions, you can ask on [Stack Overflow](https://stackoverflow.com/questions/tagged/apify), in GitHub Discussions or you can join our [Discord server](https://discord.com/invite/jyEM2PRvMU).
146
+
147
+ ## Contributing
148
+
149
+ Your code contributions are welcome, and you'll be praised to eternity! If you have any ideas for improvements, either submit an issue or create a pull request. For contribution guidelines and the code of conduct, see [CONTRIBUTING.md](https://github.com/apify/crawlee/blob/master/CONTRIBUTING.md).
150
+
151
+ ## License
152
+
153
+ This project is licensed under the Apache License 2.0 - see the [LICENSE.md](https://github.com/apify/crawlee/blob/master/LICENSE.md) file for details.
@@ -0,0 +1,54 @@
1
+ import type { BaseHttpClient as BaseHttpClientInterface, CrawleeLogger, SendRequestOptions, SessionFingerprint } from '@crawlee/types';
2
+ import { CookieJar } from 'tough-cookie';
3
+ /**
4
+ * Per-request options handed to a concrete client's `fetch` implementation.
5
+ */
6
+ export interface CustomFetchOptions {
7
+ /**
8
+ * Effective proxy URL for this request. `sendRequest` populates this from
9
+ * the explicit `SendRequestOptions.proxyUrl` override when set, falling back
10
+ * to `session.proxyInfo.url`.
11
+ */
12
+ proxyUrl?: string;
13
+ /**
14
+ * Effective cookie jar for this request. `sendRequest` populates this from
15
+ * the explicit `SendRequestOptions.cookieJar` override when set, falling
16
+ * back to `session.cookieJar` (or a fresh jar when neither is provided).
17
+ */
18
+ cookieJar?: CookieJar;
19
+ /**
20
+ * Hints about which browser-like setup this request should be impersonating —
21
+ * `browser`, `platform`, `device`, and an opaque `details` slot for richer
22
+ * payloads (e.g. a full browser fingerprint from `fingerprint-generator`).
23
+ * These are *suggestions*, not requirements: each client applies what it can
24
+ * (e.g. impit maps `browser` to its impersonation profile) and ignores the
25
+ * rest on a best-effort basis. Sourced from `SendRequestOptions.session.fingerprint`.
26
+ */
27
+ fingerprint?: SessionFingerprint;
28
+ }
29
+ /**
30
+ * Base HTTP client that provides fetch-like `sendRequest` with Crawlee-managed
31
+ * behaviors (redirect handling, proxy and cookie handling). Concrete clients
32
+ * implement only the low-level network call in `fetch`.
33
+ */
34
+ export declare abstract class BaseHttpClient implements BaseHttpClientInterface {
35
+ private log?;
36
+ constructor(options?: {
37
+ logger?: CrawleeLogger;
38
+ });
39
+ /**
40
+ * Perform the raw network request and return a single Response without any
41
+ * automatic redirect following or special error handling.
42
+ */
43
+ protected abstract fetch(input: Request, init?: RequestInit & CustomFetchOptions): Promise<Response>;
44
+ private applyCookies;
45
+ private setCookies;
46
+ private resolveRequestContext;
47
+ private createAbortSignal;
48
+ private isRedirect;
49
+ private buildRedirectRequest;
50
+ /**
51
+ * Public fetch-like method that handles redirects and uses provided proxy and cookie jar.
52
+ */
53
+ sendRequest(initialRequest: Request, options?: SendRequestOptions): Promise<Response>;
54
+ }
@@ -0,0 +1,129 @@
1
+ import { CookieJar } from 'tough-cookie';
2
+ /**
3
+ * Base HTTP client that provides fetch-like `sendRequest` with Crawlee-managed
4
+ * behaviors (redirect handling, proxy and cookie handling). Concrete clients
5
+ * implement only the low-level network call in `fetch`.
6
+ */
7
+ export class BaseHttpClient {
8
+ log;
9
+ constructor(options) {
10
+ this.log = options?.logger;
11
+ }
12
+ async applyCookies(request, cookieJar) {
13
+ try {
14
+ const requestCookies = request.headers.get('cookie') ?? '';
15
+ if (!requestCookies) {
16
+ // Fast path: no header cookies, use the jar directly.
17
+ const cookieString = await cookieJar.getCookieString(request.url);
18
+ if (cookieString) {
19
+ request.headers.set('cookie', cookieString);
20
+ }
21
+ return request;
22
+ }
23
+ // Merge jar cookies with request Cookie header. Clone the jar so we
24
+ // don't persist the header-only cookies into the session.
25
+ const merged = await cookieJar.clone();
26
+ await Promise.all(requestCookies
27
+ .split(/; */)
28
+ .filter(Boolean)
29
+ .map((pair) => merged.setCookie(pair, request.url)));
30
+ const cookieString = merged.getCookieStringSync(request.url);
31
+ if (cookieString) {
32
+ request.headers.set('cookie', cookieString);
33
+ }
34
+ }
35
+ catch (e) {
36
+ this.log?.warning(`Failed to get cookies for URL "${request.url}": ${e.message}`);
37
+ }
38
+ return request;
39
+ }
40
+ async setCookies(response, cookieJar) {
41
+ const setCookieHeaders = response.headers.getSetCookie();
42
+ for (const header of setCookieHeaders) {
43
+ try {
44
+ await cookieJar.setCookie(header, response.url);
45
+ }
46
+ catch (e) {
47
+ this.log?.warning(`Failed to set cookie for URL "${response.url}": ${e.message}`);
48
+ }
49
+ }
50
+ }
51
+ resolveRequestContext(options) {
52
+ const proxyUrl = options?.proxyUrl ?? options?.session?.proxyInfo?.url;
53
+ const cookieJar = options?.cookieJar ?? options?.session?.cookieJar ?? new CookieJar();
54
+ const signal = this.createAbortSignal(options?.signal, options?.timeoutMillis);
55
+ return {
56
+ proxyUrl,
57
+ cookieJar: cookieJar,
58
+ signal,
59
+ fingerprint: options?.session?.fingerprint,
60
+ };
61
+ }
62
+ createAbortSignal(signal, timeoutMillis) {
63
+ if (signal && timeoutMillis) {
64
+ return AbortSignal.any([signal, AbortSignal.timeout(timeoutMillis)]);
65
+ }
66
+ if (signal) {
67
+ return signal;
68
+ }
69
+ return timeoutMillis ? AbortSignal.timeout(timeoutMillis) : undefined;
70
+ }
71
+ isRedirect(response) {
72
+ const status = response.status;
73
+ return status >= 300 && status < 400 && !!response.headers.get('location');
74
+ }
75
+ buildRedirectRequest(currentRequest, response, initialRequest) {
76
+ const location = response.headers.get('location');
77
+ const nextUrl = new URL(location, response.url ?? currentRequest.url);
78
+ const prevMethod = (currentRequest.method ?? 'GET').toUpperCase();
79
+ let nextMethod = prevMethod;
80
+ let nextBody = null;
81
+ if (response.status === 303 ||
82
+ ((response.status === 301 || response.status === 302) && prevMethod === 'POST')) {
83
+ nextMethod = 'GET';
84
+ nextBody = null;
85
+ }
86
+ else {
87
+ const clonedRequest = initialRequest.clone();
88
+ nextBody = clonedRequest.body;
89
+ }
90
+ const nextHeaders = new Headers();
91
+ currentRequest.headers.forEach((value, key) => nextHeaders.set(key, value));
92
+ return new Request(nextUrl.toString(), {
93
+ method: nextMethod,
94
+ headers: nextHeaders,
95
+ body: nextBody,
96
+ credentials: currentRequest.credentials,
97
+ redirect: 'manual',
98
+ });
99
+ }
100
+ /**
101
+ * Public fetch-like method that handles redirects and uses provided proxy and cookie jar.
102
+ */
103
+ async sendRequest(initialRequest, options) {
104
+ const maxRedirects = 10;
105
+ let currentRequest = initialRequest;
106
+ let redirectCount = 0;
107
+ const { proxyUrl, cookieJar, signal, fingerprint } = this.resolveRequestContext(options);
108
+ currentRequest = initialRequest.clone();
109
+ while (true) {
110
+ await this.applyCookies(currentRequest, cookieJar);
111
+ const response = await this.fetch(currentRequest, {
112
+ signal,
113
+ proxyUrl,
114
+ cookieJar,
115
+ fingerprint,
116
+ redirect: 'manual',
117
+ });
118
+ await this.setCookies(response, cookieJar);
119
+ if (this.isRedirect(response)) {
120
+ if (redirectCount++ >= maxRedirects) {
121
+ throw new Error(`Too many redirects (${maxRedirects}) while requesting ${currentRequest.url}`);
122
+ }
123
+ currentRequest = this.buildRedirectRequest(currentRequest, response, initialRequest);
124
+ continue;
125
+ }
126
+ return response;
127
+ }
128
+ }
129
+ }
@@ -0,0 +1,9 @@
1
+ import { BaseHttpClient, type CustomFetchOptions } from './base-http-client.js';
2
+ /**
3
+ * A HTTP client implementation using the native `fetch` API.
4
+ *
5
+ * This implementation does not support proxying.
6
+ */
7
+ export declare class FetchHttpClient extends BaseHttpClient {
8
+ fetch(request: Request, options?: RequestInit & CustomFetchOptions): Promise<Response>;
9
+ }
@@ -0,0 +1,11 @@
1
+ import { BaseHttpClient } from './base-http-client.js';
2
+ /**
3
+ * A HTTP client implementation using the native `fetch` API.
4
+ *
5
+ * This implementation does not support proxying.
6
+ */
7
+ export class FetchHttpClient extends BaseHttpClient {
8
+ async fetch(request, options) {
9
+ return fetch(request, options);
10
+ }
11
+ }
package/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export { BaseHttpClient, type CustomFetchOptions } from './base-http-client.js';
2
+ export { ResponseWithUrl, type IResponseWithUrl } from './response.js';
3
+ export { FetchHttpClient } from './fetch-http-client.js';
package/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { BaseHttpClient } from './base-http-client.js';
2
+ export { ResponseWithUrl } from './response.js';
3
+ export { FetchHttpClient } from './fetch-http-client.js';
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@crawlee/http-client",
3
+ "version": "4.0.0-beta.100",
4
+ "description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.",
5
+ "engines": {
6
+ "node": ">=22.0.0"
7
+ },
8
+ "type": "module",
9
+ "exports": {
10
+ ".": "./index.js",
11
+ "./package.json": "./package.json"
12
+ },
13
+ "keywords": [
14
+ "apify",
15
+ "headless",
16
+ "chrome",
17
+ "puppeteer",
18
+ "crawler",
19
+ "scraper"
20
+ ],
21
+ "author": {
22
+ "name": "Apify",
23
+ "email": "support@apify.com",
24
+ "url": "https://apify.com"
25
+ },
26
+ "contributors": [
27
+ "Jan Curn <jan@apify.com>",
28
+ "Marek Trunkat <marek@apify.com>",
29
+ "Ondra Urban <ondra@apify.com>"
30
+ ],
31
+ "license": "Apache-2.0",
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/apify/crawlee"
35
+ },
36
+ "bugs": {
37
+ "url": "https://github.com/apify/crawlee/issues"
38
+ },
39
+ "homepage": "https://crawlee.dev",
40
+ "scripts": {
41
+ "build": "pnpm clean && pnpm compile && pnpm copy",
42
+ "clean": "rimraf ./dist",
43
+ "compile": "tsc -p tsconfig.build.json",
44
+ "copy": "tsx ../../scripts/copy.ts"
45
+ },
46
+ "publishConfig": {
47
+ "access": "public"
48
+ },
49
+ "dependencies": {
50
+ "@crawlee/types": "4.0.0-beta.100",
51
+ "tough-cookie": "^6.0.0"
52
+ },
53
+ "lerna": {
54
+ "command": {
55
+ "publish": {
56
+ "assets": []
57
+ }
58
+ }
59
+ },
60
+ "gitHead": "109b4c2097f7b9a26bfe761b3c9969dd626f8e38"
61
+ }
package/response.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ export interface IResponseWithUrl extends Response {
2
+ url: string;
3
+ }
4
+ /**
5
+ * A Response class that includes the original request URL.
6
+ *
7
+ * This class extends `Response` from `fetch` API and is fully compatible with this.
8
+ */
9
+ export declare class ResponseWithUrl extends Response implements IResponseWithUrl {
10
+ url: string;
11
+ constructor(body: BodyInit | null, init: ResponseInit & {
12
+ url?: string;
13
+ });
14
+ }
package/response.js ADDED
@@ -0,0 +1,15 @@
1
+ // See https://github.com/nodejs/undici/blob/d7707ee8fd5da2d0cc64b5fae421b965faf803c8/lib/web/fetch/constants.js#L6
2
+ const nullBodyStatus = [101, 204, 205, 304];
3
+ /**
4
+ * A Response class that includes the original request URL.
5
+ *
6
+ * This class extends `Response` from `fetch` API and is fully compatible with this.
7
+ */
8
+ export class ResponseWithUrl extends Response {
9
+ url;
10
+ constructor(body, init) {
11
+ const bodyParsed = nullBodyStatus.includes(init.status ?? 200) ? null : body;
12
+ super(bodyParsed, init);
13
+ this.url = init.url ?? '';
14
+ }
15
+ }