@crawlee/browser-pool 4.0.0-beta.67 → 4.0.0-beta.68

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 (45) hide show
  1. package/abstract-classes/browser-plugin.d.ts +29 -1
  2. package/abstract-classes/browser-plugin.d.ts.map +1 -1
  3. package/abstract-classes/browser-plugin.js +58 -3
  4. package/abstract-classes/browser-plugin.js.map +1 -1
  5. package/browser-pool.d.ts +10 -0
  6. package/browser-pool.d.ts.map +1 -1
  7. package/browser-pool.js +22 -0
  8. package/browser-pool.js.map +1 -1
  9. package/fingerprinting/hooks.d.ts.map +1 -1
  10. package/fingerprinting/hooks.js +7 -0
  11. package/fingerprinting/hooks.js.map +1 -1
  12. package/index.d.ts +3 -0
  13. package/index.d.ts.map +1 -1
  14. package/index.js +2 -0
  15. package/index.js.map +1 -1
  16. package/launch-context.d.ts +13 -0
  17. package/launch-context.d.ts.map +1 -1
  18. package/launch-context.js +9 -1
  19. package/launch-context.js.map +1 -1
  20. package/package.json +4 -4
  21. package/playwright/playwright-browser.d.ts.map +1 -1
  22. package/playwright/playwright-browser.js.map +1 -1
  23. package/playwright/playwright-controller.d.ts.map +1 -1
  24. package/playwright/playwright-controller.js +4 -0
  25. package/playwright/playwright-controller.js.map +1 -1
  26. package/playwright/playwright-plugin.d.ts +6 -0
  27. package/playwright/playwright-plugin.d.ts.map +1 -1
  28. package/playwright/playwright-plugin.js +23 -0
  29. package/playwright/playwright-plugin.js.map +1 -1
  30. package/puppeteer/puppeteer-plugin.d.ts +3 -0
  31. package/puppeteer/puppeteer-plugin.d.ts.map +1 -1
  32. package/puppeteer/puppeteer-plugin.js +77 -44
  33. package/puppeteer/puppeteer-plugin.js.map +1 -1
  34. package/remote-browser-pool.d.ts +173 -0
  35. package/remote-browser-pool.d.ts.map +1 -0
  36. package/remote-browser-pool.js +192 -0
  37. package/remote-browser-pool.js.map +1 -0
  38. package/remote-browser-provider.d.ts +84 -0
  39. package/remote-browser-provider.d.ts.map +1 -0
  40. package/remote-browser-provider.js +68 -0
  41. package/remote-browser-provider.js.map +1 -0
  42. package/utils.d.ts +7 -0
  43. package/utils.d.ts.map +1 -1
  44. package/utils.js +19 -0
  45. package/utils.js.map +1 -1
@@ -0,0 +1,192 @@
1
+ import { serviceLocator } from '@crawlee/core';
2
+ import { BrowserPool } from './browser-pool.js';
3
+ import { RemoteBrowserProvider } from './remote-browser-provider.js';
4
+ /**
5
+ * Owns the lifecycle of remote browser sessions for a single {@link RemoteBrowserPool}: endpoint
6
+ * resolution, the user's `release()` callback, and a release-at-most-once guarantee. Implements
7
+ * {@link RemoteConnection} so it can be injected into a plugin.
8
+ */
9
+ class RemoteSessionRegistry {
10
+ endpoint;
11
+ onRelease;
12
+ log;
13
+ sessions = new Map();
14
+ nextToken = 0;
15
+ constructor(endpoint, onRelease, log) {
16
+ this.endpoint = endpoint;
17
+ this.onRelease = onRelease;
18
+ this.log = log;
19
+ }
20
+ async resolve(options) {
21
+ const resolved = typeof this.endpoint === 'function' ? await this.endpoint(options) : this.endpoint;
22
+ let result;
23
+ if (typeof resolved === 'string') {
24
+ if (!resolved)
25
+ throw new Error('Remote browser endpoint resolved to an empty string.');
26
+ result = { url: resolved };
27
+ }
28
+ else if (!resolved?.url) {
29
+ throw new Error("Remote browser endpoint() must return a URL string or an object with a non-empty 'url'.");
30
+ }
31
+ else {
32
+ result = resolved;
33
+ }
34
+ const token = this.nextToken++;
35
+ this.sessions.set(token, { url: result.url, context: result.context, released: false });
36
+ return { url: result.url, token };
37
+ }
38
+ async release(token) {
39
+ const session = this.sessions.get(token);
40
+ // Release at most once per session — guards a close()/teardown race (the `released` flag is set
41
+ // synchronously before the awaited onRelease, so releaseAll() can't double-fire an in-flight release).
42
+ if (!session || session.released)
43
+ return;
44
+ session.released = true;
45
+ try {
46
+ await this.onRelease?.({ endpoint: session.url, context: session.context });
47
+ }
48
+ catch (err) {
49
+ this.log.warning('Remote browser release() failed.', { error: err?.message });
50
+ }
51
+ finally {
52
+ this.sessions.delete(token);
53
+ }
54
+ }
55
+ /** Releases every session that is still open. Called on pool teardown so no remote session leaks. */
56
+ async releaseAll() {
57
+ await Promise.all([...this.sessions.keys()].map(async (token) => this.release(token)));
58
+ }
59
+ }
60
+ /**
61
+ * An {@link IBrowserPool} implementation for remote browser services.
62
+ *
63
+ * Unlike configuring a remote browser through a crawler's `launchContext`, this pool is the single owner
64
+ * of all remote-session concerns:
65
+ * - **endpoint resolution** — static URL, per-launch function, or {@link RemoteBrowserProvider};
66
+ * - **release lifecycle** — `release()` fires exactly once per session on close/crash/teardown (no leaks,
67
+ * no double-release);
68
+ * - **concurrency** — {@link RemoteBrowserPoolOptions.maxOpenBrowsers|maxOpenBrowsers} is enforced inside
69
+ * {@link RemoteBrowserPool.newPage|newPage}, which waits for a free slot rather than overshooting.
70
+ *
71
+ * The wrapped {@link BrowserPool} and its plugin only perform the library-specific `connect()` call.
72
+ *
73
+ * Pass an instance as the crawler's `browserPool` option:
74
+ *
75
+ * ```typescript
76
+ * import { PlaywrightPlugin, RemoteBrowserPool } from '@crawlee/browser-pool';
77
+ * import { PlaywrightCrawler } from 'crawlee';
78
+ * import playwright from 'playwright';
79
+ *
80
+ * const browserPool = new RemoteBrowserPool({
81
+ * browserPlugins: [new PlaywrightPlugin(playwright.chromium)],
82
+ * endpoint: 'wss://production-sfo.browserless.io?token=xxx',
83
+ * maxOpenBrowsers: 2,
84
+ * });
85
+ *
86
+ * const crawler = new PlaywrightCrawler({ browserPool });
87
+ * ```
88
+ *
89
+ * @category Browser management
90
+ */
91
+ export class RemoteBrowserPool {
92
+ /** The wrapped pool that performs the remote connections and serves pages. */
93
+ browserPool;
94
+ /** The wrapped pool viewed through the {@link IBrowserPool} contract (the bare type widens pages to `never`). */
95
+ pool;
96
+ registry;
97
+ slotPollIntervalMillis;
98
+ log;
99
+ /** Shared by all `newPage` callers waiting for a free slot, so they don't each register their own listeners. */
100
+ _capacityChange;
101
+ constructor(options) {
102
+ const { browserPlugins, endpoint, release, maxOpenBrowsers, connection = {}, browserPoolOptions = {}, slotPollIntervalMillis = 500, } = options;
103
+ this.log = serviceLocator.getLogger().child({ prefix: 'RemoteBrowserPool' });
104
+ this.slotPollIntervalMillis = slotPollIntervalMillis;
105
+ // A RemoteBrowserProvider carries its own endpoint, release, and maxOpenBrowsers.
106
+ const provider = endpoint instanceof RemoteBrowserProvider ? endpoint : undefined;
107
+ const resolvedEndpoint = provider
108
+ ? (opts) => provider.connect(opts)
109
+ : endpoint;
110
+ const resolvedRelease = provider
111
+ ? ({ context }) => provider.release(context)
112
+ : release;
113
+ const resolvedMax = maxOpenBrowsers ?? provider?.maxOpenBrowsers;
114
+ this.registry = new RemoteSessionRegistry(resolvedEndpoint, resolvedRelease, this.log);
115
+ // Wire every plugin for remote connection.
116
+ for (const plugin of browserPlugins) {
117
+ plugin.useRemoteConnection(this.registry, connection);
118
+ }
119
+ this.browserPool = new BrowserPool({ ...browserPoolOptions, browserPlugins });
120
+ this.pool = this.browserPool;
121
+ // Release a browser's remote session once it closes. The registry dedupes (close() schedules a delayed
122
+ // kill(), so BROWSER_CLOSED can fire twice), and destroy()'s releaseAll() backstops any that never close.
123
+ this.browserPool.on("browserLaunched" /* BROWSER_POOL_EVENTS.BROWSER_LAUNCHED */, (controller) => {
124
+ controller.once("browserClosed" /* BROWSER_CONTROLLER_EVENTS.BROWSER_CLOSED */, () => {
125
+ const token = controller.launchContext._remoteToken;
126
+ if (token !== undefined)
127
+ void this.registry.release(token);
128
+ });
129
+ });
130
+ if (resolvedMax !== undefined) {
131
+ this.browserPool.maxOpenBrowsers = resolvedMax;
132
+ }
133
+ }
134
+ /** Maximum number of remote browsers that may be open at the same time. */
135
+ get maxOpenBrowsers() {
136
+ return this.browserPool.maxOpenBrowsers;
137
+ }
138
+ set maxOpenBrowsers(value) {
139
+ this.browserPool.maxOpenBrowsers = value;
140
+ }
141
+ /**
142
+ * Opens a new page, waiting first until {@link RemoteBrowserPoolOptions.maxOpenBrowsers|maxOpenBrowsers}
143
+ * allows it (either a new browser slot is free, or an active browser still has page capacity).
144
+ */
145
+ async newPage(options) {
146
+ await this._waitForFreeSlot();
147
+ return this.pool.newPage(options);
148
+ }
149
+ async closePage(page, options) {
150
+ return this.pool.closePage(page, options);
151
+ }
152
+ async extractPageState(page) {
153
+ return this.pool.extractPageState(page);
154
+ }
155
+ async injectPageState(page, state) {
156
+ return this.pool.injectPageState(page, state);
157
+ }
158
+ /** Closes all browsers, releases any still-open remote sessions, and tears down the wrapped pool. */
159
+ async destroy() {
160
+ await this.browserPool.destroy();
161
+ // Backstop: release any sessions whose browser never emitted a close (e.g. dropped on teardown).
162
+ await this.registry.releaseAll();
163
+ }
164
+ /** Resolves once the wrapped pool can serve another page without exceeding `maxOpenBrowsers`. */
165
+ async _waitForFreeSlot() {
166
+ while (!this.browserPool.hasFreeBrowserSlot() && !this.browserPool.hasActiveBrowserWithFreeCapacity()) {
167
+ await this._nextCapacityChange();
168
+ }
169
+ }
170
+ /**
171
+ * Resolves on the next browser-retired / page-closed event, or after `slotPollIntervalMillis`. All
172
+ * concurrently-waiting `newPage` calls share a single promise (and a single pair of event listeners)
173
+ * per tick, so a fleet of saturated callers doesn't fan out into N listener pairs on the pool.
174
+ */
175
+ _nextCapacityChange() {
176
+ this._capacityChange ??= new Promise((resolve) => {
177
+ const done = () => {
178
+ clearTimeout(timer);
179
+ this.browserPool.off("browserRetired" /* BROWSER_POOL_EVENTS.BROWSER_RETIRED */, done);
180
+ this.browserPool.off("pageClosed" /* BROWSER_POOL_EVENTS.PAGE_CLOSED */, done);
181
+ this._capacityChange = undefined;
182
+ resolve();
183
+ };
184
+ const timer = setTimeout(done, this.slotPollIntervalMillis);
185
+ timer.unref?.();
186
+ this.browserPool.once("browserRetired" /* BROWSER_POOL_EVENTS.BROWSER_RETIRED */, done);
187
+ this.browserPool.once("pageClosed" /* BROWSER_POOL_EVENTS.PAGE_CLOSED */, done);
188
+ });
189
+ return this._capacityChange;
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,CAAC;QACjE,CAAC,CAAC,CAAC;QAEH,OAAO,IAAI,CAAC,eAAe,CAAC;IAChC,CAAC;CACJ"}
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Abstract base class for remote browser service providers.
3
+ *
4
+ * Implement this class to encapsulate the lifecycle of a remote browser session
5
+ * (creation, connection URL resolution, and cleanup). {@link RemoteBrowserPool}
6
+ * calls {@link connect} once per browser launch and {@link release} when the browser
7
+ * closes, crashes, the pool is destroyed, or the connection fails during launch.
8
+ *
9
+ * Pass the provider instance as the `endpoint` of a {@link RemoteBrowserPool}, then
10
+ * hand the pool to a crawler via its `browserPool` option:
11
+ *
12
+ * ```typescript
13
+ * const browserPool = new RemoteBrowserPool({
14
+ * browserPlugins: [new PlaywrightPlugin(playwright.chromium)],
15
+ * endpoint: new MyProvider(),
16
+ * });
17
+ *
18
+ * const crawler = new PlaywrightCrawler({ browserPool });
19
+ * ```
20
+ *
21
+ * **Example — simple static endpoint (e.g. Browserless):**
22
+ * ```typescript
23
+ * class BrowserlessProvider extends RemoteBrowserProvider {
24
+ * maxOpenBrowsers = 2; // respect the service's concurrent session limit
25
+ *
26
+ * async connect() {
27
+ * return { url: `wss://production-sfo.browserless.io?token=${token}` };
28
+ * }
29
+ * }
30
+ * ```
31
+ *
32
+ * **Example — session lifecycle with concurrency limit (e.g. Browserbase):**
33
+ * ```typescript
34
+ * class BrowserbaseProvider extends RemoteBrowserProvider<{ id: string }> {
35
+ * maxOpenBrowsers = 2; // respect the service's concurrent session limit
36
+ *
37
+ * async connect({ proxyUrl } = {}) {
38
+ * const session = await createSession(apiKey, projectId, {
39
+ * proxies: proxyUrl ? [{ type: 'external', server: proxyUrl }] : undefined,
40
+ * });
41
+ * return { url: session.connectUrl, context: { id: session.id } };
42
+ * }
43
+ *
44
+ * async release(context: { id: string }) {
45
+ * await releaseSession(apiKey, context.id);
46
+ * }
47
+ * }
48
+ * ```
49
+ */
50
+ export declare abstract class RemoteBrowserProvider<TContext extends Record<string, unknown> = Record<string, unknown>> {
51
+ /**
52
+ * Maximum number of browsers that can be open at the same time.
53
+ * Set this to your remote service's concurrent session limit to avoid 429 errors.
54
+ */
55
+ maxOpenBrowsers?: number;
56
+ /**
57
+ * Called once per browser launch. Return the WebSocket/CDP endpoint URL
58
+ * and an optional `context` object that will be passed back to {@link release}.
59
+ *
60
+ * @param options.proxyUrl - The proxy URL resolved by Crawlee's proxy configuration
61
+ * for this browser session. Pass it to your remote service's proxy API if supported.
62
+ */
63
+ abstract connect(options?: {
64
+ proxyUrl?: string;
65
+ }): Promise<{
66
+ url: string;
67
+ context?: TContext;
68
+ }> | {
69
+ url: string;
70
+ context?: TContext;
71
+ };
72
+ /**
73
+ * Called when the browser closes, crashes, the pool is destroyed, or the
74
+ * connection fails right after {@link connect} succeeds.
75
+ * Override this to clean up remote sessions, release API resources, etc.
76
+ *
77
+ * Errors thrown here are caught and logged as warnings — they never crash the crawler.
78
+ * Safe to assume this is called at most once per {@link connect} call.
79
+ *
80
+ * @param _context The same `context` object returned by {@link connect}.
81
+ */
82
+ release(_context: TContext): Promise<void>;
83
+ }
84
+ //# sourceMappingURL=remote-browser-provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remote-browser-provider.d.ts","sourceRoot":"","sources":["../src/remote-browser-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgDG;AACH,8BAAsB,qBAAqB,CAAC,QAAQ,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IAC1G;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;;;;OAMG;IACH,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;QACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;KACrB,GAAG,OAAO,CAAC;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,QAAQ,CAAA;KAAE,CAAC,GAAG;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,QAAQ,CAAA;KAAE;IAEtF;;;;;;;;;OASG;IACG,OAAO,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;CACnD"}
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Abstract base class for remote browser service providers.
3
+ *
4
+ * Implement this class to encapsulate the lifecycle of a remote browser session
5
+ * (creation, connection URL resolution, and cleanup). {@link RemoteBrowserPool}
6
+ * calls {@link connect} once per browser launch and {@link release} when the browser
7
+ * closes, crashes, the pool is destroyed, or the connection fails during launch.
8
+ *
9
+ * Pass the provider instance as the `endpoint` of a {@link RemoteBrowserPool}, then
10
+ * hand the pool to a crawler via its `browserPool` option:
11
+ *
12
+ * ```typescript
13
+ * const browserPool = new RemoteBrowserPool({
14
+ * browserPlugins: [new PlaywrightPlugin(playwright.chromium)],
15
+ * endpoint: new MyProvider(),
16
+ * });
17
+ *
18
+ * const crawler = new PlaywrightCrawler({ browserPool });
19
+ * ```
20
+ *
21
+ * **Example — simple static endpoint (e.g. Browserless):**
22
+ * ```typescript
23
+ * class BrowserlessProvider extends RemoteBrowserProvider {
24
+ * maxOpenBrowsers = 2; // respect the service's concurrent session limit
25
+ *
26
+ * async connect() {
27
+ * return { url: `wss://production-sfo.browserless.io?token=${token}` };
28
+ * }
29
+ * }
30
+ * ```
31
+ *
32
+ * **Example — session lifecycle with concurrency limit (e.g. Browserbase):**
33
+ * ```typescript
34
+ * class BrowserbaseProvider extends RemoteBrowserProvider<{ id: string }> {
35
+ * maxOpenBrowsers = 2; // respect the service's concurrent session limit
36
+ *
37
+ * async connect({ proxyUrl } = {}) {
38
+ * const session = await createSession(apiKey, projectId, {
39
+ * proxies: proxyUrl ? [{ type: 'external', server: proxyUrl }] : undefined,
40
+ * });
41
+ * return { url: session.connectUrl, context: { id: session.id } };
42
+ * }
43
+ *
44
+ * async release(context: { id: string }) {
45
+ * await releaseSession(apiKey, context.id);
46
+ * }
47
+ * }
48
+ * ```
49
+ */
50
+ export class RemoteBrowserProvider {
51
+ /**
52
+ * Maximum number of browsers that can be open at the same time.
53
+ * Set this to your remote service's concurrent session limit to avoid 429 errors.
54
+ */
55
+ maxOpenBrowsers;
56
+ /**
57
+ * Called when the browser closes, crashes, the pool is destroyed, or the
58
+ * connection fails right after {@link connect} succeeds.
59
+ * Override this to clean up remote sessions, release API resources, etc.
60
+ *
61
+ * Errors thrown here are caught and logged as warnings — they never crash the crawler.
62
+ * Safe to assume this is called at most once per {@link connect} call.
63
+ *
64
+ * @param _context The same `context` object returned by {@link connect}.
65
+ */
66
+ async release(_context) { }
67
+ }
68
+ //# sourceMappingURL=remote-browser-provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remote-browser-provider.js","sourceRoot":"","sources":["../src/remote-browser-provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgDG;AACH,MAAM,OAAgB,qBAAqB;IACvC;;;OAGG;IACH,eAAe,CAAU;IAazB;;;;;;;;;OASG;IACH,KAAK,CAAC,OAAO,CAAC,QAAkB,IAAkB,CAAC;CACtD"}
package/utils.d.ts CHANGED
@@ -3,6 +3,13 @@ import type { PlaywrightPlugin } from './playwright/playwright-plugin.js';
3
3
  import type { PuppeteerPlugin } from './puppeteer/puppeteer-plugin.js';
4
4
  export type UnwrapPromise<T> = T extends PromiseLike<infer R> ? UnwrapPromise<R> : T;
5
5
  export declare function noop(..._args: unknown[]): void;
6
+ /**
7
+ * Strips secrets from a URL so it can be safely included in logs and error messages. Removes userinfo
8
+ * credentials and the entire query string and fragment — remote browser services routinely carry tokens
9
+ * there (e.g. Browserless `?token=…`), and we can't tell which params are sensitive. Keeps the
10
+ * protocol, host, port, and path, which are enough to diagnose connection failures.
11
+ */
12
+ export declare function sanitizeEndpointForLog(endpoint: string): string;
6
13
  /**
7
14
  * This is required when using optional dependencies.
8
15
  * Importing a type gives `any`, but `Parameters<any>` gives `unknown[]` instead of `any`
package/utils.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AAC1E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iCAAiC,CAAC;AAEvE,MAAM,MAAM,aAAa,CAAC,CAAC,IAAI,CAAC,SAAS,WAAW,CAAC,MAAM,CAAC,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;AAErF,wBAAgB,IAAI,CAAC,GAAG,KAAK,EAAE,OAAO,EAAE,GAAG,IAAI,CAAG;AAElD;;;GAGG;AACH,MAAM,MAAM,cAAc,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,GAAG,KAAK,GAAG,IAAI,OAAO,EAAE,SAAS,UAAU,CAAC,CAAC,CAAC,GAAG,GAAG,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;AAEpH,MAAM,MAAM,uBAAuB,CAE/B,KAAK,SAAS,SAAS,OAAO,EAAE,EAEhC,MAAM,SAAS,aAAa,EAAE,GAAG,EAAE,IACnC,KAAK,SAAS,SAAS,CAAC,MAAM,UAAU,EAAE,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,MAAM,UAAU,EAAE,GAAG,MAAM,IAAI,CAAC,GAE1F,UAAU,SAAS,gBAAgB,GAE/B,uBAAuB,CAAC,IAAI,EAAE,CAAC,GAAG,MAAM,EAAE,gBAAgB,CAAC,CAAC,GAE5D,UAAU,SAAS,eAAe,GAEhC,uBAAuB,CAAC,IAAI,EAAE,CAAC,GAAG,MAAM,EAAE,eAAe,CAAC,CAAC,GAE3D,KAAK,GAEX,KAAK,SAAS,EAAE,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B,CAAC,CAAC,GAE5D,UAAU,SAAS,eAAe,GAEhC,uBAAuB,CAAC,IAAI,EAAE,CAAC,GAAG,MAAM,EAAE,eAAe,CAAC,CAAC,GAE3D,KAAK,GAEX,KAAK,SAAS,EAAE,GAEd,MAAM,GAEN,KAAK,SAAS,SAAS,CAAC,MAAM,CAAC,CAAC,EAAE,GAEhC;IAAC,CAAC;CAAC,SAAS,CAAC,eAAe,GAAG,gBAAgB,CAAC,GAE5C,CAAC,EAAE,GAEH,KAAK,GAET,MAAM,CAAC"}
package/utils.js CHANGED
@@ -1,2 +1,21 @@
1
1
  export function noop(..._args) { }
2
+ /**
3
+ * Strips secrets from a URL so it can be safely included in logs and error messages. Removes userinfo
4
+ * credentials and the entire query string and fragment — remote browser services routinely carry tokens
5
+ * there (e.g. Browserless `?token=…`), and we can't tell which params are sensitive. Keeps the
6
+ * protocol, host, port, and path, which are enough to diagnose connection failures.
7
+ */
8
+ export function sanitizeEndpointForLog(endpoint) {
9
+ try {
10
+ const url = new URL(endpoint);
11
+ url.username = '';
12
+ url.password = '';
13
+ url.search = '';
14
+ url.hash = '';
15
+ return url.toString();
16
+ }
17
+ catch {
18
+ return '<invalid URL>';
19
+ }
20
+ }
2
21
  //# sourceMappingURL=utils.js.map
package/utils.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAMA,MAAM,UAAU,IAAI,CAAC,GAAG,KAAgB,IAAS,CAAC"}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAMA,MAAM,UAAU,IAAI,CAAC,GAAG,KAAgB,IAAS,CAAC;AAElD;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CAAC,QAAgB;IACnD,IAAI,CAAC;QACD,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC;QAC9B,GAAG,CAAC,QAAQ,GAAG,EAAE,CAAC;QAClB,GAAG,CAAC,QAAQ,GAAG,EAAE,CAAC;QAClB,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC;QAChB,GAAG,CAAC,IAAI,GAAG,EAAE,CAAC;QACd,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAC;IAC1B,CAAC;IAAC,MAAM,CAAC;QACL,OAAO,eAAe,CAAC;IAC3B,CAAC;AACL,CAAC"}