apify 4.0.0-beta.12 → 4.0.0-beta.120

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 (69) hide show
  1. package/README.md +29 -43
  2. package/dist/actor.d.ts +511 -167
  3. package/dist/actor.js +895 -322
  4. package/dist/apify_dataset_backend.d.ts +19 -0
  5. package/dist/apify_dataset_backend.js +77 -0
  6. package/dist/apify_file_system_storage_backend.d.ts +34 -0
  7. package/dist/apify_file_system_storage_backend.js +41 -0
  8. package/dist/apify_key_value_store_backend.d.ts +23 -0
  9. package/dist/apify_key_value_store_backend.js +56 -0
  10. package/dist/apify_request_queue_backend.d.ts +78 -0
  11. package/dist/apify_request_queue_backend.js +114 -0
  12. package/dist/apify_request_queue_shared_backend.d.ts +31 -0
  13. package/dist/apify_request_queue_shared_backend.js +193 -0
  14. package/dist/apify_request_queue_single_backend.d.ts +43 -0
  15. package/dist/apify_request_queue_single_backend.js +256 -0
  16. package/dist/apify_storage_backend.d.ts +90 -0
  17. package/dist/apify_storage_backend.js +210 -0
  18. package/dist/charging.d.ts +82 -18
  19. package/dist/charging.js +388 -128
  20. package/dist/charging_storage_backend.d.ts +53 -0
  21. package/dist/charging_storage_backend.js +109 -0
  22. package/dist/child_run_tracker.d.ts +88 -0
  23. package/dist/child_run_tracker.js +239 -0
  24. package/dist/configuration.d.ts +86 -136
  25. package/dist/configuration.js +136 -145
  26. package/dist/enqueue_links_filters.d.ts +29 -0
  27. package/dist/enqueue_links_filters.js +52 -0
  28. package/dist/errors.d.ts +31 -0
  29. package/dist/errors.js +22 -0
  30. package/dist/google_sheets.d.ts +12 -0
  31. package/dist/google_sheets.js +26 -0
  32. package/dist/index.d.ts +11 -5
  33. package/dist/index.js +8 -5
  34. package/dist/input-schemas.d.ts +7 -0
  35. package/dist/input-schemas.js +58 -0
  36. package/dist/platform_event_manager.d.ts +15 -6
  37. package/dist/platform_event_manager.js +187 -41
  38. package/dist/proxy_configuration.d.ts +66 -59
  39. package/dist/proxy_configuration.js +172 -154
  40. package/dist/smart_apify_storage_backend.d.ts +52 -0
  41. package/dist/smart_apify_storage_backend.js +73 -0
  42. package/dist/storage.d.ts +38 -0
  43. package/dist/storage.js +1 -0
  44. package/dist/utils.d.ts +28 -4
  45. package/dist/utils.js +60 -20
  46. package/package.json +117 -73
  47. package/.turbo/turbo-build.log +0 -26
  48. package/.turbo/turbo-copy.log +0 -4
  49. package/dist/LICENSE.md +0 -201
  50. package/dist/README.md +0 -98
  51. package/dist/actor.d.ts.map +0 -1
  52. package/dist/actor.js.map +0 -1
  53. package/dist/charging.d.ts.map +0 -1
  54. package/dist/charging.js.map +0 -1
  55. package/dist/configuration.d.ts.map +0 -1
  56. package/dist/configuration.js.map +0 -1
  57. package/dist/index.d.ts.map +0 -1
  58. package/dist/index.js.map +0 -1
  59. package/dist/key_value_store.d.ts +0 -17
  60. package/dist/key_value_store.d.ts.map +0 -1
  61. package/dist/key_value_store.js +0 -33
  62. package/dist/key_value_store.js.map +0 -1
  63. package/dist/package.json +0 -75
  64. package/dist/platform_event_manager.d.ts.map +0 -1
  65. package/dist/platform_event_manager.js.map +0 -1
  66. package/dist/proxy_configuration.d.ts.map +0 -1
  67. package/dist/proxy_configuration.js.map +0 -1
  68. package/dist/utils.d.ts.map +0 -1
  69. package/dist/utils.js.map +0 -1
@@ -1,6 +1,13 @@
1
- import type { ProxyConfigurationOptions as CoreProxyConfigurationOptions, ProxyInfo as CoreProxyInfo } from '@crawlee/core';
1
+ import type { ProxyConfigurationOptions as CoreProxyConfigurationOptions } from '@crawlee/core';
2
2
  import { ProxyConfiguration as CoreProxyConfiguration } from '@crawlee/core';
3
+ import type { ProxyInfo as CoreProxyInfo } from '@crawlee/types';
3
4
  import { Configuration } from './configuration.js';
5
+ /** Response of the Apify Proxy status endpoint (`proxy.apify.com/?format=json`). */
6
+ interface ProxyStatus {
7
+ connected: boolean;
8
+ connectionError: string;
9
+ isManInTheMiddle: boolean;
10
+ }
4
11
  export interface ProxyConfigurationOptions extends CoreProxyConfigurationOptions {
5
12
  /**
6
13
  * User's password for the proxy. By default, it is taken from the `APIFY_PROXY_PASSWORD`
@@ -24,6 +31,12 @@ export interface ProxyConfigurationOptions extends CoreProxyConfigurationOptions
24
31
  * on the Apify cloud, or when using the [Apify CLI](https://github.com/apify/apify-cli).
25
32
  */
26
33
  countryCode?: string;
34
+ /**
35
+ * If set, all proxied requests will use IP addresses geolocated to the specified subdivision (e.g. US state).
36
+ * Requires `countryCode` to be set. The value must follow the ISO 3166-2 subdivision code format,
37
+ * e.g. `'CA'` for California when `countryCode` is `'US'`.
38
+ */
39
+ subdivisionCode?: string;
27
40
  /**
28
41
  * Same option as `groups` which can be used to
29
42
  * configurate the proxy by UI input schema. You should use the `groups` option in your crawler code.
@@ -35,10 +48,15 @@ export interface ProxyConfigurationOptions extends CoreProxyConfigurationOptions
35
48
  */
36
49
  apifyProxyCountry?: string;
37
50
  /**
38
- * Multiple different ProxyConfigurationOptions stratified into tiers. Crawlee crawlers will switch between those tiers
39
- * based on the blocked request statistics.
51
+ * Same option as `subdivisionCode` which can be used to
52
+ * configurate the proxy by UI input schema. You should use the `subdivisionCode` option in your crawler code.
53
+ */
54
+ apifyProxySubdivision?: string;
55
+ /**
56
+ * As part of the init process, we verify the configuration by checking the proxy status endpoint.
57
+ * This can make the init slower, to opt-out of this, use `checkAccess: false` (defaults to `true`).
40
58
  */
41
- tieredProxyConfig?: Omit<ProxyConfigurationOptions, keyof CoreProxyConfigurationOptions | 'tieredProxyConfig'>[];
59
+ checkAccess?: boolean;
42
60
  }
43
61
  /**
44
62
  * The main purpose of the ProxyInfo object is to provide information
@@ -64,9 +82,6 @@ export interface ProxyConfigurationOptions extends CoreProxyConfigurationOptions
64
82
  * requestHandler({ proxyInfo }) {
65
83
  * // Getting used proxy URL
66
84
  * const proxyUrl = proxyInfo.url;
67
- *
68
- * // Getting ID of used Session
69
- * const sessionIdentifier = proxyInfo.sessionId;
70
85
  * }
71
86
  * })
72
87
  *
@@ -77,7 +92,7 @@ export interface ProxyInfo extends CoreProxyInfo {
77
92
  * An array of proxy groups to be used by the [Apify Proxy](https://docs.apify.com/proxy).
78
93
  * If not provided, the proxy will select the groups automatically.
79
94
  */
80
- groups: string[];
95
+ groups?: string[];
81
96
  /**
82
97
  * If set and relevant proxies are available in your Apify account, all proxied requests will
83
98
  * use IP addresses that are geolocated to the specified country. For example `GB` for IPs
@@ -89,6 +104,11 @@ export interface ProxyInfo extends CoreProxyInfo {
89
104
  * This parameter is optional, by default, the proxy uses all available proxy servers from all countries.
90
105
  */
91
106
  countryCode?: string;
107
+ /**
108
+ * If set, all proxied requests use IP addresses geolocated to the specified subdivision (e.g. US state).
109
+ * ISO 3166-2 subdivision code, e.g. `'CA'` when `countryCode` is `'US'`.
110
+ */
111
+ subdivisionCode?: string;
92
112
  /**
93
113
  * User's password for the proxy. By default, it is taken from the `APIFY_PROXY_PASSWORD`
94
114
  * environment variable, which is automatically set by the system when running the Actors
@@ -130,17 +150,13 @@ export interface ProxyInfo extends CoreProxyInfo {
130
150
  * @category Scaling
131
151
  */
132
152
  export declare class ProxyConfiguration extends CoreProxyConfiguration {
133
- readonly config: Configuration;
134
- private groups;
135
- private countryCode?;
136
- private password?;
137
- private hostname;
138
- private port?;
139
- private usesApifyProxy?;
153
+ #private;
154
+ readonly configuration: Configuration;
155
+ protected readonly log: import("@crawlee/core").Log;
140
156
  /**
141
157
  * @internal
142
158
  */
143
- constructor(options?: ProxyConfigurationOptions, config?: Configuration);
159
+ constructor(options?: ProxyConfigurationOptions, configuration?: Configuration);
144
160
  /**
145
161
  * Loads proxy password if token is provided and checks access to Apify Proxy and provided proxy groups
146
162
  * if Apify Proxy configuration is used.
@@ -149,67 +165,58 @@ export declare class ProxyConfiguration extends CoreProxyConfiguration {
149
165
  * You should use the {@link createProxyConfiguration} function to create a pre-initialized
150
166
  * `ProxyConfiguration` instance instead of calling this manually.
151
167
  */
152
- initialize(): Promise<boolean>;
153
- /**
154
- * This function creates a new {@link ProxyInfo} info object.
155
- * It is used by CheerioCrawler and PuppeteerCrawler to generate proxy URLs and also to allow the user to inspect
156
- * the currently used proxy via the requestHandler parameter `proxyInfo`.
157
- * Use it if you want to work with a rich representation of a proxy URL.
158
- * If you need the URL string only, use {@link ProxyConfiguration.newUrl}.
159
- * @param [sessionId]
160
- * Represents the identifier of user {@link Session} that can be managed by the {@link SessionPool} or
161
- * you can use the Apify Proxy [Session](https://docs.apify.com/proxy#sessions) identifier.
162
- * When the provided sessionId is a number, it's converted to a string. Property sessionId of
163
- * {@link ProxyInfo} is always returned as a type string.
164
- *
165
- * All the HTTP requests going through the proxy with the same session identifier
166
- * will use the same target proxy server (i.e. the same IP address).
167
- * The identifier must not be longer than 50 characters and include only the following: `0-9`, `a-z`, `A-Z`, `"."`, `"_"` and `"~"`.
168
- * @return Represents information about used proxy and its configuration.
169
- */
170
- newProxyInfo(sessionId?: string | number, options?: Parameters<CoreProxyConfiguration['newProxyInfo']>[1]): Promise<ProxyInfo | undefined>;
171
- /**
172
- * Returns a new proxy URL based on provided configuration options and the `sessionId` parameter.
173
- * @param [sessionId]
174
- * Represents the identifier of user {@link Session} that can be managed by the {@link SessionPool} or
175
- * you can use the Apify Proxy [Session](https://docs.apify.com/proxy#sessions) identifier.
176
- * When the provided sessionId is a number, it's converted to a string.
168
+ initialize(options?: {
169
+ checkAccess?: boolean;
170
+ }): Promise<boolean>;
171
+ /**
172
+ * Returns a new {@link ProxyInfo} object with a fresh proxy URL. Each call mints an
173
+ * independent URL; for Apify Proxy a random session id is embedded so consecutive
174
+ * calls resolve to different IPs.
177
175
  *
178
- * All the HTTP requests going through the proxy with the same session identifier
179
- * will use the same target proxy server (i.e. the same IP address).
180
- * The identifier must not be longer than 50 characters and include only the following: `0-9`, `a-z`, `A-Z`, `"."`, `"_"` and `"~"`.
181
- * @return A string with a proxy URL, including authentication credentials and port number.
182
- * For example, `http://bob:password123@proxy.example.com:8000`
176
+ * A passed `proxyInfo` (e.g. one restored with a persisted session) is returned unchanged, unless it is an
177
+ * Apify Proxy one. Its endpoint is specific to the host, so it is moved to the current endpoint, keeping the
178
+ * username and with it the proxy session.
179
+ */
180
+ newProxyInfo(proxyInfo?: ProxyInfo): Promise<ProxyInfo | undefined>;
181
+ /**
182
+ * Returns a new proxy URL. For Apify Proxy, each call generates a URL with a fresh
183
+ * random session id, so consecutive calls return independent URLs. For custom
184
+ * `proxyUrls`, the URLs are rotated round-robin.
183
185
  */
184
- newUrl(sessionId?: string | number, options?: Parameters<CoreProxyConfiguration['newUrl']>[1]): Promise<string | undefined>;
185
- protected _generateTieredProxyUrls(tieredProxyConfig: NonNullable<ProxyConfigurationOptions['tieredProxyConfig']>, globalOptions: ProxyConfigurationOptions): string[][];
186
+ newUrl(): Promise<string | undefined>;
186
187
  /**
187
188
  * Returns proxy username.
188
189
  */
189
- protected _getUsername(sessionId?: string): string;
190
- protected composeDefaultUrl(sessionId?: string): string;
190
+ protected getUsername(sessionId: string): string;
191
+ protected composeDefaultUrl(sessionId: string): string;
192
+ private composeUrl;
191
193
  /**
192
194
  * Fetch & set the proxy password from Apify API if an Apify token is provided.
193
195
  */
194
- protected _setPasswordIfToken(): Promise<void>;
196
+ private setPasswordIfToken;
195
197
  /**
196
198
  * Checks whether the user has access to the proxies specified in the provided ProxyConfigurationOptions.
197
199
  * If the check can not be made, it only prints a warning and allows the program to continue. This is to
198
200
  * prevent program crashes caused by short downtimes of Proxy.
199
201
  */
200
- protected _checkAccess(): Promise<boolean>;
202
+ protected checkAccess(): Promise<boolean>;
201
203
  /**
202
204
  * Apify Proxy can be down for a second or a minute, but this should not crash processes.
203
205
  */
204
- protected _fetchStatus(): Promise<{
205
- connected: boolean;
206
- connectionError: string;
207
- isManInTheMiddle: boolean;
208
- } | undefined>;
206
+ protected fetchStatus(): Promise<ProxyStatus | undefined>;
207
+ /**
208
+ * Fetches the Apify Proxy status endpoint once, *through* the proxy, so the
209
+ * response reports on this exact connection (auth + man-in-the-middle).
210
+ *
211
+ * Uses a native `node:http` forward-proxy request — an absolute request URL
212
+ * plus a `Proxy-Authorization` header — so no proxy-agent dependency is
213
+ * needed. The status endpoint (`http://proxy.apify.com`) is plain HTTP.
214
+ */
215
+ protected requestStatus(statusUrl: string, proxyUrl: string): Promise<ProxyStatus>;
209
216
  /**
210
217
  * Throws cannot combine custom proxies with Apify Proxy
211
218
  * @internal
212
219
  */
213
- protected _throwCannotCombineCustomWithApify(): void;
220
+ protected throwCannotCombineCustomWithApify(): void;
214
221
  }
215
- //# sourceMappingURL=proxy_configuration.d.ts.map
222
+ export {};
@@ -1,15 +1,24 @@
1
+ import { once } from 'node:events';
2
+ import { request as httpRequest } from 'node:http';
3
+ import { json } from 'node:stream/consumers';
1
4
  import { ProxyConfiguration as CoreProxyConfiguration } from '@crawlee/core';
2
- import { gotScraping } from 'got-scraping';
3
- import ow from 'ow';
5
+ import { z } from 'zod';
4
6
  import { APIFY_ENV_VARS, APIFY_PROXY_VALUE_REGEX } from '@apify/consts';
7
+ import defaultLog from '@apify/log';
5
8
  import { cryptoRandomObjectId } from '@apify/utilities';
9
+ import { parseArgument } from '@apify/validations';
6
10
  import { Actor } from './actor.js';
7
11
  import { Configuration } from './configuration.js';
8
- // https://docs.apify.com/proxy/datacenter-proxy#username-parameters
9
- const MAX_SESSION_ID_LENGTH = 50;
10
12
  const CHECK_ACCESS_REQUEST_TIMEOUT_MILLIS = 4_000;
11
13
  const CHECK_ACCESS_MAX_ATTEMPTS = 2;
12
14
  const COUNTRY_CODE_REGEX = /^[A-Z]{2}$/;
15
+ // ISO 3166-2 subdivision codes are 1–3 uppercase alphanumeric characters, e.g. 'CA' (California), 'NSW' (New South Wales), '9' (Wien, AT-9)
16
+ const SUBDIVISION_CODE_REGEX = /^[A-Z0-9]{1,3}$/;
17
+ // Apify Proxy session identifier embedded in the proxy username — opaque to
18
+ // users; a fresh one is minted for every URL the SDK hands out so that the
19
+ // returned proxy URLs are independent.
20
+ const SESSION_ID_LENGTH = 12;
21
+ const SESSION_USERNAME_REGEX = /(?:^|,)session-[^,]+/;
13
22
  /**
14
23
  * Configures connection to a proxy server with the provided options. Proxy servers are used to prevent target websites from blocking
15
24
  * your crawlers based on IP address rate limits or blacklists. Setting proxy configuration in your crawlers automatically configures
@@ -44,58 +53,65 @@ const COUNTRY_CODE_REGEX = /^[A-Z]{2}$/;
44
53
  * @category Scaling
45
54
  */
46
55
  export class ProxyConfiguration extends CoreProxyConfiguration {
47
- config;
48
- groups;
49
- countryCode;
50
- password;
51
- hostname;
52
- port;
53
- usesApifyProxy;
56
+ configuration;
57
+ #groups;
58
+ #countryCode;
59
+ #subdivisionCode;
60
+ #password;
61
+ #hostname;
62
+ #port;
63
+ #usesApifyProxy;
64
+ #checkAccess;
65
+ log = defaultLog.child({ prefix: 'ProxyConfiguration' });
54
66
  /**
55
67
  * @internal
56
68
  */
57
- constructor(options = {}, config = Configuration.getGlobalConfig()) {
69
+ constructor(options = {}, configuration = Configuration.getGlobalConfiguration()) {
58
70
  const { proxyUrls, newUrlFunction, ...rest } = options;
59
71
  super({
60
72
  proxyUrls,
61
73
  newUrlFunction,
62
74
  ['validateRequired']: false,
63
75
  });
64
- this.config = config;
65
- ow(rest, ow.object.exactShape({
66
- groups: ow.optional.array.ofType(ow.string.matches(APIFY_PROXY_VALUE_REGEX)),
67
- apifyProxyGroups: ow.optional.array.ofType(ow.string.matches(APIFY_PROXY_VALUE_REGEX)),
68
- countryCode: ow.optional.string.matches(COUNTRY_CODE_REGEX),
69
- apifyProxyCountry: ow.optional.string.matches(COUNTRY_CODE_REGEX),
70
- password: ow.optional.string,
71
- tieredProxyUrls: ow.optional.array.ofType(ow.array.ofType(ow.string)),
72
- tieredProxyConfig: ow.optional.array.ofType(ow.object),
73
- }));
74
- const { groups = [], apifyProxyGroups = [], countryCode, apifyProxyCountry, password = config.get('proxyPassword'), tieredProxyConfig, tieredProxyUrls, } = options;
75
- this.tieredProxyUrls ??= tieredProxyUrls;
76
- if (tieredProxyConfig) {
77
- this.tieredProxyUrls = this._generateTieredProxyUrls(tieredProxyConfig, options);
78
- }
76
+ this.configuration = configuration;
77
+ parseArgument(rest, z
78
+ .object({
79
+ groups: z.array(z.string().regex(APIFY_PROXY_VALUE_REGEX)).optional(),
80
+ apifyProxyGroups: z.array(z.string().regex(APIFY_PROXY_VALUE_REGEX)).optional(),
81
+ countryCode: z.string().regex(COUNTRY_CODE_REGEX).optional(),
82
+ apifyProxyCountry: z.string().regex(COUNTRY_CODE_REGEX).optional(),
83
+ subdivisionCode: z.string().regex(SUBDIVISION_CODE_REGEX).optional(),
84
+ apifyProxySubdivision: z.string().regex(SUBDIVISION_CODE_REGEX).optional(),
85
+ password: z.string().optional(),
86
+ checkAccess: z.boolean().optional(),
87
+ })
88
+ .strict());
89
+ const { groups = [], apifyProxyGroups = [], countryCode, apifyProxyCountry, subdivisionCode, apifyProxySubdivision, password = configuration.proxyPassword, } = options;
79
90
  const groupsToUse = groups.length ? groups : apifyProxyGroups;
80
91
  const countryCodeToUse = countryCode || apifyProxyCountry;
81
- const hostname = config.get('proxyHostname');
82
- const port = config.get('proxyPort');
92
+ const subdivisionCodeToUse = subdivisionCode || apifyProxySubdivision;
93
+ const hostname = configuration.proxyHostname;
94
+ const port = configuration.proxyPort;
95
+ // The Apify Proxy subdivision is expressed as part of the country
96
+ // username parameter (`country-US_CA`), so a country is required.
97
+ if (subdivisionCodeToUse && !countryCodeToUse) {
98
+ throw new Error('ProxyConfiguration: "subdivisionCode" requires "countryCode" to be set.');
99
+ }
83
100
  // Validation
84
- if ((proxyUrls || newUrlFunction) &&
85
- (groupsToUse.length || countryCodeToUse)) {
86
- this._throwCannotCombineCustomWithApify();
101
+ if ((proxyUrls || newUrlFunction) && (groupsToUse.length || countryCodeToUse || subdivisionCodeToUse)) {
102
+ this.throwCannotCombineCustomWithApify();
87
103
  }
88
- if (proxyUrls && newUrlFunction)
89
- this._throwCannotCombineCustomMethods();
90
- this.groups = groupsToUse;
91
- this.countryCode = countryCodeToUse;
92
- this.password = password;
93
- this.hostname = hostname;
94
- this.port = port;
95
- this.usesApifyProxy = !this.proxyUrls && !this.newUrlFunction;
96
- if (proxyUrls && proxyUrls.some((url) => url.includes('apify.com'))) {
104
+ this.#groups = groupsToUse;
105
+ this.#countryCode = countryCodeToUse;
106
+ this.#subdivisionCode = subdivisionCodeToUse;
107
+ this.#password = password;
108
+ this.#hostname = hostname;
109
+ this.#port = port;
110
+ this.#usesApifyProxy = !proxyUrls && !newUrlFunction;
111
+ this.#checkAccess = options.checkAccess;
112
+ if (proxyUrls && proxyUrls.some((url) => url?.includes('apify.com'))) {
97
113
  this.log.warning('Some Apify proxy features may work incorrectly. Please consider setting up Apify properties instead of `proxyUrls`.\n' +
98
- 'See https://sdk.apify.com/docs/guides/proxy-management#apify-proxy-configuration');
114
+ 'See https://docs.apify.com/sdk/js/docs/concepts/proxy-management#apify-proxy-configuration');
99
115
  }
100
116
  }
101
117
  /**
@@ -106,12 +122,12 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
106
122
  * You should use the {@link createProxyConfiguration} function to create a pre-initialized
107
123
  * `ProxyConfiguration` instance instead of calling this manually.
108
124
  */
109
- async initialize() {
110
- if (this.usesApifyProxy) {
111
- if (!this.password) {
112
- await this._setPasswordIfToken();
125
+ async initialize(options) {
126
+ if (this.#usesApifyProxy) {
127
+ if (!this.#password) {
128
+ await this.setPasswordIfToken();
113
129
  }
114
- if (!this.password) {
130
+ if (!this.#password) {
115
131
  if (Actor.isAtHome()) {
116
132
  throw new Error(`Apify Proxy password must be provided using options.password or the "${APIFY_ENV_VARS.PROXY_PASSWORD}" environment variable. ` +
117
133
  `You can also provide your Apify token via the "${APIFY_ENV_VARS.TOKEN}" environment variable, ` +
@@ -124,131 +140,98 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
124
140
  `so that the SDK can fetch the proxy password from Apify API, when ${APIFY_ENV_VARS.PROXY_PASSWORD} is not defined`);
125
141
  }
126
142
  }
127
- return this._checkAccess();
143
+ if ((options?.checkAccess ?? this.#checkAccess) !== false) {
144
+ return this.checkAccess();
145
+ }
128
146
  }
129
147
  return true;
130
148
  }
131
149
  /**
132
- * This function creates a new {@link ProxyInfo} info object.
133
- * It is used by CheerioCrawler and PuppeteerCrawler to generate proxy URLs and also to allow the user to inspect
134
- * the currently used proxy via the requestHandler parameter `proxyInfo`.
135
- * Use it if you want to work with a rich representation of a proxy URL.
136
- * If you need the URL string only, use {@link ProxyConfiguration.newUrl}.
137
- * @param [sessionId]
138
- * Represents the identifier of user {@link Session} that can be managed by the {@link SessionPool} or
139
- * you can use the Apify Proxy [Session](https://docs.apify.com/proxy#sessions) identifier.
140
- * When the provided sessionId is a number, it's converted to a string. Property sessionId of
141
- * {@link ProxyInfo} is always returned as a type string.
150
+ * Returns a new {@link ProxyInfo} object with a fresh proxy URL. Each call mints an
151
+ * independent URL; for Apify Proxy a random session id is embedded so consecutive
152
+ * calls resolve to different IPs.
142
153
  *
143
- * All the HTTP requests going through the proxy with the same session identifier
144
- * will use the same target proxy server (i.e. the same IP address).
145
- * The identifier must not be longer than 50 characters and include only the following: `0-9`, `a-z`, `A-Z`, `"."`, `"_"` and `"~"`.
146
- * @return Represents information about used proxy and its configuration.
154
+ * A passed `proxyInfo` (e.g. one restored with a persisted session) is returned unchanged, unless it is an
155
+ * Apify Proxy one. Its endpoint is specific to the host, so it is moved to the current endpoint, keeping the
156
+ * username and with it the proxy session.
147
157
  */
148
- async newProxyInfo(sessionId, options) {
149
- if (typeof sessionId === 'number')
150
- sessionId = `${sessionId}`;
151
- ow(sessionId, ow.optional.string
152
- .maxLength(MAX_SESSION_ID_LENGTH)
153
- .matches(APIFY_PROXY_VALUE_REGEX));
154
- const proxyInfo = await super.newProxyInfo(sessionId, options);
155
- if (!proxyInfo)
158
+ async newProxyInfo(proxyInfo) {
159
+ // Only Apify Proxy infos carry `groups` and a proxy session in the username.
160
+ if (proxyInfo &&
161
+ !(this.#usesApifyProxy && 'groups' in proxyInfo && SESSION_USERNAME_REGEX.test(proxyInfo.username ?? ''))) {
156
162
  return proxyInfo;
157
- const { groups, countryCode, password, port, hostname } = (this.usesApifyProxy ? this : new URL(proxyInfo.url));
158
- return {
159
- ...proxyInfo,
160
- sessionId,
161
- groups,
162
- countryCode,
163
- // this.password is not encoded, but the password from the URL will be, we need to normalize
164
- password: this.usesApifyProxy
165
- ? (password ?? '')
166
- : decodeURIComponent(password),
167
- hostname,
168
- port: port,
163
+ }
164
+ const url = proxyInfo?.username ? this.composeUrl(proxyInfo.username) : await this.newUrl();
165
+ if (!url)
166
+ return undefined;
167
+ const parsed = new URL(url);
168
+ const result = {
169
+ url,
170
+ username: decodeURIComponent(parsed.username),
171
+ password: decodeURIComponent(parsed.password),
172
+ hostname: parsed.hostname,
173
+ port: parsed.port,
169
174
  };
175
+ // A refreshed info keeps its own groups/country, which match its username rather than this config.
176
+ if (proxyInfo)
177
+ return { ...proxyInfo, ...result };
178
+ if (this.#usesApifyProxy) {
179
+ result.groups = this.#groups;
180
+ if (this.#countryCode !== undefined)
181
+ result.countryCode = this.#countryCode;
182
+ if (this.#subdivisionCode !== undefined)
183
+ result.subdivisionCode = this.#subdivisionCode;
184
+ }
185
+ return result;
170
186
  }
171
187
  /**
172
- * Returns a new proxy URL based on provided configuration options and the `sessionId` parameter.
173
- * @param [sessionId]
174
- * Represents the identifier of user {@link Session} that can be managed by the {@link SessionPool} or
175
- * you can use the Apify Proxy [Session](https://docs.apify.com/proxy#sessions) identifier.
176
- * When the provided sessionId is a number, it's converted to a string.
177
- *
178
- * All the HTTP requests going through the proxy with the same session identifier
179
- * will use the same target proxy server (i.e. the same IP address).
180
- * The identifier must not be longer than 50 characters and include only the following: `0-9`, `a-z`, `A-Z`, `"."`, `"_"` and `"~"`.
181
- * @return A string with a proxy URL, including authentication credentials and port number.
182
- * For example, `http://bob:password123@proxy.example.com:8000`
188
+ * Returns a new proxy URL. For Apify Proxy, each call generates a URL with a fresh
189
+ * random session id, so consecutive calls return independent URLs. For custom
190
+ * `proxyUrls`, the URLs are rotated round-robin.
183
191
  */
184
- async newUrl(sessionId, options) {
185
- if (typeof sessionId === 'number')
186
- sessionId = `${sessionId}`;
187
- ow(sessionId, ow.optional.string
188
- .maxLength(MAX_SESSION_ID_LENGTH)
189
- .matches(APIFY_PROXY_VALUE_REGEX));
190
- if (this.newUrlFunction) {
191
- return ((await this._callNewUrlFunction(sessionId, {
192
- request: options?.request,
193
- })) ?? undefined);
194
- }
195
- if (this.proxyUrls) {
196
- return this._handleCustomUrl(sessionId);
192
+ async newUrl() {
193
+ if (!this.#usesApifyProxy) {
194
+ return super.newUrl();
197
195
  }
198
- if (this.tieredProxyUrls) {
199
- return (this._handleTieredUrl(sessionId ?? cryptoRandomObjectId(6), options).proxyUrl ?? undefined);
200
- }
201
- return this.composeDefaultUrl(sessionId);
202
- }
203
- _generateTieredProxyUrls(tieredProxyConfig, globalOptions) {
204
- return tieredProxyConfig.map((config) => [
205
- new ProxyConfiguration({
206
- ...globalOptions,
207
- ...config,
208
- tieredProxyConfig: undefined,
209
- }).composeDefaultUrl(),
210
- ]);
196
+ return this.composeDefaultUrl(cryptoRandomObjectId(SESSION_ID_LENGTH));
211
197
  }
212
198
  /**
213
199
  * Returns proxy username.
214
200
  */
215
- _getUsername(sessionId) {
216
- let username;
217
- const { groups, countryCode } = this;
201
+ getUsername(sessionId) {
218
202
  const parts = [];
219
- if (groups && groups.length) {
220
- parts.push(`groups-${groups.join('+')}`);
203
+ if (this.#groups && this.#groups.length) {
204
+ parts.push(`groups-${this.#groups.join('+')}`);
221
205
  }
222
- if (sessionId) {
223
- parts.push(`session-${sessionId}`);
206
+ parts.push(`session-${sessionId}`);
207
+ if (this.#subdivisionCode) {
208
+ parts.push(`country-${this.#countryCode}_${this.#subdivisionCode}`);
224
209
  }
225
- if (countryCode) {
226
- parts.push(`country-${countryCode}`);
210
+ else if (this.#countryCode) {
211
+ parts.push(`country-${this.#countryCode}`);
227
212
  }
228
- username = parts.join(',');
229
- if (parts.length === 0)
230
- username = 'auto';
231
- return username;
213
+ return parts.join(',');
232
214
  }
233
215
  composeDefaultUrl(sessionId) {
234
- const username = this._getUsername(sessionId);
235
- const url = new URL(`http://${this.hostname}:${this.port}`);
216
+ return this.composeUrl(this.getUsername(sessionId));
217
+ }
218
+ composeUrl(username) {
219
+ const url = new URL(`http://${this.#hostname}:${this.#port}`);
236
220
  url.username = `${username}`;
237
- url.password = `${this.password}`;
221
+ url.password = `${this.#password}`;
238
222
  const urlString = url.toString();
239
223
  return urlString.substring(0, urlString.length - 1);
240
224
  }
241
225
  /**
242
226
  * Fetch & set the proxy password from Apify API if an Apify token is provided.
243
227
  */
244
- // TODO: Make this private
245
- async _setPasswordIfToken() {
246
- const token = this.config.get('token');
228
+ async setPasswordIfToken() {
229
+ const { token } = this.configuration;
247
230
  if (!token)
248
231
  return;
249
232
  try {
250
233
  const user = await Actor.apifyClient.user().get();
251
- this.password = user.proxy?.password;
234
+ this.#password = user?.proxy?.password ?? undefined;
252
235
  }
253
236
  catch (error) {
254
237
  if (Actor.isAtHome()) {
@@ -266,14 +249,16 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
266
249
  * If the check can not be made, it only prints a warning and allows the program to continue. This is to
267
250
  * prevent program crashes caused by short downtimes of Proxy.
268
251
  */
269
- async _checkAccess() {
270
- const status = await this._fetchStatus();
252
+ async checkAccess() {
253
+ const status = await this.fetchStatus();
271
254
  if (!status) {
272
255
  this.log.warning('Apify Proxy access check timed out. Watch out for errors with status code 407. ' +
273
256
  "If you see some, it most likely means you don't have access to either all or some of the proxies you're trying to use.");
274
257
  return true;
275
258
  }
276
259
  const { connected, connectionError, isManInTheMiddle } = status;
260
+ // Declared `readonly false` on the base class; the status check is the one place that
261
+ // learns the actual value, so bypass the readonly marker.
277
262
  this.isManInTheMiddle = isManInTheMiddle;
278
263
  if (connected) {
279
264
  return true;
@@ -290,18 +275,16 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
290
275
  /**
291
276
  * Apify Proxy can be down for a second or a minute, but this should not crash processes.
292
277
  */
293
- async _fetchStatus() {
294
- const proxyStatusUrl = this.config.get('proxyStatusUrl', 'http://proxy.apify.com');
295
- const requestOpts = {
296
- url: `${proxyStatusUrl}/?format=json`,
297
- proxyUrl: await this.newUrl(),
298
- timeout: { request: CHECK_ACCESS_REQUEST_TIMEOUT_MILLIS },
299
- responseType: 'json',
300
- };
278
+ async fetchStatus() {
279
+ const { proxyStatusUrl } = this.configuration;
280
+ const statusUrl = `${proxyStatusUrl}/?format=json`;
281
+ const proxyUrl = await this.newUrl();
282
+ // Without a proxy URL we can't perform the (proxied) status check.
283
+ if (!proxyUrl)
284
+ return undefined;
301
285
  for (let attempt = 1; attempt <= CHECK_ACCESS_MAX_ATTEMPTS; attempt++) {
302
286
  try {
303
- const response = await gotScraping(requestOpts);
304
- return response.body;
287
+ return await this.requestStatus(statusUrl, proxyUrl);
305
288
  }
306
289
  catch {
307
290
  // retry connection errors
@@ -309,14 +292,49 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
309
292
  }
310
293
  return undefined;
311
294
  }
295
+ /**
296
+ * Fetches the Apify Proxy status endpoint once, *through* the proxy, so the
297
+ * response reports on this exact connection (auth + man-in-the-middle).
298
+ *
299
+ * Uses a native `node:http` forward-proxy request — an absolute request URL
300
+ * plus a `Proxy-Authorization` header — so no proxy-agent dependency is
301
+ * needed. The status endpoint (`http://proxy.apify.com`) is plain HTTP.
302
+ */
303
+ async requestStatus(statusUrl, proxyUrl) {
304
+ const target = new URL(statusUrl);
305
+ const proxy = new URL(proxyUrl);
306
+ const headers = { host: target.host };
307
+ if (proxy.username) {
308
+ const credentials = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
309
+ headers['proxy-authorization'] = `Basic ${Buffer.from(credentials).toString('base64')}`;
310
+ }
311
+ const request = httpRequest({
312
+ host: proxy.hostname,
313
+ port: proxy.port,
314
+ // Absolute-form request URI tells the proxy to forward the request.
315
+ path: target.href,
316
+ headers,
317
+ signal: AbortSignal.timeout(CHECK_ACCESS_REQUEST_TIMEOUT_MILLIS),
318
+ });
319
+ request.end();
320
+ // `once` rejects if the request emits `error` first (connection refused,
321
+ // timeout/abort), so failures propagate to the retry loop in `fetchStatus`.
322
+ const [response] = (await once(request, 'response'));
323
+ const statusCode = response.statusCode ?? 0;
324
+ if (statusCode < 200 || statusCode >= 300) {
325
+ response.resume(); // drain so the socket can be freed
326
+ throw new Error(`Apify Proxy status check responded with status code ${statusCode}.`);
327
+ }
328
+ return (await json(response));
329
+ }
312
330
  /**
313
331
  * Throws cannot combine custom proxies with Apify Proxy
314
332
  * @internal
315
333
  */
316
- _throwCannotCombineCustomWithApify() {
334
+ throwCannotCombineCustomWithApify() {
317
335
  throw new Error('Cannot combine custom proxies with Apify Proxy! ' +
318
336
  'It is not allowed to set "options.proxyUrls" or "options.newUrlFunction" combined with ' +
319
- '"options.groups" or "options.apifyProxyGroups" and "options.countryCode" or "options.apifyProxyCountry".');
337
+ '"options.groups", "options.apifyProxyGroups", "options.countryCode", "options.apifyProxyCountry", ' +
338
+ '"options.subdivisionCode" or "options.apifyProxySubdivision".');
320
339
  }
321
340
  }
322
- //# sourceMappingURL=proxy_configuration.js.map