@trawlme/skills 0.1.0 → 1.1.0

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
@@ -11,7 +11,10 @@ Follows the [Anthropic Agent Skills](https://github.com/anthropics/skills) layou
11
11
 
12
12
  | Skill | What it does |
13
13
  |---|---|
14
- | `trawl` | Use the `trawl` CLI to manage scraps (auth, list, run, watch, debug) |
14
+ | `trawl-cli` | Use the `trawl` CLI to manage scraps via @trawlme/cli (auth, list, create, run, watch, debug). |
15
+ | `trawl-scrap-design` | Best practices for writing the Puppeteer script body — selectors, returnData shape, params, validation, anti-patterns. |
16
+ | `trawl-scrap-account` | Authentication — Trawl-managed credentials, BYO-cookies (embedded and persisted flavours), session reuse. |
17
+ | `trawl-scrap-local-test` | Run a scrap locally with headed Chrome before publishing, mirroring the worker entry contract. |
15
18
 
16
19
  ## Install
17
20
 
@@ -32,7 +35,7 @@ npx @trawlme/skills install --local
32
35
  Install a specific skill only:
33
36
 
34
37
  ```bash
35
- npx @trawlme/skills install trawl
38
+ npx @trawlme/skills install trawl-cli
36
39
  ```
37
40
 
38
41
  ### Option 2 — via the Trawl CLI
@@ -46,15 +49,21 @@ trawl skills install
46
49
 
47
50
  The CLI bundles the skills and keeps them in sync with the CLI version.
48
51
 
52
+ ## Migrating from v0.1.x
53
+
54
+ In v0.1.x there was a single skill named `trawl`. v0.2.0 splits it into four focused skills (see the bundled skills table above). When you run `npx @trawlme/skills install` (or `update`), the installer detects the legacy `~/.claude/skills/trawl/` directory and removes it before installing the new four. No manual cleanup needed.
55
+
56
+ Restart Claude Code after the install for the new skills to be picked up.
57
+
49
58
  ## Usage
50
59
 
51
60
  Once installed, restart Claude Code. Skills auto-trigger when you ask Claude about Trawl, scraps, scheduling jobs, or use the `trawl` CLI.
52
61
 
53
62
  Example prompts:
54
- - "list my failed scraps from last week"
55
- - "create a scrap that scrapes example.com daily at 9am"
56
- - "why did scrap 64a... fail?"
57
- - "show me the data from my latest run"
63
+ - "list my failed scraps from last week" (`trawl-cli`)
64
+ - "create a scrap that scrapes example.com daily at 9am" (`trawl-cli` + `trawl-scrap-design`)
65
+ - "scrape a site behind login without giving Trawl my credentials" (`trawl-scrap-account`)
66
+ - "test my scrap locally before pushing" (`trawl-scrap-local-test`)
58
67
 
59
68
  ## Commands
60
69
 
@@ -69,7 +78,7 @@ trawlme-skills help Print usage
69
78
 
70
79
  ## Prerequisites
71
80
 
72
- The `trawl` skill assumes `@trawlme/cli` is installed and the user is authenticated:
81
+ The `trawl-cli` skill assumes `@trawlme/cli` is installed and the user is authenticated:
73
82
 
74
83
  ```bash
75
84
  npm install -g @trawlme/cli
package/bin/install.js CHANGED
@@ -26,6 +26,26 @@ function getVersion() {
26
26
  return pkg.version;
27
27
  }
28
28
 
29
+ const LEGACY_SKILL_DIRS = ['trawl']; // names removed in v0.2.0 due to rename
30
+
31
+ function migrateLegacy(scope) {
32
+ const base = getSkillsBase(scope);
33
+ for (const name of LEGACY_SKILL_DIRS) {
34
+ const legacy = join(base, name);
35
+ if (!existsSync(legacy)) continue;
36
+ try {
37
+ rmSync(legacy, { recursive: true, force: true });
38
+ if (existsSync(legacy)) {
39
+ console.warn(`[trawlme-skills] Legacy skill "${name}/" detected but could not be removed — please delete ${legacy} manually.`);
40
+ } else {
41
+ console.log(`[trawlme-skills] Legacy skill "${name}/" detected — removed (renamed in v0.2.0)`);
42
+ }
43
+ } catch (err) {
44
+ console.warn(`[trawlme-skills] Failed to remove legacy "${name}/": ${err.message}. Please delete ${legacy} manually.`);
45
+ }
46
+ }
47
+ }
48
+
29
49
  function installOne(name, scope) {
30
50
  const src = join(SKILLS_SOURCE, name);
31
51
  const dest = join(getSkillsBase(scope), name);
@@ -85,6 +105,7 @@ switch (cmd) {
85
105
  console.error('No skills found in package.');
86
106
  process.exit(1);
87
107
  }
108
+ migrateLegacy(scope);
88
109
  for (const name of skills) {
89
110
  const dest = installOne(name, scope);
90
111
  console.log(`✓ Installed "${name}" at ${dest}`);
package/package.json CHANGED
@@ -1,22 +1,32 @@
1
1
  {
2
2
  "name": "@trawlme/skills",
3
- "version": "0.1.0",
3
+ "version": "1.1.0",
4
4
  "description": "Claude Code skills for the Trawl CLI — teaches Claude how to manage scraps via @trawlme/cli",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "trawlme-skills": "bin/install.js"
8
8
  },
9
9
  "files": [
10
- "skills",
11
- "bin",
10
+ "skills/**/*.md",
11
+ "skills/**/run-local.mjs",
12
+ "bin/install.js",
12
13
  "README.md",
13
14
  "LICENSE"
14
15
  ],
15
16
  "engines": {
16
17
  "node": ">=18"
17
18
  },
19
+ "peerDependencies": {
20
+ "puppeteer-core": "^22.0.0"
21
+ },
22
+ "peerDependenciesMeta": {
23
+ "puppeteer-core": {
24
+ "optional": true
25
+ }
26
+ },
18
27
  "scripts": {
19
- "install-skill": "node bin/install.js"
28
+ "install-skill": "node bin/install.js",
29
+ "test": "node bin/install.test.mjs && node skills/trawl-scrap-local-test/scripts/run-local.test.mjs"
20
30
  },
21
31
  "keywords": [
22
32
  "trawl",
@@ -1,6 +1,6 @@
1
1
  ---
2
- name: trawl
3
- description: Use this skill when the user wants to manage Trawl scraps (scraping jobs) — listing, creating, running, watching, or inspecting them — or when working with the `trawl` command-line tool from the `@trawlme/cli` package. Trawl is a hosted scraping platform where each "scrap" is a Puppeteer-based scraping job that can run on a cron schedule and emit data.
2
+ name: trawl-cli
3
+ description: Use the `trawl` CLI to manage scraps via @trawlme/cli — listing, creating, running, watching, debugging. Triggers when the user mentions trawl, scraps, scheduled scraping jobs they own, or uses the `trawl` command. Does NOT cover writing the Puppeteer script body (see trawl-scrap-design), authentication flows (see trawl-scrap-account), or local test runs (see trawl-scrap-local-test).
4
4
  ---
5
5
 
6
6
  # Trawl CLI
@@ -15,7 +15,7 @@ Trigger when the user mentions:
15
15
  - The `trawl` CLI command (e.g. `trawl scraps list`)
16
16
  - Wanting to create / run / inspect a scraping job
17
17
 
18
- Do NOT trigger for generic "scrape this URL" requests with no Trawl context — point them at a generic Puppeteer/Playwright approach instead.
18
+ Do NOT trigger for generic "scrape this URL" requests with no Trawl context.
19
19
 
20
20
  ## Prerequisites
21
21
 
@@ -37,7 +37,7 @@ If the user gets `Session expired or invalid. Run: trawl login`, their stored JW
37
37
 
38
38
  ## Core commands
39
39
 
40
- All commands accept `--json` (where listed) for machine-readable output. Use `--json` whenever you need to pipe into other commands or parse the result.
40
+ All commands accept `--json` (where listed) for machine-readable or pipeable output.
41
41
 
42
42
  ### List scraps
43
43
 
@@ -70,14 +70,7 @@ Flags:
70
70
  - `-r, --request` — the Puppeteer script body (must call `returnData(arr)`)
71
71
  - `-s, --scrapper` — engine, defaults to `puppeteer`
72
72
 
73
- Minimal Puppeteer request body:
74
-
75
- ```js
76
- var page = await browser.newPage();
77
- await page.goto(TRAWL.url, { waitUntil: 'domcontentloaded' });
78
- var items = await page.$$eval('a', els => els.map(e => ({ title: e.textContent })));
79
- returnData(items);
80
- ```
73
+ For the script body, see the `trawl-scrap-design` skill.
81
74
 
82
75
  ### Update a scrap
83
76
 
@@ -104,16 +97,9 @@ trawl scraps rm <id> # prompts for confirmation
104
97
  trawl scraps rm <id> --force # no prompt, useful in scripts
105
98
  ```
106
99
 
107
- ## Scrap accounts (per-scrap auth)
108
-
109
- When the target site requires login, attach credentials to a scrap:
100
+ ## Scrap accounts
110
101
 
111
- ```bash
112
- trawl scraps account set <id> -u user@example.com -p '<password>'
113
- trawl scraps account status <id> --json # check session validity
114
- trawl scraps account clear-session <id> # force re-login on next run
115
- trawl scraps account delete <id> --force # remove stored creds
116
- ```
102
+ For per-scrap authentication, see the `trawl-scrap-account` skill. CLI commands: `trawl scraps account set/status/clear-session/delete`.
117
103
 
118
104
  ## Common patterns
119
105
 
@@ -144,7 +130,7 @@ trawl scraps run <id> --watch
144
130
 
145
131
  ## Output shapes (JSON)
146
132
 
147
- A scrap object has at minimum:
133
+ Scrap object shape:
148
134
 
149
135
  ```json
150
136
  {
@@ -161,7 +147,7 @@ A scrap object has at minimum:
161
147
  }
162
148
  ```
163
149
 
164
- `trawl scraps data <id> --json` returns whatever array the user's script passed to `returnData(...)`.
150
+ `trawl scraps data <id> --json` returns the array passed to `returnData(...)`.
165
151
 
166
152
  ## Errors to recognize
167
153
 
@@ -173,6 +159,6 @@ A scrap object has at minimum:
173
159
 
174
160
  ## What this skill does NOT do
175
161
 
176
- - Doesn't write the Puppeteer scraping logic for the user — that's their domain. Suggest patterns but let them iterate.
177
- - Doesn't bypass site anti-bot measures. If a scrap fails because of bot detection, the answer is on Trawl's side (worker fingerprint, sessions), not the CLI.
178
- - Doesn't manage billing, organizations, or workers. Those live on the web app at trawl.me.
162
+ - Script body → `trawl-scrap-design`
163
+ - Authentication / session injection → `trawl-scrap-account`
164
+ - Local debugging runs → `trawl-scrap-local-test`
@@ -0,0 +1,107 @@
1
+ ---
2
+ name: trawl-scrap-account
3
+ description: Use when scraping a site that requires authentication. Triggers on "scrape an authenticated site", "behind login", "I don't want to give my credentials to Trawl", "inject cookies", "reuse a session", "MFA", or any prompt about cookies/sessions on Trawl. Does NOT cover CLI account management (see trawl-cli), general script structure (see trawl-scrap-design), or local test runs (see trawl-scrap-local-test).
4
+ ---
5
+
6
+ # Trawl Scrap Account
7
+
8
+ Use when the target site requires authentication. Covers three flows: Trawl-managed credentials (legacy), BYO-cookies embedded in the script (flavour A), and BYO-cookies persisted via the Trawl API (flavour B).
9
+
10
+ ## The worker boundary
11
+
12
+ > **Don't add stealth in your script.** Trawl's worker handles fingerprinting, proxy rotation, and bot-detection countermeasures centrally. Adding stealth plugins, UA spoofing, viewport randomisation, or aggressive jitter in your script duplicates worker policy and causes drift. The worker's policy evolves; your script's hardcoded tricks won't.
13
+
14
+ Injecting cookies does not change the worker's fingerprint policy.
15
+
16
+ ## Decision tree
17
+
18
+ 1. **Plain username/password login, no MFA** → use **Trawl-managed credentials** (section below). Trawl stores credentials encrypted; the script reads `account.username` / `account.password` at runtime and calls `saveSession()` after a successful login to reuse the session on subsequent runs.
19
+
20
+ 2. **One-shot test or short-lived experiment, or you want to verify your cookies work before setting up persistence** → use **Flavour A — Embedded BYO-cookies**. Hard-code the cookie array directly in the script body. Accepts the trade-off that cookies are in plain text in the script source.
21
+
22
+ 3. **MFA, SSO, OAuth, or you don't want to hand credentials to Trawl** → use **Flavour B — Persisted BYO-cookies**. Export cookies from a logged-in browser session, push them into `account.session.cookies` via the Trawl API persistence endpoint, and the script reads them back before navigation. Cookies are encrypted at rest.
23
+
24
+ ## Trawl-managed credentials (legacy flow)
25
+
26
+ The script receives two VM globals injected by the worker:
27
+
28
+ - `account.username` — the username stored for this scrap account.
29
+ - `account.password` — the password stored for this scrap account.
30
+
31
+ After a successful login, call `saveSession(await page.cookies())` immediately. The worker persists the cookie array encrypted at rest and exposes it as `account.session.cookies` on the next run.
32
+
33
+ ```js
34
+ const page = await browser.newPage();
35
+
36
+ if (account.session?.cookies) {
37
+ // Saved session exists — restore cookies and skip the login flow.
38
+ await page.setCookie(...account.session.cookies);
39
+ await page.goto('https://example.com/dashboard', { waitUntil: 'domcontentloaded' });
40
+ } else {
41
+ // First run (or cleared session) — perform full login.
42
+ await page.goto('https://example.com/login', { waitUntil: 'domcontentloaded' });
43
+ await page.type('#username', account.username);
44
+ await page.type('#password', account.password);
45
+ await Promise.all([
46
+ page.click('button[type=submit]'),
47
+ page.waitForNavigation({ waitUntil: 'networkidle2' }),
48
+ ]);
49
+ // Persist cookies for the next run.
50
+ await saveSession(await page.cookies());
51
+ }
52
+ ```
53
+
54
+ See `references/session-flow.md` for the expanded pattern with error handling.
55
+
56
+ ## Flavour A — Embedded BYO-cookies
57
+
58
+ Hard-code the cookie array directly in the script body. Call `page.setCookie(...cookies)` before any `page.goto` on the target domain.
59
+
60
+ ```js
61
+ const cookies = [
62
+ {
63
+ name: 'session_id',
64
+ value: 'abc123',
65
+ domain: '.example.com',
66
+ path: '/',
67
+ httpOnly: true,
68
+ secure: true,
69
+ },
70
+ ];
71
+
72
+ const page = await browser.newPage();
73
+ await page.setCookie(...cookies);
74
+ await page.goto('https://example.com/dashboard', { waitUntil: 'domcontentloaded' });
75
+ ```
76
+
77
+ **Trade-off:** Cookies are in plain text in the script source. Use only for short-lived experiments or pre-validation before setting up flavour B. See `references/cookie-injection.md` for the export walkthrough.
78
+
79
+ ## Flavour B — Persisted BYO-cookies
80
+
81
+ Export cookies from a logged-in browser session and push them into `account.session.cookies` via the Trawl API persistence endpoint. The worker encrypts them at rest; the script reads the same global as the managed flow:
82
+
83
+ ```js
84
+ if (!account.session?.cookies) {
85
+ throw new Error('Flavour B requires account.session.cookies — push them via the persistence endpoint first.');
86
+ }
87
+
88
+ const page = await browser.newPage();
89
+ await page.setCookie(...account.session.cookies);
90
+ await page.goto('https://example.com/dashboard', { waitUntil: 'domcontentloaded' });
91
+ ```
92
+
93
+ Requires the persistence endpoint to be live (check Trawl API reference). See `references/cookie-injection.md` for domain matching, HttpOnly export, localStorage, and expiry handling.
94
+
95
+ ## Anti-patterns to avoid
96
+
97
+ Authentication does not change the worker boundary rules (see `trawl-scrap-design`):
98
+
99
+ - No stealth plugins even when cookies are set.
100
+ - No `waitForTimeout` — use state-based waits.
101
+ - No deep CSS chains for post-login selectors.
102
+
103
+ ## What this skill does NOT cover
104
+
105
+ - Scraping logic → `trawl-scrap-design`
106
+ - CLI account management → `trawl-cli` (`trawl scraps account set/status/clear-session/delete`)
107
+ - Local debugging runs → `trawl-scrap-local-test`
@@ -0,0 +1,95 @@
1
+ ---
2
+ title: Cookie Injection
3
+ ---
4
+
5
+ ### setCookie before goto
6
+
7
+ Call `page.setCookie(...cookies)` before `page.goto`. Cookies set after `goto` are ignored — request headers are already sent.
8
+
9
+ ```js
10
+ const page = await browser.newPage();
11
+ await page.setCookie(...cookies); // must come before goto
12
+ await page.goto('https://example.com/dashboard', { waitUntil: 'domcontentloaded' });
13
+ ```
14
+
15
+ ### HttpOnly cookies are invisible from JS
16
+
17
+ `document.cookie` and `page.evaluate(() => document.cookie)` silently skip HttpOnly cookies — the partial set won't authenticate the session. This is the most common silent failure.
18
+
19
+ Capture the full cookie set via:
20
+ - **DevTools** → Application → Cookies → select the domain → copy to JSON manually.
21
+ - **A WebExtensions-based Chrome extension** from https://chromewebstore.google.com/search/cookie%20exporter
22
+
23
+ ### Domain matching gotchas
24
+
25
+ Three distinct forms:
26
+
27
+ - `.example.com` (leading dot) — matches apex + all subdomains. Most session cookies use this.
28
+ - `example.com` (no dot) — apex only.
29
+ - `www.example.com` — that subdomain only.
30
+
31
+ When cookies don't apply, check `domain` first. Export the exact value from DevTools.
32
+
33
+ ```json
34
+ [
35
+ {
36
+ "name": "session_id",
37
+ "value": "abc123",
38
+ "domain": ".example.com",
39
+ "path": "/",
40
+ "httpOnly": true,
41
+ "secure": true
42
+ }
43
+ ]
44
+ ```
45
+
46
+ ### localStorage / sessionStorage parallel save
47
+
48
+ Some sites store JWTs in `localStorage`, not cookies. Detection signal: navigation succeeds but immediately redirects to `/login` despite valid cookies.
49
+
50
+ Capture localStorage from a logged-in session:
51
+
52
+ ```js
53
+ // In DevTools console on the logged-in page:
54
+ JSON.stringify(localStorage)
55
+ ```
56
+
57
+ Replay after `goto` via `page.evaluate`:
58
+
59
+ ```js
60
+ await page.goto('https://example.com/dashboard', { waitUntil: 'domcontentloaded' });
61
+ await page.evaluate((data) => {
62
+ for (const [k, v] of Object.entries(data)) localStorage.setItem(k, v);
63
+ }, capturedLocalStorage);
64
+ await page.reload({ waitUntil: 'domcontentloaded' });
65
+ ```
66
+
67
+ ### Cookies don't persist across worker runs except via Trawl session
68
+
69
+ The worker starts a fresh browser context on each run. Persistence requires:
70
+
71
+ - `saveSession(await page.cookies())` — stores encrypted, exposed as `account.session.cookies` next run.
72
+ - Flavour B persistence endpoint — cookies pushed externally.
73
+
74
+ Flavour A re-injects cookies from the script source on every run.
75
+
76
+ ### Exporting cookies from Chrome — walkthrough
77
+
78
+ 1. Log in to the target site in Chrome.
79
+ 2. Open DevTools → Application → Storage → Cookies → select the domain.
80
+ 3. Copy values to a JSON array matching `CookieParam` shape (`name`, `value`, `domain`, `path`, `httpOnly`, `secure`).
81
+
82
+ Or use a cookie-export extension: https://chromewebstore.google.com/search/cookie%20exporter
83
+
84
+ ### Storage state expiry
85
+
86
+ Signs of expired cookies:
87
+ - Navigation lands on `/login` or identity-provider redirect.
88
+ - First protected request returns 401 or 403.
89
+ - Page loads but user-specific data is absent (silent guest view).
90
+
91
+ Refresh:
92
+ 1. Log in locally in a fresh Chrome session.
93
+ 2. Export new cookies (walkthrough above).
94
+ 3. Re-upload via flavour B, or update the embedded array (flavour A).
95
+ 4. Trawl-managed flow: `trawl scraps account clear-session <id>` to force re-login on next run.
@@ -0,0 +1,86 @@
1
+ ---
2
+ title: Session Flow
3
+ ---
4
+
5
+ ### saveSession(cookies)
6
+
7
+ Async helper injected by the worker. Call after confirming login succeeded — not on the login page or an error page.
8
+
9
+ ```js
10
+ await saveSession(await page.cookies());
11
+ ```
12
+
13
+ The worker persists the cookie array encrypted. On the next run, `account.session.cookies` is populated and the login flow is skipped. Call once per run only.
14
+
15
+ ### Reuse pattern (full code)
16
+
17
+ ```js
18
+ const page = await browser.newPage();
19
+
20
+ if (account.session?.cookies) {
21
+ // Saved session exists — restore cookies and skip the login flow.
22
+ await page.setCookie(...account.session.cookies);
23
+ await page.goto('https://example.com/dashboard', { waitUntil: 'domcontentloaded' });
24
+ } else {
25
+ // First run (or cleared session) — perform full login.
26
+ await page.goto('https://example.com/login', { waitUntil: 'domcontentloaded' });
27
+ await page.type('#username', account.username);
28
+ await page.type('#password', account.password);
29
+ await Promise.all([
30
+ page.click('button[type=submit]'),
31
+ page.waitForNavigation({ waitUntil: 'networkidle2' }),
32
+ ]);
33
+ // Persist for the next run.
34
+ await saveSession(await page.cookies());
35
+ }
36
+ ```
37
+
38
+ `account.session` is `undefined` on the first run — hence the optional chain. Both branches must reach the same post-login URL before scraping starts.
39
+
40
+ ### Forced re-login
41
+
42
+ ```bash
43
+ trawl scraps account clear-session <scrap-id>
44
+ ```
45
+
46
+ The next run finds `account.session` undefined, falls into the login branch, and re-runs `saveSession` on success.
47
+
48
+ ### When the login flow itself breaks
49
+
50
+ Two failure modes:
51
+
52
+ **Navigation failed** — `page.waitForNavigation` throws (network error or timeout). The `try/catch` catches this only; it does NOT detect wrong credentials.
53
+
54
+ **Wrong credentials** — site redirects back to `/login` (navigational success, so `try/catch` never fires). Detect by checking `page.url()` after navigation resolves.
55
+
56
+ ```js
57
+ const page = await browser.newPage();
58
+
59
+ try {
60
+ await page.goto('https://example.com/login', { waitUntil: 'domcontentloaded' });
61
+ await page.type('#username', account.username);
62
+ await page.type('#password', account.password);
63
+ await Promise.all([
64
+ page.click('button[type=submit]'),
65
+ page.waitForNavigation({ waitUntil: 'networkidle2', timeout: 10000 }),
66
+ ]);
67
+ } catch (err) {
68
+ // Navigation timed out or network failed — distinct from wrong-credentials.
69
+ throw new Error(`Login navigation failed: ${err.message}`);
70
+ }
71
+
72
+ if (page.url().includes('/login')) {
73
+ // Form rejected our credentials and we're still on the login page.
74
+ throw new Error('Login failed: wrong credentials');
75
+ }
76
+
77
+ // Persist for next run only after we've confirmed login success.
78
+ await saveSession(await page.cookies());
79
+ ```
80
+
81
+ **Login form changed** — selector breakage, not credentials. Throw with the broken selector name so AI Fix can surface it:
82
+
83
+ ```js
84
+ const usernameField = await page.$('#username');
85
+ if (!usernameField) throw new Error('Login form changed — #username selector not found. Update the selector.');
86
+ ```
@@ -0,0 +1,141 @@
1
+ ---
2
+ name: trawl-scrap-design
3
+ description: Use when writing or fixing the Puppeteer script body for a Trawl scrap. Triggers on "create a scrap that...", "fix my scrap", "why does my scrap return 0 items", "scrape <site>", or any prompt about what to put inside the script. Does NOT cover CLI commands (see trawl-cli), authentication flows (see trawl-scrap-account), or local test runs (see trawl-scrap-local-test).
4
+ ---
5
+
6
+ # Trawl Scrap Design
7
+
8
+ Use when writing the Puppeteer script body that runs on a Trawl worker.
9
+
10
+ ## The worker boundary
11
+
12
+ The worker handles fingerprinting, proxy escalation, AI Fix, and schema validation. Your script handles selectors, returnData shape, params, and graceful failure. See `references/anti-patterns.md`.
13
+
14
+ > **Don't add stealth in your script.** Trawl's worker handles fingerprinting, proxy rotation, and bot-detection countermeasures centrally. Adding stealth plugins, UA spoofing, viewport randomisation, or aggressive jitter in your script duplicates worker policy and causes drift. The worker's policy evolves; your script's hardcoded tricks won't.
15
+
16
+ ## Selectors
17
+
18
+ Selector priority (most to least resilient):
19
+
20
+ 1. `data-*` attribute — stable across visual redesigns
21
+ 2. `aria-*` / `role` — semantically meaningful
22
+ 3. Stable class (short, non-generated, meaningful name)
23
+ 4. XPath with text anchor — use when no attribute is reliable
24
+
25
+ **One named selector per logical field.** Declare as constants at the top with a comment explaining the choice — AI Fix uses that context to pick a replacement when the selector breaks.
26
+
27
+ ```js
28
+ // data-testid is stable — the engineering team committed to never removing it
29
+ const PRICE_SEL = '[data-testid="product-price"]';
30
+ // Aria role used because the class name is generated (hash suffix)
31
+ const ADD_TO_CART_SEL = '[role="button"][aria-label="Add to cart"]';
32
+
33
+ const price = await page.$eval(PRICE_SEL, (el) => el.textContent.trim());
34
+ ```
35
+
36
+ ## Waits
37
+
38
+ - **`page.waitForSelector(selector)`** — most targeted; use as the default.
39
+ - **`page.waitForNetworkIdle()`** — for SPA-heavy pages where DOM updates trail XHR completion.
40
+ - **`page.waitForFunction(fn)`** — for state conditions that don't map to a single selector (e.g. item count growing).
41
+ - **`page.waitForResponse(urlMatcher)`** — to gate on a specific API call completing.
42
+
43
+ **Never use `page.waitForTimeout(N)`** — it is deprecated, flaky, and slow. Always use state-based waits.
44
+
45
+ ```js
46
+ // Good: state-based wait
47
+ await page.waitForSelector('[data-testid="results-loaded"]');
48
+
49
+ // Bad: fixed delay — never do this
50
+ // await page.waitForTimeout(3000);
51
+ ```
52
+
53
+ ## returnData shape
54
+
55
+ Return a flat JSON array. Each item is a plain object.
56
+
57
+ - Explicit `null` for optional fields that are absent — do not omit the key.
58
+ - Numbers as numbers, not strings — parse before returning.
59
+ - Dates as ISO-8601 UTC — `new Date(...).toISOString()`.
60
+
61
+ See `references/returndata-shapes.md` for full rules and examples.
62
+
63
+ ```js
64
+ returnData([
65
+ {
66
+ title: 'Widget Pro',
67
+ price: 29.99, // number, not "€29.99"
68
+ currency: 'EUR',
69
+ published_at: new Date('2024-03-15').toISOString(), // ISO-8601 UTC
70
+ discount_pct: null, // explicit null, not omitted
71
+ },
72
+ ]);
73
+ ```
74
+
75
+ ## Params
76
+
77
+ - **`TRAWL.url`** — the target URL, set by the scrap schedule. Treat as immutable; never override it.
78
+ - **`TRAWL.<custom>`** — any custom parameter defined in Settings → Parameters.
79
+ - **`RANDOM(...)`** — a helper that returns a random value from a list (see Trawl params docs).
80
+ - **`DATE(±N, unit, format)`** — a date helper that returns a formatted date offset from now.
81
+
82
+ Validate inputs early — throw before any network call if a required param is missing.
83
+
84
+ ```js
85
+ const { url, category } = TRAWL;
86
+ if (!category) throw new Error('Missing required param: category (set in Settings → Parameters)');
87
+
88
+ await page.goto(url, { waitUntil: 'domcontentloaded' });
89
+ ```
90
+
91
+ ## Resilience
92
+
93
+ Wrap each logical field in its own `try/catch` and return what you have. Throw only for structural failures that make the entire run meaningless.
94
+
95
+ ```js
96
+ let price = null;
97
+ try {
98
+ price = parseFloat(await page.$eval(PRICE_SEL, (el) => el.textContent.replace(/[^0-9.]/g, '')));
99
+ } catch (err) {
100
+ console.error('price extraction failed:', err.message);
101
+ // continue — return partial data with price: null
102
+ }
103
+
104
+ // Structural failure: the page never loaded — throw so the worker retries / escalates
105
+ const bodyText = await page.$eval('body', (el) => el.textContent);
106
+ if (bodyText.includes('Access Denied')) throw new Error('Access denied — escalate proxy tier');
107
+ ```
108
+
109
+ **Throw only for:**
110
+ - Auth missing (session cookie expired, login redirect)
111
+ - Page never loaded or returned a fatal error
112
+ - Required param missing
113
+
114
+ ## Anti-patterns (don't do this)
115
+
116
+ Full detail in `references/anti-patterns.md`. Summary:
117
+
118
+ - No `puppeteer-extra-plugin-stealth` or any stealth plugin in your script.
119
+ - No `setUserAgent(...)` — conflicts with worker UA policy.
120
+ - No `waitForTimeout(N)` — deprecated and flaky.
121
+ - No deep CSS chains (`div > div > div > span`) — break on every redesign.
122
+ - No random jitter as anti-bot defence — detection happens at fingerprint level before timing matters.
123
+ - No silent `.catch(() => {})` around data extraction.
124
+
125
+ ## Interaction patterns (when the page needs them)
126
+
127
+ Some pages hide data behind real UI interactions — scroll, hover, click, form fill. These are about **functional correctness**, not bot evasion. See `references/interaction-patterns.md` for patterns: lazy-load scroll, hover-to-reveal, click-to-expand, `page.type` form fill, state-transition waits, "next" pagination.
128
+
129
+ ## Canonical Trawl docs
130
+
131
+ - *Trawl Scraping docs (in-app help center)* — selector basics, `returnData`, scrap lifecycle.
132
+ - *Trawl Scraping Advanced docs* — proxy tiers, escalation triggers, rate-limit guidance.
133
+ - *Trawl Data Quality docs* — `checkSchema` usage; note that `validation_failed` is a distinct history status from `error` and `0 items`.
134
+ - *Trawl AI Features docs* — AI Fix quotas, how selector comments improve AI Fix accuracy.
135
+ - *Trawl Schedule + Parameters docs* — `TRAWL.<custom>` params, `RANDOM(...)` and `DATE(...)` helpers.
136
+
137
+ ## What this skill does NOT cover
138
+
139
+ - CLI commands → `trawl-cli`
140
+ - Authentication flows → `trawl-scrap-account`
141
+ - Local test runs → `trawl-scrap-local-test`
@@ -0,0 +1,86 @@
1
+ # Anti-Patterns — Trawl Scrap Scripts
2
+
3
+ These patterns are forbidden in Trawl scrap scripts. Each has a rationale and a public source citation.
4
+
5
+ ---
6
+
7
+ ## No in-script stealth libraries
8
+
9
+ `puppeteer-extra-plugin-stealth` is legacy — newer approaches operate at the CDP launch layer. Adding any stealth plugin duplicates what the worker does centrally and will drift when worker policy evolves. For stronger fingerprinting, use a higher proxy tier (*Trawl Scraping Advanced docs*).
10
+
11
+ Source: [scrapfly.io/blog/posts/puppeteer-stealth-complete-guide](https://scrapfly.io/blog/posts/puppeteer-stealth-complete-guide)
12
+
13
+ ---
14
+
15
+ ## No User-Agent spoofing
16
+
17
+ `page.setUserAgent(...)` is ineffective — detection cross-references UA against Client Hints, WebGL, canvas, and audio fingerprints. A spoofed UA string alone is easier to flag, not harder, and conflicts with the worker's UA policy.
18
+
19
+ Source: [browser-use.com/posts/bot-detection](https://browser-use.com/posts/bot-detection)
20
+
21
+ ---
22
+
23
+ ## No random jitter as primary defence
24
+
25
+ Bot detection decides at the fingerprint level — milliseconds before any timing signal exists. `Math.random() * 500` delays have no effect. Small jitter (200–800ms) is acceptable for **rate-limit politeness** only, never as an anti-bot mechanism.
26
+
27
+ Source: [browser-use.com/posts/bot-detection](https://browser-use.com/posts/bot-detection)
28
+
29
+ ---
30
+
31
+ ## No fixed setTimeout / waitForTimeout
32
+
33
+ `page.waitForTimeout(N)` is deprecated. `setTimeout` is unreliable under load and slows every run unconditionally. Use state-based waits:
34
+ - `page.waitForSelector(selector)` — most targeted
35
+ - `page.waitForNetworkIdle()` — for SPA-heavy pages
36
+ - `page.waitForFunction(fn)` — for complex DOM conditions
37
+ - `page.waitForResponse(urlMatcher)` — for API-driven state changes
38
+
39
+ Sources:
40
+ - [pptr.dev/api/puppeteer.page.waitfornetworkidle](https://pptr.dev/api/puppeteer.page.waitfornetworkidle)
41
+ - [dev.to/checkly/avoiding-hard-waits-in-playwright-and-puppeteer-272](https://dev.to/checkly/avoiding-hard-waits-in-playwright-and-puppeteer-272)
42
+
43
+ ---
44
+
45
+ ## No deep CSS chains
46
+
47
+ `div > div:nth-child(2) > div > span.price`-style selectors break on every layout refactor and give AI Fix no semantic context. Anchor on semantic attributes in priority order:
48
+ 1. `data-*` — stable by engineering convention
49
+ 2. `aria-*` / `role` — semantically meaningful
50
+ 3. Short, stable class name (not generated hash)
51
+ 4. XPath with text anchor — when nothing else works
52
+
53
+ Document *why* the selector was chosen in a comment — AI Fix uses it to find an equivalent.
54
+
55
+ Source: [rebrowser.net/blog/xpath-vs-css-selectors-a-comprehensive-guide-for-web-automation-and-testing](https://rebrowser.net/blog/xpath-vs-css-selectors-a-comprehensive-guide-for-web-automation-and-testing)
56
+
57
+ ---
58
+
59
+ ## No silent catch on data writes
60
+
61
+ Never swallow extraction errors silently:
62
+
63
+ ```js
64
+ // Bad — error is hidden, returnData gets undefined or wrong data
65
+ const price = await page.$eval(PRICE_SEL, (el) => el.textContent).catch(() => {});
66
+
67
+ // Good — log the error, return explicit null, let partial data flow
68
+ let price = null;
69
+ try {
70
+ price = parseFloat(await page.$eval(PRICE_SEL, (el) => el.textContent.replace(/[^0-9.]/g, '')));
71
+ } catch (err) {
72
+ console.error('price extraction failed:', err.message);
73
+ }
74
+ ```
75
+
76
+ Silent catches hide selector breakage from AI Fix. Explicit nulls surface in Trawl's Data Quality view; hidden undefined values do not.
77
+
78
+ ---
79
+
80
+ ## Sources
81
+
82
+ - https://pptr.dev/api/puppeteer.page.waitfornetworkidle
83
+ - https://dev.to/checkly/avoiding-hard-waits-in-playwright-and-puppeteer-272
84
+ - https://rebrowser.net/blog/xpath-vs-css-selectors-a-comprehensive-guide-for-web-automation-and-testing
85
+ - https://browser-use.com/posts/bot-detection
86
+ - https://scrapfly.io/blog/posts/puppeteer-stealth-complete-guide
@@ -0,0 +1,132 @@
1
+ # Interaction Patterns — Trawl Scrap Scripts
2
+
3
+ > *These patterns are about correctness — making the page reveal the data it functionally hides behind interaction. They are NOT anti-bot stealth. The worker handles bot detection; you handle the page's real interaction surface.*
4
+
5
+ ---
6
+
7
+ ## Scroll to trigger lazy-load
8
+
9
+ Use `window.scrollBy` in a loop; wait for new content, stop when the item count stabilises.
10
+
11
+ ```js
12
+ let prev = 0;
13
+ for (let i = 0; i < 10; i++) {
14
+ await page.evaluate(() => window.scrollBy(0, window.innerHeight));
15
+ try {
16
+ await page.waitForFunction(
17
+ (p) => document.querySelectorAll('article').length > p,
18
+ { timeout: 3000 },
19
+ prev,
20
+ );
21
+ } catch {
22
+ break; // no new items loaded within timeout — list exhausted
23
+ }
24
+ prev = await page.$$eval('article', (els) => els.length);
25
+ }
26
+ ```
27
+
28
+ Stop when item count is unchanged after a scroll, or a "end of results" sentinel appears.
29
+
30
+ ---
31
+
32
+ ## Hover to reveal
33
+
34
+ Content only rendered on `mouseenter` — read the value after the hover, not before.
35
+
36
+ ```js
37
+ const HOVER_TARGET = '[data-testid="price-trigger"]';
38
+ const REVEALED_PRICE = '[data-testid="price-tooltip"]';
39
+
40
+ await page.hover(HOVER_TARGET);
41
+ await page.waitForSelector(REVEALED_PRICE, { timeout: 5000 });
42
+ const price = await page.$eval(REVEALED_PRICE, (el) => el.textContent.trim());
43
+ ```
44
+
45
+ ---
46
+
47
+ ## Click to expand (FAQ, accordions, "show more")
48
+
49
+ Click each trigger, wait for the expanded region, then read its content.
50
+
51
+ ```js
52
+ const TRIGGERS = await page.$$('[data-testid="faq-question"]');
53
+ const results = [];
54
+ for (const trigger of TRIGGERS) {
55
+ await trigger.click();
56
+ // Wait for the sibling answer panel to become visible
57
+ await page.waitForSelector('[data-testid="faq-answer"]:not([hidden])', { timeout: 3000 });
58
+ const answer = await page.$eval('[data-testid="faq-answer"]:not([hidden])', (el) => el.textContent.trim());
59
+ const question = await trigger.evaluate((el) => el.textContent.trim());
60
+ results.push({ question, answer });
61
+ }
62
+ ```
63
+
64
+ ---
65
+
66
+ ## Form fill via page.type()
67
+
68
+ `page.type` fires `keydown`/`keypress`/`keyup` per character. Some sites reject paste-style instant assignment (`el.value = ...`).
69
+
70
+ ```js
71
+ // Good: per-keystroke events
72
+ await page.type('[name="search"]', 'quarterly report 2024');
73
+
74
+ // Bad: instant assignment — often rejected by form validation listeners
75
+ // await page.evaluate(() => { document.querySelector('[name="search"]').value = 'quarterly report 2024'; });
76
+
77
+ await page.keyboard.press('Enter');
78
+ await page.waitForNavigation({ waitUntil: 'domcontentloaded' });
79
+ ```
80
+
81
+ ---
82
+
83
+ ## Wait for state transitions between chained actions
84
+
85
+ After a click that triggers an XHR, prefer `waitForResponse` or `waitForNetworkIdle` over a fixed delay.
86
+
87
+ ```js
88
+ // Good: gate on the API response
89
+ const [response] = await Promise.all([
90
+ page.waitForResponse((res) => res.url().includes('/api/products') && res.status() === 200),
91
+ page.click('[data-testid="load-more"]'),
92
+ ]);
93
+ const data = await response.json();
94
+
95
+ // Also acceptable for SPA-heavy pages:
96
+ await page.click('[data-testid="tab-reviews"]');
97
+ await page.waitForNetworkIdle();
98
+ ```
99
+
100
+ ---
101
+
102
+ ## Pagination via "next" button
103
+
104
+ Click "next", wait for the first item to change. Track items across pages to detect stale pagination (same items returned).
105
+
106
+ ```js
107
+ const allItems = [];
108
+ let pageNum = 1;
109
+
110
+ while (true) {
111
+ const items = await page.$$eval('[data-testid="result-item"]', (els) =>
112
+ els.map((el) => ({ title: el.querySelector('h2')?.textContent?.trim() ?? null }))
113
+ );
114
+ allItems.push(...items);
115
+
116
+ const nextBtn = await page.$('[data-testid="pagination-next"]:not([disabled])');
117
+ if (!nextBtn) break;
118
+
119
+ const firstTitle = items[0]?.title;
120
+ await nextBtn.click();
121
+ // Wait for the first item to change — confirms the page actually advanced
122
+ await page.waitForFunction(
123
+ (prev) => document.querySelector('[data-testid="result-item"] h2')?.textContent?.trim() !== prev,
124
+ {},
125
+ firstTitle
126
+ );
127
+ pageNum++;
128
+ if (pageNum > 20) break; // safety cap
129
+ }
130
+
131
+ returnData(allItems);
132
+ ```
@@ -0,0 +1,91 @@
1
+ # returnData Shapes — Trawl Scrap Scripts
2
+
3
+ Rules for the JSON objects you pass to `returnData([...])`.
4
+
5
+ ---
6
+
7
+ ## Flat-as-possible
8
+
9
+ Return a flat object per item. Nest only when source data is genuinely nested — justify with a comment.
10
+
11
+ ```js
12
+ // Good: flat
13
+ { title: 'Widget Pro', category: 'Tools', vendor: 'Acme', price: 29.99 }
14
+
15
+ // Acceptable: nested because the source API returns a nested address object
16
+ {
17
+ name: 'Acme HQ',
18
+ address: { street: '1 Main St', city: 'Paris', country: 'FR' }, // nested: source is nested
19
+ }
20
+
21
+ // Bad: nested for no reason
22
+ {
23
+ product: { title: 'Widget Pro', category: 'Tools' }, // no reason to nest
24
+ }
25
+ ```
26
+
27
+ ---
28
+
29
+ ## null vs omission
30
+
31
+ Return `null` for absent optional fields. Never omit the key — schema validation distinguishes "null" from "key never sent", and omission breaks it silently.
32
+
33
+ ```js
34
+ // Good
35
+ { title: 'Widget Pro', discount_pct: null, badge: null }
36
+
37
+ // Bad — key omitted, breaks checkSchema expectations
38
+ { title: 'Widget Pro' }
39
+ ```
40
+
41
+ ---
42
+
43
+ ## Dates as ISO-8601 UTC
44
+
45
+ Convert dates with `new Date(...).toISOString()`. Never pass locale-formatted strings — they're timezone-ambiguous and locale-dependent.
46
+
47
+ ```js
48
+ const rawDate = await page.$eval('[data-testid="publish-date"]', (el) => el.getAttribute('datetime'));
49
+ const published_at = rawDate ? new Date(rawDate).toISOString() : null;
50
+ // e.g. "2024-03-15T00:00:00.000Z"
51
+ ```
52
+
53
+ ---
54
+
55
+ ## Numbers as numbers
56
+
57
+ Parse before returning. Return currency as a separate string field, not embedded in the number.
58
+
59
+ ```js
60
+ const rawPrice = await page.$eval(PRICE_SEL, (el) => el.textContent.trim());
61
+ // rawPrice = "€29,99"
62
+
63
+ const price = parseFloat(rawPrice.replace(',', '.').replace(/[^0-9.]/g, '')) || null;
64
+ const currency = rawPrice.match(/[A-Z]{3}|[€$£¥]/)?.[0] ?? null;
65
+
66
+ // Return:
67
+ { price: 29.99, currency: '€' }
68
+ // Not: { price: "€29,99" }
69
+ ```
70
+
71
+ ---
72
+
73
+ ## Pagination accumulates within one run
74
+
75
+ Accumulate all pages into one array and call `returnData` once at the end. Calling it per-page or per-item produces one history entry per call and breaks aggregation.
76
+
77
+ ```js
78
+ const allItems = [];
79
+
80
+ // ... pagination loop adds to allItems ...
81
+
82
+ returnData(allItems); // single call with all pages merged
83
+ ```
84
+
85
+ ---
86
+
87
+ ## Compatibility with checkSchema
88
+
89
+ - `validation_failed` is distinct from `error` (script threw) and `0 items` (empty array). Check all three when debugging data gaps.
90
+ - Missing required keys → `validation_failed`, not `error` — no retry triggered.
91
+ - See *Trawl Data Quality docs* for schema syntax and enforcement.
@@ -0,0 +1,75 @@
1
+ ---
2
+ name: trawl-scrap-local-test
3
+ description: Use when testing a Trawl scrap locally before publishing. Triggers on "test my scrap locally", "debug before push", "run scrap on my machine", "preview returnData output", or any prompt about iterating on a script before pushing. Does NOT cover writing the script body (see trawl-scrap-design), authentication flows (see trawl-scrap-account), or managing scraps via CLI (see trawl-cli).
4
+ ---
5
+
6
+ # Trawl Scrap Local Test
7
+
8
+ Validate selectors, login flow, and returnData shape locally before spending proxy budget on the worker. The harness (`scripts/run-local.mjs`) injects the same globals as the worker — `browser`, `TRAWL`, `account`, `returnData`, `saveSession` — so your script runs unchanged on your machine.
9
+
10
+ ## The worker boundary
11
+
12
+ > **Don't add stealth in your script.** Trawl's worker handles fingerprinting, proxy rotation, and bot-detection countermeasures centrally. Adding stealth plugins, UA spoofing, viewport randomisation, or aggressive jitter in your script duplicates worker policy and causes drift. The worker's policy evolves; your script's hardcoded tricks won't.
13
+
14
+ Local testing intentionally uses vanilla `puppeteer-core` — no fingerprint policy, no proxy. You're testing your script's logic, not the worker's network surface.
15
+
16
+ ## Quick-start
17
+
18
+ ```bash
19
+ # Install puppeteer-core once (it's a peer dependency, not bundled with the skill).
20
+ npm install -g puppeteer-core
21
+
22
+ # Run a scrap locally:
23
+ node ~/.claude/skills/trawl-scrap-local-test/scripts/run-local.mjs path/to/scrap.js \
24
+ --url=https://target \
25
+ --params=key=val,key2=val2
26
+ ```
27
+
28
+ ```bash
29
+ # Headless run (CI / no display):
30
+ node ~/.claude/skills/trawl-scrap-local-test/scripts/run-local.mjs path/to/scrap.js \
31
+ --url=https://target \
32
+ --headless
33
+ ```
34
+
35
+ ## Harness contract
36
+
37
+ The script body runs in a closure. The harness injects these globals, mirroring the worker:
38
+
39
+ - `browser` — the Puppeteer browser instance (headed, with DevTools open).
40
+ - `TRAWL` — object with `url` (from `--url`) and any `<custom>` keys from `--params`.
41
+ - `account` — object with `username` and `password` (from `--account-username` / `--account-password`), plus optional `session.cookies` loaded from a JSON array file via `--account-cookies`.
42
+ - `returnData(arr)` — stub that prints the array as JSON to stdout.
43
+ - `saveSession(cookies)` — stub that prints the cookie array to stdout (does not persist).
44
+
45
+ No changes to the script body are needed to run it locally.
46
+
47
+ ## CLI flags
48
+
49
+ - `--url=<url>` — sets `TRAWL.url` (use a real value if your script navigates to it).
50
+ - `--params=k=v[,k=v]*` — sets `TRAWL.<custom>` keys (comma-separated `key=value` pairs).
51
+ - `--account-username=<u>` — sets `account.username`.
52
+ - `--account-password=<p>` — sets `account.password`.
53
+ - `--account-cookies=<path>` — loads `account.session.cookies` from a JSON array file.
54
+ - `--remote` — connects to an existing Chrome at `http://127.0.0.1:9222` (instead of launching a fresh one). Useful for MFA flows — see `references/headed-debug.md`.
55
+ - `--headless` — launches Chrome headlessly (no window). Default is headed (`headless: false`) for interactive debugging.
56
+ - `--chrome=<path>` — path to a Chrome executable. Auto-detected on macOS and Linux when omitted; pass explicitly if Chrome lives in a non-standard location or you want to use Chromium.
57
+ - `--help` — prints usage.
58
+
59
+ ## Recommended workflow
60
+
61
+ 1. Iterate locally with `run-local.mjs` until selectors and `returnData` are clean.
62
+ 2. `trawl scraps update <id> -r "$(cat scrap.js)"` (see the `trawl-cli` skill for full CLI usage).
63
+ 3. `trawl scraps run <id> --watch` to confirm the worker behaves the same.
64
+
65
+ ## Limitations (intentional)
66
+
67
+ - Local runs use the user's IP — no proxy tier, no fingerprint policy.
68
+ - Local pass does not guarantee worker pass — script logic is tested, not the network surface.
69
+
70
+ ## What this skill does NOT cover
71
+
72
+ - Script body → `trawl-scrap-design`
73
+ - CLI scrap management → `trawl-cli`
74
+ - Authentication flows → `trawl-scrap-account`
75
+ - Advanced debugging (DevTools pause, network capture, attach to existing Chrome) → `references/headed-debug.md`
@@ -0,0 +1,65 @@
1
+ # Headed Debug Reference
2
+
3
+ Advanced debugging flags and techniques for `run-local.mjs`.
4
+
5
+ ## Default flags
6
+
7
+ The harness launches Chrome with `headless: false`, `slowMo: 250`, `devtools: true`. Tune `slowMo` between 100 and 500 — lower is faster, higher lets you watch each action.
8
+
9
+ ## Pause inside page.evaluate
10
+
11
+ `debugger` inside an `evaluate` callback pauses in the embedded DevTools Sources panel. Both conditions (headed + DevTools open) are met under the default harness flags.
12
+
13
+ ```js
14
+ await page.evaluate(() => {
15
+ debugger;
16
+ return document.title;
17
+ });
18
+ ```
19
+
20
+ ## Attach to an existing Chrome
21
+
22
+ Launch Chrome with a remote debugging port to log in manually (MFA, OAuth) before the script runs.
23
+
24
+ ```bash
25
+ /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \
26
+ --remote-debugging-port=9222 \
27
+ --user-data-dir=/tmp/chrome-trawl
28
+ ```
29
+
30
+ Log in manually in that Chrome window (complete MFA, solve CAPTCHA, etc.). Then attach the harness to the running instance:
31
+
32
+ ```bash
33
+ node run-local.mjs scrap.js --remote
34
+ ```
35
+
36
+ The harness calls `puppeteer.connect({ browserURL: 'http://127.0.0.1:9222' })` and opens a new page. It does not close the browser when done.
37
+
38
+ ## Intermediate snapshots
39
+
40
+ Insert `page.screenshot` between actions to see actual page state when a selector doesn't match.
41
+
42
+ ```js
43
+ await page.screenshot({ path: '/tmp/step-1.png' });
44
+ await page.click('#load-more');
45
+ await page.waitForSelector('[data-testid="results"]');
46
+ await page.screenshot({ path: '/tmp/step-2.png' });
47
+ ```
48
+
49
+ Open the PNG files in any image viewer. On macOS: `open /tmp/step-1.png`.
50
+
51
+ ## Network capture
52
+
53
+ Log `response` events to debug API-driven SPAs where the DOM may be stale while the XHR already returned data.
54
+
55
+ ```js
56
+ page.on('response', (r) => console.log(r.status(), r.url()));
57
+ ```
58
+
59
+ Place before the first `page.goto`. Filter to specific endpoints:
60
+
61
+ ```js
62
+ page.on('response', (r) => {
63
+ if (r.url().includes('/api/')) console.log(r.status(), r.url());
64
+ });
65
+ ```
@@ -0,0 +1,135 @@
1
+ #!/usr/bin/env node
2
+ // Local Trawl scrap harness — mirrors the worker entry contract.
3
+ // Globals injected: browser, TRAWL, account, returnData, saveSession.
4
+ import { readFileSync, existsSync } from 'node:fs';
5
+ import { resolve } from 'node:path';
6
+
7
+ const args = process.argv.slice(2);
8
+
9
+ function help() {
10
+ console.log(`run-local.mjs <scrap-file> [flags]
11
+
12
+ Flags:
13
+ --url=<url> TRAWL.url
14
+ --params=k=v[,k=v]* TRAWL.<custom> keys
15
+ --account-username=<user> account.username
16
+ --account-password=<pwd> account.password
17
+ --account-cookies=<path> account.session.cookies (JSON array)
18
+ --remote connect to existing Chrome at 127.0.0.1:9222
19
+ --headless launch Chrome in headless mode (no window)
20
+ --chrome=<path> path to Chrome executable (auto-detected if omitted)
21
+ --help this message
22
+ `);
23
+ }
24
+
25
+ if (args.length === 0 || args.includes('--help')) {
26
+ help();
27
+ process.exit(args.length === 0 ? 1 : 0);
28
+ }
29
+
30
+ const positional = args.filter((a) => !a.startsWith('--'));
31
+ const flags = Object.fromEntries(
32
+ args
33
+ .filter((a) => a.startsWith('--'))
34
+ .map((a) => {
35
+ const [k, ...rest] = a.replace(/^--/, '').split('=');
36
+ return [k, rest.join('=') || true];
37
+ })
38
+ );
39
+
40
+ const scrapPath = positional[0];
41
+ if (!scrapPath) {
42
+ console.error('Missing scrap file argument');
43
+ help();
44
+ process.exit(1);
45
+ }
46
+
47
+ const scrapBody = readFileSync(resolve(scrapPath), 'utf8');
48
+
49
+ const TRAWL = { url: flags.url || null };
50
+ if (typeof flags.params === 'string') {
51
+ for (const pair of flags.params.split(',')) {
52
+ const eqIdx = pair.indexOf('=');
53
+ if (eqIdx <= 0) continue;
54
+ const k = pair.slice(0, eqIdx);
55
+ const v = pair.slice(eqIdx + 1);
56
+ TRAWL[k] = v;
57
+ }
58
+ }
59
+
60
+ const account = { username: flags['account-username'] || null, password: flags['account-password'] || null };
61
+ if (flags['account-cookies']) {
62
+ const cookies = JSON.parse(readFileSync(resolve(flags['account-cookies']), 'utf8'));
63
+ account.session = { cookies };
64
+ }
65
+
66
+ let puppeteer;
67
+ try {
68
+ puppeteer = await import('puppeteer-core');
69
+ } catch {
70
+ console.error('puppeteer-core not installed. Run: npm install -g puppeteer-core');
71
+ process.exit(1);
72
+ }
73
+
74
+ // Auto-detect Chrome executable if not specified via --chrome flag.
75
+ function findChrome() {
76
+ const candidates = [
77
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
78
+ '/Applications/Chromium.app/Contents/MacOS/Chromium',
79
+ '/usr/bin/google-chrome',
80
+ '/usr/bin/chromium-browser',
81
+ '/usr/bin/chromium',
82
+ ];
83
+ return candidates.find(existsSync) || null;
84
+ }
85
+
86
+ let browser;
87
+ if (flags.remote) {
88
+ browser = await puppeteer.default.connect({ browserURL: 'http://127.0.0.1:9222' });
89
+ } else {
90
+ let executablePath;
91
+ if (typeof flags.chrome === 'string') {
92
+ if (!existsSync(flags.chrome)) {
93
+ console.error(`Chrome not found at: ${flags.chrome}`);
94
+ process.exit(1);
95
+ }
96
+ executablePath = flags.chrome;
97
+ } else {
98
+ executablePath = findChrome();
99
+ if (!executablePath) {
100
+ console.error('No Chrome executable found. Install Chrome or pass --chrome=/path/to/chrome');
101
+ process.exit(1);
102
+ }
103
+ }
104
+
105
+ browser = await puppeteer.default.launch({
106
+ executablePath,
107
+ headless: !!flags.headless,
108
+ slowMo: flags.headless ? 0 : 250,
109
+ devtools: !flags.headless,
110
+ args: ['--no-sandbox'],
111
+ });
112
+ }
113
+
114
+ const returnData = (arr) => {
115
+ console.log('--- returnData ---');
116
+ console.log(JSON.stringify(arr, null, 2));
117
+ };
118
+ const saveSession = async (cookies) => {
119
+ console.log('--- saveSession (stub) ---');
120
+ console.log(JSON.stringify(cookies, null, 2));
121
+ };
122
+
123
+ const wrapped = `(async () => {\n${scrapBody}\n})()`;
124
+
125
+ try {
126
+ const fn = new Function('browser', 'TRAWL', 'account', 'returnData', 'saveSession', `return ${wrapped}`);
127
+ await fn(browser, TRAWL, account, returnData, saveSession);
128
+ } catch (err) {
129
+ console.error('--- script error ---');
130
+ console.error(err.stack || err);
131
+ process.exitCode = 1;
132
+ } finally {
133
+ if (!flags.remote) await browser.close();
134
+ else await browser.disconnect();
135
+ }