@dream_engine/browser 0.0.0-stage → 0.1.1
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 +21 -0
- package/dist/.tsbuildinfo +1 -0
- package/dist/adapter/playwright.d.ts +27 -0
- package/dist/adapter/playwright.d.ts.map +1 -0
- package/dist/adapter/playwright.js +1087 -0
- package/dist/adapter/playwright.js.map +1 -0
- package/dist/adapter/types.d.ts +833 -0
- package/dist/adapter/types.d.ts.map +1 -0
- package/dist/adapter/types.js +9 -0
- package/dist/adapter/types.js.map +1 -0
- package/dist/api-request.d.ts +93 -0
- package/dist/api-request.d.ts.map +1 -0
- package/dist/api-request.js +284 -0
- package/dist/api-request.js.map +1 -0
- package/dist/artifacts.d.ts +99 -0
- package/dist/artifacts.d.ts.map +1 -0
- package/dist/artifacts.js +211 -0
- package/dist/artifacts.js.map +1 -0
- package/dist/browser.d.ts +79 -0
- package/dist/browser.d.ts.map +1 -0
- package/dist/browser.js +186 -0
- package/dist/browser.js.map +1 -0
- package/dist/code-execution.d.ts +12 -0
- package/dist/code-execution.d.ts.map +1 -0
- package/dist/code-execution.js +15 -0
- package/dist/code-execution.js.map +1 -0
- package/dist/context.d.ts +174 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +474 -0
- package/dist/context.js.map +1 -0
- package/dist/events.d.ts +66 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +87 -0
- package/dist/events.js.map +1 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +23 -0
- package/dist/index.js.map +1 -0
- package/dist/locator.d.ts +208 -0
- package/dist/locator.d.ts.map +1 -0
- package/dist/locator.js +402 -0
- package/dist/locator.js.map +1 -0
- package/dist/login.d.ts +76 -0
- package/dist/login.d.ts.map +1 -0
- package/dist/login.js +176 -0
- package/dist/login.js.map +1 -0
- package/dist/manager.d.ts +109 -0
- package/dist/manager.d.ts.map +1 -0
- package/dist/manager.js +320 -0
- package/dist/manager.js.map +1 -0
- package/dist/navigation.d.ts +74 -0
- package/dist/navigation.d.ts.map +1 -0
- package/dist/navigation.js +234 -0
- package/dist/navigation.js.map +1 -0
- package/dist/network.d.ts +260 -0
- package/dist/network.d.ts.map +1 -0
- package/dist/network.js +582 -0
- package/dist/network.js.map +1 -0
- package/dist/page.d.ts +512 -0
- package/dist/page.d.ts.map +1 -0
- package/dist/page.js +1493 -0
- package/dist/page.js.map +1 -0
- package/dist/selectors.d.ts +67 -0
- package/dist/selectors.d.ts.map +1 -0
- package/dist/selectors.js +137 -0
- package/dist/selectors.js.map +1 -0
- package/dist/sessions.d.ts +114 -0
- package/dist/sessions.d.ts.map +1 -0
- package/dist/sessions.js +285 -0
- package/dist/sessions.js.map +1 -0
- package/dist/smart/dom-scan.d.ts +104 -0
- package/dist/smart/dom-scan.d.ts.map +1 -0
- package/dist/smart/dom-scan.js +491 -0
- package/dist/smart/dom-scan.js.map +1 -0
- package/dist/smart/ranking.d.ts +63 -0
- package/dist/smart/ranking.d.ts.map +1 -0
- package/dist/smart/ranking.js +318 -0
- package/dist/smart/ranking.js.map +1 -0
- package/dist/smart/recovery.d.ts +106 -0
- package/dist/smart/recovery.d.ts.map +1 -0
- package/dist/smart/recovery.js +197 -0
- package/dist/smart/recovery.js.map +1 -0
- package/dist/smart/smart.d.ts +249 -0
- package/dist/smart/smart.d.ts.map +1 -0
- package/dist/smart/smart.js +840 -0
- package/dist/smart/smart.js.map +1 -0
- package/dist/trace-parser.d.ts +70 -0
- package/dist/trace-parser.d.ts.map +1 -0
- package/dist/trace-parser.js +203 -0
- package/dist/trace-parser.js.map +1 -0
- package/dist/types.d.ts +57 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/visual.d.ts +185 -0
- package/dist/visual.d.ts.map +1 -0
- package/dist/visual.js +384 -0
- package/dist/visual.js.map +1 -0
- package/package.json +37 -3
- package/README.md +0 -3
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import type { BrowserContextAdapter, Cookie, CookieFilter, CookieInput, Geolocation, HttpCredentials, CredentialsAdapter, HarReplayOptions, HarStartOptions, PageAdapter, StorageState, StorageStateOptions, TracingStartOptions } from './adapter/types.js';
|
|
2
|
+
import { type ApiRequest } from './api-request.js';
|
|
3
|
+
import type { BashirBrowser } from './browser.js';
|
|
4
|
+
import { type MockHandler, type MockResponse, type UrlMatch } from './network.js';
|
|
5
|
+
import { BashirPage } from './page.js';
|
|
6
|
+
import type { BrowserServices } from './types.js';
|
|
7
|
+
/** Serialises a function (or passes a script string through) for init scripts. */
|
|
8
|
+
export declare function scriptSource(script: string | ((arg: never) => unknown), arg?: unknown): string;
|
|
9
|
+
/** Default output directory for traces, HAR files, videos and PDFs. */
|
|
10
|
+
export declare function artifactsDir(services: BrowserServices, kind: 'traces' | 'har' | 'videos' | 'pdf' | 'coverage'): string;
|
|
11
|
+
/** Events of `context.on()`. */
|
|
12
|
+
export interface ContextEvents {
|
|
13
|
+
page: BashirPage;
|
|
14
|
+
close: undefined;
|
|
15
|
+
serviceworker: {
|
|
16
|
+
url: string;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export interface TracingOptions extends TracingStartOptions {
|
|
20
|
+
/** Default output path for `stop()`; otherwise a file under `<dataDir>/artifacts/traces`. */
|
|
21
|
+
path?: string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Playwright trace recording (open the zip with `npx playwright show-trace`). Traces contain page
|
|
25
|
+
* content, screenshots and network bodies: treat them as sensitive.
|
|
26
|
+
*/
|
|
27
|
+
export declare class ContextTracing {
|
|
28
|
+
private readonly ctx;
|
|
29
|
+
private active;
|
|
30
|
+
private chunk;
|
|
31
|
+
constructor(ctx: BashirContext);
|
|
32
|
+
get isRecording(): boolean;
|
|
33
|
+
start(options?: TracingOptions): Promise<void>;
|
|
34
|
+
/** Stops tracing and writes the trace zip. Returns its path. */
|
|
35
|
+
stop(options?: {
|
|
36
|
+
path?: string;
|
|
37
|
+
}): Promise<string>;
|
|
38
|
+
/** Stops without saving. */
|
|
39
|
+
discard(): Promise<void>;
|
|
40
|
+
/** Starts a new chunk within a running trace (one zip per chunk). */
|
|
41
|
+
startChunk(options?: {
|
|
42
|
+
name?: string;
|
|
43
|
+
title?: string;
|
|
44
|
+
}): Promise<void>;
|
|
45
|
+
stopChunk(options?: {
|
|
46
|
+
path?: string;
|
|
47
|
+
}): Promise<string>;
|
|
48
|
+
/** Groups subsequent actions under a label in the trace viewer. */
|
|
49
|
+
group(name: string): Promise<void>;
|
|
50
|
+
groupEnd(): Promise<void>;
|
|
51
|
+
}
|
|
52
|
+
/** HAR recording for a context. HAR files include headers and bodies: treat them as sensitive. */
|
|
53
|
+
export declare class ContextHar {
|
|
54
|
+
private readonly ctx;
|
|
55
|
+
private recording;
|
|
56
|
+
constructor(ctx: BashirContext);
|
|
57
|
+
get isRecording(): boolean;
|
|
58
|
+
start(options?: HarStartOptions & {
|
|
59
|
+
path?: string;
|
|
60
|
+
}): Promise<string>;
|
|
61
|
+
/** Stops recording and writes the HAR file. Returns its path. */
|
|
62
|
+
stop(): Promise<string>;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* An isolated browser context (separate cookies, storage and cache). Tabs opened in the same
|
|
66
|
+
* context share state; different contexts never do.
|
|
67
|
+
*/
|
|
68
|
+
export declare class BashirContext {
|
|
69
|
+
readonly adapter: BrowserContextAdapter;
|
|
70
|
+
readonly browser: BashirBrowser;
|
|
71
|
+
readonly services: BrowserServices;
|
|
72
|
+
readonly id: string;
|
|
73
|
+
private readonly pageMap;
|
|
74
|
+
private paused;
|
|
75
|
+
private closed;
|
|
76
|
+
private readonly offPage;
|
|
77
|
+
readonly tracing: ContextTracing;
|
|
78
|
+
readonly har: ContextHar;
|
|
79
|
+
private readonly emitter;
|
|
80
|
+
private apiRequest;
|
|
81
|
+
private readonly disposers;
|
|
82
|
+
private readonly mocks;
|
|
83
|
+
constructor(adapter: BrowserContextAdapter, browser: BashirBrowser, services: BrowserServices);
|
|
84
|
+
/** Opens a new tab in this context. */
|
|
85
|
+
newPage(): Promise<BashirPage>;
|
|
86
|
+
/** @internal Wraps a page created outside newPage (popups). */
|
|
87
|
+
wrapExistingPage(adapter: PageAdapter): BashirPage;
|
|
88
|
+
/** @internal */
|
|
89
|
+
forgetPage(page: BashirPage): void;
|
|
90
|
+
pages(): BashirPage[];
|
|
91
|
+
getPage(pageId: string): BashirPage | undefined;
|
|
92
|
+
/** Running service workers (URLs redacted). Chromium only; other engines return an empty list. */
|
|
93
|
+
serviceWorkers(): Array<{
|
|
94
|
+
url: string;
|
|
95
|
+
}>;
|
|
96
|
+
/**
|
|
97
|
+
* Virtual WebAuthn authenticator (Playwright's `context.credentials`): `install()` before pages
|
|
98
|
+
* call `navigator.credentials`, then seed passkeys with `create(rpId)` or read them with `get()`.
|
|
99
|
+
* Returned credentials include the private key: store them like passwords. Local API only.
|
|
100
|
+
*/
|
|
101
|
+
get credentials(): CredentialsAdapter;
|
|
102
|
+
/**
|
|
103
|
+
* Answers matching requests of every page in this context (Playwright's `context.route`). Page
|
|
104
|
+
* mocks take precedence; the network policy and block rules still run first. Returns a remover.
|
|
105
|
+
*/
|
|
106
|
+
mock(match: UrlMatch, handler: MockHandler | MockResponse, options?: {
|
|
107
|
+
times?: number;
|
|
108
|
+
}): Promise<() => Promise<void>>;
|
|
109
|
+
/** Removes context mocks for `match` (optionally only those registered with `handler`). */
|
|
110
|
+
unmock(match: UrlMatch, handler?: MockHandler | MockResponse): Promise<number>;
|
|
111
|
+
clearMocks(): Promise<void>;
|
|
112
|
+
get mockCount(): number;
|
|
113
|
+
private readonly mockFetcher;
|
|
114
|
+
/** Subscribes to `page` (a new tab, including popups), `serviceworker` or `close`. Returns an unsubscribe function. */
|
|
115
|
+
on<K extends keyof ContextEvents>(event: K, listener: (payload: ContextEvents[K]) => unknown): () => void;
|
|
116
|
+
/** Resolves with the next matching event (e.g. a popup opened by any page). */
|
|
117
|
+
waitForEvent<K extends keyof ContextEvents>(event: K, options?: {
|
|
118
|
+
predicate?: (payload: ContextEvents[K]) => boolean | Promise<boolean>;
|
|
119
|
+
timeout?: number;
|
|
120
|
+
}): Promise<ContextEvents[K]>;
|
|
121
|
+
/**
|
|
122
|
+
* An API client that shares this context's cookies (Playwright's `context.request`): cookies set
|
|
123
|
+
* by pages are sent, and cookies set by API responses become visible to pages. Every request and
|
|
124
|
+
* redirect hop is checked against the network policy and goes through the egress proxy.
|
|
125
|
+
*/
|
|
126
|
+
request(): Promise<ApiRequest>;
|
|
127
|
+
cookies(urls?: string | string[]): Promise<Cookie[]>;
|
|
128
|
+
addCookies(cookies: CookieInput[]): Promise<void>;
|
|
129
|
+
/** Removes all cookies, or only those matching `filter` (name, domain, path; strings or RegExps). */
|
|
130
|
+
clearCookies(filter?: CookieFilter): Promise<void>;
|
|
131
|
+
/**
|
|
132
|
+
* Sets (or with null, clears) HTTP Basic credentials for the context. Set `origin` so the
|
|
133
|
+
* credentials are only sent to that origin.
|
|
134
|
+
*/
|
|
135
|
+
setHTTPCredentials(credentials: HttpCredentials | null): Promise<void>;
|
|
136
|
+
/** Cookies and localStorage for persistence (authentication state). Treat as a secret. */
|
|
137
|
+
/** Cookies and localStorage (plus IndexedDB with `{ indexedDB: true }`). Treat as secrets. */
|
|
138
|
+
storageState(options?: StorageStateOptions): Promise<StorageState>;
|
|
139
|
+
/** Writes storage state to a file readable only by the current user (mode 0600). */
|
|
140
|
+
saveStorageState(path: string, options?: {
|
|
141
|
+
indexedDB?: boolean;
|
|
142
|
+
}): Promise<void>;
|
|
143
|
+
/** Replaces cookies and localStorage with a saved state (object or file path). */
|
|
144
|
+
setStorageState(state: StorageState | string): Promise<void>;
|
|
145
|
+
/** Grants browser permissions (e.g. "geolocation", "clipboard-read", "notifications"), optionally for one origin. */
|
|
146
|
+
grantPermissions(permissions: string[], options?: {
|
|
147
|
+
origin?: string;
|
|
148
|
+
}): Promise<void>;
|
|
149
|
+
clearPermissions(): Promise<void>;
|
|
150
|
+
/** Emulates a location; also grant the "geolocation" permission for pages to read it. Null clears it. */
|
|
151
|
+
setGeolocation(geolocation: Geolocation | null): Promise<void>;
|
|
152
|
+
/** Emulates loss of network connectivity for every page in the context. */
|
|
153
|
+
setOffline(offline: boolean): Promise<void>;
|
|
154
|
+
/** Headers sent with every request from this context (merged with page-level headers). */
|
|
155
|
+
setExtraHTTPHeaders(headers: Record<string, string>): Promise<void>;
|
|
156
|
+
/** Runs a script in every page and frame of the context before any page script. */
|
|
157
|
+
addInitScript<A>(script: string | ((arg: A) => unknown), arg?: A): Promise<void>;
|
|
158
|
+
/** Exposes a Node.js function as `window[name]` in every page of the context. */
|
|
159
|
+
exposeFunction(name: string, fn: (...args: never[]) => unknown): Promise<void>;
|
|
160
|
+
/**
|
|
161
|
+
* Answers matching requests from a recorded HAR file. Requests missing from the HAR are aborted
|
|
162
|
+
* (default) or, with `notFound: "fallback"`, sent to the network under the normal network policy.
|
|
163
|
+
*/
|
|
164
|
+
routeFromHAR(path: string, options?: HarReplayOptions): Promise<void>;
|
|
165
|
+
/** Pauses the context: page operations throw SessionError until resumed. */
|
|
166
|
+
pause(): void;
|
|
167
|
+
resume(): void;
|
|
168
|
+
get isPaused(): boolean;
|
|
169
|
+
get isClosed(): boolean;
|
|
170
|
+
/** @internal */
|
|
171
|
+
assertActive(): void;
|
|
172
|
+
close(): Promise<void>;
|
|
173
|
+
}
|
|
174
|
+
//# sourceMappingURL=context.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,qBAAqB,EACrB,MAAM,EACN,YAAY,EACZ,WAAW,EACX,WAAW,EACX,eAAe,EACf,kBAAkB,EAClB,gBAAgB,EAChB,eAAe,EACf,WAAW,EACX,YAAY,EACZ,mBAAmB,EACnB,mBAAmB,EACpB,MAAM,oBA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,MAAM,CAAC,EAAE,MAAM,CAAA;KAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAKzF,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC;IAIvC,yGAAyG;IACnG,cAAc,CAAC,WAAW,EAAE,WAAW,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IAWpE,2EAA2E;IACrE,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAKjD,0FAA0F;IACpF,mBAAmB,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAOzE,mFAAmF;IAC7E,aAAa,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK,OAAO,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAMtF,iFAAiF;IAC3E,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,GAAG,IAAI,EAAE,KAAK,EAAE,KAAK,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAOpF;;;OAGG;IACG,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC;IAO/E,4EAA4E;IAC5E,KAAK,IAAI,IAAI;IAIb,MAAM,IAAI,IAAI;IAId,IAAI,QAAQ,IAAI,OAAO,CAEtB;IAED,IAAI,QAAQ,IAAI,OAAO,CAEtB;IAED,gBAAgB;IAChB,YAAY,IAAI,IAAI;IAKd,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAa7B"}
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { SessionError, ValidationError, createId, redactUrl } from '@dream_engine/core';
|
|
4
|
+
import { parseSetCookie } from './api-request.js';
|
|
5
|
+
import { TypedEmitter } from './events.js';
|
|
6
|
+
import { confineOutput, noteArtifact } from './artifacts.js';
|
|
7
|
+
import { assertCodeExecution } from './code-execution.js';
|
|
8
|
+
import { MockRegistry } from './network.js';
|
|
9
|
+
import { BashirPage } from './page.js';
|
|
10
|
+
/** Serialises a function (or passes a script string through) for init scripts. */
|
|
11
|
+
export function scriptSource(script, arg) {
|
|
12
|
+
if (typeof script === 'string')
|
|
13
|
+
return script;
|
|
14
|
+
if (typeof script !== 'function')
|
|
15
|
+
throw new ValidationError('script must be a string or a function');
|
|
16
|
+
return `(${script.toString()})(${arg === undefined ? '' : JSON.stringify(arg)});`;
|
|
17
|
+
}
|
|
18
|
+
/** Default output directory for traces, HAR files, videos and PDFs. */
|
|
19
|
+
export function artifactsDir(services, kind) {
|
|
20
|
+
const dir = join(services.config.runtime.dataDir, 'artifacts', kind);
|
|
21
|
+
mkdirSync(dir, { recursive: true });
|
|
22
|
+
return dir;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Playwright trace recording (open the zip with `npx playwright show-trace`). Traces contain page
|
|
26
|
+
* content, screenshots and network bodies: treat them as sensitive.
|
|
27
|
+
*/
|
|
28
|
+
export class ContextTracing {
|
|
29
|
+
ctx;
|
|
30
|
+
active = null;
|
|
31
|
+
chunk = 0;
|
|
32
|
+
constructor(ctx) {
|
|
33
|
+
this.ctx = ctx;
|
|
34
|
+
}
|
|
35
|
+
get isRecording() {
|
|
36
|
+
return this.active !== null;
|
|
37
|
+
}
|
|
38
|
+
async start(options = {}) {
|
|
39
|
+
if (this.active)
|
|
40
|
+
throw new ValidationError('Tracing is already running in this context');
|
|
41
|
+
const { path: requested, ...rest } = options;
|
|
42
|
+
const path = requested ? confineOutput(this.ctx.services, requested) : undefined;
|
|
43
|
+
await this.ctx.adapter.tracing.start({ screenshots: true, snapshots: true, ...rest });
|
|
44
|
+
this.active = { path };
|
|
45
|
+
}
|
|
46
|
+
/** Stops tracing and writes the trace zip. Returns its path. */
|
|
47
|
+
async stop(options = {}) {
|
|
48
|
+
if (!this.active)
|
|
49
|
+
throw new ValidationError('Tracing is not running');
|
|
50
|
+
const out = options.path
|
|
51
|
+
? confineOutput(this.ctx.services, options.path)
|
|
52
|
+
: (this.active.path ?? join(artifactsDir(this.ctx.services, 'traces'), `${createId('trace')}.zip`));
|
|
53
|
+
mkdirSync(dirname(out), { recursive: true });
|
|
54
|
+
this.active = null;
|
|
55
|
+
await this.ctx.adapter.tracing.stop(out);
|
|
56
|
+
noteArtifact(this.ctx.services, 'traces', out);
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
/** Stops without saving. */
|
|
60
|
+
async discard() {
|
|
61
|
+
if (!this.active)
|
|
62
|
+
return;
|
|
63
|
+
this.active = null;
|
|
64
|
+
await this.ctx.adapter.tracing.stop();
|
|
65
|
+
}
|
|
66
|
+
/** Starts a new chunk within a running trace (one zip per chunk). */
|
|
67
|
+
async startChunk(options = {}) {
|
|
68
|
+
if (!this.active)
|
|
69
|
+
throw new ValidationError('Start tracing before starting a chunk');
|
|
70
|
+
await this.ctx.adapter.tracing.startChunk(options);
|
|
71
|
+
}
|
|
72
|
+
async stopChunk(options = {}) {
|
|
73
|
+
if (!this.active)
|
|
74
|
+
throw new ValidationError('Tracing is not running');
|
|
75
|
+
const out = options.path
|
|
76
|
+
? confineOutput(this.ctx.services, options.path)
|
|
77
|
+
: join(artifactsDir(this.ctx.services, 'traces'), `${createId('trace')}-${++this.chunk}.zip`);
|
|
78
|
+
mkdirSync(dirname(out), { recursive: true });
|
|
79
|
+
await this.ctx.adapter.tracing.stopChunk(out);
|
|
80
|
+
noteArtifact(this.ctx.services, 'traces', out);
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
/** Groups subsequent actions under a label in the trace viewer. */
|
|
84
|
+
async group(name) {
|
|
85
|
+
return this.ctx.adapter.tracing.group(name);
|
|
86
|
+
}
|
|
87
|
+
async groupEnd() {
|
|
88
|
+
return this.ctx.adapter.tracing.groupEnd();
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** HAR recording for a context. HAR files include headers and bodies: treat them as sensitive. */
|
|
92
|
+
export class ContextHar {
|
|
93
|
+
ctx;
|
|
94
|
+
recording = null;
|
|
95
|
+
constructor(ctx) {
|
|
96
|
+
this.ctx = ctx;
|
|
97
|
+
}
|
|
98
|
+
get isRecording() {
|
|
99
|
+
return this.recording !== null;
|
|
100
|
+
}
|
|
101
|
+
async start(options = {}) {
|
|
102
|
+
if (this.recording)
|
|
103
|
+
throw new ValidationError('HAR recording is already running in this context');
|
|
104
|
+
const { path, ...rest } = options;
|
|
105
|
+
const out = path
|
|
106
|
+
? confineOutput(this.ctx.services, path)
|
|
107
|
+
: join(artifactsDir(this.ctx.services, 'har'), `${createId('har')}.${rest.content === 'attach' ? 'zip' : 'har'}`);
|
|
108
|
+
mkdirSync(dirname(out), { recursive: true });
|
|
109
|
+
await this.ctx.adapter.tracing.startHar(out, rest);
|
|
110
|
+
this.recording = out;
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
/** Stops recording and writes the HAR file. Returns its path. */
|
|
114
|
+
async stop() {
|
|
115
|
+
if (!this.recording)
|
|
116
|
+
throw new ValidationError('HAR recording is not running');
|
|
117
|
+
const out = this.recording;
|
|
118
|
+
this.recording = null;
|
|
119
|
+
await this.ctx.adapter.tracing.stopHar();
|
|
120
|
+
noteArtifact(this.ctx.services, 'har', out);
|
|
121
|
+
return out;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* An isolated browser context (separate cookies, storage and cache). Tabs opened in the same
|
|
126
|
+
* context share state; different contexts never do.
|
|
127
|
+
*/
|
|
128
|
+
export class BashirContext {
|
|
129
|
+
adapter;
|
|
130
|
+
browser;
|
|
131
|
+
services;
|
|
132
|
+
id = createId('ctx');
|
|
133
|
+
pageMap = new Map();
|
|
134
|
+
paused = false;
|
|
135
|
+
closed = false;
|
|
136
|
+
offPage;
|
|
137
|
+
tracing;
|
|
138
|
+
har;
|
|
139
|
+
emitter;
|
|
140
|
+
apiRequest = null;
|
|
141
|
+
disposers = [];
|
|
142
|
+
mocks = new MockRegistry(async () => {
|
|
143
|
+
await Promise.all(this.pages().map((p) => p.network.syncRouting()));
|
|
144
|
+
});
|
|
145
|
+
constructor(adapter, browser, services) {
|
|
146
|
+
this.adapter = adapter;
|
|
147
|
+
this.browser = browser;
|
|
148
|
+
this.services = services;
|
|
149
|
+
this.emitter = new TypedEmitter((event) => {
|
|
150
|
+
if (event === 'serviceworker')
|
|
151
|
+
this.disposers.push(adapter.onServiceWorker((w) => void this.emitter.emit('serviceworker', { url: redactUrl(w.url) })));
|
|
152
|
+
}, (event, error) => this.services.logger.warn('context event listener failed', { event: String(event), error: error?.message }));
|
|
153
|
+
this.tracing = new ContextTracing(this);
|
|
154
|
+
this.har = new ContextHar(this);
|
|
155
|
+
// Pages opened by the site (window.open, target=_blank) are wrapped automatically.
|
|
156
|
+
this.offPage = adapter.onPage((p) => {
|
|
157
|
+
if (!this.pageMap.has(p))
|
|
158
|
+
this.wrapExistingPage(p);
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/** Opens a new tab in this context. */
|
|
162
|
+
async newPage() {
|
|
163
|
+
this.assertActive();
|
|
164
|
+
const adapter = await this.adapter.newPage();
|
|
165
|
+
const page = this.wrapExistingPage(adapter);
|
|
166
|
+
// Context mocks must be active before the caller navigates.
|
|
167
|
+
if (this.mocks.size)
|
|
168
|
+
await page.network.syncRouting();
|
|
169
|
+
return page;
|
|
170
|
+
}
|
|
171
|
+
/** @internal Wraps a page created outside newPage (popups). */
|
|
172
|
+
wrapExistingPage(adapter) {
|
|
173
|
+
const existing = this.pageMap.get(adapter);
|
|
174
|
+
if (existing)
|
|
175
|
+
return existing;
|
|
176
|
+
const page = new BashirPage(adapter, this, this.services);
|
|
177
|
+
page.network.setFetcher(this.mockFetcher);
|
|
178
|
+
void page.network
|
|
179
|
+
.inheritMocks(this.mocks)
|
|
180
|
+
.catch((error) => this.services.logger.warn('could not install context mocks on page', { error: error.message }));
|
|
181
|
+
this.pageMap.set(adapter, page);
|
|
182
|
+
this.services.events.emit('page:created', { pageId: page.id, contextId: this.id, url: adapter.url() });
|
|
183
|
+
void this.emitter.emit('page', page);
|
|
184
|
+
return page;
|
|
185
|
+
}
|
|
186
|
+
/** @internal */
|
|
187
|
+
forgetPage(page) {
|
|
188
|
+
for (const [k, v] of this.pageMap)
|
|
189
|
+
if (v === page)
|
|
190
|
+
this.pageMap.delete(k);
|
|
191
|
+
}
|
|
192
|
+
pages() {
|
|
193
|
+
return [...this.pageMap.values()].filter((p) => !p.isClosed);
|
|
194
|
+
}
|
|
195
|
+
getPage(pageId) {
|
|
196
|
+
return this.pages().find((p) => p.id === pageId);
|
|
197
|
+
}
|
|
198
|
+
/** Running service workers (URLs redacted). Chromium only; other engines return an empty list. */
|
|
199
|
+
serviceWorkers() {
|
|
200
|
+
return this.adapter.serviceWorkers().map((w) => ({ url: redactUrl(w.url) }));
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Virtual WebAuthn authenticator (Playwright's `context.credentials`): `install()` before pages
|
|
204
|
+
* call `navigator.credentials`, then seed passkeys with `create(rpId)` or read them with `get()`.
|
|
205
|
+
* Returned credentials include the private key: store them like passwords. Local API only.
|
|
206
|
+
*/
|
|
207
|
+
get credentials() {
|
|
208
|
+
const c = () => {
|
|
209
|
+
this.assertActive();
|
|
210
|
+
return this.adapter.credentials;
|
|
211
|
+
};
|
|
212
|
+
const rp = (rpId) => {
|
|
213
|
+
if (typeof rpId !== 'string' || !/^[a-z0-9.-]+$/i.test(rpId))
|
|
214
|
+
throw new ValidationError('rpId must be a host name such as example.com');
|
|
215
|
+
return rpId;
|
|
216
|
+
};
|
|
217
|
+
return {
|
|
218
|
+
install: async () => c().install(),
|
|
219
|
+
create: async (rpId, options) => c().create(rp(rpId), options),
|
|
220
|
+
get: async (filter) => c().get(filter),
|
|
221
|
+
delete: async (id) => {
|
|
222
|
+
if (typeof id !== 'string' || !id)
|
|
223
|
+
throw new ValidationError('credential id must be a non-empty string');
|
|
224
|
+
return c().delete(id);
|
|
225
|
+
},
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Answers matching requests of every page in this context (Playwright's `context.route`). Page
|
|
230
|
+
* mocks take precedence; the network policy and block rules still run first. Returns a remover.
|
|
231
|
+
*/
|
|
232
|
+
async mock(match, handler, options = {}) {
|
|
233
|
+
this.assertActive();
|
|
234
|
+
return this.mocks.add(match, handler, options);
|
|
235
|
+
}
|
|
236
|
+
/** Removes context mocks for `match` (optionally only those registered with `handler`). */
|
|
237
|
+
async unmock(match, handler) {
|
|
238
|
+
return this.mocks.remove(match, handler);
|
|
239
|
+
}
|
|
240
|
+
async clearMocks() {
|
|
241
|
+
await this.mocks.clear();
|
|
242
|
+
}
|
|
243
|
+
get mockCount() {
|
|
244
|
+
return this.mocks.size;
|
|
245
|
+
}
|
|
246
|
+
mockFetcher = async (request, options) => {
|
|
247
|
+
const api = await this.request();
|
|
248
|
+
const drop = new Set(['cookie', 'host', 'content-length', 'connection', 'accept-encoding']);
|
|
249
|
+
const headers = Object.fromEntries(Object.entries(options.headers ?? request.headers).filter(([k]) => !k.startsWith(':') && !drop.has(k.toLowerCase())));
|
|
250
|
+
const init = { method: options.method ?? request.method, headers };
|
|
251
|
+
const body = options.postData ?? request.postData;
|
|
252
|
+
if (body !== null && body !== undefined && body !== '')
|
|
253
|
+
init.data = body;
|
|
254
|
+
if (options.maxRedirects !== undefined)
|
|
255
|
+
init.maxRedirects = options.maxRedirects;
|
|
256
|
+
if (options.timeout !== undefined)
|
|
257
|
+
init.timeout = options.timeout;
|
|
258
|
+
const res = await api.fetch(options.url ?? request.url, init);
|
|
259
|
+
return {
|
|
260
|
+
url: res.url,
|
|
261
|
+
status: res.status,
|
|
262
|
+
statusText: res.statusText,
|
|
263
|
+
headers: res.headers,
|
|
264
|
+
body: res.body,
|
|
265
|
+
text: () => res.text(),
|
|
266
|
+
json: () => res.json(),
|
|
267
|
+
};
|
|
268
|
+
};
|
|
269
|
+
/** Subscribes to `page` (a new tab, including popups), `serviceworker` or `close`. Returns an unsubscribe function. */
|
|
270
|
+
on(event, listener) {
|
|
271
|
+
return this.emitter.on(event, listener);
|
|
272
|
+
}
|
|
273
|
+
/** Resolves with the next matching event (e.g. a popup opened by any page). */
|
|
274
|
+
async waitForEvent(event, options = {}) {
|
|
275
|
+
return this.emitter.waitFor(event, {
|
|
276
|
+
timeout: options.timeout ?? this.services.config.browser.timeout,
|
|
277
|
+
...(options.predicate ? { predicate: options.predicate } : {}),
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* An API client that shares this context's cookies (Playwright's `context.request`): cookies set
|
|
282
|
+
* by pages are sent, and cookies set by API responses become visible to pages. Every request and
|
|
283
|
+
* redirect hop is checked against the network policy and goes through the egress proxy.
|
|
284
|
+
*/
|
|
285
|
+
async request() {
|
|
286
|
+
try {
|
|
287
|
+
this.assertActive();
|
|
288
|
+
}
|
|
289
|
+
catch (error) {
|
|
290
|
+
return Promise.reject(error);
|
|
291
|
+
}
|
|
292
|
+
if (!this.apiRequest) {
|
|
293
|
+
const create = this.services.createApiRequest;
|
|
294
|
+
if (!create)
|
|
295
|
+
return Promise.reject(new ValidationError('API requests need a BrowserManager-created context'));
|
|
296
|
+
const opts = {
|
|
297
|
+
jar: {
|
|
298
|
+
header: async (url) => {
|
|
299
|
+
const list = await this.adapter.cookies([url]);
|
|
300
|
+
return list.length ? list.map((c) => `${c.name}=${c.value}`).join('; ') : null;
|
|
301
|
+
},
|
|
302
|
+
store: async (url, lines) => {
|
|
303
|
+
for (const line of lines) {
|
|
304
|
+
const parsed = parseSetCookie(line, url);
|
|
305
|
+
if (!parsed) {
|
|
306
|
+
this.services.logger.debug('rejected Set-Cookie from API response', { url: redactUrl(url) });
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
if (parsed.kind === 'delete')
|
|
310
|
+
await this.adapter.clearCookies({ name: parsed.name, domain: parsed.domain, path: parsed.path });
|
|
311
|
+
else
|
|
312
|
+
await this.adapter.addCookies([parsed.cookie]);
|
|
313
|
+
}
|
|
314
|
+
},
|
|
315
|
+
},
|
|
316
|
+
};
|
|
317
|
+
if (this.services.config.browser.userAgent)
|
|
318
|
+
opts.userAgent = this.services.config.browser.userAgent;
|
|
319
|
+
this.apiRequest = create(opts);
|
|
320
|
+
this.apiRequest.catch(() => (this.apiRequest = null));
|
|
321
|
+
}
|
|
322
|
+
return this.apiRequest;
|
|
323
|
+
}
|
|
324
|
+
async cookies(urls) {
|
|
325
|
+
return this.adapter.cookies(urls === undefined ? undefined : Array.isArray(urls) ? urls : [urls]);
|
|
326
|
+
}
|
|
327
|
+
async addCookies(cookies) {
|
|
328
|
+
this.assertActive();
|
|
329
|
+
return this.adapter.addCookies(cookies);
|
|
330
|
+
}
|
|
331
|
+
/** Removes all cookies, or only those matching `filter` (name, domain, path; strings or RegExps). */
|
|
332
|
+
async clearCookies(filter) {
|
|
333
|
+
return this.adapter.clearCookies(filter);
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Sets (or with null, clears) HTTP Basic credentials for the context. Set `origin` so the
|
|
337
|
+
* credentials are only sent to that origin.
|
|
338
|
+
*/
|
|
339
|
+
async setHTTPCredentials(credentials) {
|
|
340
|
+
this.assertActive();
|
|
341
|
+
if (credentials && (typeof credentials.username !== 'string' || typeof credentials.password !== 'string'))
|
|
342
|
+
throw new ValidationError('HTTP credentials need string username and password');
|
|
343
|
+
if (credentials?.origin) {
|
|
344
|
+
try {
|
|
345
|
+
if (new URL(credentials.origin).origin !== credentials.origin)
|
|
346
|
+
throw new Error('not an origin');
|
|
347
|
+
}
|
|
348
|
+
catch {
|
|
349
|
+
throw new ValidationError('credentials.origin must be an origin such as https://example.com');
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
return this.adapter.setHTTPCredentials(credentials);
|
|
353
|
+
}
|
|
354
|
+
/** Cookies and localStorage for persistence (authentication state). Treat as a secret. */
|
|
355
|
+
/** Cookies and localStorage (plus IndexedDB with `{ indexedDB: true }`). Treat as secrets. */
|
|
356
|
+
async storageState(options = {}) {
|
|
357
|
+
return this.adapter.storageState(options);
|
|
358
|
+
}
|
|
359
|
+
/** Writes storage state to a file readable only by the current user (mode 0600). */
|
|
360
|
+
async saveStorageState(path, options = {}) {
|
|
361
|
+
path = confineOutput(this.services, path);
|
|
362
|
+
const state = await this.adapter.storageState(options);
|
|
363
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
364
|
+
writeFileSync(path, JSON.stringify(state), { mode: 0o600 });
|
|
365
|
+
chmodSync(path, 0o600);
|
|
366
|
+
noteArtifact(this.services, 'storage', path);
|
|
367
|
+
}
|
|
368
|
+
/** Replaces cookies and localStorage with a saved state (object or file path). */
|
|
369
|
+
async setStorageState(state) {
|
|
370
|
+
this.assertActive();
|
|
371
|
+
const value = typeof state === 'string' ? JSON.parse(readFileSync(state, 'utf8')) : state;
|
|
372
|
+
if (!value || !Array.isArray(value.cookies) || !Array.isArray(value.origins))
|
|
373
|
+
throw new ValidationError('Invalid storage state: expected { cookies, origins }');
|
|
374
|
+
await this.adapter.setStorageState(value);
|
|
375
|
+
}
|
|
376
|
+
/** Grants browser permissions (e.g. "geolocation", "clipboard-read", "notifications"), optionally for one origin. */
|
|
377
|
+
async grantPermissions(permissions, options = {}) {
|
|
378
|
+
this.assertActive();
|
|
379
|
+
return this.adapter.grantPermissions(permissions, options.origin);
|
|
380
|
+
}
|
|
381
|
+
async clearPermissions() {
|
|
382
|
+
return this.adapter.clearPermissions();
|
|
383
|
+
}
|
|
384
|
+
/** Emulates a location; also grant the "geolocation" permission for pages to read it. Null clears it. */
|
|
385
|
+
async setGeolocation(geolocation) {
|
|
386
|
+
this.assertActive();
|
|
387
|
+
if (geolocation) {
|
|
388
|
+
const { latitude, longitude, accuracy } = geolocation;
|
|
389
|
+
if (!(latitude >= -90 && latitude <= 90) || !(longitude >= -180 && longitude <= 180))
|
|
390
|
+
throw new ValidationError('latitude must be within [-90, 90] and longitude within [-180, 180]');
|
|
391
|
+
if (accuracy !== undefined && !(accuracy >= 0))
|
|
392
|
+
throw new ValidationError('accuracy must be >= 0');
|
|
393
|
+
}
|
|
394
|
+
return this.adapter.setGeolocation(geolocation);
|
|
395
|
+
}
|
|
396
|
+
/** Emulates loss of network connectivity for every page in the context. */
|
|
397
|
+
async setOffline(offline) {
|
|
398
|
+
this.assertActive();
|
|
399
|
+
return this.adapter.setOffline(offline);
|
|
400
|
+
}
|
|
401
|
+
/** Headers sent with every request from this context (merged with page-level headers). */
|
|
402
|
+
async setExtraHTTPHeaders(headers) {
|
|
403
|
+
this.assertActive();
|
|
404
|
+
for (const [k, v] of Object.entries(headers))
|
|
405
|
+
if (typeof v !== 'string' || /[\r\n]/.test(k + v))
|
|
406
|
+
throw new ValidationError(`Invalid header ${JSON.stringify(k)}`);
|
|
407
|
+
return this.adapter.setExtraHTTPHeaders(headers);
|
|
408
|
+
}
|
|
409
|
+
/** Runs a script in every page and frame of the context before any page script. */
|
|
410
|
+
async addInitScript(script, arg) {
|
|
411
|
+
this.assertActive();
|
|
412
|
+
assertCodeExecution(this.services, 'context.addInitScript');
|
|
413
|
+
return this.adapter.addInitScript(scriptSource(script, arg));
|
|
414
|
+
}
|
|
415
|
+
/** Exposes a Node.js function as `window[name]` in every page of the context. */
|
|
416
|
+
async exposeFunction(name, fn) {
|
|
417
|
+
this.assertActive();
|
|
418
|
+
assertCodeExecution(this.services, 'context.exposeFunction');
|
|
419
|
+
if (!/^[A-Za-z_$][\w$]*$/.test(name))
|
|
420
|
+
throw new ValidationError('Function name must be a valid JavaScript identifier');
|
|
421
|
+
return this.adapter.exposeFunction(name, fn);
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Answers matching requests from a recorded HAR file. Requests missing from the HAR are aborted
|
|
425
|
+
* (default) or, with `notFound: "fallback"`, sent to the network under the normal network policy.
|
|
426
|
+
*/
|
|
427
|
+
async routeFromHAR(path, options = {}) {
|
|
428
|
+
this.assertActive();
|
|
429
|
+
if (!options.update && !existsSync(path))
|
|
430
|
+
throw new ValidationError(`HAR file not found: ${path}`);
|
|
431
|
+
// update: true writes the HAR when the context closes.
|
|
432
|
+
return this.adapter.routeFromHAR(options.update ? confineOutput(this.services, path) : path, options);
|
|
433
|
+
}
|
|
434
|
+
/** Pauses the context: page operations throw SessionError until resumed. */
|
|
435
|
+
pause() {
|
|
436
|
+
this.paused = true;
|
|
437
|
+
}
|
|
438
|
+
resume() {
|
|
439
|
+
this.paused = false;
|
|
440
|
+
}
|
|
441
|
+
get isPaused() {
|
|
442
|
+
return this.paused;
|
|
443
|
+
}
|
|
444
|
+
get isClosed() {
|
|
445
|
+
return this.closed;
|
|
446
|
+
}
|
|
447
|
+
/** @internal */
|
|
448
|
+
assertActive() {
|
|
449
|
+
if (this.closed)
|
|
450
|
+
throw new SessionError('Browser context is closed', { details: { contextId: this.id } });
|
|
451
|
+
if (this.paused)
|
|
452
|
+
throw new SessionError('Session is paused; resume it before interacting', { details: { contextId: this.id } });
|
|
453
|
+
}
|
|
454
|
+
async close() {
|
|
455
|
+
if (this.closed)
|
|
456
|
+
return;
|
|
457
|
+
this.closed = true;
|
|
458
|
+
this.offPage();
|
|
459
|
+
for (const d of this.disposers.splice(0))
|
|
460
|
+
d();
|
|
461
|
+
if (this.apiRequest)
|
|
462
|
+
await this.apiRequest.then((r) => r.dispose()).catch(() => undefined);
|
|
463
|
+
void this.emitter.emit('close', undefined).finally(() => this.emitter.clear());
|
|
464
|
+
if (this.har.isRecording)
|
|
465
|
+
await this.har.stop().catch(() => undefined);
|
|
466
|
+
if (this.tracing.isRecording)
|
|
467
|
+
await this.tracing.discard().catch(() => undefined);
|
|
468
|
+
for (const p of this.pages())
|
|
469
|
+
await p.close().catch(() => undefined);
|
|
470
|
+
await this.adapter.close().catch(() => undefined);
|
|
471
|
+
this.browser.forgetContext(this);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
//# sourceMappingURL=context.js.map
|