@liqi0816/chrome-devtools-mcp-rebrowser 1.0.0 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  This project wraps [chrome-devtools-mcp](https://github.com/ChromeDevTools/chrome-devtools-mcp) with [rebrowser-patches](https://github.com/rebrowser/rebrowser-patches) to make AI agents undetectable by anti-bot systems like Cloudflare and DataDome.
4
4
 
5
+ ![negative bot detection result](./are-you-a-bot.webp)
6
+
5
7
  ## šŸ¤– AI
6
8
 
7
9
  Yes, I used AI. I also committed the full conversations as the real design documents (`.ai-conversations/` - private submodule, ask me for access).
@@ -16,7 +18,6 @@ Code is MIT. What license applies to human-AI conversation transcripts is an ope
16
18
 
17
19
  - **Node.js** ≄ 20.19.0 LTS
18
20
  - **Chrome** running with remote debugging enabled (go to `chrome://inspect/#remote-debugging`)
19
- - **Git** installed (provides `patch.exe` on Windows, needed for applying patches)
20
21
 
21
22
  ### Usage via `npx` (recommended)
22
23
 
@@ -32,7 +33,7 @@ No cloning or manual setup needed. Just configure your MCP client:
32
33
  "command": "npx",
33
34
  "args": [
34
35
  "-y",
35
- "chrome-devtools-mcp-rebrowser@latest",
36
+ "@liqi0816/chrome-devtools-mcp-rebrowser@latest",
36
37
  "--auto-connect",
37
38
  "--performance-crux=false",
38
39
  "--usage-statistics=false",
@@ -81,7 +82,7 @@ Then configure the MCP server to use the local entry point:
81
82
 
82
83
  ## How It Works
83
84
 
84
- `chrome-devtools-mcp` is Google's official MCP server for Chrome DevTools. It bundles its own copy of Puppeteer (v24.39.1) internally. This project intercepts its `puppeteer.connect()` and `puppeteer.launch()` calls and redirects them through a separately installed, rebrowser-patched version of `puppeteer-core`.
85
+ `chrome-devtools-mcp` is Google's official MCP server for Chrome DevTools. It bundles its own copy of Puppeteer internally. This project intercepts its `puppeteer.connect()` and `puppeteer.launch()` calls and redirects them through a separately installed, rebrowser-patched version of `puppeteer-core`.
85
86
 
86
87
  ### Architecture
87
88
 
@@ -89,7 +90,7 @@ Then configure the MCP server to use the local entry point:
89
90
  launch.mjs (entry point)
90
91
  │
91
92
  ā”œā”€ Imports patched puppeteer-core (node_modules/puppeteer-core)
92
- │ └─ puppeteer-core@24.39.1 + rebrowser-patches applied
93
+ │ └─ puppeteer-core@24.40.0 + rebrowser-patches applied
93
94
  │
94
95
  ā”œā”€ Imports bundled puppeteer from chrome-devtools-mcp
95
96
  │ └─ node_modules/chrome-devtools-mcp/build/src/third_party/index.js
@@ -114,8 +115,16 @@ DevToolsConnectionAdapter.js (patched)
114
115
  ### Why the Monkey-Patching?
115
116
 
116
117
  - `chrome-devtools-mcp` bundles Puppeteer in a single rollup file (`third_party/index.js`), so you can't simply swap out `puppeteer-core` via `package.json`.
117
- - `rebrowser-puppeteer` (the drop-in replacement) is only available up to v24.8.1, but `chrome-devtools-mcp@0.20.3` requires Puppeteer v24.39.1 APIs (e.g., `page.emulateFocusedPage()`).
118
- - Solution: install `puppeteer-core@24.39.1` separately, apply `rebrowser-patches` to it, then redirect the bundled Puppeteer's calls through the patched version.
118
+ - `rebrowser-puppeteer` (the drop-in replacement) is only available up to v24.8.1, but recent `chrome-devtools-mcp` releases require newer Puppeteer APIs (e.g., `page.emulateFocusedPage()` from v24.39+).
119
+ - Solution: install a compatible `puppeteer-core` separately, apply `rebrowser-patches` to it, then redirect the bundled Puppeteer's calls through the patched version.
120
+
121
+ ### Why `puppeteer-core` and `rebrowser-patches` are pinned to exact versions
122
+
123
+ You'll see `"puppeteer-core": "24.40.0"` and `"rebrowser-patches": "1.0.19"` (no caret) in `package.json`. This is deliberate — these two **must** move in lockstep:
124
+
125
+ `rebrowser-patches` is a set of **line-by-line unified diffs** against puppeteer-core's compiled output. Any upstream puppeteer-core release can add/remove lines near a hunk and make the patch stop applying — even patch-level releases. For example, `rebrowser-patches@1.0.19` was cut against puppeteer-core 24.40.x, and newer puppeteer-core (24.41+) adds fields to `IsolatedWorld.js` that break hunks (see [issue #4](https://github.com/liqi0816/chrome-devtools-mcp-rebrowser/issues/4)). Conversely, a newer `rebrowser-patches` release could target a different puppeteer-core line layout and stop applying to 24.40.0.
126
+
127
+ Both pins are bumped together whenever a new `rebrowser-patches` release catches up to a newer puppeteer-core. The remaining dependencies (`chrome-devtools-mcp`, `diff`) still float on `^` ranges because their APIs are stable and the patches we apply use fuzzy matching.
119
128
 
120
129
  ## Flags
121
130
 
@@ -185,21 +194,17 @@ This is an acceptable tradeoff since `Runtime.enable` is the primary CDP detecti
185
194
  - Check that `DevToolsActivePort` file exists in Chrome's user data directory
186
195
 
187
196
  ### Patch fails with "FAILED" hunks
188
- - The `es5-iife` hunk failure is expected and harmless
189
- - If CJS/ESM hunks fail, the puppeteer-core version may have changed too much. Try adjusting the `--fuzz` value or manually applying the changes
197
+ - The installed `puppeteer-core` version drifted past what `rebrowser-patches` knows how to patch. `postinstall.mjs` prints the exact installed versions and a link to [issue #4](https://github.com/liqi0816/chrome-devtools-mcp-rebrowser/issues/4) when this happens. Re-run with `npx -y @liqi0816/chrome-devtools-mcp-rebrowser@latest` — the pinned `puppeteer-core` and `rebrowser-patches` in `package.json` should keep the install reproducible.
190
198
 
191
199
  ### "emulateFocusedPage is not a function" (or similar)
192
- - Version mismatch: ensure `puppeteer-core` in `package.json` matches the version in `chrome-devtools-mcp`'s `devDependencies` (currently `24.39.1`)
193
-
194
- ### Postinstall fails — "`patch` command not found"
195
- - On Linux/macOS: `patch` is usually pre-installed. If not: `sudo apt install patch` or `brew install gpatch`.
196
- - On Windows: Install [Git for Windows](https://gitforwindows.org/) — it bundles `patch.exe` at `C:\Program Files\Git\usr\bin\patch.exe`. Make sure it's on your PATH.
200
+ - Version mismatch: ensure `puppeteer-core` in `package.json` is a version whose API is supported by the bundled Puppeteer inside `chrome-devtools-mcp` (see the Version Compatibility table below).
197
201
 
198
202
  ## Version Compatibility
199
203
 
200
- | Package | Version |
201
- |---------|---------|
202
- | chrome-devtools-mcp | 0.20.3 |
203
- | puppeteer-core | 24.39.1 |
204
- | rebrowser-patches | 1.0.19 |
205
- | Node.js | ≄ 20.19.0 |
204
+ | Package | Version | Pinned? |
205
+ |---------|---------|---------|
206
+ | chrome-devtools-mcp | ^0.22.0 | floats (fuzzy patch) |
207
+ | puppeteer-core | 24.40.0 | **exact** ([why](#why-puppeteer-core-and-rebrowser-patches-are-pinned-to-exact-versions)) |
208
+ | rebrowser-patches | 1.0.19 | **exact** ([why](#why-puppeteer-core-and-rebrowser-patches-are-pinned-to-exact-versions)) |
209
+ | diff | ^8.0.4 | floats |
210
+ | Node.js | ≄ 20.19.0 | — |
package/launch.mjs CHANGED
@@ -8,7 +8,8 @@ const require = createRequire(import.meta.url);
8
8
  // ---------------------------------------------------------------------------
9
9
  // Step 1: Import the patched puppeteer-core
10
10
  // ---------------------------------------------------------------------------
11
- // This is puppeteer-core@24.39.1 with rebrowser-patches applied in-place.
11
+ // This is puppeteer-core (pinned in package.json — currently 24.40.0) with
12
+ // rebrowser-patches applied in-place by postinstall.mjs.
12
13
  // The patches disable Runtime.Enable (the primary CDP detection vector),
13
14
  // change sourceURL from pptr:... to app.js, and rename the utility world.
14
15
  import puppeteerCore from 'puppeteer-core';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liqi0816/chrome-devtools-mcp-rebrowser",
3
- "version": "1.0.0",
3
+ "version": "1.0.3",
4
4
  "description": "Chrome DevTools MCP server with rebrowser anti-detection patches — undetectable by Cloudflare, DataDome, and other anti-bot systems",
5
5
  "keywords": [
6
6
  "mcp",
@@ -24,7 +24,7 @@
24
24
  "type": "module",
25
25
  "main": "launch.mjs",
26
26
  "bin": {
27
- "chrome-devtools-mcp-rebrowser": "./launch.mjs"
27
+ "chrome-devtools-mcp-rebrowser": "launch.mjs"
28
28
  },
29
29
  "files": [
30
30
  "launch.mjs",
@@ -35,12 +35,15 @@
35
35
  ],
36
36
  "scripts": {
37
37
  "postinstall": "node postinstall.mjs",
38
- "start": "node launch.mjs"
38
+ "start": "node launch.mjs",
39
+ "smoke-test": "node smoke-test.mjs",
40
+ "prepublishOnly": "npm run smoke-test"
39
41
  },
40
42
  "dependencies": {
41
- "chrome-devtools-mcp": "^0.20.3",
42
- "puppeteer-core": "^24.39.1",
43
- "rebrowser-patches": "^1.0.19"
43
+ "chrome-devtools-mcp": "^0.22.0",
44
+ "diff": "^8.0.4",
45
+ "puppeteer-core": "24.40.0",
46
+ "rebrowser-patches": "1.0.19"
44
47
  },
45
48
  "publishConfig": {
46
49
  "access": "public"
package/postinstall.mjs CHANGED
@@ -5,134 +5,184 @@
5
5
  * DevToolsConnectionAdapter patch so that `npx chrome-devtools-mcp-rebrowser`
6
6
  * works out of the box with zero manual setup.
7
7
  *
8
+ * Uses the pure-JS `diff` (jsdiff) library to apply unified patches,
9
+ * eliminating platform-specific differences between macOS/Linux/Windows
10
+ * `patch` binaries.
11
+ *
8
12
  * Runs after `npm install` (via package.json "postinstall" script).
9
13
  */
10
14
 
11
- import { execFile as execFileCb } from 'node:child_process';
12
- import { promisify } from 'node:util';
13
15
  import { createRequire } from 'node:module';
14
16
  import { dirname, join, resolve } from 'node:path';
15
- import { readFile, writeFile, unlink, mkdtemp } from 'node:fs/promises';
16
- import { tmpdir } from 'node:os';
17
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
18
+ import { parsePatch, applyPatch } from 'diff';
17
19
 
18
- const execFile = promisify(execFileCb);
19
20
  const require = createRequire(import.meta.url);
20
21
 
21
22
  // ---------------------------------------------------------------------------
22
23
  // Helpers
23
24
  // ---------------------------------------------------------------------------
24
25
 
25
- /** Resolve the directory of an installed package by its main/package.json */
26
+ /**
27
+ * Resolve the directory of an installed package by its main/package.json.
28
+ * @param {string} packageName
29
+ */
26
30
  function pkgDir(packageName) {
27
- const entry = require.resolve(`${packageName}/package.json`);
28
- return dirname(entry);
31
+ return dirname(require.resolve(`${packageName}/package.json`));
29
32
  }
30
33
 
31
- /** Find `patch` executable — on Windows try Git's bundled copy too */
32
- async function findPatch() {
33
- for (const base of [
34
- '',
35
- 'C:\\Program Files\\Git\\usr\\bin',
36
- 'C:\\Program Files (x86)\\Git\\usr\\bin',
37
- ]) {
38
- const cmd = join(base, 'patch');
39
- try {
40
- await execFile(cmd, ['--version']);
41
- return cmd;
42
- } catch {
43
- // not found, try next
44
- }
45
- }
46
- console.error(
47
- '✘ Could not find the `patch` command.\n' +
48
- ' On Linux/macOS it is usually pre-installed.\n' +
49
- ' On Windows, install Git for Windows — it bundles patch.exe in\n' +
50
- ' C:\\Program Files\\Git\\usr\\bin\\patch.exe\n' +
51
- ' and make sure it is on your PATH.',
52
- );
53
- throw new Error('Could not find `patch` executable');
34
+ /**
35
+ * Fuzzy line comparator for jsdiff's applyPatch.
36
+ *
37
+ * jsdiff has a hard constraint: context lines immediately adjacent to an
38
+ * insertion must match *exactly* (regardless of fuzzFactor). This fails when
39
+ * an upstream update adds parameters: `newPage()` → `newPage(options)`.
40
+ *
41
+ * This compareLine requires everything outside parentheses to match exactly,
42
+ * and inside parentheses one side must be a substring of the other — so
43
+ * `f()` matches `f(options)` but `f(a)` does NOT match `f(completely_different)`.
44
+ *
45
+ * This is safe because jsdiff keeps the file's original content for context
46
+ * lines — the comparator only affects *where* the hunk is placed.
47
+ *
48
+ * @param {number} _lineNumber — 1-based line number in the target file
49
+ * @param {string} line — line from the target file
50
+ * @param {'+' | '-' | ' '} _operation — hunk operation (unused)
51
+ * @param {string} patchContent — expected line from the patch
52
+ */
53
+ function fuzzyCompareLine(_lineNumber, line, _operation, patchContent) {
54
+ if (line === patchContent) return true;
55
+ if (line == null || patchContent == null) return false;
56
+
57
+ const openL = line.indexOf('('), closeL = line.lastIndexOf(')');
58
+ const openP = patchContent.indexOf('('), closeP = patchContent.lastIndexOf(')');
59
+ if (openL < 0 || closeL < 0 || openP < 0 || closeP < 0) return false;
60
+
61
+ // Everything outside the parens must match exactly
62
+ if (line.slice(0, openL) !== patchContent.slice(0, openP)) return false;
63
+ if (line.slice(closeL + 1) !== patchContent.slice(closeP + 1)) return false;
64
+
65
+ // Inside: one must be a substring of the other
66
+ const innerL = line.slice(openL + 1, closeL);
67
+ const innerP = patchContent.slice(openP + 1, closeP);
68
+ return innerL.includes(innerP) || innerP.includes(innerL);
54
69
  }
55
70
 
56
71
  /**
57
- * Strip hunks that target paths matching `filterRe` from a unified diff.
58
- * Returns the filtered patch as a string.
72
+ * Apply a single-file patch with fuzzing.
73
+ * Returns the patched string, or false if it cannot be applied.
74
+ * @param {string} source — original file content
75
+ * @param {import('diff').StructuredPatch} filePatch — parsed single-file patch
76
+ * @param {number} [maxFuzz=10] — maximum fuzz factor (number of context lines that can mismatch)
59
77
  */
60
- function stripHunksFromPatch(patchContent, filterRe) {
61
- const lines = patchContent.split('\n');
62
- const kept = [];
63
- let skipping = false;
64
-
65
- for (const line of lines) {
66
- // Each file section starts with "--- a/..."
67
- if (line.startsWith('--- a/')) {
68
- const path = line.slice('--- a/'.length);
69
- skipping = filterRe.test(path);
70
- }
71
- if (!skipping) kept.push(line);
72
- }
73
- return kept.join('\n');
78
+ function applyWithFuzz(source, filePatch, maxFuzz = 10) {
79
+ // Try with exact context lines first (jsdiff internally tries 0..maxFuzz errors)
80
+ const exact = applyPatch(source, filePatch, { fuzzFactor: maxFuzz });
81
+ if (exact !== false) return exact;
82
+ // Fallback: fuzzy context for changed function signatures (e.g. newPage() → newPage(options))
83
+ return applyPatch(source, filePatch, { fuzzFactor: maxFuzz, compareLine: fuzzyCompareLine });
74
84
  }
75
85
 
76
86
  /**
77
- * Apply a patch file to a target directory.
78
- *
79
- * Captures stdout/stderr so we can distinguish "already applied" from real
80
- * failures. With `--forward`, GNU patch exits 1 both when every hunk was
81
- * previously applied *and* when some hunks genuinely fail. We tell the two
82
- * apart by checking the output for FAILED hunks.
87
+ * Apply a multi-file unified patch to a target directory.
88
+ * Handles new files (/dev/null → b/path) and skips already-patched files.
89
+ * @param {string} targetDir — absolute path to the package root
90
+ * @param {string} patchContent — raw unified diff string
91
+ * @param {object} [options]
92
+ * @param {number} [options.maxFuzz] — maximum fuzz factor passed to applyWithFuzz
93
+ * @param {(fp: import('diff').StructuredPatch) => boolean} [options.filter] — predicate to select file patches
94
+ * @returns {Promise<{applied: number, skipped: number, failed: string[]}>}
83
95
  */
84
- async function applyPatch(patchBin, targetDir, patchFile, { fuzz } = {}) {
85
- const args = [
86
- '--batch',
87
- '-p1',
88
- `--input=${patchFile}`,
89
- '--verbose',
90
- '--no-backup-if-mismatch',
91
- '--reject-file=-',
92
- '--forward',
93
- ];
94
- if (fuzz != null) args.push(`--fuzz=${fuzz}`);
95
-
96
- try {
97
- const { stdout, stderr } = await execFile(patchBin, args, { cwd: targetDir });
98
- process.stdout.write(stdout);
99
- process.stderr.write(stderr);
100
- console.log(`āœ” Patch applied successfully in ${targetDir}`);
101
- } catch (err) {
102
- // execFile rejects for any non-zero exit code.
103
- process.stdout.write(err.stdout);
104
- process.stderr.write(err.stderr);
105
-
106
- // Check whether every hunk was "Reversed (or previously applied)".
107
- // If so (and there are zero FAILED hunks), this is a genuine
108
- // "already applied" situation.
109
- const hasFailedHunks = /FAILED/i.test(err.stdout);
110
- const hasReversed = /Reversed \(or previously applied\) patch detected/i.test(err.stdout);
111
-
112
- if (hasReversed && !hasFailedHunks) {
113
- console.log(`āœ” Patch already applied in ${targetDir} (skipped)`);
114
- return;
96
+ async function applyMultiPatch(targetDir, patchContent, { maxFuzz , filter } = {}) {
97
+ let filePatches = parsePatch(patchContent);
98
+ if (filter) filePatches = filePatches.filter(filter);
99
+
100
+ const stats = { applied: 0, skipped: 0, failed: [] };
101
+
102
+ for (const fp of filePatches) {
103
+ // New file: oldFileName is "/dev/null", use newFileName ("b/path/to/file")
104
+ // Existing file: oldFileName is "a/path/to/file"
105
+ const isNewFile = fp.oldFileName === '/dev/null';
106
+ const rel = isNewFile ? fp.newFileName.slice(2) : fp.oldFileName.slice(2);
107
+
108
+ // For new files, check if already created by a previous run
109
+ let src;
110
+ try { src = await readFile(join(targetDir, rel), 'utf8'); }
111
+ catch (e) {
112
+ if (e.code === 'ENOENT' && isNewFile) src = '';
113
+ else throw e;
115
114
  }
116
115
 
117
- // Any other non-zero exit is a real error.
118
- throw new Error(
119
- `✘ Patch failed in ${targetDir} (exit code ${err.code ?? err.status ?? '?'})`,
120
- );
116
+ // Check if patch content is already present (idempotent)
117
+ const added = fp.hunks.flatMap(h => h.lines.filter(l => l[0] === '+').map(l => l.slice(1).trim())).filter(Boolean);
118
+ if (added.length > 0 && added.every(l => src.includes(l))) { stats.skipped++; continue; }
119
+
120
+ const result = applyWithFuzz(src, fp, maxFuzz);
121
+ if (result !== false) {
122
+ const dest = join(targetDir, rel);
123
+ if (isNewFile) await mkdir(dirname(dest), { recursive: true });
124
+ await writeFile(dest, result);
125
+ stats.applied++;
126
+ } else {
127
+ stats.failed.push(rel);
128
+ }
121
129
  }
130
+ return stats;
122
131
  }
123
132
 
124
133
  // ---------------------------------------------------------------------------
125
134
  // Main
126
135
  // ---------------------------------------------------------------------------
127
136
 
137
+ /**
138
+ * Read the installed version of a package, or 'unknown' if it can't be resolved.
139
+ * @param {string} packageName
140
+ */
141
+ function pkgVersion(packageName) {
142
+ try { return require(`${packageName}/package.json`).version; }
143
+ catch { return 'unknown'; }
144
+ }
145
+
146
+ /**
147
+ * Print a big, impossible-to-miss error block with diagnostic info and a link to
148
+ * the known-compatibility issue. Tuned specifically for issue #4: a
149
+ * `puppeteer-core` / `rebrowser-patches` version mismatch silently produces an
150
+ * unpatchable install. Both are now pinned exact in package.json, so this path
151
+ * should only fire if a user has overridden the pins or is running from a fork.
152
+ *
153
+ * @param {string} stage — human-readable stage name that failed
154
+ * @param {string[]} failed — list of patch target files that did not apply
155
+ * @param {Record<string, string>} versions — installed versions for context
156
+ */
157
+ function printPatchFailureReport(stage, failed, versions) {
158
+ const lines = [
159
+ '',
160
+ '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━',
161
+ `✘ chrome-devtools-mcp-rebrowser postinstall: ${stage} FAILED`,
162
+ '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━',
163
+ '',
164
+ 'The following patch targets could not be applied:',
165
+ ...failed.map(f => ` • ${f}`),
166
+ '',
167
+ 'Installed versions:',
168
+ ...Object.entries(versions).map(([k, v]) => ` • ${k}: ${v}`),
169
+ '',
170
+ 'This usually means one of the patched dependencies was upgraded past',
171
+ 'what rebrowser-patches knows how to handle. See:',
172
+ ' https://github.com/liqi0816/chrome-devtools-mcp-rebrowser/issues/4',
173
+ '',
174
+ 'Quickest workaround: pin the known-good versions locally, e.g.',
175
+ ' npx -y @liqi0816/chrome-devtools-mcp-rebrowser@1.0.3',
176
+ '(or whatever the latest published version is).',
177
+ '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━',
178
+ '',
179
+ ];
180
+ console.error(lines.join('\n'));
181
+ }
182
+
128
183
  async function main() {
129
184
  console.log('\nšŸ”§ chrome-devtools-mcp-rebrowser: postinstall\n');
130
185
 
131
- // 1. Locate patch executable
132
- const patchBin = await findPatch();
133
- console.log(`Using patch: ${patchBin}\n`);
134
-
135
- // 2. Resolve package directories
136
186
  const puppeteerCoreDir = pkgDir('puppeteer-core');
137
187
  const rebrowserPatchesDir = pkgDir('rebrowser-patches');
138
188
  const chromeDevtoolsMcpDir = pkgDir('chrome-devtools-mcp');
@@ -140,48 +190,40 @@ async function main() {
140
190
  dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/i, '$1')),
141
191
  );
142
192
 
143
- console.log(`puppeteer-core: ${puppeteerCoreDir}`);
144
- console.log(`rebrowser-patches: ${rebrowserPatchesDir}`);
145
- console.log(`chrome-devtools-mcp: ${chromeDevtoolsMcpDir}`);
146
- console.log(`own package: ${ownDir}\n`);
147
-
148
- // 3. Apply rebrowser-patches to puppeteer-core (with fuzz for version tolerance)
149
- // The upstream patch includes hunks for lib/es5-iife/ which is a bundled
150
- // build that doesn't exist in every puppeteer-core release and doesn't
151
- // affect Node-side behaviour. We strip those hunks so they can't cause
152
- // spurious failures.
153
- const rebrowserPatchFile = join(
154
- rebrowserPatchesDir,
155
- 'patches',
156
- 'puppeteer-core',
157
- 'lib.patch',
193
+ const versions = {
194
+ 'puppeteer-core': pkgVersion('puppeteer-core'),
195
+ 'rebrowser-patches': pkgVersion('rebrowser-patches'),
196
+ 'chrome-devtools-mcp': pkgVersion('chrome-devtools-mcp'),
197
+ };
198
+ console.log('Installed:', Object.entries(versions).map(([k, v]) => `${k}@${v}`).join(', '));
199
+ console.log('');
200
+
201
+ // 1. Apply rebrowser-patches to puppeteer-core
202
+ console.log('--- Applying rebrowser-patches to puppeteer-core ---');
203
+ const rebrowserPatch = await readFile(
204
+ join(rebrowserPatchesDir, 'patches', 'puppeteer-core', 'lib.patch'), 'utf8',
158
205
  );
159
-
160
- const rawPatch = await readFile(rebrowserPatchFile, 'utf8');
161
- const filteredPatch = stripHunksFromPatch(rawPatch, /^lib\/es5-iife\//);
162
-
163
- // Write the filtered patch to a temp file
164
- const tmpDir = await mkdtemp(join(tmpdir(), 'rebrowser-'));
165
- const filteredPatchFile = join(tmpDir, 'lib-no-es5-iife.patch');
166
- await writeFile(filteredPatchFile, filteredPatch);
167
-
168
- try {
169
- console.log('--- Applying rebrowser-patches to puppeteer-core (es5-iife stripped) ---');
170
- await applyPatch(patchBin, puppeteerCoreDir, filteredPatchFile, { fuzz: 10 });
171
- } finally {
172
- // Clean up temp file
173
- await unlink(filteredPatchFile).catch(() => {});
206
+ const r1 = await applyMultiPatch(puppeteerCoreDir, rebrowserPatch, {
207
+ maxFuzz: 10,
208
+ filter: ({ oldFileName }) => !oldFileName.startsWith('a/lib/es5-iife')
209
+ });
210
+ console.log(` āœ” ${r1.applied} applied, ${r1.skipped} skipped`);
211
+ if (r1.failed.length) {
212
+ printPatchFailureReport('rebrowser-patches → puppeteer-core', r1.failed, versions);
213
+ throw new Error(`Failed patches: ${r1.failed.join(', ')}`);
174
214
  }
175
215
 
176
- // 4. Apply DevToolsConnectionAdapter patch to chrome-devtools-mcp
177
- const adapterPatchFile = join(
178
- ownDir,
179
- 'patches',
180
- 'chrome-devtools-mcp',
181
- 'DevToolsConnectionAdapter.js.patch',
216
+ // 2. Apply DevToolsConnectionAdapter patch to chrome-devtools-mcp
217
+ console.log('--- Applying DevToolsConnectionAdapter patch ---');
218
+ const adapterPatch = await readFile(
219
+ join(ownDir, 'patches', 'chrome-devtools-mcp', 'DevToolsConnectionAdapter.js.patch'), 'utf8',
182
220
  );
183
- console.log('\n--- Applying DevToolsConnectionAdapter patch to chrome-devtools-mcp ---');
184
- await applyPatch(patchBin, chromeDevtoolsMcpDir, adapterPatchFile);
221
+ const r2 = await applyMultiPatch(chromeDevtoolsMcpDir, adapterPatch, { maxFuzz: 2 });
222
+ console.log(` āœ” ${r2.applied} applied, ${r2.skipped} skipped`);
223
+ if (r2.failed.length) {
224
+ printPatchFailureReport('DevToolsConnectionAdapter patch → chrome-devtools-mcp', r2.failed, versions);
225
+ throw new Error(`Failed patches: ${r2.failed.join(', ')}`);
226
+ }
185
227
 
186
228
  console.log('\nāœ… All patches applied. Ready to use!\n');
187
229
  }