@rezkam/browser-tools 1.0.4 → 1.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/CHANGELOG.md +13 -0
- package/README.md +39 -1
- package/bin/browser-tools.mjs +2 -0
- package/package.json +4 -2
- package/scripts/browser-control.mjs +134 -20
- package/scripts/browser-platform.mjs +96 -0
- package/scripts/cdp-event-capture.mjs +45 -26
- package/scripts/gif-recorder.mjs +51 -46
- package/scripts/har-capture.mjs +75 -35
- package/scripts/pick.mjs +12 -8
- package/scripts/record-cdp.mjs +7 -27
- package/scripts/record-har.mjs +7 -27
- package/scripts/recording-lifecycle.mjs +33 -0
- package/scripts/resource-helper.mjs +8 -10
- package/scripts/serve.mjs +42 -0
- package/scripts/tab-broker.mjs +284 -0
- package/scripts/tab-pool.mjs +195 -0
package/scripts/gif-recorder.mjs
CHANGED
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
sleep,
|
|
23
23
|
} from './browser-control.mjs';
|
|
24
24
|
import { openPrivateFile } from './cdp-common.mjs';
|
|
25
|
+
import { createRecordingLifecycle } from './recording-lifecycle.mjs';
|
|
25
26
|
|
|
26
27
|
export const DEFAULT_GIF_FPS = 10;
|
|
27
28
|
export const DEFAULT_GIF_COLORS = 128;
|
|
@@ -220,22 +221,31 @@ export function createFfmpegGifEncoder({
|
|
|
220
221
|
output,
|
|
221
222
|
], { stdio: ['pipe', 'ignore', 'pipe'] });
|
|
222
223
|
|
|
223
|
-
let
|
|
224
|
+
let state = { phase: 'encoding' };
|
|
224
225
|
let stderr = '';
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
226
|
+
const fail = (error) => { if (state.phase !== 'failed') state = { phase: 'failed', error }; };
|
|
227
|
+
child.once('error', fail);
|
|
228
|
+
child.stdin.on('error', fail);
|
|
228
229
|
child.stderr.on('data', (chunk) => {
|
|
229
230
|
stderr += chunk.toString('utf-8');
|
|
230
231
|
});
|
|
231
232
|
const closed = new Promise((resolve) => {
|
|
232
|
-
child.once('close', (code, signal) =>
|
|
233
|
+
child.once('close', (code, signal) => {
|
|
234
|
+
if (state.phase !== 'failed') {
|
|
235
|
+
if (code === 0) state = { phase: 'closed' };
|
|
236
|
+
else {
|
|
237
|
+
const termination = signal ? `signal ${signal}` : `exit status ${code}`;
|
|
238
|
+
fail(new Error(`ffmpeg failed to encode GIF (${termination})${stderr.trim() ? `: ${stderr.trim()}` : ''}`));
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
resolve();
|
|
242
|
+
});
|
|
233
243
|
});
|
|
234
244
|
|
|
235
245
|
return {
|
|
236
246
|
async writeFrame(frame) {
|
|
237
|
-
if (
|
|
238
|
-
if (
|
|
247
|
+
if (state.phase === 'failed') throw state.error;
|
|
248
|
+
if (state.phase !== 'encoding') {
|
|
239
249
|
throw new Error(`ffmpeg exited before GIF recording finished${stderr.trim() ? `: ${stderr.trim()}` : ''}`);
|
|
240
250
|
}
|
|
241
251
|
await new Promise((resolveWrite, rejectWrite) => {
|
|
@@ -243,13 +253,10 @@ export function createFfmpegGifEncoder({
|
|
|
243
253
|
});
|
|
244
254
|
},
|
|
245
255
|
async stop() {
|
|
246
|
-
if (
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
if (
|
|
250
|
-
const termination = result.signal ? `signal ${result.signal}` : `exit status ${result.code}`;
|
|
251
|
-
throw new Error(`ffmpeg failed to encode GIF (${termination})${stderr.trim() ? `: ${stderr.trim()}` : ''}`);
|
|
252
|
-
}
|
|
256
|
+
if (state.phase === 'encoding') state = { phase: 'finishing' };
|
|
257
|
+
if (!child.stdin.destroyed && !child.stdin.writableEnded) child.stdin.end();
|
|
258
|
+
await closed;
|
|
259
|
+
if (state.phase === 'failed') throw state.error;
|
|
253
260
|
chmodSync(output, 0o600);
|
|
254
261
|
},
|
|
255
262
|
};
|
|
@@ -306,6 +313,24 @@ export async function recordGifSession({
|
|
|
306
313
|
colors,
|
|
307
314
|
scale,
|
|
308
315
|
});
|
|
316
|
+
const lifecycle = createRecordingLifecycle('gif');
|
|
317
|
+
// Finalization belongs to this session, including when finalization itself fails.
|
|
318
|
+
let encoderState = { phase: 'open' };
|
|
319
|
+
const finalize = () => {
|
|
320
|
+
if (encoderState.phase === 'open') {
|
|
321
|
+
const result = Promise.resolve().then(() => encoder.stop());
|
|
322
|
+
encoderState = { phase: 'closing', result };
|
|
323
|
+
result.then(
|
|
324
|
+
() => { encoderState = { phase: 'closed', result }; },
|
|
325
|
+
(error) => { encoderState = { phase: 'failed', result, error }; },
|
|
326
|
+
);
|
|
327
|
+
}
|
|
328
|
+
return encoderState.result;
|
|
329
|
+
};
|
|
330
|
+
const phase = async (next, reason) => {
|
|
331
|
+
lifecycle.transition(next, reason ? { reason } : {});
|
|
332
|
+
await onPhase(next, reason);
|
|
333
|
+
};
|
|
309
334
|
const frameIntervalMs = 1000 / fps;
|
|
310
335
|
let nextFrameAt = now();
|
|
311
336
|
let frameCount = 0;
|
|
@@ -334,9 +359,9 @@ export async function recordGifSession({
|
|
|
334
359
|
};
|
|
335
360
|
|
|
336
361
|
try {
|
|
337
|
-
await
|
|
362
|
+
await phase('pre-roll');
|
|
338
363
|
await capturePeriod(preRollMs);
|
|
339
|
-
await
|
|
364
|
+
await phase('recording');
|
|
340
365
|
|
|
341
366
|
const deadline = now() + maxDurationSeconds * 1000;
|
|
342
367
|
while (!shouldStop() && now() < deadline) {
|
|
@@ -345,12 +370,14 @@ export async function recordGifSession({
|
|
|
345
370
|
|
|
346
371
|
const stopRequested = shouldStop();
|
|
347
372
|
const reason = stopRequested ? 'requested' : 'max-duration';
|
|
348
|
-
await
|
|
373
|
+
await phase('post-roll', reason);
|
|
349
374
|
await capturePeriod(postRollMs);
|
|
350
|
-
await
|
|
375
|
+
await finalize();
|
|
376
|
+
lifecycle.transition('completed');
|
|
351
377
|
return { reason, frameCount };
|
|
352
378
|
} catch (error) {
|
|
353
|
-
|
|
379
|
+
lifecycle.transition('failed', { error });
|
|
380
|
+
await finalize().catch(() => {});
|
|
354
381
|
throw error;
|
|
355
382
|
}
|
|
356
383
|
}
|
|
@@ -369,25 +396,18 @@ export async function runGifRecordingWorker({
|
|
|
369
396
|
const normalizedPort = normalizePort(port);
|
|
370
397
|
const stateFile = gifRecordingStateFile(normalizedPort);
|
|
371
398
|
const startedAt = new Date().toISOString();
|
|
372
|
-
const
|
|
399
|
+
const metadata = {
|
|
373
400
|
managedBy: 'browser-tools-gif-recorder',
|
|
374
401
|
pid: process.pid,
|
|
375
402
|
port: normalizedPort,
|
|
376
403
|
output,
|
|
377
404
|
ownerTokenHash: ownerTokenHash(ownerToken),
|
|
378
|
-
status: 'starting',
|
|
379
|
-
phase: 'starting',
|
|
380
405
|
startedAt,
|
|
381
406
|
options: { fps, colors, scale, preRollMs, postRollMs, maxDurationSeconds },
|
|
382
407
|
};
|
|
383
|
-
writePrivateJson(stateFile,
|
|
408
|
+
const lifecycle = createRecordingLifecycle('gif', metadata, (state) => writePrivateJson(stateFile, state));
|
|
384
409
|
|
|
385
410
|
let browser;
|
|
386
|
-
let currentState = baseState;
|
|
387
|
-
const updateState = (changes) => {
|
|
388
|
-
currentState = { ...currentState, ...changes };
|
|
389
|
-
writePrivateJson(stateFile, currentState);
|
|
390
|
-
};
|
|
391
411
|
|
|
392
412
|
try {
|
|
393
413
|
browser = await connectBrowser(normalizedPort, { ownerToken });
|
|
@@ -402,26 +422,11 @@ export async function runGifRecordingWorker({
|
|
|
402
422
|
postRollMs,
|
|
403
423
|
maxDurationSeconds,
|
|
404
424
|
shouldStop: () => existsSync(gifRecordingStopFile(normalizedPort)),
|
|
405
|
-
onPhase: (phase, reason
|
|
406
|
-
status: phase === 'recording' ? 'recording' : currentState.status,
|
|
407
|
-
phase,
|
|
408
|
-
readyAt: phase === 'recording' ? new Date().toISOString() : currentState.readyAt,
|
|
409
|
-
reason: reason ?? currentState.reason,
|
|
410
|
-
}),
|
|
411
|
-
});
|
|
412
|
-
updateState({
|
|
413
|
-
status: 'completed',
|
|
414
|
-
phase: 'completed',
|
|
415
|
-
reason: result.reason,
|
|
416
|
-
completedAt: new Date().toISOString(),
|
|
425
|
+
onPhase: (phase, reason) => lifecycle.transition(phase, reason ? { reason } : {}),
|
|
417
426
|
});
|
|
427
|
+
lifecycle.transition('completed', { reason: result.reason });
|
|
418
428
|
} catch (error) {
|
|
419
|
-
|
|
420
|
-
status: 'failed',
|
|
421
|
-
phase: 'failed',
|
|
422
|
-
error: error.message,
|
|
423
|
-
completedAt: new Date().toISOString(),
|
|
424
|
-
});
|
|
429
|
+
lifecycle.transition('failed', { error: error.message });
|
|
425
430
|
throw error;
|
|
426
431
|
} finally {
|
|
427
432
|
browser?.disconnect();
|
package/scripts/har-capture.mjs
CHANGED
|
@@ -21,6 +21,7 @@ import {
|
|
|
21
21
|
writePrivateJson,
|
|
22
22
|
} from './cdp-common.mjs';
|
|
23
23
|
import { parseBoundedNumber } from './gif-recorder.mjs';
|
|
24
|
+
import { createRecordingLifecycle } from './recording-lifecycle.mjs';
|
|
24
25
|
|
|
25
26
|
const { version: BROWSER_TOOLS_VERSION } = createRequire(import.meta.url)('../package.json');
|
|
26
27
|
|
|
@@ -161,6 +162,10 @@ export function parseHarCaptureOptions(args) {
|
|
|
161
162
|
};
|
|
162
163
|
}
|
|
163
164
|
|
|
165
|
+
function requestInFlight(entry) {
|
|
166
|
+
return entry && ['requesting', 'responding'].includes(entry.state);
|
|
167
|
+
}
|
|
168
|
+
|
|
164
169
|
export class HarCollector {
|
|
165
170
|
constructor(options, { pageId = 'page_0', pageUrl = '', pageTitle = '' } = {}) {
|
|
166
171
|
this.options = options;
|
|
@@ -175,7 +180,6 @@ export class HarCollector {
|
|
|
175
180
|
this.responseExtraIndexes = new Map();
|
|
176
181
|
this.pendingRequestExtra = new Map();
|
|
177
182
|
this.pendingResponseExtra = new Map();
|
|
178
|
-
this.activeRequestIds = new Set();
|
|
179
183
|
this.lastActivityAt = Date.now();
|
|
180
184
|
}
|
|
181
185
|
|
|
@@ -204,7 +208,8 @@ export class HarCollector {
|
|
|
204
208
|
this.requestIndexes.set(event.requestId, entryIndex + 1);
|
|
205
209
|
if (event.redirectResponse) {
|
|
206
210
|
const redirected = this.currentByRequestId.get(event.requestId);
|
|
207
|
-
if (redirected) {
|
|
211
|
+
if (requestInFlight(redirected)) {
|
|
212
|
+
redirected.state = 'redirected';
|
|
208
213
|
redirected.response = event.redirectResponse;
|
|
209
214
|
redirected.responseTimestamp = event.timestamp;
|
|
210
215
|
redirected.finishedTimestamp = event.timestamp;
|
|
@@ -214,12 +219,12 @@ export class HarCollector {
|
|
|
214
219
|
|
|
215
220
|
if (!this.requestMatches(event)) {
|
|
216
221
|
this.currentByRequestId.delete(event.requestId);
|
|
217
|
-
this.activeRequestIds.delete(event.requestId);
|
|
218
222
|
return;
|
|
219
223
|
}
|
|
220
224
|
|
|
221
225
|
const requestEntries = this.entriesByRequestId.get(event.requestId) || [];
|
|
222
226
|
const entry = {
|
|
227
|
+
state: 'requesting',
|
|
223
228
|
requestId: event.requestId,
|
|
224
229
|
request: event.request,
|
|
225
230
|
resourceType: event.type || 'Other',
|
|
@@ -240,7 +245,6 @@ export class HarCollector {
|
|
|
240
245
|
this.entriesByRequestId.set(event.requestId, requestEntries);
|
|
241
246
|
this.entries.push(entry);
|
|
242
247
|
this.currentByRequestId.set(event.requestId, entry);
|
|
243
|
-
this.activeRequestIds.add(event.requestId);
|
|
244
248
|
}
|
|
245
249
|
|
|
246
250
|
requestWillBeSentExtraInfo(event) {
|
|
@@ -270,7 +274,8 @@ export class HarCollector {
|
|
|
270
274
|
responseReceived(event) {
|
|
271
275
|
this.lastActivityAt = Date.now();
|
|
272
276
|
const entry = this.currentByRequestId.get(event.requestId);
|
|
273
|
-
if (!entry) return;
|
|
277
|
+
if (!requestInFlight(entry)) return;
|
|
278
|
+
entry.state = 'responding';
|
|
274
279
|
entry.response = event.response;
|
|
275
280
|
entry.responseTimestamp = event.timestamp;
|
|
276
281
|
if (event.type) entry.resourceType = event.type;
|
|
@@ -284,8 +289,8 @@ export class HarCollector {
|
|
|
284
289
|
async loadingFinished(event, session) {
|
|
285
290
|
this.lastActivityAt = Date.now();
|
|
286
291
|
const entry = this.currentByRequestId.get(event.requestId);
|
|
287
|
-
|
|
288
|
-
|
|
292
|
+
if (!requestInFlight(entry)) return;
|
|
293
|
+
entry.state = 'completed';
|
|
289
294
|
entry.finishedTimestamp = event.timestamp;
|
|
290
295
|
entry.encodedDataLength = Number(event.encodedDataLength || 0);
|
|
291
296
|
if (!this.options.capture.includes('bodies') || !this.responseMatches(entry)) return;
|
|
@@ -299,8 +304,8 @@ export class HarCollector {
|
|
|
299
304
|
loadingFailed(event) {
|
|
300
305
|
this.lastActivityAt = Date.now();
|
|
301
306
|
const entry = this.currentByRequestId.get(event.requestId);
|
|
302
|
-
|
|
303
|
-
|
|
307
|
+
if (!requestInFlight(entry)) return;
|
|
308
|
+
entry.state = 'failed';
|
|
304
309
|
entry.finishedTimestamp = event.timestamp;
|
|
305
310
|
entry.failed = {
|
|
306
311
|
errorText: event.errorText,
|
|
@@ -312,7 +317,8 @@ export class HarCollector {
|
|
|
312
317
|
async waitForDrain({ idleMs = this.options.idleMs, timeoutMs = this.options.drainTimeoutMs } = {}) {
|
|
313
318
|
const deadline = Date.now() + timeoutMs;
|
|
314
319
|
while (Date.now() < deadline) {
|
|
315
|
-
|
|
320
|
+
const active = [...this.currentByRequestId.values()].some(requestInFlight);
|
|
321
|
+
if (!active && Date.now() - this.lastActivityAt >= idleMs) return true;
|
|
316
322
|
await sleep(50);
|
|
317
323
|
}
|
|
318
324
|
return false;
|
|
@@ -450,34 +456,68 @@ export async function runHarCapture({
|
|
|
450
456
|
pageUrl: page.url(),
|
|
451
457
|
pageTitle: await page.title().catch(() => ''),
|
|
452
458
|
});
|
|
459
|
+
const lifecycle = createRecordingLifecycle('har');
|
|
453
460
|
const pending = new Set();
|
|
454
|
-
const
|
|
455
|
-
|
|
456
|
-
|
|
461
|
+
const fail = (error) => {
|
|
462
|
+
if (lifecycle.phase !== 'failed') lifecycle.transition('failed', { error });
|
|
463
|
+
};
|
|
464
|
+
const assertHealthy = () => {
|
|
465
|
+
if (lifecycle.phase === 'failed') throw lifecycle.snapshot().error;
|
|
457
466
|
};
|
|
467
|
+
const handlers = new Map();
|
|
468
|
+
const subscribe = (method, handle) => {
|
|
469
|
+
const listener = (event) => {
|
|
470
|
+
if (['completed', 'failed'].includes(lifecycle.phase)) return;
|
|
471
|
+
try {
|
|
472
|
+
const task = Promise.resolve(handle(event));
|
|
473
|
+
pending.add(task);
|
|
474
|
+
task.then(() => pending.delete(task), (error) => { pending.delete(task); fail(error); });
|
|
475
|
+
} catch (error) {
|
|
476
|
+
fail(error);
|
|
477
|
+
}
|
|
478
|
+
};
|
|
479
|
+
handlers.set(method, listener);
|
|
480
|
+
session.on(method, listener);
|
|
481
|
+
};
|
|
482
|
+
subscribe('Network.requestWillBeSent', (event) => collector.requestWillBeSent(event));
|
|
483
|
+
subscribe('Network.requestWillBeSentExtraInfo', (event) => collector.requestWillBeSentExtraInfo(event));
|
|
484
|
+
subscribe('Network.responseReceived', (event) => collector.responseReceived(event));
|
|
485
|
+
subscribe('Network.responseReceivedExtraInfo', (event) => collector.responseReceivedExtraInfo(event));
|
|
486
|
+
subscribe('Network.requestServedFromCache', (event) => collector.requestServedFromCache(event));
|
|
487
|
+
subscribe('Network.loadingFinished', (event) => collector.loadingFinished(event, session));
|
|
488
|
+
subscribe('Network.loadingFailed', (event) => collector.loadingFailed(event));
|
|
458
489
|
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
490
|
+
try {
|
|
491
|
+
await session.send('Network.enable', {
|
|
492
|
+
maxTotalBufferSize: Math.max(options.maxBodyBytes * 4, 4 * 1024 * 1024),
|
|
493
|
+
maxResourceBufferSize: options.maxBodyBytes,
|
|
494
|
+
maxPostDataSize: options.maxBodyBytes,
|
|
495
|
+
});
|
|
496
|
+
assertHealthy();
|
|
497
|
+
lifecycle.transition('recording');
|
|
498
|
+
await onPhase('recording');
|
|
499
|
+
|
|
500
|
+
const deadline = Date.now() + options.maxDurationSeconds * 1000;
|
|
501
|
+
while (lifecycle.phase === 'recording' && !shouldStop() && Date.now() < deadline) await sleep(100);
|
|
502
|
+
assertHealthy();
|
|
503
|
+
const reason = shouldStop() ? 'requested' : 'max-duration';
|
|
504
|
+
lifecycle.transition('draining', { reason });
|
|
505
|
+
await onPhase('draining', reason);
|
|
506
|
+
await collector.waitForDrain();
|
|
507
|
+
// Freeze the event stream before awaiting body reads, so the final set cannot grow.
|
|
508
|
+
for (const [method, handler] of handlers) session.off(method, handler);
|
|
509
|
+
await Promise.allSettled([...pending]);
|
|
510
|
+
assertHealthy();
|
|
511
|
+
const har = collector.build();
|
|
512
|
+
lifecycle.transition('completed');
|
|
513
|
+
return { reason, har, eventCount: collector.entries.length };
|
|
514
|
+
} catch (error) {
|
|
515
|
+
fail(error);
|
|
516
|
+
throw error;
|
|
517
|
+
} finally {
|
|
518
|
+
for (const [method, handler] of handlers) session.off(method, handler);
|
|
519
|
+
// On failure, let the session owner detach before waiting for stalled body reads.
|
|
520
|
+
}
|
|
481
521
|
}
|
|
482
522
|
|
|
483
523
|
export function writeHar(file, har) {
|
package/scripts/pick.mjs
CHANGED
|
@@ -97,7 +97,8 @@ export function installPicker() {
|
|
|
97
97
|
new Promise((resolve, reject) => {
|
|
98
98
|
const selections = [];
|
|
99
99
|
const selectedEls = new Set();
|
|
100
|
-
let
|
|
100
|
+
let state = 'selecting';
|
|
101
|
+
const active = () => state === 'selecting' || state === 'multi-selecting';
|
|
101
102
|
|
|
102
103
|
const overlay = document.createElement('div');
|
|
103
104
|
overlay.style.cssText =
|
|
@@ -130,20 +131,21 @@ export function installPicker() {
|
|
|
130
131
|
};
|
|
131
132
|
|
|
132
133
|
const finish = (result) => {
|
|
133
|
-
if (
|
|
134
|
-
|
|
134
|
+
if (!active()) return;
|
|
135
|
+
state = result === null ? 'cancelled' : 'completed';
|
|
135
136
|
cleanup();
|
|
136
137
|
resolve(result);
|
|
137
138
|
};
|
|
138
139
|
|
|
139
140
|
const fail = (error) => {
|
|
140
|
-
if (
|
|
141
|
-
|
|
141
|
+
if (!active()) return;
|
|
142
|
+
state = 'failed';
|
|
142
143
|
cleanup();
|
|
143
144
|
reject(new Error(`Picker failed to extract element info: ${errorMessage(error)}`));
|
|
144
145
|
};
|
|
145
146
|
|
|
146
147
|
const onMove = (e) => {
|
|
148
|
+
if (!active()) return;
|
|
147
149
|
const el = document.elementFromPoint(e.clientX, e.clientY);
|
|
148
150
|
if (!el || overlay.contains(el) || banner.contains(el)) return;
|
|
149
151
|
const r = el.getBoundingClientRect();
|
|
@@ -156,7 +158,7 @@ export function installPicker() {
|
|
|
156
158
|
};
|
|
157
159
|
|
|
158
160
|
const onClick = (e) => {
|
|
159
|
-
if (banner.contains(e.target)) return;
|
|
161
|
+
if (!active() || banner.contains(e.target)) return;
|
|
160
162
|
e.preventDefault();
|
|
161
163
|
e.stopPropagation();
|
|
162
164
|
const el = document.elementFromPoint(e.clientX, e.clientY);
|
|
@@ -168,10 +170,11 @@ export function installPicker() {
|
|
|
168
170
|
selectedEls.add(el);
|
|
169
171
|
el.style.outline = '3px solid #10b981';
|
|
170
172
|
selections.push(info(el));
|
|
173
|
+
state = 'multi-selecting';
|
|
171
174
|
refresh();
|
|
172
175
|
}
|
|
173
176
|
} else {
|
|
174
|
-
finish(
|
|
177
|
+
finish(state === 'multi-selecting' ? selections : info(el));
|
|
175
178
|
}
|
|
176
179
|
} catch (error) {
|
|
177
180
|
fail(error);
|
|
@@ -179,11 +182,12 @@ export function installPicker() {
|
|
|
179
182
|
};
|
|
180
183
|
|
|
181
184
|
const onKey = (e) => {
|
|
185
|
+
if (!active()) return;
|
|
182
186
|
if (e.key === 'Escape') {
|
|
183
187
|
e.preventDefault();
|
|
184
188
|
finish(null);
|
|
185
189
|
}
|
|
186
|
-
if (e.key === 'Enter' &&
|
|
190
|
+
if (e.key === 'Enter' && state === 'multi-selecting') {
|
|
187
191
|
e.preventDefault();
|
|
188
192
|
finish(selections);
|
|
189
193
|
}
|
package/scripts/record-cdp.mjs
CHANGED
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
requiredOptionValue,
|
|
21
21
|
} from './browser-control.mjs';
|
|
22
22
|
import { openPrivateFile, privateOutputPath, withPageCdpSession } from './cdp-common.mjs';
|
|
23
|
+
import { createRecordingLifecycle } from './recording-lifecycle.mjs';
|
|
23
24
|
import {
|
|
24
25
|
CDP_CAPTURE_STOP_TIMEOUT_MS,
|
|
25
26
|
assertCdpRecordingOwner,
|
|
@@ -173,23 +174,18 @@ async function runWorker(args) {
|
|
|
173
174
|
const output = requiredOptionValue(args, '--output', null);
|
|
174
175
|
const options = decodeOptions(requiredOptionValue(args, '--worker-options', null));
|
|
175
176
|
const startedAt = new Date().toISOString();
|
|
176
|
-
|
|
177
|
+
const metadata = {
|
|
177
178
|
managedBy: 'browser-tools-cdp-recorder',
|
|
178
179
|
kind: CAPTURE_KIND,
|
|
179
180
|
pid: process.pid,
|
|
180
181
|
port,
|
|
181
182
|
output,
|
|
182
183
|
ownerTokenHash: ownerTokenHash(ownerToken),
|
|
183
|
-
status: 'starting',
|
|
184
|
-
phase: 'starting',
|
|
185
184
|
startedAt,
|
|
186
185
|
options,
|
|
187
186
|
};
|
|
188
|
-
const
|
|
189
|
-
state
|
|
190
|
-
updateCdpRecordingState(CAPTURE_KIND, port, state);
|
|
191
|
-
};
|
|
192
|
-
update({});
|
|
187
|
+
const lifecycle = createRecordingLifecycle(CAPTURE_KIND, metadata,
|
|
188
|
+
(state) => updateCdpRecordingState(CAPTURE_KIND, port, state));
|
|
193
189
|
|
|
194
190
|
let outputFd = null;
|
|
195
191
|
try {
|
|
@@ -200,31 +196,15 @@ async function runWorker(args) {
|
|
|
200
196
|
options,
|
|
201
197
|
shouldStop: () => existsSync(cdpRecordingStopFile(CAPTURE_KIND, port)),
|
|
202
198
|
writeEvent: (event) => writeSync(outputFd, `${JSON.stringify(event)}\n`),
|
|
203
|
-
onPhase: (phase, reason
|
|
204
|
-
status: phase === 'recording' ? 'recording' : state.status,
|
|
205
|
-
phase,
|
|
206
|
-
reason: reason ?? state.reason,
|
|
207
|
-
readyAt: phase === 'recording' ? new Date().toISOString() : state.readyAt,
|
|
208
|
-
}),
|
|
199
|
+
onPhase: (phase, reason) => lifecycle.transition(phase, reason ? { reason } : {}),
|
|
209
200
|
});
|
|
210
201
|
});
|
|
211
202
|
closeSync(outputFd);
|
|
212
203
|
outputFd = null;
|
|
213
|
-
|
|
214
|
-
status: 'completed',
|
|
215
|
-
phase: 'completed',
|
|
216
|
-
reason: result.reason,
|
|
217
|
-
eventCount: result.eventCount,
|
|
218
|
-
completedAt: new Date().toISOString(),
|
|
219
|
-
});
|
|
204
|
+
lifecycle.transition('completed', { reason: result.reason, eventCount: result.eventCount });
|
|
220
205
|
} catch (error) {
|
|
221
206
|
if (outputFd !== null) closeSync(outputFd);
|
|
222
|
-
|
|
223
|
-
status: 'failed',
|
|
224
|
-
phase: 'failed',
|
|
225
|
-
error: error.message,
|
|
226
|
-
completedAt: new Date().toISOString(),
|
|
227
|
-
});
|
|
207
|
+
lifecycle.transition('failed', { error: error.message });
|
|
228
208
|
throw error;
|
|
229
209
|
}
|
|
230
210
|
}
|
package/scripts/record-har.mjs
CHANGED
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
requiredOptionValue,
|
|
21
21
|
} from './browser-control.mjs';
|
|
22
22
|
import { privateOutputPath, withPageCdpSession } from './cdp-common.mjs';
|
|
23
|
+
import { createRecordingLifecycle } from './recording-lifecycle.mjs';
|
|
23
24
|
import {
|
|
24
25
|
CDP_CAPTURE_STOP_TIMEOUT_MS,
|
|
25
26
|
assertCdpRecordingOwner,
|
|
@@ -188,23 +189,18 @@ async function runWorker(args) {
|
|
|
188
189
|
const output = requiredOptionValue(args, '--output', null);
|
|
189
190
|
const options = decodeOptions(requiredOptionValue(args, '--worker-options', null));
|
|
190
191
|
const startedAt = new Date().toISOString();
|
|
191
|
-
|
|
192
|
+
const metadata = {
|
|
192
193
|
managedBy: 'browser-tools-cdp-recorder',
|
|
193
194
|
kind: CAPTURE_KIND,
|
|
194
195
|
pid: process.pid,
|
|
195
196
|
port,
|
|
196
197
|
output,
|
|
197
198
|
ownerTokenHash: ownerTokenHash(ownerToken),
|
|
198
|
-
status: 'starting',
|
|
199
|
-
phase: 'starting',
|
|
200
199
|
startedAt,
|
|
201
200
|
options,
|
|
202
201
|
};
|
|
203
|
-
const
|
|
204
|
-
state
|
|
205
|
-
updateCdpRecordingState(CAPTURE_KIND, port, state);
|
|
206
|
-
};
|
|
207
|
-
update({});
|
|
202
|
+
const lifecycle = createRecordingLifecycle(CAPTURE_KIND, metadata,
|
|
203
|
+
(state) => updateCdpRecordingState(CAPTURE_KIND, port, state));
|
|
208
204
|
|
|
209
205
|
try {
|
|
210
206
|
const result = await withPageCdpSession(port, ownerToken, async ({ page, session }) => runHarCapture({
|
|
@@ -212,28 +208,12 @@ async function runWorker(args) {
|
|
|
212
208
|
page,
|
|
213
209
|
options,
|
|
214
210
|
shouldStop: () => existsSync(cdpRecordingStopFile(CAPTURE_KIND, port)),
|
|
215
|
-
onPhase: (phase, reason
|
|
216
|
-
status: phase === 'recording' ? 'recording' : state.status,
|
|
217
|
-
phase,
|
|
218
|
-
reason: reason ?? state.reason,
|
|
219
|
-
readyAt: phase === 'recording' ? new Date().toISOString() : state.readyAt,
|
|
220
|
-
}),
|
|
211
|
+
onPhase: (phase, reason) => lifecycle.transition(phase, reason ? { reason } : {}),
|
|
221
212
|
}));
|
|
222
213
|
writeHar(output, result.har);
|
|
223
|
-
|
|
224
|
-
status: 'completed',
|
|
225
|
-
phase: 'completed',
|
|
226
|
-
reason: result.reason,
|
|
227
|
-
eventCount: result.eventCount,
|
|
228
|
-
completedAt: new Date().toISOString(),
|
|
229
|
-
});
|
|
214
|
+
lifecycle.transition('completed', { reason: result.reason, eventCount: result.eventCount });
|
|
230
215
|
} catch (error) {
|
|
231
|
-
|
|
232
|
-
status: 'failed',
|
|
233
|
-
phase: 'failed',
|
|
234
|
-
error: error.message,
|
|
235
|
-
completedAt: new Date().toISOString(),
|
|
236
|
-
});
|
|
216
|
+
lifecycle.transition('failed', { error: error.message });
|
|
237
217
|
throw error;
|
|
238
218
|
}
|
|
239
219
|
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Each recording owns its phase. The legacy status field is a projection, never another state.
|
|
2
|
+
const PATHS = {
|
|
3
|
+
gif: ['starting', 'pre-roll', 'recording', 'post-roll', 'completed'],
|
|
4
|
+
har: ['starting', 'recording', 'draining', 'completed'],
|
|
5
|
+
cdp: ['starting', 'recording', 'post-wait', 'completed'],
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
export function createRecordingLifecycle(kind, metadata = {}, persist = () => {}) {
|
|
9
|
+
const path = PATHS[kind];
|
|
10
|
+
if (!path) throw new Error(`Unknown recording kind: ${kind}`);
|
|
11
|
+
let state = { ...metadata, phase: 'starting', status: 'starting' };
|
|
12
|
+
persist({ ...state });
|
|
13
|
+
|
|
14
|
+
return {
|
|
15
|
+
get phase() { return state.phase; },
|
|
16
|
+
snapshot() { return { ...state }; },
|
|
17
|
+
transition(phase, details = {}) {
|
|
18
|
+
const current = path.indexOf(state.phase);
|
|
19
|
+
const terminal = state.phase === 'completed' || state.phase === 'failed';
|
|
20
|
+
if (terminal || (phase !== 'failed' && path[current + 1] !== phase)) {
|
|
21
|
+
throw new Error(`Invalid ${kind} recording transition: ${state.phase} -> ${phase}`);
|
|
22
|
+
}
|
|
23
|
+
const status = ['completed', 'failed'].includes(phase) ? phase
|
|
24
|
+
: path.indexOf(phase) >= path.indexOf('recording') ? 'recording' : 'starting';
|
|
25
|
+
const next = { ...state, ...details, phase, status };
|
|
26
|
+
if (phase === 'recording') next.readyAt = new Date().toISOString();
|
|
27
|
+
if (phase === 'completed' || phase === 'failed') next.completedAt = new Date().toISOString();
|
|
28
|
+
persist({ ...next });
|
|
29
|
+
state = next;
|
|
30
|
+
return { ...state };
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
@@ -65,10 +65,10 @@ function normalizePageResult(pageResult, closePage) {
|
|
|
65
65
|
if (pageResult && typeof pageResult === 'object' && Object.hasOwn(pageResult, 'page')) {
|
|
66
66
|
return {
|
|
67
67
|
page: pageResult.page,
|
|
68
|
-
|
|
68
|
+
ownership: (Object.hasOwn(pageResult, 'closePage') ? pageResult.closePage : closePage) ? 'owned' : 'borrowed',
|
|
69
69
|
};
|
|
70
70
|
}
|
|
71
|
-
return { page: pageResult, closePage };
|
|
71
|
+
return { page: pageResult, ownership: closePage ? 'owned' : 'borrowed' };
|
|
72
72
|
}
|
|
73
73
|
|
|
74
74
|
export async function runBrowserResource({
|
|
@@ -82,16 +82,14 @@ export async function runBrowserResource({
|
|
|
82
82
|
if (typeof run !== 'function') throw new Error('Missing Resource Helper run function');
|
|
83
83
|
|
|
84
84
|
const browser = await connect(port, connectOptionsForOwner(ownerToken));
|
|
85
|
-
let page = null;
|
|
86
|
-
let shouldClosePage = closePage;
|
|
87
|
-
|
|
88
85
|
try {
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
86
|
+
const resource = normalizePageResult(getPage ? await getPage(browser) : null, closePage);
|
|
87
|
+
try {
|
|
88
|
+
return await run({ browser, page: resource.page });
|
|
89
|
+
} finally {
|
|
90
|
+
if (resource.ownership === 'owned') await closeResourcePage(resource.page);
|
|
91
|
+
}
|
|
93
92
|
} finally {
|
|
94
|
-
if (shouldClosePage) await closeResourcePage(page);
|
|
95
93
|
if (browser && typeof browser.disconnect === 'function') browser.disconnect();
|
|
96
94
|
}
|
|
97
95
|
}
|