@crawlee/basic 4.0.0-beta.19 → 4.0.0-beta.191

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 (86) hide show
  1. package/README.md +14 -14
  2. package/index.d.ts +11 -2
  3. package/index.js +11 -1
  4. package/internals/autoscaling/autoscaled_pool.d.ts +198 -0
  5. package/internals/autoscaling/autoscaled_pool.js +388 -0
  6. package/internals/autoscaling/concurrency_system.d.ts +275 -0
  7. package/internals/autoscaling/concurrency_system.js +365 -0
  8. package/internals/autoscaling/cpu_load_signal.d.ts +43 -0
  9. package/internals/autoscaling/cpu_load_signal.js +46 -0
  10. package/internals/autoscaling/event_loop_load_signal.d.ts +51 -0
  11. package/internals/autoscaling/event_loop_load_signal.js +60 -0
  12. package/internals/autoscaling/index.d.ts +9 -0
  13. package/internals/autoscaling/index.js +9 -0
  14. package/internals/autoscaling/load_signal.d.ts +98 -0
  15. package/internals/autoscaling/load_signal.js +103 -0
  16. package/internals/autoscaling/memory_load_signal.d.ts +47 -0
  17. package/internals/autoscaling/memory_load_signal.js +104 -0
  18. package/internals/autoscaling/snapshotter.d.ts +84 -0
  19. package/internals/autoscaling/snapshotter.js +67 -0
  20. package/internals/autoscaling/storage_backend_load_signal.d.ts +56 -0
  21. package/internals/autoscaling/storage_backend_load_signal.js +73 -0
  22. package/internals/autoscaling/system_status.d.ts +122 -0
  23. package/internals/autoscaling/system_status.js +139 -0
  24. package/internals/autoscaling/weighted_avg.d.ts +5 -0
  25. package/internals/autoscaling/weighted_avg.js +14 -0
  26. package/internals/basic-crawler.d.ts +465 -335
  27. package/internals/basic-crawler.js +1402 -820
  28. package/internals/cookie_utils.d.ts +44 -0
  29. package/internals/cookie_utils.js +122 -0
  30. package/internals/crawler-run.d.ts +76 -0
  31. package/internals/crawler-run.js +142 -0
  32. package/internals/crawlers/context_pipeline.d.ts +71 -0
  33. package/internals/crawlers/context_pipeline.js +117 -0
  34. package/internals/crawlers/crawler_commons.d.ts +194 -0
  35. package/internals/crawlers/crawler_commons.js +1 -0
  36. package/internals/crawlers/error_snapshotter.d.ts +57 -0
  37. package/internals/crawlers/error_snapshotter.js +117 -0
  38. package/internals/crawlers/error_tracker.d.ts +54 -0
  39. package/internals/crawlers/error_tracker.js +308 -0
  40. package/internals/crawlers/index.d.ts +5 -0
  41. package/internals/crawlers/index.js +4 -0
  42. package/internals/crawlers/internals/types.d.ts +7 -0
  43. package/internals/crawlers/internals/types.js +1 -0
  44. package/internals/crawlers/statistics.d.ts +318 -0
  45. package/internals/crawlers/statistics.js +525 -0
  46. package/internals/crawling_request.d.ts +86 -0
  47. package/internals/crawling_request.js +127 -0
  48. package/internals/enqueue_links/enqueue_links.d.ts +152 -0
  49. package/internals/enqueue_links/enqueue_links.js +76 -0
  50. package/internals/enqueue_links/index.d.ts +2 -0
  51. package/internals/enqueue_links/index.js +2 -0
  52. package/internals/enqueue_links/shared.d.ts +99 -0
  53. package/internals/enqueue_links/shared.js +258 -0
  54. package/internals/errors.d.ts +55 -0
  55. package/internals/errors.js +67 -0
  56. package/internals/http.d.ts +9 -0
  57. package/internals/http.js +28 -0
  58. package/internals/request-timeout.d.ts +48 -0
  59. package/internals/request-timeout.js +73 -0
  60. package/internals/router.d.ts +306 -0
  61. package/internals/router.js +310 -0
  62. package/internals/send-request.d.ts +4 -4
  63. package/internals/send-request.js +22 -11
  64. package/internals/session_pool/consts.d.ts +3 -0
  65. package/internals/session_pool/consts.js +3 -0
  66. package/internals/session_pool/errors.d.ts +7 -0
  67. package/internals/session_pool/errors.js +11 -0
  68. package/internals/session_pool/fingerprint.d.ts +9 -0
  69. package/internals/session_pool/fingerprint.js +30 -0
  70. package/internals/session_pool/index.d.ts +4 -0
  71. package/internals/session_pool/index.js +4 -0
  72. package/internals/session_pool/session.d.ts +153 -0
  73. package/internals/session_pool/session.js +221 -0
  74. package/internals/session_pool/session_pool.d.ts +242 -0
  75. package/internals/session_pool/session_pool.js +429 -0
  76. package/internals/sitemap_request_loader.d.ts +196 -0
  77. package/internals/sitemap_request_loader.js +432 -0
  78. package/internals/throttling_request_manager.d.ts +214 -0
  79. package/internals/throttling_request_manager.js +825 -0
  80. package/package.json +19 -13
  81. package/index.d.ts.map +0 -1
  82. package/index.js.map +0 -1
  83. package/internals/basic-crawler.d.ts.map +0 -1
  84. package/internals/basic-crawler.js.map +0 -1
  85. package/internals/send-request.d.ts.map +0 -1
  86. package/internals/send-request.js.map +0 -1
@@ -0,0 +1,194 @@
1
+ import type { Awaitable, Dictionary, HttpRequestOptions, ISession, ProxyInfo, SendRequestOptions } from '@crawlee/types';
2
+ import type { ReadonlyDeep } from 'type-fest';
3
+ import type { AddRequestsBatchedResult, CrawleeLogger, Dataset, KeyValueStore, Request, RequestOptions, Source, StorageIdentifier } from '@crawlee/core';
4
+ import type { EnqueueUrlsOptions } from '../enqueue_links/index.js';
5
+ import type { CrawlingRequest } from '../crawling_request.js';
6
+ /** @internal */
7
+ export type IsAny<T> = 0 extends 1 & T ? true : false;
8
+ /**
9
+ * A request input (URL string, request-options object, or {@link Request}) whose `userData` is typed
10
+ * according to its `label`, based on a router's route map.
11
+ *
12
+ * When the route map is open (the default `Record<string, ...>`), this is just the regular loose
13
+ * {@link Source} input. When the map declares concrete labels, providing a `label` requires the matching
14
+ * `userData` shape and rejects labels not present in the map; unlabeled requests keep loose `userData`.
15
+ */
16
+ export type LabeledSource<Routes extends Record<keyof Routes, Dictionary>> = string extends keyof Routes ? string | Source : string | Request | ({
17
+ requestsFromUrl?: string;
18
+ regex?: RegExp;
19
+ } & ({
20
+ [Label in keyof Routes & string]: Omit<Partial<RequestOptions<Routes[Label]>>, 'label'> & {
21
+ label: Label;
22
+ };
23
+ }[keyof Routes & string] | (Omit<Partial<RequestOptions>, 'label'> & {
24
+ label?: undefined;
25
+ })));
26
+ /**
27
+ * The iterable/array of {@link LabeledSource} inputs accepted by the label-aware `addRequests`/`run`
28
+ * methods of a crawler bound to a typed router.
29
+ */
30
+ export type TypedRequestsLike<Routes extends Record<keyof Routes, Dictionary>> = AsyncIterable<LabeledSource<Routes>> | Iterable<LabeledSource<Routes>> | LabeledSource<Routes>[];
31
+ /**
32
+ * The label-aware `addRequests` method signature exposed on a request handler's context when the crawler is
33
+ * bound to a typed router. Mirrors {@link RestrictedCrawlingContext.addRequests} with typed sources.
34
+ */
35
+ export type TypedContextAddRequests<Routes extends Record<keyof Routes, Dictionary>> = (requestsLike: ReadonlyDeep<LabeledSource<Routes>[]>, options?: ReadonlyDeep<EnqueueUrlsOptions>) => Promise<AddRequestsBatchedResult>;
36
+ /**
37
+ * An `enqueueLinks`-options object with its `label`/`userData` retyped according to a router's route map: a
38
+ * declared `label` requires the matching `userData` shape (unknown labels are rejected), while unlabeled
39
+ * calls keep loose `userData`. Returns the options unchanged when the route map is open (the default).
40
+ */
41
+ type TypedEnqueueLinksOptions<Options, Routes extends Record<keyof Routes, Dictionary>> = string extends keyof Routes ? Options : Omit<Options, 'label' | 'userData'> & ({
42
+ [Label in keyof Routes & string]: {
43
+ label: Label;
44
+ userData?: Routes[Label];
45
+ };
46
+ }[keyof Routes & string] | {
47
+ label?: undefined;
48
+ userData?: Dictionary;
49
+ });
50
+ /**
51
+ * Transforms a context's existing `enqueueLinks` method so that the `label`/`userData` in its options follow
52
+ * the router's route map, while preserving everything else about the signature (argument optionality and
53
+ * return type, which differ between crawler types).
54
+ */
55
+ export type TypedContextEnqueueLinks<EnqueueLinks, Routes extends Record<keyof Routes, Dictionary>> = EnqueueLinks extends (options?: infer Options) => infer Result ? (options?: TypedEnqueueLinksOptions<Options, Routes>) => Result : EnqueueLinks extends (options: infer Options) => infer Result ? (options: TypedEnqueueLinksOptions<Options, Routes>) => Result : EnqueueLinks;
56
+ export type WithRequired<T, K extends keyof T> = T & {
57
+ [P in K]-?: T[P];
58
+ };
59
+ export type LoadedRequest<R extends Request> = WithRequired<R, 'id' | 'loadedUrl'>;
60
+ /** @internal */
61
+ export type LoadedContext<Context extends RestrictedCrawlingContext> = IsAny<Context> extends true ? Context : {
62
+ request: LoadedRequest<Context['request']>;
63
+ } & Omit<Context, 'request'>;
64
+ export interface RestrictedCrawlingContext<UserData extends Dictionary = Dictionary> {
65
+ id: string;
66
+ session: ISession;
67
+ /**
68
+ * An object with information about currently used proxy by the crawler
69
+ * and configured by the {@link ProxyConfiguration} class.
70
+ */
71
+ proxyInfo?: ProxyInfo;
72
+ /**
73
+ * The request being processed.
74
+ */
75
+ request: CrawlingRequest<UserData>;
76
+ /**
77
+ * This function allows you to push data to a {@link Dataset} specified by name, or the one currently used by the crawler.
78
+ *
79
+ * Shortcut for `crawler.pushData()`.
80
+ *
81
+ * @param [data] Data to be pushed to the default dataset.
82
+ */
83
+ pushData(data: ReadonlyDeep<Parameters<Dataset['pushData']>[0]>, datasetIdentifier?: string | StorageIdentifier): Promise<void>;
84
+ /**
85
+ * Add requests directly to the request queue currently used by the crawler.
86
+ *
87
+ * Optionally, the function allows you to filter the target URLs using an array of glob or regexp patterns,
88
+ * the same way {@link CrawlingContext.enqueueLinks|`enqueueLinks`} does for extracted links.
89
+ *
90
+ * @param requests The requests to add
91
+ * @param options Options for the request queue
92
+ */
93
+ addRequests: (requestsLike: ReadonlyDeep<(string | Source)[]>, options?: ReadonlyDeep<EnqueueUrlsOptions>) => Promise<AddRequestsBatchedResult>;
94
+ /**
95
+ * Returns the state - a piece of mutable persistent data shared across all the request handler runs.
96
+ */
97
+ useState: <State extends Dictionary = Dictionary>(defaultValue?: State) => Promise<State>;
98
+ /**
99
+ * Get a key-value store with given name or id, or the default one for the crawler.
100
+ */
101
+ getKeyValueStore: (identifier?: string | StorageIdentifier) => Promise<Pick<KeyValueStore, 'id' | 'name' | 'getValue' | 'getAutoSavedValue' | 'setValue' | 'getPublicUrl'>>;
102
+ /**
103
+ * A preconfigured logger for the request handler.
104
+ */
105
+ log: CrawleeLogger;
106
+ }
107
+ export interface CrawlingContext<UserData extends Dictionary = Dictionary> extends RestrictedCrawlingContext<UserData> {
108
+ /**
109
+ * Fires HTTP request via the internal HTTP client, allowing to override the request options on the fly.
110
+ *
111
+ * This is handy when you work with a browser crawler but want to execute some requests outside it (e.g. API requests).
112
+ * Check the [Skipping navigations for certain requests](https://crawlee.dev/js/docs/examples/skip-navigation) example for
113
+ * more detailed explanation of how to do that.
114
+ *
115
+ * ```ts
116
+ * async requestHandler({ sendRequest }) {
117
+ * const { body } = await sendRequest({
118
+ * // override headers only
119
+ * headers: { ... },
120
+ * });
121
+ * },
122
+ * ```
123
+ */
124
+ sendRequest: (requestOverrides?: Partial<HttpRequestOptions>, optionsOverrides?: SendRequestOptions) => Promise<Response>;
125
+ /**
126
+ * Register a function to be called at the very end of the request handling process. This is useful for resources that should be accessible to error handlers, for instance.
127
+ *
128
+ * The callback runs *outside* the request's storage transaction, so storage writes made here are
129
+ * applied immediately and are **not** rolled back when the request fails. In
130
+ * {@link AdaptivePlaywrightCrawler} it also runs once per request handler attempt, so a write
131
+ * here can land more than once for a single request. Push results from the request handler itself.
132
+ */
133
+ registerDeferredCleanup(cleanup: () => Promise<unknown>): void;
134
+ /**
135
+ * Registers `callback` to run once the request's storage writes have been committed, or once
136
+ * committing them has failed - the point where a write made in the handler can finally be reacted
137
+ * to where it was made. Two things belong here: side effects that must agree with what actually
138
+ * landed (result counters, progress reporting), and handling of a write that did not land at all.
139
+ *
140
+ * ```ts
141
+ * async requestHandler({ pushData, afterStorageCommit, useState }) {
142
+ * const state = await useState({ itemCount: 0 });
143
+ *
144
+ * await pushData(item);
145
+ * afterStorageCommit((error) => {
146
+ * if (error) {
147
+ * throw new NonRetryableError('The page is too big to store', { cause: error });
148
+ * }
149
+ * state.itemCount++;
150
+ * });
151
+ * }
152
+ * ```
153
+ *
154
+ * `useState()` is deliberately not transactional, which is what makes the counter case necessary:
155
+ * incrementing in the handler would keep the increment for a request that pushes an item and then
156
+ * fails, while the item itself is rolled back.
157
+ *
158
+ * Callbacks run in registration order, after the commit and before the request is marked as handled.
159
+ * The first one to throw propagates and the rest do not run; on a failed commit its error replaces
160
+ * the commit error, so a callback can decide what the request fails with. After a *successful*
161
+ * commit, a callback that throws fails the request **without a retry** whatever it throws - the
162
+ * writes are already durable and retrying would duplicate them, so anything that is not already a
163
+ * {@link NonRetryableError} is wrapped in an {@link AfterCommitError}.
164
+ *
165
+ * Callbacks are *not* run when the request handler itself fails - nothing was written, and
166
+ * `errorHandler` / `failedRequestHandler` cover that.
167
+ *
168
+ * Throws when storage is not transactional (`transactionalStorage: false`) - writes are then applied
169
+ * as they are made and throw at the call site on their own. In {@link AdaptivePlaywrightCrawler}
170
+ * the callback belongs to the current request handler attempt, so it runs only for the attempt whose
171
+ * writes are the ones being committed.
172
+ */
173
+ afterStorageCommit(callback: (error?: Error) => Awaitable<void>): void;
174
+ /**
175
+ * Gives the current request `secs` more seconds to finish, for when how long it needs is only apparent
176
+ * once it is already running - a listing page that turns out to have far more to scroll through than
177
+ * usual, say. Prefer `requestHandlerTimeoutSecs`, or a per-route override via
178
+ * {@link Router.addHandler|`router.addHandler`}, whenever the time needed is known up front.
179
+ *
180
+ * ```ts
181
+ * router.addHandler('LIST', async ({ extendTimeout, page }) => {
182
+ * const pageCount = await countPages(page);
183
+ * extendTimeout(pageCount * 10);
184
+ * await scrapeAllPages(page);
185
+ * });
186
+ * ```
187
+ *
188
+ * Extends the request handler's own timeout and the crawler's internal one together, so the extension
189
+ * is not immediately undone by the latter. Calling it from a handler that has already timed out does
190
+ * nothing.
191
+ */
192
+ extendTimeout(secs: number): void;
193
+ }
194
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,57 @@
1
+ import type { KeyValueStore } from '@crawlee/core';
2
+ import type { CrawlingContext } from '../crawlers/crawler_commons.js';
3
+ import type { ErrnoException } from './error_tracker.js';
4
+ import type { SnapshottableProperties } from './internals/types.js';
5
+ interface BrowserCrawlingContext {
6
+ saveSnapshot: (options: {
7
+ key: string;
8
+ }) => Promise<void>;
9
+ }
10
+ export interface SnapshotResult {
11
+ screenshotFileName?: string;
12
+ htmlFileName?: string;
13
+ }
14
+ interface ErrorSnapshot {
15
+ screenshotFileName?: string;
16
+ screenshotFileUrl?: string;
17
+ htmlFileName?: string;
18
+ htmlFileUrl?: string;
19
+ }
20
+ /**
21
+ * ErrorSnapshotter class is used to capture a screenshot of the page and a snapshot of the HTML when an error occurs during web crawling.
22
+ *
23
+ * This functionality is opt-in, and can be enabled via the crawler options:
24
+ *
25
+ * ```ts
26
+ * const crawler = new BasicCrawler({
27
+ * // ...
28
+ * statistics: new Statistics({ saveErrorSnapshots: true }),
29
+ * });
30
+ * ```
31
+ */
32
+ export declare class ErrorSnapshotter {
33
+ static readonly MAX_ERROR_CHARACTERS = 30;
34
+ static readonly MAX_HASH_LENGTH = 30;
35
+ static readonly MAX_FILENAME_LENGTH = 250;
36
+ static readonly BASE_MESSAGE = "An error occurred";
37
+ static readonly SNAPSHOT_PREFIX = "ERROR_SNAPSHOT";
38
+ /**
39
+ * Capture a snapshot of the error context.
40
+ */
41
+ captureSnapshot(error: ErrnoException, context: CrawlingContext & SnapshottableProperties): Promise<ErrorSnapshot>;
42
+ /**
43
+ * Captures a snapshot of the current page using the context.saveSnapshot function.
44
+ * This function is applicable for browser contexts only.
45
+ * Returns an object containing the filenames of the screenshot and HTML file.
46
+ */
47
+ contextCaptureSnapshot(context: BrowserCrawlingContext, fileName: string): Promise<SnapshotResult | undefined>;
48
+ /**
49
+ * Save the HTML snapshot of the page, and return the key it was stored under.
50
+ */
51
+ saveHTMLSnapshot(html: string, keyValueStore: Pick<KeyValueStore, 'setValue'>, fileName: string): Promise<string | undefined>;
52
+ /**
53
+ * Generate a unique fileName for each error snapshot.
54
+ */
55
+ generateFilename(error: ErrnoException): string;
56
+ }
57
+ export {};
@@ -0,0 +1,117 @@
1
+ import crypto from 'node:crypto';
2
+ /**
3
+ * ErrorSnapshotter class is used to capture a screenshot of the page and a snapshot of the HTML when an error occurs during web crawling.
4
+ *
5
+ * This functionality is opt-in, and can be enabled via the crawler options:
6
+ *
7
+ * ```ts
8
+ * const crawler = new BasicCrawler({
9
+ * // ...
10
+ * statistics: new Statistics({ saveErrorSnapshots: true }),
11
+ * });
12
+ * ```
13
+ */
14
+ export class ErrorSnapshotter {
15
+ static MAX_ERROR_CHARACTERS = 30;
16
+ static MAX_HASH_LENGTH = 30;
17
+ static MAX_FILENAME_LENGTH = 250;
18
+ static BASE_MESSAGE = 'An error occurred';
19
+ static SNAPSHOT_PREFIX = 'ERROR_SNAPSHOT';
20
+ /**
21
+ * Capture a snapshot of the error context.
22
+ */
23
+ async captureSnapshot(error, context) {
24
+ try {
25
+ const page = context?.page;
26
+ const body = context?.body;
27
+ const keyValueStore = await context?.getKeyValueStore();
28
+ // If the key-value store is not available, or the body and page are not available, return empty filenames
29
+ if (!keyValueStore || (!body && !page)) {
30
+ return {};
31
+ }
32
+ const fileName = this.generateFilename(error);
33
+ let screenshotFileName;
34
+ let htmlFileName;
35
+ if (page) {
36
+ const capturedFiles = await this.contextCaptureSnapshot(context, fileName);
37
+ if (capturedFiles) {
38
+ screenshotFileName = capturedFiles.screenshotFileName;
39
+ htmlFileName = capturedFiles.htmlFileName;
40
+ }
41
+ // If the snapshot for browsers failed to capture the HTML, try to capture it from the page content
42
+ if (!htmlFileName) {
43
+ const html = await page.content();
44
+ htmlFileName = html ? await this.saveHTMLSnapshot(html, keyValueStore, fileName) : undefined;
45
+ }
46
+ }
47
+ else if (typeof body === 'string') {
48
+ // for non-browser contexts
49
+ htmlFileName = await this.saveHTMLSnapshot(body, keyValueStore, fileName);
50
+ }
51
+ return {
52
+ screenshotFileName,
53
+ screenshotFileUrl: screenshotFileName && (await keyValueStore.getPublicUrl(screenshotFileName)),
54
+ htmlFileName,
55
+ htmlFileUrl: htmlFileName && (await keyValueStore.getPublicUrl(htmlFileName)),
56
+ };
57
+ }
58
+ catch {
59
+ return {};
60
+ }
61
+ }
62
+ /**
63
+ * Captures a snapshot of the current page using the context.saveSnapshot function.
64
+ * This function is applicable for browser contexts only.
65
+ * Returns an object containing the filenames of the screenshot and HTML file.
66
+ */
67
+ async contextCaptureSnapshot(context, fileName) {
68
+ try {
69
+ await context.saveSnapshot({ key: fileName });
70
+ return {
71
+ screenshotFileName: `${fileName}.jpg`,
72
+ htmlFileName: `${fileName}.html`,
73
+ };
74
+ }
75
+ catch {
76
+ return undefined;
77
+ }
78
+ }
79
+ /**
80
+ * Save the HTML snapshot of the page, and return the key it was stored under.
81
+ */
82
+ async saveHTMLSnapshot(html, keyValueStore, fileName) {
83
+ try {
84
+ await keyValueStore.setValue(fileName, html, { contentType: 'text/html' });
85
+ // The record key is `fileName` - returning it with an `.html` suffix (as v3 did,
86
+ // where local storage put the extension in the key) would break `getPublicUrl`.
87
+ return fileName;
88
+ }
89
+ catch {
90
+ return undefined;
91
+ }
92
+ }
93
+ /**
94
+ * Generate a unique fileName for each error snapshot.
95
+ */
96
+ generateFilename(error) {
97
+ const { SNAPSHOT_PREFIX, BASE_MESSAGE, MAX_HASH_LENGTH, MAX_ERROR_CHARACTERS, MAX_FILENAME_LENGTH } = ErrorSnapshotter;
98
+ // Create a hash of the error stack trace
99
+ const errorStackHash = crypto
100
+ .createHash('sha1')
101
+ .update(error.stack || error.message || '')
102
+ .digest('hex')
103
+ .slice(0, MAX_HASH_LENGTH);
104
+ const errorMessagePrefix = (error.message || BASE_MESSAGE).slice(0, MAX_ERROR_CHARACTERS).trim();
105
+ /**
106
+ * Remove non-word characters from the start and end of a string.
107
+ */
108
+ const sanitizeString = (str) => {
109
+ return str.replace(/^\W+|\W+$/g, '');
110
+ };
111
+ // Generate fileName and remove disallowed characters
112
+ const fileName = `${SNAPSHOT_PREFIX}_${sanitizeString(errorStackHash)}_${sanitizeString(errorMessagePrefix)}`
113
+ .replace(/\W+/g, '-') // Replace non-word characters with a dash
114
+ .slice(0, MAX_FILENAME_LENGTH);
115
+ return fileName;
116
+ }
117
+ }
@@ -0,0 +1,54 @@
1
+ import type { CrawlingContext } from '../crawlers/crawler_commons.js';
2
+ import { ErrorSnapshotter } from './error_snapshotter.js';
3
+ import type { SnapshottableProperties } from './internals/types.js';
4
+ /**
5
+ * Node.js Error interface
6
+ */
7
+ export interface ErrnoException extends Error {
8
+ errno?: number;
9
+ code?: string | number;
10
+ path?: string;
11
+ syscall?: string;
12
+ cause?: any;
13
+ }
14
+ export interface ErrorTrackerOptions {
15
+ showErrorCode: boolean;
16
+ showErrorName: boolean;
17
+ showStackTrace: boolean;
18
+ showFullStack: boolean;
19
+ showErrorMessage: boolean;
20
+ showFullMessage: boolean;
21
+ saveErrorSnapshots: boolean;
22
+ }
23
+ /**
24
+ * This class tracks errors and computes a summary of information like:
25
+ * - where the errors happened
26
+ * - what the error names are
27
+ * - what the error codes are
28
+ * - what is the general error message
29
+ *
30
+ * This is extremely useful when there are dynamic error messages, such as argument validation.
31
+ *
32
+ * Since the structure of the `tracker.result` object differs when using different options,
33
+ * it's typed as `Record<string, unknown>`. The most deep object has a `count` property, which is a number.
34
+ *
35
+ * It's possible to get the total amount of errors via the `tracker.total` property.
36
+ */
37
+ export declare class ErrorTracker {
38
+ #private;
39
+ result: Record<string, unknown>;
40
+ total: number;
41
+ errorSnapshotter?: ErrorSnapshotter;
42
+ constructor(options?: Partial<ErrorTrackerOptions>);
43
+ private updateGroup;
44
+ add(error: ErrnoException): void;
45
+ /**
46
+ * This method is async, because it captures a snapshot of the error context.
47
+ * We added this new method to avoid breaking changes.
48
+ */
49
+ addAsync(error: ErrnoException, context?: CrawlingContext): Promise<void>;
50
+ getUniqueErrorCount(): number;
51
+ getMostPopularErrors(count: number): [number, string[]][];
52
+ captureSnapshot(storage: Record<string, unknown>, error: ErrnoException, context: CrawlingContext & SnapshottableProperties): Promise<void>;
53
+ reset(): void;
54
+ }