@cbxss/eoka 0.0.0-stage → 0.1.0-beta.2
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 +577 -2
- package/dist/LICENSE +21 -0
- package/dist/browser-install-diagnostics.d.ts +1 -0
- package/dist/browser-install-diagnostics.js +21 -0
- package/dist/browser-install-engine.d.ts +10 -0
- package/dist/browser-install-engine.js +286 -0
- package/dist/browser-install-inventory.d.ts +34 -0
- package/dist/browser-install-inventory.js +107 -0
- package/dist/browser-install-worker.d.ts +21 -0
- package/dist/browser-install-worker.js +65 -0
- package/dist/browser-install.d.ts +22 -0
- package/dist/browser-install.js +7 -0
- package/dist/browser.d.ts +59 -0
- package/dist/browser.js +445 -0
- package/dist/client.d.ts +11 -0
- package/dist/client.js +1 -0
- package/dist/errors.d.ts +33 -0
- package/dist/errors.js +44 -0
- package/dist/generated/protocol.d.ts +3929 -0
- package/dist/generated/protocol.js +2 -0
- package/dist/generated/schema-bundle.json +18964 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.js +11 -0
- package/dist/install-errors.d.ts +4 -0
- package/dist/install-errors.js +6 -0
- package/dist/operations.d.ts +22 -0
- package/dist/operations.js +87 -0
- package/dist/page.d.ts +77 -0
- package/dist/page.js +250 -0
- package/dist/platform.d.ts +4 -0
- package/dist/platform.js +27 -0
- package/dist/recording.d.ts +27 -0
- package/dist/recording.js +124 -0
- package/dist/release-manifest.json +101 -0
- package/dist/release.d.ts +36 -0
- package/dist/release.js +76 -0
- package/dist/server-binary.d.ts +11 -0
- package/dist/server-binary.js +107 -0
- package/dist/transport.d.ts +89 -0
- package/dist/transport.js +737 -0
- package/examples/capture.mjs +36 -0
- package/examples/consume-schema.mjs +7 -0
- package/examples/explicit-paths.mjs +42 -0
- package/examples/install-browser.mjs +20 -0
- package/examples/offline.mjs +20 -0
- package/package.json +70 -4
package/dist/browser.js
ADDED
|
@@ -0,0 +1,445 @@
|
|
|
1
|
+
import { access, chmod, mkdir, mkdtemp, rm, stat } from 'node:fs/promises';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join, resolve } from 'node:path';
|
|
5
|
+
import { ConfigurationError, EokaError, ProtocolError, TransportError } from './errors.js';
|
|
6
|
+
import { Operation } from './operations.js';
|
|
7
|
+
import { Page } from './page.js';
|
|
8
|
+
import { Recording } from './recording.js';
|
|
9
|
+
import { SidecarTransport } from './transport.js';
|
|
10
|
+
import { installBrowser } from './browser-install.js';
|
|
11
|
+
import { resolveServerBinary } from './server-binary.js';
|
|
12
|
+
function validateTimeout(value, name) {
|
|
13
|
+
if (value !== undefined && (!Number.isFinite(value) || value <= 0 || value > 2_147_483_647)) {
|
|
14
|
+
throw new ConfigurationError(`${name} must be finite, positive and at most 2147483647 milliseconds`);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function pathOption(value, name) {
|
|
18
|
+
if (typeof value !== 'string' || value.trim() === '' || value.includes('\0')) {
|
|
19
|
+
throw new ConfigurationError(`${name} must be a nonempty filesystem path`);
|
|
20
|
+
}
|
|
21
|
+
return resolve(value);
|
|
22
|
+
}
|
|
23
|
+
async function executablePath(value, name) {
|
|
24
|
+
const absolute = pathOption(value, name);
|
|
25
|
+
try {
|
|
26
|
+
if (!(await stat(absolute)).isFile())
|
|
27
|
+
throw new Error('not a regular file');
|
|
28
|
+
await access(absolute, process.platform === 'win32' ? constants.F_OK : constants.X_OK);
|
|
29
|
+
}
|
|
30
|
+
catch (cause) {
|
|
31
|
+
throw new ConfigurationError(`${name} is not an accessible executable: ${absolute}`, { cause });
|
|
32
|
+
}
|
|
33
|
+
return absolute;
|
|
34
|
+
}
|
|
35
|
+
function checkAbort(signal, requestState = 'not_sent') {
|
|
36
|
+
if (signal?.aborted) {
|
|
37
|
+
const reason = signal.reason;
|
|
38
|
+
throw new TransportError(reason instanceof TransportError ? reason.code : 'Aborted', reason instanceof TransportError ? reason.message : 'Browser lifecycle operation was aborted; cleanup is not canceled', { cause: reason, requestState });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function remainingTimeout(deadline) {
|
|
42
|
+
if (deadline === undefined)
|
|
43
|
+
return undefined;
|
|
44
|
+
const remaining = deadline - performance.now();
|
|
45
|
+
if (remaining <= 0)
|
|
46
|
+
throw new TransportError('DeadlineExceeded', 'Browser lifecycle operation exceeded its local deadline', { requestState: 'not_sent' });
|
|
47
|
+
return remaining;
|
|
48
|
+
}
|
|
49
|
+
function localOptions(options, deadline) {
|
|
50
|
+
const timeoutMs = remainingTimeout(deadline);
|
|
51
|
+
const local = {};
|
|
52
|
+
if (options.signal !== undefined)
|
|
53
|
+
local.signal = options.signal;
|
|
54
|
+
if (options.operationId !== undefined)
|
|
55
|
+
local.operationId = options.operationId;
|
|
56
|
+
if (timeoutMs !== undefined)
|
|
57
|
+
local.timeoutMs = timeoutMs;
|
|
58
|
+
return local;
|
|
59
|
+
}
|
|
60
|
+
function lifecycleScope(options) {
|
|
61
|
+
validateTimeout(options.timeoutMs, 'timeoutMs');
|
|
62
|
+
validateTimeout(options.shutdownTimeoutMs, 'shutdownTimeoutMs');
|
|
63
|
+
checkAbort(options.signal);
|
|
64
|
+
const deadline = options.timeoutMs === undefined ? undefined : performance.now() + options.timeoutMs;
|
|
65
|
+
const controller = new AbortController();
|
|
66
|
+
const abort = () => controller.abort(new TransportError('Aborted', 'Browser lifecycle operation was aborted; cleanup is not canceled', { cause: options.signal?.reason, requestState: 'not_sent' }));
|
|
67
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
68
|
+
const timer = options.timeoutMs === undefined ? undefined : setTimeout(() => {
|
|
69
|
+
controller.abort(new TransportError('DeadlineExceeded', 'Browser lifecycle operation exceeded its local deadline', { requestState: 'not_sent' }));
|
|
70
|
+
}, options.timeoutMs);
|
|
71
|
+
return {
|
|
72
|
+
options: { ...options, signal: controller.signal },
|
|
73
|
+
deadline,
|
|
74
|
+
dispose: () => {
|
|
75
|
+
clearTimeout(timer);
|
|
76
|
+
options.signal?.removeEventListener('abort', abort);
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
function lifecycleFailure(primary, signal, deadline) {
|
|
81
|
+
if (signal?.aborted && signal.reason instanceof TransportError && primary instanceof EokaError && ['Aborted', 'InstallationAborted', 'InstallationTimeout'].includes(primary.code)) {
|
|
82
|
+
return new TransportError(signal.reason.code, signal.reason.message, { cause: primary, requestState: primary.requestState ?? 'not_sent', requestId: primary.requestId, stderr: primary.stderr });
|
|
83
|
+
}
|
|
84
|
+
if (deadline !== undefined && primary instanceof EokaError && primary.code === 'InstallationTimeout') {
|
|
85
|
+
return new TransportError('DeadlineExceeded', 'Browser lifecycle operation exceeded its local deadline', { cause: primary, requestState: 'not_sent' });
|
|
86
|
+
}
|
|
87
|
+
return primary;
|
|
88
|
+
}
|
|
89
|
+
async function runtimeDirectory(root) {
|
|
90
|
+
try {
|
|
91
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
92
|
+
const directory = await mkdtemp(join(root, 'e-'));
|
|
93
|
+
try {
|
|
94
|
+
if (process.platform !== 'win32')
|
|
95
|
+
await chmod(directory, 0o700);
|
|
96
|
+
return directory;
|
|
97
|
+
}
|
|
98
|
+
catch (primary) {
|
|
99
|
+
await removeRuntime(directory, primary);
|
|
100
|
+
throw primary;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
catch (cause) {
|
|
104
|
+
throw new ConfigurationError(`Could not create private browser runtime under ${root}`, { cause });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
async function removeRuntime(directory, primary) {
|
|
108
|
+
try {
|
|
109
|
+
await rm(directory, { recursive: true, force: true });
|
|
110
|
+
}
|
|
111
|
+
catch (cause) {
|
|
112
|
+
const cleanup = new TransportError('RuntimeCleanup', `Could not remove owned browser runtime ${directory}`, { cause });
|
|
113
|
+
if (primary !== undefined)
|
|
114
|
+
throw new AggregateError([primary, cleanup], 'Browser lifecycle failed and owned runtime cleanup failed', { cause: primary });
|
|
115
|
+
throw cleanup;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
async function removeClosedRuntime(directory, transport, primary) {
|
|
119
|
+
if (transport !== undefined && !transport.ownedProcessesTerminated) {
|
|
120
|
+
const cleanup = new TransportError('RuntimeCleanupUncertain', `Owned browser runtime retained at ${directory}: sidecar process-tree termination could not be confirmed`, { data: { runtimeDir: directory } });
|
|
121
|
+
if (primary !== undefined)
|
|
122
|
+
throw new AggregateError([primary, cleanup], 'Browser lifecycle failed and owned runtime was retained because process cleanup is uncertain', { cause: primary });
|
|
123
|
+
throw cleanup;
|
|
124
|
+
}
|
|
125
|
+
await removeRuntime(directory, primary);
|
|
126
|
+
}
|
|
127
|
+
function validateEndpoint(value) {
|
|
128
|
+
let endpoint;
|
|
129
|
+
try {
|
|
130
|
+
endpoint = new URL(value);
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
throw new ConfigurationError('browserWSEndpoint must be a ws:// browser DevTools endpoint');
|
|
134
|
+
}
|
|
135
|
+
if (typeof value !== 'string' || endpoint.protocol !== 'ws:' || !endpoint.hostname || endpoint.username || endpoint.password || value.includes('?') || value.includes('#') || !/^\/devtools\/browser\/[^/]+$/.test(endpoint.pathname)) {
|
|
136
|
+
throw new ConfigurationError('browserWSEndpoint must be a ws:// browser DevTools endpoint without credentials, query or fragment; wss:// is unsupported');
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
function launchParams(options) {
|
|
140
|
+
const params = { headless: options.headless ?? true, sandbox: options.sandbox ?? true, deviceScaleFactor: null };
|
|
141
|
+
for (const name of ['headless', 'sandbox']) {
|
|
142
|
+
if (options[name] !== undefined && typeof options[name] !== 'boolean')
|
|
143
|
+
throw new ConfigurationError(`${name} must be a boolean`);
|
|
144
|
+
}
|
|
145
|
+
for (const name of ['userAgent', 'timezone']) {
|
|
146
|
+
if (options[name] !== undefined) {
|
|
147
|
+
if (typeof options[name] !== 'string')
|
|
148
|
+
throw new ConfigurationError(`${name} must be a string`);
|
|
149
|
+
params[name] = options[name];
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
for (const name of ['runtimeDir', 'userDataDir']) {
|
|
153
|
+
if (options[name] !== undefined)
|
|
154
|
+
params[name] = pathOption(options[name], name);
|
|
155
|
+
}
|
|
156
|
+
if (options.viewport !== undefined) {
|
|
157
|
+
const viewport = options.viewport;
|
|
158
|
+
if (!viewport || !Number.isInteger(viewport.width) || !Number.isInteger(viewport.height) || viewport.width < 1 || viewport.height < 1 || viewport.width > 2_147_483_647 || viewport.height > 2_147_483_647) {
|
|
159
|
+
throw new ConfigurationError('viewport width and height must be positive integers at most 2147483647');
|
|
160
|
+
}
|
|
161
|
+
if (viewport.deviceScaleFactor !== undefined && (!Number.isFinite(viewport.deviceScaleFactor) || viewport.deviceScaleFactor <= 0)) {
|
|
162
|
+
throw new ConfigurationError('viewport deviceScaleFactor must be finite and positive');
|
|
163
|
+
}
|
|
164
|
+
params.viewportWidth = viewport.width;
|
|
165
|
+
params.viewportHeight = viewport.height;
|
|
166
|
+
params.deviceScaleFactor = viewport.deviceScaleFactor ?? null;
|
|
167
|
+
}
|
|
168
|
+
if (options.proxy !== undefined) {
|
|
169
|
+
const proxy = options.proxy;
|
|
170
|
+
let endpoint;
|
|
171
|
+
try {
|
|
172
|
+
endpoint = new URL(proxy.server);
|
|
173
|
+
}
|
|
174
|
+
catch {
|
|
175
|
+
throw new ConfigurationError('proxy.server must be an http:// or socks5:// URL with host and port');
|
|
176
|
+
}
|
|
177
|
+
if (!['http:', 'socks5:'].includes(endpoint.protocol) || !endpoint.hostname || !endpoint.port || endpoint.username || endpoint.password || !['', '/'].includes(endpoint.pathname) || proxy.server.includes('?') || proxy.server.includes('#')) {
|
|
178
|
+
throw new ConfigurationError('proxy.server must include host and port without credentials, path, query or fragment');
|
|
179
|
+
}
|
|
180
|
+
const username = proxy.username ?? null;
|
|
181
|
+
const password = proxy.password ?? null;
|
|
182
|
+
if ((username === null) !== (password === null) || (username !== null && typeof username !== 'string') || (password !== null && typeof password !== 'string')) {
|
|
183
|
+
throw new ConfigurationError('proxy credentials require both username and password strings');
|
|
184
|
+
}
|
|
185
|
+
params.proxy = { server: proxy.server, username, password };
|
|
186
|
+
}
|
|
187
|
+
return params;
|
|
188
|
+
}
|
|
189
|
+
export class Browser {
|
|
190
|
+
#transport;
|
|
191
|
+
#sessionInfo;
|
|
192
|
+
#capabilities;
|
|
193
|
+
#shutdownTimeoutMs;
|
|
194
|
+
#closePromise;
|
|
195
|
+
#pageOwners = new Set();
|
|
196
|
+
#creationCleanupFailures = [];
|
|
197
|
+
#runtimeCleanup;
|
|
198
|
+
constructor(transport, sessionInfo, shutdownTimeoutMs, runtimeDir) {
|
|
199
|
+
this.#transport = transport;
|
|
200
|
+
this.#sessionInfo = Object.freeze(sessionInfo);
|
|
201
|
+
this.#capabilities = new Set(transport.hello.capabilities);
|
|
202
|
+
this.#shutdownTimeoutMs = shutdownTimeoutMs;
|
|
203
|
+
this.#runtimeCleanup = runtimeDir === undefined
|
|
204
|
+
? Promise.resolve()
|
|
205
|
+
: transport.whenClosed().then(() => removeClosedRuntime(runtimeDir, transport), () => removeClosedRuntime(runtimeDir, transport));
|
|
206
|
+
void this.#runtimeCleanup.catch(() => { });
|
|
207
|
+
}
|
|
208
|
+
static async launch(options = {}) {
|
|
209
|
+
const params = launchParams(options);
|
|
210
|
+
if (options.download !== undefined && !['auto', 'never'].includes(options.download))
|
|
211
|
+
throw new ConfigurationError("download must be 'auto' or 'never'");
|
|
212
|
+
if (options.onProgress !== undefined && typeof options.onProgress !== 'function')
|
|
213
|
+
throw new ConfigurationError('onProgress must be a function');
|
|
214
|
+
const browserCacheDir = options.browserCacheDir === undefined ? undefined : pathOption(options.browserCacheDir, 'browserCacheDir');
|
|
215
|
+
const env = { ...process.env, ...options.serverEnv };
|
|
216
|
+
const root = pathOption(options.runtimeDir ?? env.EOKA_RUNTIME_DIR ?? tmpdir(), 'runtimeDir');
|
|
217
|
+
const scope = lifecycleScope(options);
|
|
218
|
+
let runtimeDir;
|
|
219
|
+
const runtimeOwner = {};
|
|
220
|
+
try {
|
|
221
|
+
const server = await resolveServerBinary({ ...(options.serverPath === undefined ? {} : { serverPath: options.serverPath }), env, signal: scope.options.signal });
|
|
222
|
+
checkAbort(scope.options.signal);
|
|
223
|
+
remainingTimeout(scope.deadline);
|
|
224
|
+
const chromePath = options.executablePath ?? env.EOKA_CHROME_PATH;
|
|
225
|
+
let expectedBrowserVersion;
|
|
226
|
+
if (chromePath !== undefined) {
|
|
227
|
+
params.executablePath = await executablePath(chromePath, 'executablePath');
|
|
228
|
+
}
|
|
229
|
+
else {
|
|
230
|
+
const installation = await installBrowser({
|
|
231
|
+
...(browserCacheDir === undefined ? {} : { browserCacheDir }),
|
|
232
|
+
...(options.download === undefined ? {} : { download: options.download }),
|
|
233
|
+
...(options.onProgress === undefined ? {} : { onProgress: options.onProgress }),
|
|
234
|
+
...localOptions(scope.options, scope.deadline),
|
|
235
|
+
env,
|
|
236
|
+
});
|
|
237
|
+
params.executablePath = installation.executablePath;
|
|
238
|
+
expectedBrowserVersion = installation.buildId;
|
|
239
|
+
}
|
|
240
|
+
checkAbort(scope.options.signal);
|
|
241
|
+
remainingTimeout(scope.deadline);
|
|
242
|
+
runtimeDir = await runtimeDirectory(root);
|
|
243
|
+
params.runtimeDir = runtimeDir;
|
|
244
|
+
const childEnv = { ...env, TMPDIR: runtimeDir, TMP: runtimeDir, TEMP: runtimeDir };
|
|
245
|
+
const redactionValues = [params.proxy?.username, params.proxy?.password].filter((value) => typeof value === 'string' && value.length > 0);
|
|
246
|
+
return await Browser.start(scope.options, server.executablePath, childEnv, 'browser.launch', params, scope.deadline, redactionValues, runtimeDir, server.expectedServerVersion, expectedBrowserVersion, runtimeOwner);
|
|
247
|
+
}
|
|
248
|
+
catch (primary) {
|
|
249
|
+
const failure = lifecycleFailure(primary, scope.options.signal, scope.deadline);
|
|
250
|
+
if (runtimeDir !== undefined)
|
|
251
|
+
await removeClosedRuntime(runtimeDir, runtimeOwner.transport, failure);
|
|
252
|
+
throw failure;
|
|
253
|
+
}
|
|
254
|
+
finally {
|
|
255
|
+
scope.dispose();
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
static async connect(options) {
|
|
259
|
+
validateEndpoint(options.browserWSEndpoint);
|
|
260
|
+
for (const name of ['executablePath', 'headless', 'sandbox', 'viewport', 'runtimeDir', 'browserCacheDir', 'download', 'onProgress', 'userDataDir', 'userAgent', 'timezone', 'proxy']) {
|
|
261
|
+
if (Object.hasOwn(options, name))
|
|
262
|
+
throw new ConfigurationError(`connect does not accept the launch option ${name}`);
|
|
263
|
+
}
|
|
264
|
+
const scope = lifecycleScope(options);
|
|
265
|
+
try {
|
|
266
|
+
const env = { ...process.env, ...options.serverEnv };
|
|
267
|
+
const server = await resolveServerBinary({ ...(options.serverPath === undefined ? {} : { serverPath: options.serverPath }), env, signal: scope.options.signal });
|
|
268
|
+
return await Browser.start(scope.options, server.executablePath, env, 'browser.connect', { wsEndpoint: options.browserWSEndpoint }, scope.deadline, [options.browserWSEndpoint], undefined, server.expectedServerVersion);
|
|
269
|
+
}
|
|
270
|
+
catch (primary) {
|
|
271
|
+
throw lifecycleFailure(primary, scope.options.signal, scope.deadline);
|
|
272
|
+
}
|
|
273
|
+
finally {
|
|
274
|
+
scope.dispose();
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
static async start(options, serverPath, env, method, params, deadline, redactionValues, runtimeDir, expectedServerVersion, expectedBrowserVersion, runtimeOwner) {
|
|
278
|
+
checkAbort(options.signal);
|
|
279
|
+
const transport = await SidecarTransport.start({
|
|
280
|
+
serverPath,
|
|
281
|
+
env,
|
|
282
|
+
redactionValues,
|
|
283
|
+
...localOptions(options, deadline),
|
|
284
|
+
...(options.shutdownTimeoutMs === undefined ? {} : { shutdownTimeoutMs: options.shutdownTimeoutMs }),
|
|
285
|
+
...(runtimeOwner === undefined ? {} : { onTransport: (transport) => { runtimeOwner.transport = transport; } }),
|
|
286
|
+
});
|
|
287
|
+
try {
|
|
288
|
+
if (expectedServerVersion !== undefined && transport.hello.serverVersion !== expectedServerVersion) {
|
|
289
|
+
throw new ProtocolError(`Packaged server version mismatch: expected ${expectedServerVersion}, received ${transport.hello.serverVersion}`, { requestState: 'acknowledged' });
|
|
290
|
+
}
|
|
291
|
+
const session = await transport.invoke(method, params, localOptions(options, deadline));
|
|
292
|
+
if (!session || !['owned', 'borrowed'].includes(session.ownership) || typeof session.browserVersion !== 'string' || !session.browserVersion.trim() || (method === 'browser.connect' && session.ownership !== 'borrowed')) {
|
|
293
|
+
throw new ProtocolError('Invalid browser session ownership or browserVersion', { requestState: 'acknowledged' });
|
|
294
|
+
}
|
|
295
|
+
if (expectedBrowserVersion !== undefined && session.browserVersion !== expectedBrowserVersion && session.browserVersion !== `Chrome/${expectedBrowserVersion}` && session.browserVersion !== `HeadlessChrome/${expectedBrowserVersion}`) {
|
|
296
|
+
throw new ProtocolError(`Managed browser version mismatch: expected ${expectedBrowserVersion}, received ${session.browserVersion}`, { requestState: 'acknowledged' });
|
|
297
|
+
}
|
|
298
|
+
checkAbort(options.signal, 'acknowledged');
|
|
299
|
+
return new Browser(transport, session, options.shutdownTimeoutMs ?? 45_000, runtimeDir);
|
|
300
|
+
}
|
|
301
|
+
catch (primary) {
|
|
302
|
+
try {
|
|
303
|
+
await transport.close();
|
|
304
|
+
}
|
|
305
|
+
catch (cleanup) {
|
|
306
|
+
throw new AggregateError([primary, cleanup], 'Browser lifecycle failed and sidecar cleanup failed; browser cleanup may be uncertain', { cause: primary });
|
|
307
|
+
}
|
|
308
|
+
throw primary;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
get hello() { return this.#transport.hello; }
|
|
312
|
+
get sessionInfo() { return this.#sessionInfo; }
|
|
313
|
+
get ownership() { return this.#sessionInfo.ownership; }
|
|
314
|
+
get browserVersion() { return this.#sessionInfo.browserVersion; }
|
|
315
|
+
supports(method) { return this.#transport.supports(method); }
|
|
316
|
+
hasCapability(name) { return this.#capabilities.has(name); }
|
|
317
|
+
invoke(method, params, options) {
|
|
318
|
+
return this.#transport.invoke(method, params, options);
|
|
319
|
+
}
|
|
320
|
+
page(id) { return new Page(this, id); }
|
|
321
|
+
operation(id) { return new Operation(this, id); }
|
|
322
|
+
recording(id) { return new Recording(this, id); }
|
|
323
|
+
async tabs(options) {
|
|
324
|
+
return (await this.invoke('browser.tabs', {}, options)).tabs;
|
|
325
|
+
}
|
|
326
|
+
async pages(options) {
|
|
327
|
+
return (await this.tabs(options)).map(tab => this.page(tab.id));
|
|
328
|
+
}
|
|
329
|
+
operations(params = {}, options) {
|
|
330
|
+
return this.invoke('operations.list', params, options);
|
|
331
|
+
}
|
|
332
|
+
newPage(url, options = {}) {
|
|
333
|
+
const result = this.createPage(url, options);
|
|
334
|
+
const owner = result.then(() => { this.#pageOwners.delete(owner); }, () => { this.#pageOwners.delete(owner); });
|
|
335
|
+
this.#pageOwners.add(owner);
|
|
336
|
+
return result;
|
|
337
|
+
}
|
|
338
|
+
async createPage(url, options) {
|
|
339
|
+
if (url !== undefined && (typeof url !== 'string' || !url.trim()))
|
|
340
|
+
throw new ConfigurationError('newPage URL must be a nonempty string');
|
|
341
|
+
validateTimeout(options.timeoutMs, 'timeoutMs');
|
|
342
|
+
const deadline = options.timeoutMs === undefined ? undefined : performance.now() + options.timeoutMs;
|
|
343
|
+
const tracked = this.#transport.invokeTracked('browser.new_page', {}, localOptions(options, deadline));
|
|
344
|
+
let result;
|
|
345
|
+
try {
|
|
346
|
+
result = await tracked.result;
|
|
347
|
+
}
|
|
348
|
+
catch (primary) {
|
|
349
|
+
if (primary instanceof Error && 'requestState' in primary && primary.requestState === 'not_sent')
|
|
350
|
+
throw primary;
|
|
351
|
+
const cleanup = this.cleanupAbandonedCreation(tracked.completion);
|
|
352
|
+
try {
|
|
353
|
+
await cleanup;
|
|
354
|
+
}
|
|
355
|
+
catch (failure) {
|
|
356
|
+
this.#creationCleanupFailures.push(failure);
|
|
357
|
+
throw new AggregateError([primary, failure], 'New page creation failed and late-created-tab cleanup failed', { cause: primary });
|
|
358
|
+
}
|
|
359
|
+
throw primary;
|
|
360
|
+
}
|
|
361
|
+
const page = this.page(result.pageId);
|
|
362
|
+
try {
|
|
363
|
+
if (url !== undefined)
|
|
364
|
+
await page.goto(url, { ...options, ...localOptions(options, deadline) });
|
|
365
|
+
checkAbort(options.signal, 'acknowledged');
|
|
366
|
+
return page;
|
|
367
|
+
}
|
|
368
|
+
catch (primary) {
|
|
369
|
+
try {
|
|
370
|
+
const cleanup = await this.#transport.invokeCleanup('browser.close_tab', { pageId: page.id }, { timeoutMs: this.#shutdownTimeoutMs });
|
|
371
|
+
if (cleanup.cleanupError)
|
|
372
|
+
throw new TransportError('CleanupFailed', 'Created tab was closed but input cleanup failed', { data: cleanup });
|
|
373
|
+
}
|
|
374
|
+
catch (cleanup) {
|
|
375
|
+
throw new AggregateError([primary, cleanup], 'New page failed and created-tab cleanup failed', { cause: primary });
|
|
376
|
+
}
|
|
377
|
+
throw primary;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
async cleanupAbandonedCreation(completion) {
|
|
381
|
+
const deadline = performance.now() + this.#shutdownTimeoutMs;
|
|
382
|
+
let timer;
|
|
383
|
+
let timedOut = false;
|
|
384
|
+
try {
|
|
385
|
+
const result = await Promise.race([
|
|
386
|
+
completion,
|
|
387
|
+
new Promise((_, reject) => {
|
|
388
|
+
timer = setTimeout(() => {
|
|
389
|
+
timedOut = true;
|
|
390
|
+
reject(new TransportError('CleanupUncertain', 'Abandoned page creation did not return its page ID within the cleanup deadline; a borrowed browser may retain the unknown tab'));
|
|
391
|
+
}, this.#shutdownTimeoutMs);
|
|
392
|
+
}),
|
|
393
|
+
]);
|
|
394
|
+
const cleanup = await this.#transport.invokeCleanup('browser.close_tab', { pageId: result.pageId }, { timeoutMs: remainingTimeout(deadline) ?? this.#shutdownTimeoutMs });
|
|
395
|
+
if (cleanup.cleanupError)
|
|
396
|
+
throw new TransportError('CleanupFailed', 'Late-created tab was closed but input cleanup failed', { data: cleanup });
|
|
397
|
+
}
|
|
398
|
+
catch (cause) {
|
|
399
|
+
const uncertainty = new TransportError('CleanupUncertain', 'Could not establish cleanup of an abandoned page creation', { cause });
|
|
400
|
+
if (timedOut) {
|
|
401
|
+
try {
|
|
402
|
+
await this.#transport.close();
|
|
403
|
+
}
|
|
404
|
+
catch (cleanup) {
|
|
405
|
+
throw new AggregateError([uncertainty, cleanup], 'Abandoned page creation and sidecar cleanup remain uncertain', { cause: uncertainty });
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
throw uncertainty;
|
|
409
|
+
}
|
|
410
|
+
finally {
|
|
411
|
+
clearTimeout(timer);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
close() {
|
|
415
|
+
this.#closePromise ??= (async () => {
|
|
416
|
+
this.#transport.quiesce();
|
|
417
|
+
await Promise.all(this.#pageOwners);
|
|
418
|
+
let transportFailure;
|
|
419
|
+
try {
|
|
420
|
+
await this.#transport.close();
|
|
421
|
+
}
|
|
422
|
+
catch (failure) {
|
|
423
|
+
transportFailure = failure;
|
|
424
|
+
}
|
|
425
|
+
let runtimeFailure;
|
|
426
|
+
try {
|
|
427
|
+
await this.#runtimeCleanup;
|
|
428
|
+
}
|
|
429
|
+
catch (failure) {
|
|
430
|
+
runtimeFailure = failure;
|
|
431
|
+
}
|
|
432
|
+
const failures = [...this.#creationCleanupFailures];
|
|
433
|
+
if (transportFailure !== undefined)
|
|
434
|
+
failures.unshift(transportFailure);
|
|
435
|
+
if (runtimeFailure !== undefined)
|
|
436
|
+
failures.push(runtimeFailure);
|
|
437
|
+
if (failures.length === 1 && this.#creationCleanupFailures.length === 0 && runtimeFailure === undefined)
|
|
438
|
+
throw transportFailure;
|
|
439
|
+
if (failures.length)
|
|
440
|
+
throw new AggregateError(failures, 'Browser disposal includes resource cleanup failures', { cause: failures[0] });
|
|
441
|
+
})();
|
|
442
|
+
return this.#closePromise;
|
|
443
|
+
}
|
|
444
|
+
[Symbol.asyncDispose]() { return this.close(); }
|
|
445
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { MethodName, MethodParams, MethodResults } from './generated/protocol.js';
|
|
2
|
+
export interface CallOptions {
|
|
3
|
+
signal?: AbortSignal;
|
|
4
|
+
timeoutMs?: number;
|
|
5
|
+
operationId?: string;
|
|
6
|
+
}
|
|
7
|
+
export interface InvokeClient {
|
|
8
|
+
invoke<M extends MethodName>(method: M, params: MethodParams[M], options?: CallOptions): Promise<MethodResults[M]>;
|
|
9
|
+
supports?(method: string): boolean;
|
|
10
|
+
hasCapability?(name: string): boolean;
|
|
11
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { ActionReceipt, ServerError } from './generated/protocol.js';
|
|
2
|
+
export type RequestState = 'not_sent' | 'may_have_been_sent' | 'acknowledged';
|
|
3
|
+
export interface ErrorDetails {
|
|
4
|
+
requestId?: number | undefined;
|
|
5
|
+
operationId?: string | undefined;
|
|
6
|
+
requestState?: RequestState | undefined;
|
|
7
|
+
receipt?: ActionReceipt | undefined;
|
|
8
|
+
data?: unknown;
|
|
9
|
+
stderr?: string | undefined;
|
|
10
|
+
cause?: unknown;
|
|
11
|
+
}
|
|
12
|
+
export declare class EokaError extends Error {
|
|
13
|
+
readonly code: string;
|
|
14
|
+
requestId?: number | undefined;
|
|
15
|
+
operationId?: string | undefined;
|
|
16
|
+
requestState?: RequestState | undefined;
|
|
17
|
+
receipt?: ActionReceipt | undefined;
|
|
18
|
+
data?: unknown;
|
|
19
|
+
stderr?: string | undefined;
|
|
20
|
+
constructor(code: string, message: string, details?: ErrorDetails);
|
|
21
|
+
}
|
|
22
|
+
export declare class ConfigurationError extends EokaError {
|
|
23
|
+
constructor(message: string, details?: ErrorDetails);
|
|
24
|
+
}
|
|
25
|
+
export declare class TransportError extends EokaError {
|
|
26
|
+
}
|
|
27
|
+
export declare class ProtocolError extends EokaError {
|
|
28
|
+
constructor(message: string, details?: ErrorDetails);
|
|
29
|
+
}
|
|
30
|
+
export declare class ServerOperationError extends EokaError {
|
|
31
|
+
readonly wireError: ServerError;
|
|
32
|
+
constructor(wireError: ServerError, details?: ErrorDetails);
|
|
33
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export class EokaError extends Error {
|
|
2
|
+
code;
|
|
3
|
+
requestId;
|
|
4
|
+
operationId;
|
|
5
|
+
requestState;
|
|
6
|
+
receipt;
|
|
7
|
+
data;
|
|
8
|
+
stderr;
|
|
9
|
+
constructor(code, message, details = {}) {
|
|
10
|
+
super(message, { cause: details.cause });
|
|
11
|
+
this.name = new.target.name;
|
|
12
|
+
this.code = code;
|
|
13
|
+
this.requestId = details.requestId;
|
|
14
|
+
this.operationId = details.operationId;
|
|
15
|
+
this.requestState = details.requestState;
|
|
16
|
+
this.receipt = details.receipt;
|
|
17
|
+
this.data = details.data;
|
|
18
|
+
this.stderr = details.stderr;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export class ConfigurationError extends EokaError {
|
|
22
|
+
constructor(message, details = {}) {
|
|
23
|
+
super('Configuration', message, details);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
export class TransportError extends EokaError {
|
|
27
|
+
}
|
|
28
|
+
export class ProtocolError extends EokaError {
|
|
29
|
+
constructor(message, details = {}) {
|
|
30
|
+
super('Protocol', message, details);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export class ServerOperationError extends EokaError {
|
|
34
|
+
wireError;
|
|
35
|
+
constructor(wireError, details = {}) {
|
|
36
|
+
super(wireError.code, wireError.message, {
|
|
37
|
+
...details,
|
|
38
|
+
data: wireError.data,
|
|
39
|
+
operationId: wireError.data?.operation_id ?? details.operationId,
|
|
40
|
+
receipt: wireError.data?.receipt ?? details.receipt,
|
|
41
|
+
});
|
|
42
|
+
this.wireError = wireError;
|
|
43
|
+
}
|
|
44
|
+
}
|