@webhands/core 0.1.0 → 0.3.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/LICENSE +661 -0
- package/README.md +177 -0
- package/dist/cookies-export.d.ts +5 -5
- package/dist/cookies-export.d.ts.map +1 -1
- package/dist/cookies-export.js +4 -4
- package/dist/errors.d.ts +24 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +24 -0
- package/dist/errors.js.map +1 -1
- package/dist/hand-host.d.ts +217 -0
- package/dist/hand-host.d.ts.map +1 -0
- package/dist/hand-host.js +351 -0
- package/dist/hand-host.js.map +1 -0
- package/dist/hand-loading.d.ts +128 -0
- package/dist/hand-loading.d.ts.map +1 -0
- package/dist/hand-loading.js +143 -0
- package/dist/hand-loading.js.map +1 -0
- package/dist/index.d.ts +6 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/playwright-attach-transport.d.ts +9 -0
- package/dist/playwright-attach-transport.d.ts.map +1 -1
- package/dist/playwright-attach-transport.js +53 -91
- package/dist/playwright-attach-transport.js.map +1 -1
- package/dist/playwright-launch-transport.d.ts +81 -62
- package/dist/playwright-launch-transport.d.ts.map +1 -1
- package/dist/playwright-launch-transport.js +143 -210
- package/dist/playwright-launch-transport.js.map +1 -1
- package/dist/remote-session.d.ts +12 -2
- package/dist/remote-session.d.ts.map +1 -1
- package/dist/remote-session.js +37 -6
- package/dist/remote-session.js.map +1 -1
- package/dist/seam.d.ts +13 -5
- package/dist/seam.d.ts.map +1 -1
- package/dist/session-rpc.d.ts +76 -12
- package/dist/session-rpc.d.ts.map +1 -1
- package/dist/session-rpc.js +76 -8
- package/dist/session-rpc.js.map +1 -1
- package/dist/stub-transport.d.ts +2 -2
- package/dist/stub-transport.d.ts.map +1 -1
- package/dist/stub-transport.js +11 -0
- package/dist/stub-transport.js.map +1 -1
- package/package.json +24 -2
- package/src/cookies-export.ts +5 -5
- package/src/errors.ts +31 -0
- package/src/hand-host.ts +511 -0
- package/src/hand-loading.ts +254 -0
- package/src/index.ts +24 -2
- package/src/playwright-attach-transport.ts +65 -119
- package/src/playwright-launch-transport.ts +235 -249
- package/src/remote-session.ts +43 -5
- package/src/seam.ts +13 -5
- package/src/session-rpc.ts +121 -11
- package/src/stub-transport.ts +15 -3
|
@@ -1,25 +1,98 @@
|
|
|
1
1
|
import {stat} from 'node:fs/promises';
|
|
2
|
+
import {chromium, type BrowserContext, type Page} from 'playwright';
|
|
2
3
|
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
} from '
|
|
8
|
-
import {MissingBrowserBinaryError, MissingProfileError} from './errors.js';
|
|
4
|
+
MissingBrowserBinaryError,
|
|
5
|
+
MissingProfileError,
|
|
6
|
+
MissingStealthDependencyError,
|
|
7
|
+
} from './errors.js';
|
|
8
|
+
import {composeWithHands, type Hand, type HandContext} from './hand-host.js';
|
|
9
9
|
import {
|
|
10
10
|
resolveProfileLocation,
|
|
11
11
|
type ProfileLocationOptions,
|
|
12
12
|
} from './profile-location.js';
|
|
13
|
-
import type {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
13
|
+
import type {OpenTarget, Session, Transport} from './seam.js';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The subset of Playwright's `chromium` browser type the launch transport uses.
|
|
17
|
+
*
|
|
18
|
+
* Patchright is an API-compatible Playwright fork, so its `chromium` has the
|
|
19
|
+
* SAME shape (ADR-0003 stays intact: this structural type, like Playwright's
|
|
20
|
+
* own types, is confined to this module and never crosses the seam). We type the
|
|
21
|
+
* lazily-imported stealth chromium against THIS rather than importing any
|
|
22
|
+
* Patchright type, so the dependency stays optional at the type level too.
|
|
23
|
+
*/
|
|
24
|
+
type ChromiumLauncher = Pick<typeof chromium, 'launchPersistentContext'>;
|
|
25
|
+
|
|
26
|
+
/** The shape `await import('patchright')` is expected to expose. */
|
|
27
|
+
interface StealthModule {
|
|
28
|
+
readonly chromium: ChromiumLauncher;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* How the transport obtains the stealth (`patchright`) chromium. This is an
|
|
33
|
+
* INTERNAL test seam, not a public API: tests inject a fake module (or a
|
|
34
|
+
* rejecting importer) here so no real browser/Patchright is needed, exactly as
|
|
35
|
+
* production uses the default lazy `import('patchright')`. It is deliberately
|
|
36
|
+
* NOT on {@link OpenTarget} (ADR-0003: the seam stays free of Playwright/CDP/
|
|
37
|
+
* Patchright concerns).
|
|
38
|
+
*/
|
|
39
|
+
export type StealthChromiumImporter = () => Promise<StealthModule>;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Construction-time policy for {@link PlaywrightLaunchTransport}.
|
|
43
|
+
*
|
|
44
|
+
* Stealth is a TRANSPORT-CONSTRUCTION policy (which browser engine + launch
|
|
45
|
+
* flags to use), not a per-open target detail, so it lives here and NOT on
|
|
46
|
+
* {@link OpenTarget} (which stays Playwright/CDP-free per ADR-0003).
|
|
47
|
+
*/
|
|
48
|
+
export interface PlaywrightLaunchTransportOptions {
|
|
49
|
+
/**
|
|
50
|
+
* Opt-in Patchright-backed stealth launch. Default `false` (vanilla
|
|
51
|
+
* Playwright). When `true`, the transport launches via the lazily-imported
|
|
52
|
+
* optional `patchright` package, which patches the CDP `Runtime.enable`
|
|
53
|
+
* automation tell that anti-bot WAFs detect (ADR-0002 keeps this as one extra
|
|
54
|
+
* layer, not a replacement for a real profile/IP). If `patchright` is not
|
|
55
|
+
* installed it throws {@link MissingStealthDependencyError}; it NEVER silently
|
|
56
|
+
* falls back to vanilla.
|
|
57
|
+
*/
|
|
58
|
+
readonly stealth?: boolean;
|
|
59
|
+
/**
|
|
60
|
+
* Drive a browser ALREADY INSTALLED ON THE SYSTEM instead of the bundled
|
|
61
|
+
* Chromium, named by its install identity (e.g. `'chrome'` to drive the system
|
|
62
|
+
* Google Chrome, Patchright's recommended setup; also `'msedge'`,
|
|
63
|
+
* `'chrome-beta'`, ...). Applies to BOTH stealth and vanilla launches when set.
|
|
64
|
+
* When omitted, Playwright/Patchright's bundled Chromium is used.
|
|
65
|
+
*
|
|
66
|
+
* Maps to Playwright's `channel` launch option internally; we name it
|
|
67
|
+
* `systemBrowser` so the public surface speaks domain language ("use a browser
|
|
68
|
+
* I already have installed") rather than the Playwright term (ADR-0003 keeps
|
|
69
|
+
* Playwright vocabulary out of the public surface).
|
|
70
|
+
*/
|
|
71
|
+
readonly systemBrowser?: string;
|
|
72
|
+
/**
|
|
73
|
+
* INTERNAL test seam: override how the stealth chromium is imported. Omit in
|
|
74
|
+
* production (defaults to `import('patchright')`). See
|
|
75
|
+
* {@link StealthChromiumImporter}.
|
|
76
|
+
*/
|
|
77
|
+
readonly importStealthChromium?: StealthChromiumImporter;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The package name of the optional stealth dependency. Kept as a runtime value
|
|
82
|
+
* (not an `import('patchright')` literal) so TypeScript does NOT try to resolve
|
|
83
|
+
* its types at build time, since it is an OPTIONAL dependency that is legitimately
|
|
84
|
+
* absent when stealth is never enabled.
|
|
85
|
+
*/
|
|
86
|
+
const STEALTH_PACKAGE = 'patchright';
|
|
87
|
+
|
|
88
|
+
/** The default lazy import of the OPTIONAL `patchright` dependency. */
|
|
89
|
+
const defaultStealthImporter: StealthChromiumImporter = async () => {
|
|
90
|
+
// Indirect (non-literal specifier) so tsc/bundlers do not resolve the
|
|
91
|
+
// optional dep eagerly, and the module load never fails when it is absent;
|
|
92
|
+
// the import only runs when stealth is opted in.
|
|
93
|
+
const specifier = STEALTH_PACKAGE;
|
|
94
|
+
return (await import(specifier)) as unknown as StealthModule;
|
|
95
|
+
};
|
|
23
96
|
|
|
24
97
|
/**
|
|
25
98
|
* The v1 concrete transport: a Playwright browser the controller LAUNCHES
|
|
@@ -37,17 +110,45 @@ import type {
|
|
|
37
110
|
* `WEBHANDS_HOME` env var, or `~/.webhands`). See
|
|
38
111
|
* {@link resolveProfileLocation}. Because that is a SHARED location, tests pass
|
|
39
112
|
* a temp `root` (or set the env var) and assert the real home is untouched.
|
|
113
|
+
*
|
|
114
|
+
* STEALTH (opt-in, default OFF): the third constructor arg can enable a
|
|
115
|
+
* Patchright-backed launch ({@link PlaywrightLaunchTransportOptions}). Patchright
|
|
116
|
+
* is an OPTIONAL dependency imported lazily only when stealth is enabled; if it
|
|
117
|
+
* is absent the transport throws {@link MissingStealthDependencyError} rather
|
|
118
|
+
* than falling back to vanilla. This addresses ONLY the CDP `Runtime.enable`
|
|
119
|
+
* automation tell; a real profile/IP/session reputation still matter (ADR-0002).
|
|
40
120
|
*/
|
|
41
121
|
export class PlaywrightLaunchTransport implements Transport {
|
|
42
122
|
readonly #location: ProfileLocationOptions;
|
|
123
|
+
readonly #hands: readonly Hand[];
|
|
124
|
+
readonly #stealth: boolean;
|
|
125
|
+
readonly #systemBrowser: string | undefined;
|
|
126
|
+
readonly #importStealthChromium: StealthChromiumImporter;
|
|
43
127
|
|
|
44
128
|
/**
|
|
45
129
|
* @param location overrides for where profiles live (a `root` dir and/or an
|
|
46
130
|
* `env`). Omit in production to use `~/.webhands`; pass a temp
|
|
47
131
|
* `root` in tests to isolate the shared profile location.
|
|
132
|
+
* @param hands explicitly-loaded third-party hands to compose alongside the
|
|
133
|
+
* built-ins (Phase 2, ADR-0007). These come from {@link loadHands} against
|
|
134
|
+
* the operator's explicit config; the transport does NOT discover them. Omit
|
|
135
|
+
* for the built-ins-only surface.
|
|
136
|
+
* @param options transport-construction policy, notably the opt-in `stealth`
|
|
137
|
+
* toggle and optional `systemBrowser` (see
|
|
138
|
+
* {@link PlaywrightLaunchTransportOptions}). Defaults to vanilla Playwright,
|
|
139
|
+
* bundled Chromium, stealth OFF.
|
|
48
140
|
*/
|
|
49
|
-
constructor(
|
|
141
|
+
constructor(
|
|
142
|
+
location: ProfileLocationOptions = {},
|
|
143
|
+
hands: readonly Hand[] = [],
|
|
144
|
+
options: PlaywrightLaunchTransportOptions = {},
|
|
145
|
+
) {
|
|
50
146
|
this.#location = location;
|
|
147
|
+
this.#hands = hands;
|
|
148
|
+
this.#stealth = options.stealth === true;
|
|
149
|
+
this.#systemBrowser = options.systemBrowser;
|
|
150
|
+
this.#importStealthChromium =
|
|
151
|
+
options.importStealthChromium ?? defaultStealthImporter;
|
|
51
152
|
}
|
|
52
153
|
|
|
53
154
|
async open(target: OpenTarget): Promise<Session> {
|
|
@@ -72,14 +173,41 @@ export class PlaywrightLaunchTransport implements Transport {
|
|
|
72
173
|
|
|
73
174
|
const headless = target.headed !== true;
|
|
74
175
|
|
|
176
|
+
// Pick the engine: the lazily-imported stealth (Patchright) chromium when
|
|
177
|
+
// opted in, else vanilla Playwright's. Resolving the stealth module is where
|
|
178
|
+
// an absent optional dependency surfaces as the typed
|
|
179
|
+
// MissingStealthDependencyError (we never fall back to vanilla silently).
|
|
180
|
+
const launcher = this.#stealth
|
|
181
|
+
? await this.#resolveStealthLauncher()
|
|
182
|
+
: chromium;
|
|
183
|
+
|
|
184
|
+
// Launch options: forward headless, the optional systemBrowser (Playwright's
|
|
185
|
+
// `channel`, e.g. 'chrome' to drive system Chrome, Patchright's recommended
|
|
186
|
+
// setup), and for stealth drop Playwright's automation-flavoured default
|
|
187
|
+
// args so they cannot re-add the fingerprint Patchright just removed.
|
|
188
|
+
const launchOptions: Parameters<
|
|
189
|
+
typeof chromium.launchPersistentContext
|
|
190
|
+
>[1] = {headless};
|
|
191
|
+
if (this.#systemBrowser !== undefined) {
|
|
192
|
+
launchOptions.channel = this.#systemBrowser;
|
|
193
|
+
}
|
|
194
|
+
if (this.#stealth) {
|
|
195
|
+
launchOptions.ignoreDefaultArgs = ['--enable-automation'];
|
|
196
|
+
}
|
|
197
|
+
|
|
75
198
|
let context: BrowserContext;
|
|
76
199
|
try {
|
|
77
|
-
context = await
|
|
78
|
-
|
|
79
|
-
|
|
200
|
+
context = await launcher.launchPersistentContext(
|
|
201
|
+
loc.profileDir,
|
|
202
|
+
launchOptions,
|
|
203
|
+
);
|
|
80
204
|
} catch (cause) {
|
|
81
205
|
if (isMissingBrowserBinary(cause)) {
|
|
82
|
-
|
|
206
|
+
// With systemBrowser set (e.g. 'chrome') the "binary missing" failure
|
|
207
|
+
// means the SYSTEM browser is absent, not the bundled Chromium; name
|
|
208
|
+
// what is actually missing so the CLI's fix message is accurate.
|
|
209
|
+
const browser = this.#systemBrowser ?? 'chromium';
|
|
210
|
+
throw new MissingBrowserBinaryError(browser, undefined, {cause});
|
|
83
211
|
}
|
|
84
212
|
throw cause;
|
|
85
213
|
}
|
|
@@ -88,7 +216,34 @@ export class PlaywrightLaunchTransport implements Transport {
|
|
|
88
216
|
// the single active page (PRD: single active session in v1). Create one if
|
|
89
217
|
// the build ever changes that invariant.
|
|
90
218
|
const pwPage = context.pages()[0] ?? (await context.newPage());
|
|
91
|
-
return makeSession(context, pwPage);
|
|
219
|
+
return makeSession(context, pwPage, this.#hands);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Resolve the stealth (`patchright`) chromium via the injected lazy importer.
|
|
224
|
+
*
|
|
225
|
+
* Confines the brittle "optional dependency absent" detection to ONE spot
|
|
226
|
+
* (mirroring {@link isMissingBrowserBinary}): any failure to import the
|
|
227
|
+
* optional package becomes the typed {@link MissingStealthDependencyError}, so
|
|
228
|
+
* the caller never silently degrades to vanilla Playwright.
|
|
229
|
+
*/
|
|
230
|
+
async #resolveStealthLauncher(): Promise<ChromiumLauncher> {
|
|
231
|
+
let mod: StealthModule;
|
|
232
|
+
try {
|
|
233
|
+
mod = await this.#importStealthChromium();
|
|
234
|
+
} catch (cause) {
|
|
235
|
+
throw new MissingStealthDependencyError('patchright', undefined, {
|
|
236
|
+
cause,
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
if (
|
|
240
|
+
mod === null ||
|
|
241
|
+
typeof mod !== 'object' ||
|
|
242
|
+
typeof mod.chromium?.launchPersistentContext !== 'function'
|
|
243
|
+
) {
|
|
244
|
+
throw new MissingStealthDependencyError('patchright');
|
|
245
|
+
}
|
|
246
|
+
return mod.chromium;
|
|
92
247
|
}
|
|
93
248
|
}
|
|
94
249
|
|
|
@@ -107,6 +262,11 @@ async function isExistingDirectory(path: string): Promise<boolean> {
|
|
|
107
262
|
* does not export a typed error for this, so we detect on the message (it
|
|
108
263
|
* instructs the user to run `playwright install`). We confine that brittle
|
|
109
264
|
* string match to this one spot and re-raise as a stable typed error.
|
|
265
|
+
*
|
|
266
|
+
* This also covers the `channel: 'chrome'` case, where the missing binary is the
|
|
267
|
+
* SYSTEM Chrome, not the bundled Chromium. Playwright phrases that as the
|
|
268
|
+
* channel/distribution not being found; we match those variants too so the
|
|
269
|
+
* stealth+system-Chrome path still yields the typed MissingBrowserBinaryError.
|
|
110
270
|
*/
|
|
111
271
|
function isMissingBrowserBinary(cause: unknown): boolean {
|
|
112
272
|
const message = cause instanceof Error ? cause.message : String(cause ?? '');
|
|
@@ -115,12 +275,29 @@ function isMissingBrowserBinary(cause: unknown): boolean {
|
|
|
115
275
|
/please run the following command to download new browsers/i.test(
|
|
116
276
|
message,
|
|
117
277
|
) ||
|
|
118
|
-
/playwright install/i.test(message)
|
|
278
|
+
/playwright install/i.test(message) ||
|
|
279
|
+
// channel: 'chrome' (or other system channels) not installed on the host.
|
|
280
|
+
/Chromium distribution '.*' is not found/i.test(message) ||
|
|
281
|
+
/No "?(chrome|msedge|chromium)"? .* found/i.test(message)
|
|
119
282
|
);
|
|
120
283
|
}
|
|
121
284
|
|
|
122
|
-
/**
|
|
123
|
-
|
|
285
|
+
/**
|
|
286
|
+
* Wrap a live Playwright persistent context into the seam's {@link Session}.
|
|
287
|
+
*
|
|
288
|
+
* The VERB surface comes from the shared hand-host ({@link composeBuiltInPage}),
|
|
289
|
+
* which is the single place the eight built-in verbs are composed (no duplicated
|
|
290
|
+
* page-object literal). Only the SESSION LIFECYCLE is per-transport here: the
|
|
291
|
+
* launch transport listens on the context's `'close'` event and its `close()`
|
|
292
|
+
* calls `context.close()`, which KILLS the browser this transport spawned
|
|
293
|
+
* (contrast the attach transport, which detaches without killing the user's
|
|
294
|
+
* browser, ADR-0002).
|
|
295
|
+
*/
|
|
296
|
+
function makeSession(
|
|
297
|
+
context: BrowserContext,
|
|
298
|
+
pwPage: Page,
|
|
299
|
+
extraHands: readonly Hand[],
|
|
300
|
+
): Session {
|
|
124
301
|
let closed = false;
|
|
125
302
|
const ensureOpen = () => {
|
|
126
303
|
if (closed) {
|
|
@@ -128,236 +305,45 @@ function makeSession(context: BrowserContext, pwPage: PwPage): Session {
|
|
|
128
305
|
}
|
|
129
306
|
};
|
|
130
307
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
},
|
|
144
|
-
async snapshot(options?: SnapshotOptions): Promise<Snapshot> {
|
|
145
|
-
ensureOpen();
|
|
146
|
-
const url = pwPage.url();
|
|
147
|
-
if (options?.full === true) {
|
|
148
|
-
// `--full`: the raw DOM. `documentElement.outerHTML` is the serialized
|
|
149
|
-
// live DOM (post-script render), which is what an agent that wants the
|
|
150
|
-
// real HTML expects — not the original network response.
|
|
151
|
-
const content = await pwPage.evaluate(
|
|
152
|
-
() => document.documentElement.outerHTML,
|
|
153
|
-
);
|
|
154
|
-
return {url, view: 'full', content};
|
|
155
|
-
}
|
|
156
|
-
// Default: the token-cheap accessibility tree + visible text with stable
|
|
157
|
-
// `[ref=...]` element refs. Playwright's `ariaSnapshot({mode: 'ai'})`
|
|
158
|
-
// emits exactly that — a YAML aria tree (roles + accessible names +
|
|
159
|
-
// text) where each node carries a stable `[ref=eN]` reference, assigned
|
|
160
|
-
// deterministically by traversal order so re-snapshotting an unchanged
|
|
161
|
-
// page yields the same refs. The string crosses the seam as opaque,
|
|
162
|
-
// transport-neutral text (no Playwright type leaks, ADR-0003).
|
|
163
|
-
const content = await pwPage.ariaSnapshot({mode: 'ai'});
|
|
164
|
-
return {url, view: 'accessibility', content};
|
|
165
|
-
},
|
|
166
|
-
async click(t): Promise<void> {
|
|
167
|
-
ensureOpen();
|
|
168
|
-
await clickLocator(pwPage, t);
|
|
169
|
-
},
|
|
170
|
-
async type(t, text): Promise<void> {
|
|
171
|
-
ensureOpen();
|
|
172
|
-
await resolveLocator(pwPage, t).fill(text);
|
|
173
|
-
},
|
|
174
|
-
async eval(expression: string): Promise<unknown> {
|
|
175
|
-
ensureOpen();
|
|
176
|
-
// The `eval` escape hatch (PRD story 9): run the raw JS EXPRESSION in the
|
|
177
|
-
// page and return its serializable result. Playwright's `evaluate`
|
|
178
|
-
// already IS the seam's serialization contract (see {@link Page.eval}):
|
|
179
|
-
// it passes a string as an expression, awaits a returned Promise, and
|
|
180
|
-
// structurally clones the result out of the page by VALUE. That clone is
|
|
181
|
-
// richer than JSON: it preserves NaN/Infinity/BigInt and circular
|
|
182
|
-
// structures (back-refs become a `[Circular]` marker), yields `undefined`
|
|
183
|
-
// for functions/symbols, and returns an opaque preview string for a live
|
|
184
|
-
// host object (a DOM node never crosses the process boundary). A page-side
|
|
185
|
-
// throw rejects. We pass it straight through rather than re-encode it:
|
|
186
|
-
// wrapping the value in a transport-specific envelope would invent a
|
|
187
|
-
// dialect the seam deliberately avoids. The thrown error is a plain
|
|
188
|
-
// `Error`, so no Playwright/CDP type leaks across the seam (ADR-0003).
|
|
189
|
-
return pwPage.evaluate(expression);
|
|
190
|
-
},
|
|
191
|
-
async wait(condition: WaitCondition): Promise<void> {
|
|
192
|
-
ensureOpen();
|
|
193
|
-
await waitFor(pwPage, condition);
|
|
194
|
-
},
|
|
195
|
-
async cookies(): Promise<readonly Cookie[]> {
|
|
196
|
-
ensureOpen();
|
|
197
|
-
const raw = await context.cookies();
|
|
198
|
-
return raw.map(toSeamCookie);
|
|
199
|
-
},
|
|
200
|
-
async setCookies(cookies): Promise<void> {
|
|
201
|
-
ensureOpen();
|
|
202
|
-
await context.addCookies(cookies.map(fromSeamCookie));
|
|
203
|
-
},
|
|
308
|
+
// Resolves the first time the context is gone — whether the USER closed the
|
|
309
|
+
// window (Playwright fires the context 'close' event) or our own close()
|
|
310
|
+
// ran. This is what lets `setup-profile` hold the headed window open and
|
|
311
|
+
// block on waitForClose() until the human is done.
|
|
312
|
+
let resolveClosed!: () => void;
|
|
313
|
+
const closedSignal = new Promise<void>((resolve) => {
|
|
314
|
+
resolveClosed = resolve;
|
|
315
|
+
});
|
|
316
|
+
const markClosed = () => {
|
|
317
|
+
if (closed) return;
|
|
318
|
+
closed = true;
|
|
319
|
+
resolveClosed();
|
|
204
320
|
};
|
|
321
|
+
context.on('close', markClosed);
|
|
322
|
+
|
|
323
|
+
// Build the verb surface from the built-in hands over a live hand-context.
|
|
324
|
+
// The host keeps the live `pwPage`/`context` in-process (they never cross the
|
|
325
|
+
// seam, ADR-0003); the hand-context carries live page access only.
|
|
326
|
+
const handContext: HandContext = {pwPage, context, ensureOpen};
|
|
327
|
+
const {page, dispose: disposeHands} = composeWithHands(
|
|
328
|
+
handContext,
|
|
329
|
+
extraHands,
|
|
330
|
+
);
|
|
205
331
|
|
|
206
332
|
return {
|
|
207
333
|
page,
|
|
208
334
|
async close(): Promise<void> {
|
|
209
|
-
if (closed)
|
|
210
|
-
|
|
335
|
+
if (closed) {
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
// Dispose the hands first (their in-process resources), THEN tear down
|
|
339
|
+
// the browser: context.close() fires the 'close' event, which runs
|
|
340
|
+
// markClosed and KILLS the browser this transport spawned.
|
|
341
|
+
await disposeHands();
|
|
211
342
|
await context.close();
|
|
343
|
+
markClosed();
|
|
344
|
+
},
|
|
345
|
+
waitForClose(): Promise<void> {
|
|
346
|
+
return closedSignal;
|
|
212
347
|
},
|
|
213
|
-
};
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
/**
|
|
217
|
-
* Run the `wait` verb's three forms (PRD story 10) against a Playwright page.
|
|
218
|
-
*
|
|
219
|
-
* - `timeout` — pace by a fixed delay (`waitForTimeout`), so an agent can act
|
|
220
|
-
* like a human and let XHR-rendered content land.
|
|
221
|
-
* - `locator` — block until the addressed element appears (`Locator.waitFor()`),
|
|
222
|
-
* the form for content rendered AFTER `goto` settled on `load`.
|
|
223
|
-
* - `navigation` — block until the NEXT navigation settles to `load`. We use
|
|
224
|
-
* `waitForNavigation()` even though Playwright marks it `@deprecated` ("racy,
|
|
225
|
-
* use waitForURL"): that deprecation targets in-process TEST code that can arm
|
|
226
|
-
* the wait BEFORE the action and pass a target URL. Neither holds here. Across
|
|
227
|
-
* this seam verbs are DISCRETE sequential calls (`click` then `wait`), so we
|
|
228
|
-
* CANNOT arm before the trigger; and the realistic trigger is an async,
|
|
229
|
-
* JS-driven transition (a redirect / SPA route change that fires AFTER the
|
|
230
|
-
* agent's action, the "let XHR-rendered content load" case of story 10), so
|
|
231
|
-
* "wait for the NEXT navigation" is exactly right — whereas `waitForLoadState`
|
|
232
|
-
* would see the already-loaded current page and return before the pending
|
|
233
|
-
* transition. `waitForURL` is unusable because the verb has no target URL by
|
|
234
|
-
* design (the agent waits for "a navigation", not a known address). (See the
|
|
235
|
-
* task's ## Decisions note.)
|
|
236
|
-
*
|
|
237
|
-
* Shared by both Playwright transports so the verb behaviour stays identical
|
|
238
|
-
* (the forward-note's "do NOT write a parallel second implementation").
|
|
239
|
-
*/
|
|
240
|
-
export async function waitFor(
|
|
241
|
-
page: PwPage,
|
|
242
|
-
condition: WaitCondition,
|
|
243
|
-
): Promise<void> {
|
|
244
|
-
switch (condition.kind) {
|
|
245
|
-
case 'timeout':
|
|
246
|
-
await page.waitForTimeout(condition.ms);
|
|
247
|
-
return;
|
|
248
|
-
case 'locator':
|
|
249
|
-
await resolveLocator(page, condition.target).waitFor();
|
|
250
|
-
return;
|
|
251
|
-
case 'navigation':
|
|
252
|
-
// eslint-disable-next-line @typescript-eslint/no-deprecated
|
|
253
|
-
await page.waitForNavigation();
|
|
254
|
-
return;
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
/**
|
|
259
|
-
* Resolve a raw Playwright locator EXPRESSION (ADR-0004) against the page. The
|
|
260
|
-
* verb surface passes locator expressions like `getByRole('button', …)`; we
|
|
261
|
-
* evaluate them in a small sandbox where `page`/`p` is the page, so the full
|
|
262
|
-
* Playwright locator grammar is available without leaking the type across the
|
|
263
|
-
* seam.
|
|
264
|
-
*
|
|
265
|
-
* Exported (with {@link clickLocator}/{@link waitFor}) so the attach transport
|
|
266
|
-
* resolves locators IDENTICALLY — one resolution path, no parallel addressing
|
|
267
|
-
* scheme (the forward-note's "do NOT write a parallel second implementation").
|
|
268
|
-
*/
|
|
269
|
-
export function resolveLocator(page: PwPage, expression: string) {
|
|
270
|
-
// eslint-disable-next-line no-new-func
|
|
271
|
-
const factory = new Function('page', 'p', `return (${expression});`) as (
|
|
272
|
-
page: PwPage,
|
|
273
|
-
p: PwPage,
|
|
274
|
-
) => ReturnType<PwPage['locator']>;
|
|
275
|
-
return factory(page, page);
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
/**
|
|
279
|
-
* How long a normal, actionability-checked `click` may wait before we treat the
|
|
280
|
-
* element as un-clickable and fall back to a dispatched click. Short on purpose:
|
|
281
|
-
* a hidden custom input never becomes actionable, so the regular click would
|
|
282
|
-
* otherwise burn Playwright's full default timeout (30s) before the escape path
|
|
283
|
-
* runs. The visible-element happy path clicks immediately and never hits this;
|
|
284
|
-
* this bound is the latency cost paid ONLY on the hidden/non-actionable path,
|
|
285
|
-
* and is long enough to tolerate a slow-but-eventually-actionable element
|
|
286
|
-
* (animations, late layout) before deciding to dispatch.
|
|
287
|
-
*/
|
|
288
|
-
const NORMAL_CLICK_TIMEOUT_MS = 1_000;
|
|
289
|
-
|
|
290
|
-
/**
|
|
291
|
-
* Run the `click` verb against a Playwright page (PRD story 8), shared by both
|
|
292
|
-
* Playwright transports so the verb behaves identically (mirrors {@link waitFor};
|
|
293
|
-
* the forward-note's "do NOT write a parallel second implementation").
|
|
294
|
-
*
|
|
295
|
-
* First try a normal `Locator.click()`, which AUTO-WAITS for the element to be
|
|
296
|
-
* visible and actionable — the right behaviour for a real button. A hidden
|
|
297
|
-
* custom input (the case the prd calls out) NEVER becomes actionable, so that
|
|
298
|
-
* click times out; on a Playwright `TimeoutError` we fall back to
|
|
299
|
-
* `dispatchEvent('click')`, which fires a click WITHOUT the actionability
|
|
300
|
-
* checks. The fallback is deliberately the documented Playwright escape (a
|
|
301
|
-
* sibling to the `eval` hatch, ADR-0004), not a reimplemented click: we keep
|
|
302
|
-
* the locator a raw resolved expression and only change HOW the resolved
|
|
303
|
-
* locator is clicked.
|
|
304
|
-
*
|
|
305
|
-
* Only a timeout triggers the fallback. The fallback `dispatchEvent` is itself
|
|
306
|
-
* bounded by the same short timeout, so a locator that resolves NO element (a
|
|
307
|
-
* bad locator) surfaces its timeout quickly instead of hanging the dispatch on
|
|
308
|
-
* Playwright's 30s default — the dispatch escape is for elements that EXIST but
|
|
309
|
-
* are not actionable (hidden custom inputs), not for absent ones.
|
|
310
|
-
*/
|
|
311
|
-
export async function clickLocator(
|
|
312
|
-
page: PwPage,
|
|
313
|
-
expression: string,
|
|
314
|
-
): Promise<void> {
|
|
315
|
-
const target = resolveLocator(page, expression);
|
|
316
|
-
try {
|
|
317
|
-
await target.click({timeout: NORMAL_CLICK_TIMEOUT_MS});
|
|
318
|
-
} catch (cause) {
|
|
319
|
-
if (!(cause instanceof pwErrors.TimeoutError)) {
|
|
320
|
-
throw cause;
|
|
321
|
-
}
|
|
322
|
-
// The element never became actionable (e.g. a hidden custom input). Fire
|
|
323
|
-
// the click without actionability checks, the prd's explicit escape path.
|
|
324
|
-
await target.dispatchEvent('click', {timeout: NORMAL_CLICK_TIMEOUT_MS});
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
/** Map a Playwright cookie to the transport-neutral seam {@link Cookie}. */
|
|
329
|
-
function toSeamCookie(c: {
|
|
330
|
-
name: string;
|
|
331
|
-
value: string;
|
|
332
|
-
domain?: string;
|
|
333
|
-
path?: string;
|
|
334
|
-
expires?: number;
|
|
335
|
-
httpOnly?: boolean;
|
|
336
|
-
secure?: boolean;
|
|
337
|
-
sameSite?: 'Strict' | 'Lax' | 'None';
|
|
338
|
-
}): Cookie {
|
|
339
|
-
return {
|
|
340
|
-
name: c.name,
|
|
341
|
-
value: c.value,
|
|
342
|
-
domain: c.domain,
|
|
343
|
-
path: c.path,
|
|
344
|
-
expires: c.expires,
|
|
345
|
-
httpOnly: c.httpOnly,
|
|
346
|
-
secure: c.secure,
|
|
347
|
-
sameSite: c.sameSite,
|
|
348
|
-
};
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
/** Map a seam {@link Cookie} to a Playwright cookie shape. */
|
|
352
|
-
function fromSeamCookie(c: Cookie) {
|
|
353
|
-
return {
|
|
354
|
-
name: c.name,
|
|
355
|
-
value: c.value,
|
|
356
|
-
domain: c.domain,
|
|
357
|
-
path: c.path,
|
|
358
|
-
expires: c.expires,
|
|
359
|
-
httpOnly: c.httpOnly,
|
|
360
|
-
secure: c.secure,
|
|
361
|
-
sameSite: c.sameSite,
|
|
362
348
|
};
|
|
363
349
|
}
|
package/src/remote-session.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import {
|
|
2
|
+
callHandVerb,
|
|
2
3
|
makeRpcPage,
|
|
3
4
|
SESSION_RPC_PATH,
|
|
4
5
|
type SessionRpcRequest,
|
|
@@ -11,7 +12,7 @@ import type {Session} from './seam.js';
|
|
|
11
12
|
* long-lived `serve` process over HTTP (ADR-0005).
|
|
12
13
|
*
|
|
13
14
|
* Each `webhands <verb>` is a thin client: it cannot hold a JS
|
|
14
|
-
* reference to the server's live page, so this proxy turns every {@link
|
|
15
|
+
* reference to the server's live page, so this proxy turns every {@link WebHandsPage}
|
|
15
16
|
* verb into a session-RPC call to the running server (see `session-rpc.ts`) and
|
|
16
17
|
* returns the result. The verb command code is UNCHANGED — it still calls
|
|
17
18
|
* `provider(target)` then runs verbs against the returned `Session.page` then
|
|
@@ -24,8 +25,21 @@ import type {Session} from './seam.js';
|
|
|
24
25
|
* (`stop`), exactly as ADR-0005 requires. This is the whole reason cross-
|
|
25
26
|
* invocation persistence works: the page state survives because the client's
|
|
26
27
|
* `close()` does not reach across to the server's session.
|
|
28
|
+
*
|
|
29
|
+
* THIRD-PARTY HAND VERBS (Phase 2, Model B; ADR-0007). Pass the NAMES of the
|
|
30
|
+
* hand verbs the served process loaded as `handVerbs`; each is attached to the
|
|
31
|
+
* returned `page` as a dynamic method forwarding over the RPC via
|
|
32
|
+
* {@link callHandVerb}, so the agent gains those tools WITHOUT ever holding a
|
|
33
|
+
* live page handle. They are NOT on the seam `WebHandsPage` type (the seam knows only
|
|
34
|
+
* the eight built-ins), so a caller reaches them through a cast, exactly as a
|
|
35
|
+
* third-party hand verb is reached on the in-process composed page. The result
|
|
36
|
+
* crosses the wire as a serializable value and a page/in-hand throw rejects
|
|
37
|
+
* faithfully, the same contract as the built-in verbs.
|
|
27
38
|
*/
|
|
28
|
-
export function connectRemoteSession(
|
|
39
|
+
export function connectRemoteSession(
|
|
40
|
+
baseUrl: string,
|
|
41
|
+
handVerbs: readonly string[] = [],
|
|
42
|
+
): Session {
|
|
29
43
|
const endpoint = new URL(SESSION_RPC_PATH, baseUrl).toString();
|
|
30
44
|
|
|
31
45
|
const send = async (request: SessionRpcRequest): Promise<unknown> => {
|
|
@@ -56,11 +70,35 @@ export function connectRemoteSession(baseUrl: string): Session {
|
|
|
56
70
|
throw new Error(reply.error);
|
|
57
71
|
};
|
|
58
72
|
|
|
73
|
+
let resolveClosed!: () => void;
|
|
74
|
+
const closedSignal = new Promise<void>((resolve) => {
|
|
75
|
+
resolveClosed = resolve;
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
const page = makeRpcPage(send);
|
|
79
|
+
// Attach each loaded hand verb as a dynamic method that forwards over the same
|
|
80
|
+
// RPC `send`. The seam `WebHandsPage` type names only the built-ins, so these live on
|
|
81
|
+
// the runtime object alongside them (mirroring how a hand verb composes into
|
|
82
|
+
// the in-process page object); callers reach them through a cast.
|
|
83
|
+
const pageWithHands = page as unknown as Record<string, unknown>;
|
|
84
|
+
for (const name of handVerbs) {
|
|
85
|
+
pageWithHands[name] = (...args: readonly unknown[]): Promise<unknown> =>
|
|
86
|
+
callHandVerb(send, name, ...args);
|
|
87
|
+
}
|
|
88
|
+
|
|
59
89
|
return {
|
|
60
|
-
page
|
|
90
|
+
page,
|
|
61
91
|
async close() {
|
|
62
|
-
// Intentionally a no-op: the served process owns the
|
|
63
|
-
// (see this module's overview). Teardown is the
|
|
92
|
+
// Intentionally a no-op against the SERVER: the served process owns the
|
|
93
|
+
// session's lifetime (see this module's overview). Teardown is the
|
|
94
|
+
// explicit `stop` verb. We still resolve the local close signal so a
|
|
95
|
+
// caller awaiting waitForClose() on this client handle unblocks.
|
|
96
|
+
resolveClosed();
|
|
97
|
+
},
|
|
98
|
+
waitForClose(): Promise<void> {
|
|
99
|
+
// A client never waits on the user closing the window — that is the
|
|
100
|
+
// server's concern; this resolves on a local close() call.
|
|
101
|
+
return closedSignal;
|
|
64
102
|
},
|
|
65
103
|
};
|
|
66
104
|
}
|