codeplay-common 4.3.2 → 4.3.4

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.
@@ -0,0 +1,1468 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+ const readline = require('node:readline/promises');
4
+ const { spawn, spawnSync } = require('node:child_process');
5
+
6
+ const screenshotDirectory = path.join(__dirname, 'Auto-Screenshot', 'Responsive');
7
+ const inFrameDirectory = path.join(__dirname, 'Auto-Screenshot', 'In-Frame');
8
+ const capacitorConfigPath = path.join(__dirname, 'capacitor.config.json');
9
+ const temporaryDirectory = path.join(__dirname, 'agent-temp');
10
+ const browserExecutablePaths = [
11
+ 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
12
+ 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
13
+ 'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe',
14
+ 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',
15
+ ];
16
+
17
+ const deviceProfiles = [
18
+ {
19
+ name: 'android-phone',
20
+ label: 'Android phone',
21
+ outputDirectory: 'Android',
22
+ frameType: 'android-phone',
23
+ width: 360,
24
+ height: 800,
25
+ deviceScaleFactor: 3,
26
+ orientationSensitive: true,
27
+ mobile: true,
28
+ },
29
+ {
30
+ name: 'android-tablet',
31
+ label: 'Android tablet',
32
+ outputDirectory: 'Android-Tab',
33
+ frameType: 'tablet',
34
+ width: 800,
35
+ height: 1280,
36
+ deviceScaleFactor: 2,
37
+ orientationSensitive: true,
38
+ mobile: true,
39
+ },
40
+ {
41
+ name: 'iphone',
42
+ label: 'iPhone 6.9-inch App Store viewport',
43
+ outputDirectory: 'iPhone',
44
+ frameType: 'iphone',
45
+ width: 440,
46
+ height: 956,
47
+ deviceScaleFactor: 3,
48
+ framedWidth: 1284,
49
+ framedHeight: 2778,
50
+ orientationSensitive: true,
51
+ mobile: true,
52
+ },
53
+ {
54
+ name: 'ipad',
55
+ label: 'iPad 13-inch App Store viewport',
56
+ outputDirectory: 'iPad',
57
+ frameType: 'tablet',
58
+ width: 1032,
59
+ height: 1376,
60
+ deviceScaleFactor: 2,
61
+ framedWidth: 2048,
62
+ framedHeight: 2732,
63
+ orientationSensitive: true,
64
+ mobile: true,
65
+ },
66
+ {
67
+ name: 'apple-vision-pro',
68
+ label: 'Apple Vision Pro',
69
+ outputDirectory: 'Apple-Vision-Pro',
70
+ frameType: 'apple-vision-pro',
71
+ width: 3840,
72
+ height: 2160,
73
+ deviceScaleFactor: 1,
74
+ framedWidth: 3840,
75
+ framedHeight: 2160,
76
+ mobile: false,
77
+ },
78
+ {
79
+ name: 'apple-tv',
80
+ label: 'Apple TV',
81
+ outputDirectory: 'Apple-TV',
82
+ frameType: 'apple-tv',
83
+ width: 1920,
84
+ height: 1080,
85
+ deviceScaleFactor: 1,
86
+ framedWidth: 1920,
87
+ framedHeight: 1080,
88
+ mobile: false,
89
+ },
90
+ {
91
+ name: 'apple-watch',
92
+ label: 'Apple Watch Ultra 3',
93
+ outputDirectory: 'Apple-Watch',
94
+ frameType: 'apple-watch',
95
+ width: 422,
96
+ height: 514,
97
+ deviceScaleFactor: 1,
98
+ framedWidth: 422,
99
+ framedHeight: 514,
100
+ mobile: true,
101
+ },
102
+ {
103
+ name: 'amazon-mobile',
104
+ label: 'Amazon mobile store viewport',
105
+ outputDirectory: 'Amazon-Phone',
106
+ frameType: 'android-phone',
107
+ width: 360,
108
+ height: 640,
109
+ deviceScaleFactor: 3,
110
+ orientationSensitive: true,
111
+ mobile: true,
112
+ },
113
+ {
114
+ name: 'amazon-fire-tablet',
115
+ label: 'Amazon Fire tablet store viewport',
116
+ outputDirectory: 'Amazon-Tab',
117
+ frameType: 'tablet',
118
+ width: 800,
119
+ height: 1280,
120
+ deviceScaleFactor: 2,
121
+ orientationSensitive: true,
122
+ mobile: true,
123
+ },
124
+ {
125
+ name: 'amazon-fire-tv',
126
+ label: 'Amazon Fire TV store viewport',
127
+ outputDirectory: 'Amazon-TV',
128
+ frameType: 'tv',
129
+ width: 1920,
130
+ height: 1080,
131
+ deviceScaleFactor: 1,
132
+ mobile: false,
133
+ },
134
+ {
135
+ name: 'android-tv',
136
+ label: 'Android TV',
137
+ outputDirectory: 'Android-TV',
138
+ frameType: 'tv',
139
+ width: 1920,
140
+ height: 1080,
141
+ deviceScaleFactor: 1,
142
+ mobile: false,
143
+ },
144
+ {
145
+ name: 'chromebook',
146
+ label: 'Chromebook-sized viewport',
147
+ outputDirectory: 'Chromebook',
148
+ frameType: 'laptop',
149
+ width: 1366,
150
+ height: 768,
151
+ deviceScaleFactor: 1,
152
+ mobile: false,
153
+ },
154
+ {
155
+ name: 'android-xr',
156
+ label: 'Android XR 2D panel approximation',
157
+ outputDirectory: 'Android-XR',
158
+ frameType: 'xr',
159
+ width: 1920,
160
+ height: 1080,
161
+ deviceScaleFactor: 1,
162
+ mobile: false,
163
+ },
164
+ {
165
+ name: 'mac',
166
+ label: 'Mac-sized viewport',
167
+ outputDirectory: 'Mac',
168
+ frameType: 'laptop',
169
+ width: 1440,
170
+ height: 900,
171
+ deviceScaleFactor: 2,
172
+ mobile: false,
173
+ },
174
+ ];
175
+
176
+ function getConfiguredOrientation() {
177
+ const config = JSON.parse(fs.readFileSync(capacitorConfigPath, 'utf8'));
178
+ return String(config.android?.ORIENTATION || 'portrait').toLowerCase() === 'landscape'
179
+ ? 'landscape'
180
+ : 'portrait';
181
+ }
182
+
183
+ function orientProfile(profile, orientation) {
184
+ if (orientation !== 'landscape' || !profile.orientationSensitive) {
185
+ return profile;
186
+ }
187
+
188
+ return {
189
+ ...profile,
190
+ width: profile.height,
191
+ height: profile.width,
192
+ framedWidth: profile.framedHeight,
193
+ framedHeight: profile.framedWidth,
194
+ };
195
+ }
196
+
197
+ function runAdb(args, options = {}) {
198
+ const result = spawnSync('adb', args, {
199
+ encoding: 'utf8',
200
+ timeout: 30000,
201
+ windowsHide: true,
202
+ ...options,
203
+ });
204
+
205
+ if (result.error) {
206
+ if (result.error.code === 'ENOENT') {
207
+ throw new Error('ADB was not found. Add Android platform-tools to your PATH.');
208
+ }
209
+
210
+ if (result.error.code === 'ETIMEDOUT') {
211
+ throw new Error('ADB did not respond within 30 seconds. Check the device connection.');
212
+ }
213
+
214
+ throw result.error;
215
+ }
216
+
217
+ if (result.status !== 0) {
218
+ throw new Error(result.stderr.trim() || `ADB exited with code ${result.status}.`);
219
+ }
220
+
221
+ return result.stdout.trim();
222
+ }
223
+
224
+ function getConnectedDevice() {
225
+ const devices = runAdb(['devices'])
226
+ .split(/\r?\n/)
227
+ .map((line) => line.match(/^(\S+)\s+device$/))
228
+ .filter(Boolean)
229
+ .map((match) => match[1]);
230
+
231
+ if (!devices.length) {
232
+ throw new Error('no_connected_device');
233
+ }
234
+
235
+ return devices[0];
236
+ }
237
+
238
+ function getAppId() {
239
+ const config = JSON.parse(fs.readFileSync(capacitorConfigPath, 'utf8'));
240
+
241
+ if (!config.appId) {
242
+ throw new Error('capacitor.config.json does not contain an appId.');
243
+ }
244
+
245
+ return config.appId;
246
+ }
247
+
248
+ function getWebViewSocket(deviceId, appId) {
249
+ const processIds = runAdb(['-s', deviceId, 'shell', 'pidof', appId])
250
+ .split(/\s+/)
251
+ .filter(Boolean);
252
+
253
+ if (!processIds.length) {
254
+ throw new Error(`The app process is not running: ${appId}`);
255
+ }
256
+
257
+ const sockets = runAdb(['-s', deviceId, 'shell', 'cat', '/proc/net/unix']);
258
+
259
+ for (const processId of processIds) {
260
+ const socketName = `webview_devtools_remote_${processId}`;
261
+
262
+ if (sockets.includes(`@${socketName}`)) {
263
+ return socketName;
264
+ }
265
+ }
266
+
267
+ throw new Error(
268
+ 'The running app does not expose a debuggable WebView. Use a debug/live-reload build with WebView debugging enabled.',
269
+ );
270
+ }
271
+
272
+ function sanitizeName(input, fallback) {
273
+ const sanitized = input
274
+ .trim()
275
+ .replace(/[<>:"/\\|?*\u0000-\u001F]/g, '_')
276
+ .replace(/[. ]+$/g, '');
277
+
278
+ return sanitized || fallback;
279
+ }
280
+
281
+ function getSelectedOutputDirectories(selectedProfiles) {
282
+ return [...new Set(selectedProfiles.flatMap((profile) => ([
283
+ path.join(screenshotDirectory, profile.outputDirectory),
284
+ path.join(inFrameDirectory, profile.outputDirectory),
285
+ ])))];
286
+ }
287
+
288
+ function getNextNumberedFileName(selectedProfiles) {
289
+ const highestNumber = getSelectedOutputDirectories(selectedProfiles)
290
+ .filter((directory) => fs.existsSync(directory))
291
+ .reduce((highestAcrossDirectories, directory) => {
292
+ const highestInDirectory = fs.readdirSync(directory, { withFileTypes: true })
293
+ .filter((entry) => entry.isFile())
294
+ .reduce((highest, entry) => {
295
+ const match = entry.name.match(/^(\d+)\.png$/i);
296
+ return match ? Math.max(highest, Number(match[1])) : highest;
297
+ }, 0);
298
+
299
+ return Math.max(highestAcrossDirectories, highestInDirectory);
300
+ }, 0);
301
+
302
+ return `${highestNumber + 1}.png`;
303
+ }
304
+
305
+ function getUniqueFileName(prefix, selectedProfiles) {
306
+ const outputDirectories = getSelectedOutputDirectories(selectedProfiles);
307
+ let fileName = `${prefix}.png`;
308
+ let duplicateNumber = 2;
309
+
310
+ while (outputDirectories.some((directory) => (
311
+ fs.existsSync(path.join(directory, fileName))
312
+ ))) {
313
+ fileName = `${prefix}-${duplicateNumber}.png`;
314
+ duplicateNumber += 1;
315
+ }
316
+
317
+ return fileName;
318
+ }
319
+
320
+ function getScreenshotFileName(fileNameInput, selectedProfiles) {
321
+ const inputWithoutExtension = fileNameInput.trim().replace(/\.png$/i, '');
322
+
323
+ if (!inputWithoutExtension) {
324
+ return getNextNumberedFileName(selectedProfiles);
325
+ }
326
+
327
+ let prefix = sanitizeName(inputWithoutExtension, '');
328
+
329
+ if (!prefix) {
330
+ return getNextNumberedFileName(selectedProfiles);
331
+ }
332
+
333
+ if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(prefix)) {
334
+ prefix = `${prefix}_`;
335
+ }
336
+
337
+ return getUniqueFileName(prefix, selectedProfiles);
338
+ }
339
+
340
+ function parseArguments() {
341
+ const args = process.argv.slice(2);
342
+ const options = {
343
+ dryRun: false,
344
+ frameExisting: false,
345
+ help: false,
346
+ list: false,
347
+ prefix: '',
348
+ profiles: '',
349
+ };
350
+
351
+ for (let index = 0; index < args.length; index += 1) {
352
+ const argument = args[index];
353
+
354
+ if (argument === '--dry-run') {
355
+ options.dryRun = true;
356
+ } else if (argument === '--frame-existing') {
357
+ options.frameExisting = true;
358
+ } else if (argument === '--help' || argument === '-h') {
359
+ options.help = true;
360
+ } else if (argument === '--list') {
361
+ options.list = true;
362
+ } else if (argument === '--prefix') {
363
+ options.prefix = args[index + 1] || '';
364
+ index += 1;
365
+ } else if (argument === '--profiles') {
366
+ options.profiles = args[index + 1] || '';
367
+ index += 1;
368
+ } else {
369
+ throw new Error(`Unknown argument: ${argument}`);
370
+ }
371
+ }
372
+
373
+ return options;
374
+ }
375
+
376
+ function printProfiles() {
377
+ const orientation = getConfiguredOrientation();
378
+
379
+ for (const baseProfile of deviceProfiles) {
380
+ const profile = orientProfile(baseProfile, orientation);
381
+ const outputWidth = profile.width * profile.deviceScaleFactor;
382
+ const outputHeight = profile.height * profile.deviceScaleFactor;
383
+ const framedSize = profile.framedWidth
384
+ ? `, framed PNG ${profile.framedWidth}x${profile.framedHeight}`
385
+ : '';
386
+ console.log(
387
+ `${profile.name.padEnd(15)} ${profile.label} `
388
+ + `(folder ${profile.outputDirectory}, viewport ${profile.width}x${profile.height}, `
389
+ + `PNG ${outputWidth}x${outputHeight}${framedSize})`,
390
+ );
391
+ }
392
+ }
393
+
394
+ function printHelp() {
395
+ console.log('Capture the current live Android WebView at multiple responsive viewport sizes.');
396
+ console.log('');
397
+ console.log('Usage:');
398
+ console.log(' node take-responsive-screenshot.js');
399
+ console.log(' node take-responsive-screenshot.js --profiles iphone,ipad');
400
+ console.log(' node take-responsive-screenshot.js --prefix home --profiles android-phone,ipad');
401
+ console.log(' node take-responsive-screenshot.js --frame-existing');
402
+ console.log(' node take-responsive-screenshot.js --dry-run');
403
+ console.log(' node take-responsive-screenshot.js --list');
404
+ }
405
+
406
+ function selectProfiles(input) {
407
+ const orientation = getConfiguredOrientation();
408
+ const names = input
409
+ .split(',')
410
+ .map((name) => name.trim().toLowerCase())
411
+ .filter(Boolean);
412
+
413
+ if (!names.length || names.includes('all')) {
414
+ return deviceProfiles.map((profile) => orientProfile(profile, orientation));
415
+ }
416
+
417
+ const selectedProfiles = names.map((name) => {
418
+ const profile = deviceProfiles.find((candidate) => candidate.name === name);
419
+
420
+ if (!profile) {
421
+ throw new Error(`Unknown profile: ${name}. Run with --list to see valid profiles.`);
422
+ }
423
+
424
+ return profile;
425
+ });
426
+
427
+ return [...new Map(selectedProfiles.map((profile) => [profile.name, profile])).values()]
428
+ .map((profile) => orientProfile(profile, orientation));
429
+ }
430
+
431
+ class CdpClient {
432
+ constructor(webSocketUrl) {
433
+ this.nextId = 1;
434
+ this.pendingCommands = new Map();
435
+ this.socket = new WebSocket(webSocketUrl);
436
+ }
437
+
438
+ connect() {
439
+ return new Promise((resolve, reject) => {
440
+ const timeout = setTimeout(() => {
441
+ reject(new Error('Timed out while connecting to the app WebView.'));
442
+ }, 10000);
443
+
444
+ this.socket.addEventListener('open', () => {
445
+ clearTimeout(timeout);
446
+ resolve();
447
+ }, { once: true });
448
+
449
+ this.socket.addEventListener('error', () => {
450
+ clearTimeout(timeout);
451
+ reject(new Error('Could not connect to the app WebView debugging socket.'));
452
+ }, { once: true });
453
+
454
+ this.socket.addEventListener('message', (event) => {
455
+ const message = JSON.parse(event.data);
456
+
457
+ if (!message.id || !this.pendingCommands.has(message.id)) {
458
+ return;
459
+ }
460
+
461
+ const pendingCommand = this.pendingCommands.get(message.id);
462
+ this.pendingCommands.delete(message.id);
463
+
464
+ if (message.error) {
465
+ pendingCommand.reject(new Error(message.error.message));
466
+ } else {
467
+ pendingCommand.resolve(message.result);
468
+ }
469
+ });
470
+
471
+ this.socket.addEventListener('close', () => {
472
+ for (const pendingCommand of this.pendingCommands.values()) {
473
+ pendingCommand.reject(new Error('The app WebView debugging connection closed.'));
474
+ }
475
+
476
+ this.pendingCommands.clear();
477
+ });
478
+ });
479
+ }
480
+
481
+ send(method, params = {}) {
482
+ return new Promise((resolve, reject) => {
483
+ const id = this.nextId;
484
+ this.nextId += 1;
485
+ this.pendingCommands.set(id, { resolve, reject });
486
+ this.socket.send(JSON.stringify({ id, method, params }));
487
+ });
488
+ }
489
+
490
+ close() {
491
+ this.socket.close();
492
+ }
493
+ }
494
+
495
+ async function getWebViewTarget(localPort) {
496
+ const response = await fetch(`http://127.0.0.1:${localPort}/json/list`);
497
+
498
+ if (!response.ok) {
499
+ throw new Error(`WebView target discovery failed with HTTP ${response.status}.`);
500
+ }
501
+
502
+ const targets = await response.json();
503
+ const pageTargets = targets.filter((target) => (
504
+ target.type === 'page'
505
+ && target.webSocketDebuggerUrl
506
+ && target.url !== 'about:blank'
507
+ ));
508
+
509
+ const visibleTarget = pageTargets.find((target) => {
510
+ try {
511
+ return JSON.parse(target.description || '{}').visible !== false;
512
+ } catch {
513
+ return true;
514
+ }
515
+ });
516
+
517
+ const target = visibleTarget || pageTargets[0];
518
+
519
+ if (!target) {
520
+ throw new Error('No rendered page was found in the app WebView.');
521
+ }
522
+
523
+ return target;
524
+ }
525
+
526
+ async function getPageDetails(client) {
527
+ const evaluation = await client.send('Runtime.evaluate', {
528
+ expression: `JSON.stringify({
529
+ title: document.title,
530
+ url: location.href,
531
+ width: innerWidth,
532
+ height: innerHeight,
533
+ devicePixelRatio: devicePixelRatio,
534
+ readyState: document.readyState
535
+ })`,
536
+ returnByValue: true,
537
+ });
538
+
539
+ return JSON.parse(evaluation.result.value);
540
+ }
541
+
542
+ async function capturePageSnapshot(client) {
543
+ const evaluation = await client.send('Runtime.evaluate', {
544
+ expression: `(async () => {
545
+ const clonedRoot = document.documentElement.cloneNode(true);
546
+ const originalElements = [document.documentElement, ...document.querySelectorAll('*')];
547
+ const clonedElements = [clonedRoot, ...clonedRoot.querySelectorAll('*')];
548
+
549
+ const blobToDataUrl = (blob) => new Promise((resolve, reject) => {
550
+ const reader = new FileReader();
551
+ reader.onload = () => resolve(reader.result);
552
+ reader.onerror = () => reject(reader.error);
553
+ reader.readAsDataURL(blob);
554
+ });
555
+
556
+ const imageToDataUrl = (element) => {
557
+ const width = element.naturalWidth || element.clientWidth;
558
+ const height = element.naturalHeight || element.clientHeight;
559
+
560
+ if (!width || !height) return '';
561
+
562
+ const canvas = document.createElement('canvas');
563
+ canvas.width = width;
564
+ canvas.height = height;
565
+ canvas.getContext('2d').drawImage(element, 0, 0, width, height);
566
+ return canvas.toDataURL('image/png');
567
+ };
568
+
569
+ for (let index = 0; index < originalElements.length; index += 1) {
570
+ const original = originalElements[index];
571
+ const clone = clonedElements[index];
572
+
573
+ if (!clone) continue;
574
+
575
+ if (original.scrollTop || original.scrollLeft) {
576
+ clone.setAttribute('data-responsive-scroll-top', String(original.scrollTop));
577
+ clone.setAttribute('data-responsive-scroll-left', String(original.scrollLeft));
578
+ }
579
+
580
+ if (original instanceof HTMLInputElement) {
581
+ clone.setAttribute('value', original.value);
582
+ clone.toggleAttribute('checked', original.checked);
583
+ } else if (original instanceof HTMLTextAreaElement) {
584
+ clone.textContent = original.value;
585
+ } else if (original instanceof HTMLSelectElement) {
586
+ for (let optionIndex = 0; optionIndex < original.options.length; optionIndex += 1) {
587
+ clone.options[optionIndex].selected = original.options[optionIndex].selected;
588
+ }
589
+ } else if (original instanceof HTMLCanvasElement) {
590
+ try {
591
+ const replacement = document.createElement('img');
592
+ replacement.src = original.toDataURL('image/png');
593
+ replacement.alt = original.getAttribute('aria-label') || '';
594
+ replacement.setAttribute('style', original.getAttribute('style') || '');
595
+ clone.replaceWith(replacement);
596
+ } catch {
597
+ // Keep the canvas element when its pixels cannot be exported.
598
+ }
599
+ } else if (original instanceof HTMLVideoElement && original.readyState >= 2) {
600
+ try {
601
+ const replacement = document.createElement('img');
602
+ replacement.src = imageToDataUrl(original);
603
+ replacement.alt = original.getAttribute('aria-label') || '';
604
+ replacement.setAttribute('style', original.getAttribute('style') || '');
605
+ clone.replaceWith(replacement);
606
+ } catch {
607
+ clone.setAttribute('poster', original.poster || '');
608
+ }
609
+ } else if (original instanceof HTMLImageElement && original.complete) {
610
+ try {
611
+ clone.setAttribute('src', imageToDataUrl(original) || original.currentSrc || original.src);
612
+ clone.removeAttribute('srcset');
613
+ } catch {
614
+ clone.setAttribute('src', original.currentSrc || original.src);
615
+ }
616
+ }
617
+ }
618
+
619
+ const stylesheetLinks = [...document.querySelectorAll('link[rel="stylesheet"]')];
620
+ const clonedStylesheetLinks = [...clonedRoot.querySelectorAll('link[rel="stylesheet"]')];
621
+
622
+ await Promise.all(stylesheetLinks.map(async (link, index) => {
623
+ try {
624
+ const response = await fetch(link.href);
625
+ if (!response.ok) return;
626
+
627
+ const cssText = (await response.text()).replace(
628
+ /url\\(\\s*(['"]?)(?!data:|blob:|#)([^'"\\)]+)\\1\\s*\\)/gi,
629
+ (match, quote, resourceUrl) => {
630
+ try {
631
+ return 'url("' + new URL(resourceUrl.trim(), link.href).href + '")';
632
+ } catch {
633
+ return match;
634
+ }
635
+ },
636
+ );
637
+ const style = document.createElement('style');
638
+ style.textContent = cssText;
639
+ clonedStylesheetLinks[index].replaceWith(style);
640
+ } catch {
641
+ clonedStylesheetLinks[index].href = link.href;
642
+ }
643
+ }));
644
+
645
+ clonedRoot.querySelectorAll('script, link[rel="modulepreload"]').forEach((element) => element.remove());
646
+ clonedRoot.querySelectorAll('meta[http-equiv="Content-Security-Policy"]').forEach(
647
+ (element) => element.remove(),
648
+ );
649
+
650
+ const base = document.createElement('base');
651
+ base.href = location.href;
652
+ clonedRoot.querySelector('head').prepend(base);
653
+
654
+ const replayStyle = document.createElement('style');
655
+ replayStyle.textContent = [
656
+ '*,*::before,*::after{animation-play-state:paused!important;}',
657
+ '*{scrollbar-width:none!important;}',
658
+ '*::-webkit-scrollbar{width:0!important;height:0!important;display:none!important;}',
659
+ ].join('');
660
+ clonedRoot.querySelector('head').append(replayStyle);
661
+
662
+ return {
663
+ html: '<!doctype html>' + clonedRoot.outerHTML,
664
+ scrollX,
665
+ scrollY,
666
+ };
667
+ })()`,
668
+ awaitPromise: true,
669
+ returnByValue: true,
670
+ });
671
+
672
+ if (evaluation.exceptionDetails) {
673
+ throw new Error('The current WebView page could not be serialized.');
674
+ }
675
+
676
+ return evaluation.result.value;
677
+ }
678
+
679
+ function findBrowserExecutable() {
680
+ const executablePath = browserExecutablePaths.find((candidate) => (
681
+ fs.existsSync(candidate)
682
+ ));
683
+
684
+ if (!executablePath) {
685
+ throw new Error('Google Chrome or Microsoft Edge was not found on this computer.');
686
+ }
687
+
688
+ return executablePath;
689
+ }
690
+
691
+ function delay(milliseconds) {
692
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
693
+ }
694
+
695
+ async function launchReplayBrowser() {
696
+ fs.mkdirSync(temporaryDirectory, { recursive: true });
697
+
698
+ const profileDirectory = path.join(
699
+ temporaryDirectory,
700
+ `responsive-screenshot-chrome-${process.pid}-${Date.now()}`,
701
+ );
702
+ fs.mkdirSync(profileDirectory, { recursive: true });
703
+
704
+ const browserProcess = spawn(findBrowserExecutable(), [
705
+ '--headless=new',
706
+ '--remote-debugging-port=0',
707
+ `--user-data-dir=${profileDirectory}`,
708
+ '--no-first-run',
709
+ '--no-default-browser-check',
710
+ '--disable-background-networking',
711
+ '--remote-allow-origins=*',
712
+ 'about:blank',
713
+ ], {
714
+ stdio: 'ignore',
715
+ windowsHide: true,
716
+ });
717
+
718
+ const activePortPath = path.join(profileDirectory, 'DevToolsActivePort');
719
+ const deadline = Date.now() + 15000;
720
+
721
+ while (!fs.existsSync(activePortPath)) {
722
+ if (browserProcess.exitCode !== null) {
723
+ throw new Error('The local replay browser closed before it was ready.');
724
+ }
725
+
726
+ if (Date.now() >= deadline) {
727
+ browserProcess.kill();
728
+ throw new Error('Timed out while starting the local replay browser.');
729
+ }
730
+
731
+ await delay(100);
732
+ }
733
+
734
+ const [port] = fs.readFileSync(activePortPath, 'utf8').trim().split(/\r?\n/);
735
+ const versionResponse = await fetch(`http://127.0.0.1:${port}/json/version`);
736
+ const version = await versionResponse.json();
737
+ const client = new CdpClient(version.webSocketDebuggerUrl);
738
+ await client.connect();
739
+
740
+ return {
741
+ browserProcess,
742
+ client,
743
+ port,
744
+ profileDirectory,
745
+ };
746
+ }
747
+
748
+ async function createReplayPage(browser) {
749
+ const createdTarget = await browser.client.send('Target.createTarget', {
750
+ url: 'about:blank',
751
+ });
752
+ const deadline = Date.now() + 10000;
753
+
754
+ while (Date.now() < deadline) {
755
+ const response = await fetch(`http://127.0.0.1:${browser.port}/json/list`);
756
+ const targets = await response.json();
757
+ const target = targets.find((candidate) => candidate.id === createdTarget.targetId);
758
+
759
+ if (target && target.webSocketDebuggerUrl) {
760
+ const client = new CdpClient(target.webSocketDebuggerUrl);
761
+ await client.connect();
762
+ await client.send('Page.enable');
763
+ await client.send('Runtime.enable');
764
+ return client;
765
+ }
766
+
767
+ await delay(100);
768
+ }
769
+
770
+ throw new Error('The local replay page did not become available.');
771
+ }
772
+
773
+ function removeTemporaryBrowserProfile(profileDirectory) {
774
+ const resolvedTemporaryRoot = path.resolve(temporaryDirectory);
775
+ const resolvedProfileDirectory = path.resolve(profileDirectory);
776
+
777
+ if (!resolvedProfileDirectory.startsWith(`${resolvedTemporaryRoot}${path.sep}`)) {
778
+ throw new Error('Refusing to remove a browser profile outside agent-temp.');
779
+ }
780
+
781
+ fs.rmSync(resolvedProfileDirectory, { recursive: true, force: true });
782
+ }
783
+
784
+ async function closeReplayBrowser(browser) {
785
+ try {
786
+ await browser.client.send('Browser.close');
787
+ } catch {
788
+ // Closing the browser can close the protocol connection before it acknowledges.
789
+ }
790
+
791
+ const deadline = Date.now() + 3000;
792
+
793
+ while (browser.browserProcess.exitCode === null && Date.now() < deadline) {
794
+ await delay(100);
795
+ }
796
+
797
+ if (browser.browserProcess.exitCode === null) {
798
+ browser.browserProcess.kill();
799
+ await delay(200);
800
+ }
801
+
802
+ browser.client.close();
803
+
804
+ for (let attempt = 1; attempt <= 5; attempt += 1) {
805
+ try {
806
+ removeTemporaryBrowserProfile(browser.profileDirectory);
807
+ return;
808
+ } catch (error) {
809
+ if (attempt === 5) {
810
+ throw error;
811
+ }
812
+
813
+ await delay(200);
814
+ }
815
+ }
816
+ }
817
+
818
+ async function waitForReplayLayout(client, snapshot) {
819
+ await client.send('Runtime.evaluate', {
820
+ expression: `(async () => {
821
+ const assetWait = Promise.all([...document.images].map((image) => {
822
+ if (image.complete) return Promise.resolve();
823
+ return new Promise((resolve) => {
824
+ image.addEventListener('load', resolve, { once: true });
825
+ image.addEventListener('error', resolve, { once: true });
826
+ });
827
+ }));
828
+
829
+ await Promise.race([
830
+ Promise.all([document.fonts.ready, assetWait]),
831
+ new Promise((resolve) => setTimeout(resolve, 5000)),
832
+ ]);
833
+
834
+ document.querySelectorAll('[data-responsive-scroll-top]').forEach((element) => {
835
+ element.scrollTop = Number(element.dataset.responsiveScrollTop);
836
+ element.scrollLeft = Number(element.dataset.responsiveScrollLeft);
837
+ });
838
+ scrollTo(${Number(snapshot.scrollX) || 0}, ${Number(snapshot.scrollY) || 0});
839
+
840
+ await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
841
+ })()`,
842
+ awaitPromise: true,
843
+ returnByValue: true,
844
+ });
845
+ }
846
+
847
+ function getFrameAdornment(frameType) {
848
+ if (frameType === 'iphone') {
849
+ return '<div class="dynamic-island"></div>';
850
+ }
851
+
852
+ if (frameType === 'android-phone') {
853
+ return '<div class="camera-dot"></div>';
854
+ }
855
+
856
+ if (frameType === 'tablet') {
857
+ return '<div class="tablet-camera"></div>';
858
+ }
859
+
860
+ if (frameType === 'tv' || frameType === 'apple-tv') {
861
+ return '<div class="tv-stand"></div>';
862
+ }
863
+
864
+ if (frameType === 'apple-watch') {
865
+ return '<div class="watch-crown"></div><div class="watch-button"></div>';
866
+ }
867
+
868
+ if (frameType === 'apple-vision-pro') {
869
+ return '<div class="vision-sensor vision-sensor-left"></div><div class="vision-sensor vision-sensor-right"></div>';
870
+ }
871
+
872
+ if (frameType === 'laptop') {
873
+ return '<div class="laptop-camera"></div><div class="laptop-base"></div>';
874
+ }
875
+
876
+ return '<div class="xr-status"></div>';
877
+ }
878
+
879
+ function createDeviceFrameHtml(profile, screenshotBuffer) {
880
+ const screenshotDataUrl = `data:image/png;base64,${screenshotBuffer.toString('base64')}`;
881
+ const aspectRatio = `${profile.width} / ${profile.height}`;
882
+
883
+ return `<!doctype html>
884
+ <html>
885
+ <head>
886
+ <meta charset="utf-8" />
887
+ <style>
888
+ * { box-sizing: border-box; }
889
+ html, body { width: 100%; height: 100%; margin: 0; overflow: hidden; }
890
+ body {
891
+ display: grid;
892
+ place-items: center;
893
+ position: relative;
894
+ background:
895
+ radial-gradient(circle at 14% 18%, rgba(45, 213, 255, 0.24), transparent 30%),
896
+ radial-gradient(circle at 86% 82%, rgba(196, 255, 61, 0.16), transparent 28%),
897
+ linear-gradient(145deg, #111827 0%, #070b12 52%, #020409 100%);
898
+ font-family: Arial, sans-serif;
899
+ }
900
+ body::before {
901
+ content: '';
902
+ position: absolute;
903
+ inset: 0;
904
+ opacity: 0.18;
905
+ background-image:
906
+ linear-gradient(rgba(255,255,255,0.045) 1px, transparent 1px),
907
+ linear-gradient(90deg, rgba(255,255,255,0.045) 1px, transparent 1px);
908
+ background-size: 7vw 7vw;
909
+ mask-image: linear-gradient(to bottom, transparent, black 28%, black 72%, transparent);
910
+ }
911
+ .device {
912
+ position: relative;
913
+ z-index: 1;
914
+ aspect-ratio: ${aspectRatio};
915
+ background: linear-gradient(145deg, #566171 0%, #171c25 18%, #05070b 55%, #384252 100%);
916
+ border: clamp(2px, 0.45vw, 9px) solid #727d8d;
917
+ box-shadow:
918
+ 0 4vh 9vh rgba(0, 0, 0, 0.68),
919
+ 0 0 0 1px rgba(255, 255, 255, 0.18) inset,
920
+ 0 0 5vh rgba(45, 213, 255, 0.12);
921
+ }
922
+ .screen {
923
+ position: relative;
924
+ width: 100%;
925
+ height: 100%;
926
+ overflow: hidden;
927
+ background: #05070b;
928
+ box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.95) inset;
929
+ }
930
+ .screen img {
931
+ display: block;
932
+ width: 100%;
933
+ height: 100%;
934
+ object-fit: cover;
935
+ }
936
+ .device.android-phone,
937
+ .device.iphone {
938
+ height: 87%;
939
+ padding: 1.25%;
940
+ border-radius: clamp(24px, 8vw, 70px);
941
+ }
942
+ .device.android-phone .screen,
943
+ .device.iphone .screen {
944
+ border-radius: clamp(19px, 6.7vw, 60px);
945
+ }
946
+ .camera-dot {
947
+ position: absolute;
948
+ z-index: 3;
949
+ top: 2.1%;
950
+ left: 50%;
951
+ width: clamp(5px, 1.8vw, 16px);
952
+ aspect-ratio: 1;
953
+ transform: translateX(-50%);
954
+ border-radius: 50%;
955
+ background: radial-gradient(circle at 36% 34%, #406891, #080b10 46%, #000 72%);
956
+ box-shadow: 0 0 0 2px #111827;
957
+ }
958
+ .dynamic-island {
959
+ position: absolute;
960
+ z-index: 3;
961
+ top: 2.2%;
962
+ left: 50%;
963
+ width: 29%;
964
+ height: 3.3%;
965
+ transform: translateX(-50%);
966
+ border-radius: 999px;
967
+ background: #000;
968
+ box-shadow: 0 0 0 1px rgba(255,255,255,0.05);
969
+ }
970
+ .device.tablet {
971
+ height: 86%;
972
+ padding: 1.05%;
973
+ border-radius: clamp(18px, 3.2vw, 48px);
974
+ }
975
+ .device.tablet .screen {
976
+ border-radius: clamp(13px, 2.5vw, 38px);
977
+ }
978
+ .device.apple-watch {
979
+ height: 82%;
980
+ padding: 2.2%;
981
+ border: clamp(3px, 1.4vw, 7px) solid #8b929b;
982
+ border-radius: 24% / 20%;
983
+ background: linear-gradient(145deg, #d5d8dc, #363b43 28%, #11151b 72%, #9299a2);
984
+ }
985
+ .device.apple-watch .screen {
986
+ border-radius: 20% / 17%;
987
+ }
988
+ .watch-crown {
989
+ position: absolute;
990
+ top: 24%;
991
+ right: -5.5%;
992
+ width: 5.5%;
993
+ height: 15%;
994
+ border-radius: 0 45% 45% 0;
995
+ background: linear-gradient(90deg, #303640, #a8afb7 55%, #424851);
996
+ box-shadow: 0 0.8vh 1.5vh rgba(0,0,0,0.45);
997
+ }
998
+ .watch-button {
999
+ position: absolute;
1000
+ top: 43%;
1001
+ right: -3.5%;
1002
+ width: 3.5%;
1003
+ height: 11%;
1004
+ border-radius: 0 35% 35% 0;
1005
+ background: #626a74;
1006
+ }
1007
+ .device.apple-vision-pro {
1008
+ width: 82%;
1009
+ padding: 0.72%;
1010
+ border: clamp(4px, 0.45vw, 18px) solid rgba(201, 214, 224, 0.92);
1011
+ border-radius: 14% / 32%;
1012
+ background: linear-gradient(145deg, #dce5eb, #55616d 25%, #151b22 72%, #aebac3);
1013
+ box-shadow:
1014
+ 0 5vh 11vh rgba(0,0,0,0.68),
1015
+ 0 0 5vh rgba(180,225,255,0.2),
1016
+ 0 0 0 1px rgba(255,255,255,0.4) inset;
1017
+ }
1018
+ .device.apple-vision-pro .screen {
1019
+ border-radius: 13% / 29%;
1020
+ }
1021
+ .vision-sensor {
1022
+ position: absolute;
1023
+ z-index: 3;
1024
+ top: 48%;
1025
+ width: clamp(8px, 0.8vw, 30px);
1026
+ aspect-ratio: 1;
1027
+ border-radius: 50%;
1028
+ background: radial-gradient(circle at 38% 35%, #567793, #05080c 55%, #000 75%);
1029
+ box-shadow: 0 0 0 2px rgba(147,166,181,0.55);
1030
+ }
1031
+ .vision-sensor-left { left: 3.2%; }
1032
+ .vision-sensor-right { right: 3.2%; }
1033
+ .tablet-camera,
1034
+ .laptop-camera {
1035
+ position: absolute;
1036
+ z-index: 3;
1037
+ top: 0.48%;
1038
+ left: 50%;
1039
+ width: clamp(3px, 0.55vw, 10px);
1040
+ aspect-ratio: 1;
1041
+ transform: translateX(-50%);
1042
+ border-radius: 50%;
1043
+ background: #080b10;
1044
+ box-shadow: 0 0 0 1px #526071;
1045
+ }
1046
+ .device.tv,
1047
+ .device.apple-tv {
1048
+ width: 82%;
1049
+ padding: 0.62%;
1050
+ border-radius: clamp(8px, 1.1vw, 24px);
1051
+ transform: translateY(-4%);
1052
+ }
1053
+ .device.tv .screen,
1054
+ .device.apple-tv .screen { border-radius: clamp(4px, 0.55vw, 12px); }
1055
+ .tv-stand {
1056
+ position: absolute;
1057
+ z-index: -1;
1058
+ left: 50%;
1059
+ bottom: -13%;
1060
+ width: 24%;
1061
+ height: 13%;
1062
+ transform: translateX(-50%);
1063
+ background: linear-gradient(90deg, #11161f, #697383 50%, #11161f);
1064
+ clip-path: polygon(42% 0, 58% 0, 67% 76%, 94% 86%, 100% 100%, 0 100%, 6% 86%, 33% 76%);
1065
+ filter: drop-shadow(0 1.5vh 1.5vh rgba(0,0,0,0.55));
1066
+ }
1067
+ .device.laptop {
1068
+ width: 82%;
1069
+ padding: 0.75% 0.75% 1.15%;
1070
+ border-radius: clamp(8px, 1.2vw, 24px);
1071
+ transform: translateY(-3%);
1072
+ }
1073
+ .device.laptop .screen { border-radius: clamp(4px, 0.55vw, 12px); }
1074
+ .laptop-base {
1075
+ position: absolute;
1076
+ z-index: -1;
1077
+ left: 50%;
1078
+ bottom: -7.5%;
1079
+ width: 112%;
1080
+ height: 8%;
1081
+ transform: translateX(-50%);
1082
+ border-radius: 0 0 50% 50% / 0 0 70% 70%;
1083
+ background: linear-gradient(#697383, #202631 45%, #090c11);
1084
+ box-shadow: 0 1.5vh 2vh rgba(0,0,0,0.48);
1085
+ }
1086
+ .device.xr {
1087
+ width: 82%;
1088
+ padding: 0.58%;
1089
+ border: clamp(2px, 0.32vw, 7px) solid rgba(128, 230, 255, 0.9);
1090
+ border-radius: clamp(18px, 2.5vw, 48px);
1091
+ background: rgba(13, 22, 34, 0.82);
1092
+ box-shadow:
1093
+ 0 4vh 10vh rgba(0,0,0,0.65),
1094
+ 0 0 7vh rgba(45,213,255,0.34),
1095
+ 0 0 0 1px rgba(255,255,255,0.22) inset;
1096
+ }
1097
+ .device.xr .screen { border-radius: clamp(13px, 2vw, 38px); }
1098
+ .xr-status {
1099
+ position: absolute;
1100
+ top: -2.4%;
1101
+ left: 50%;
1102
+ width: 13%;
1103
+ height: 1.1%;
1104
+ transform: translateX(-50%);
1105
+ border-radius: 999px;
1106
+ background: #6fe8ff;
1107
+ box-shadow: 0 0 1.8vh #2dd5ff;
1108
+ }
1109
+ </style>
1110
+ </head>
1111
+ <body>
1112
+ <main class="device ${profile.frameType}">
1113
+ <div class="screen"><img src="${screenshotDataUrl}" /></div>
1114
+ ${getFrameAdornment(profile.frameType)}
1115
+ </main>
1116
+ </body>
1117
+ </html>`;
1118
+ }
1119
+
1120
+ async function captureFramedScreenshot(
1121
+ client,
1122
+ screenshotBuffer,
1123
+ profile,
1124
+ screenshotFileName,
1125
+ skipExisting = false,
1126
+ ) {
1127
+ const framedProfileDirectory = path.join(inFrameDirectory, profile.outputDirectory);
1128
+ const framedScreenshotPath = path.join(framedProfileDirectory, screenshotFileName);
1129
+
1130
+ if (skipExisting && fs.existsSync(framedScreenshotPath)) {
1131
+ console.log(`Skipped existing framed screenshot: ${framedScreenshotPath}`);
1132
+ return false;
1133
+ }
1134
+
1135
+ const hasCustomFrameSize = Boolean(profile.framedWidth && profile.framedHeight);
1136
+ const frameWidth = profile.framedWidth || profile.width;
1137
+ const frameHeight = profile.framedHeight || profile.height;
1138
+ const frameScaleFactor = hasCustomFrameSize ? 1 : profile.deviceScaleFactor;
1139
+
1140
+ await client.send('Emulation.setDeviceMetricsOverride', {
1141
+ width: frameWidth,
1142
+ height: frameHeight,
1143
+ deviceScaleFactor: frameScaleFactor,
1144
+ mobile: false,
1145
+ screenWidth: frameWidth,
1146
+ screenHeight: frameHeight,
1147
+ positionX: 0,
1148
+ positionY: 0,
1149
+ });
1150
+
1151
+ const frameTree = await client.send('Page.getFrameTree');
1152
+ await client.send('Page.setDocumentContent', {
1153
+ frameId: frameTree.frameTree.frame.id,
1154
+ html: createDeviceFrameHtml(profile, screenshotBuffer),
1155
+ });
1156
+ await client.send('Runtime.evaluate', {
1157
+ expression: `new Promise((resolve) => {
1158
+ const image = document.querySelector('img');
1159
+ const ready = () => requestAnimationFrame(() => requestAnimationFrame(resolve));
1160
+ if (image.complete) ready();
1161
+ else {
1162
+ image.addEventListener('load', ready, { once: true });
1163
+ image.addEventListener('error', ready, { once: true });
1164
+ }
1165
+ })`,
1166
+ awaitPromise: true,
1167
+ returnByValue: true,
1168
+ });
1169
+
1170
+ const framedScreenshot = await client.send('Page.captureScreenshot', {
1171
+ format: 'png',
1172
+ fromSurface: true,
1173
+ captureBeyondViewport: false,
1174
+ });
1175
+
1176
+ fs.mkdirSync(framedProfileDirectory, { recursive: true });
1177
+ fs.writeFileSync(
1178
+ framedScreenshotPath,
1179
+ Buffer.from(framedScreenshot.data, 'base64'),
1180
+ { flag: 'wx' },
1181
+ );
1182
+ console.log(`Saved framed ${profile.label}: ${framedScreenshotPath}`);
1183
+ return true;
1184
+ }
1185
+
1186
+ async function captureProfile(client, snapshot, profile, screenshotFileName) {
1187
+ await client.send('Emulation.setDeviceMetricsOverride', {
1188
+ width: profile.width,
1189
+ height: profile.height,
1190
+ deviceScaleFactor: profile.deviceScaleFactor,
1191
+ mobile: profile.mobile,
1192
+ screenWidth: profile.width,
1193
+ screenHeight: profile.height,
1194
+ positionX: 0,
1195
+ positionY: 0,
1196
+ });
1197
+
1198
+ const frameTree = await client.send('Page.getFrameTree');
1199
+ await client.send('Page.setDocumentContent', {
1200
+ frameId: frameTree.frameTree.frame.id,
1201
+ html: snapshot.html,
1202
+ });
1203
+ await waitForReplayLayout(client, snapshot);
1204
+
1205
+ const screenshot = await client.send('Page.captureScreenshot', {
1206
+ format: 'png',
1207
+ fromSurface: true,
1208
+ captureBeyondViewport: false,
1209
+ });
1210
+
1211
+ const profileDirectory = path.join(screenshotDirectory, profile.outputDirectory);
1212
+ const screenshotPath = path.join(profileDirectory, screenshotFileName);
1213
+ const screenshotBuffer = Buffer.from(screenshot.data, 'base64');
1214
+
1215
+ fs.mkdirSync(profileDirectory, { recursive: true });
1216
+ fs.writeFileSync(screenshotPath, screenshotBuffer, { flag: 'wx' });
1217
+ console.log(`Saved ${profile.label}: ${screenshotPath}`);
1218
+ await captureFramedScreenshot(
1219
+ client,
1220
+ screenshotBuffer,
1221
+ profile,
1222
+ screenshotFileName,
1223
+ );
1224
+ }
1225
+
1226
+ async function captureScreenshotSet(
1227
+ deviceClient,
1228
+ replayClient,
1229
+ selectedProfiles,
1230
+ fileNameInput,
1231
+ ) {
1232
+ console.log('Capturing the current rendered page and resolved native data...');
1233
+ const snapshot = await capturePageSnapshot(deviceClient);
1234
+ const screenshotFileName = getScreenshotFileName(fileNameInput, selectedProfiles);
1235
+
1236
+ for (const profile of selectedProfiles) {
1237
+ await captureProfile(replayClient, snapshot, profile, screenshotFileName);
1238
+ }
1239
+
1240
+ console.log(`Responsive screenshot set completed: ${screenshotFileName}`);
1241
+ }
1242
+
1243
+ async function frameExistingScreenshots(selectedProfiles) {
1244
+ let replayBrowser;
1245
+ let replayClient;
1246
+ let framedCount = 0;
1247
+ let failedCount = 0;
1248
+
1249
+ try {
1250
+ replayBrowser = await launchReplayBrowser();
1251
+ replayClient = await createReplayPage(replayBrowser);
1252
+
1253
+ for (const profile of selectedProfiles) {
1254
+ const profileDirectory = path.join(screenshotDirectory, profile.outputDirectory);
1255
+
1256
+ if (!fs.existsSync(profileDirectory)) {
1257
+ continue;
1258
+ }
1259
+
1260
+ const screenshotFiles = fs.readdirSync(profileDirectory, { withFileTypes: true })
1261
+ .filter((entry) => entry.isFile() && /\.png$/i.test(entry.name))
1262
+ .map((entry) => entry.name)
1263
+ .sort((first, second) => first.localeCompare(second, undefined, { numeric: true }));
1264
+
1265
+ for (const screenshotFileName of screenshotFiles) {
1266
+ const screenshotPath = path.join(profileDirectory, screenshotFileName);
1267
+
1268
+ try {
1269
+ const wasCreated = await captureFramedScreenshot(
1270
+ replayClient,
1271
+ fs.readFileSync(screenshotPath),
1272
+ profile,
1273
+ screenshotFileName,
1274
+ true,
1275
+ );
1276
+ if (wasCreated) framedCount += 1;
1277
+ } catch (error) {
1278
+ failedCount += 1;
1279
+ console.error(`Failed to frame ${screenshotPath}: ${error.message}`);
1280
+ }
1281
+ }
1282
+ }
1283
+ } finally {
1284
+ if (replayClient) {
1285
+ replayClient.close();
1286
+ }
1287
+
1288
+ if (replayBrowser) {
1289
+ await closeReplayBrowser(replayBrowser);
1290
+ }
1291
+ }
1292
+
1293
+ console.log(`Existing screenshot framing completed: ${framedCount} created.`);
1294
+
1295
+ if (failedCount) {
1296
+ throw new Error(`${failedCount} existing screenshot(s) could not be framed.`);
1297
+ }
1298
+ }
1299
+
1300
+ async function runInteractiveCaptureLoop(
1301
+ deviceClient,
1302
+ replayClient,
1303
+ selectedProfiles,
1304
+ ) {
1305
+ const terminal = readline.createInterface({
1306
+ input: process.stdin,
1307
+ output: process.stdout,
1308
+ prompt: 'Enter a filename, or press Enter for the next number: ',
1309
+ });
1310
+
1311
+ terminal.on('SIGINT', () => terminal.close());
1312
+
1313
+ console.log(`Screenshots will be saved in: ${screenshotDirectory}`);
1314
+ console.log('Press Ctrl+C to exit.');
1315
+ terminal.prompt();
1316
+
1317
+ for await (const fileNameInput of terminal) {
1318
+ try {
1319
+ await captureScreenshotSet(
1320
+ deviceClient,
1321
+ replayClient,
1322
+ selectedProfiles,
1323
+ fileNameInput,
1324
+ );
1325
+ } catch (error) {
1326
+ console.error(`Responsive screenshot failed: ${error.message}`);
1327
+ }
1328
+
1329
+ terminal.prompt();
1330
+ }
1331
+
1332
+ console.log('\nResponsive screenshot tool closed.');
1333
+ }
1334
+
1335
+ async function getInteractiveOptions(options) {
1336
+ if (!process.stdin.isTTY || options.dryRun) {
1337
+ return options;
1338
+ }
1339
+
1340
+ const terminal = readline.createInterface({
1341
+ input: process.stdin,
1342
+ output: process.stdout,
1343
+ });
1344
+
1345
+ try {
1346
+ if (!options.profiles) {
1347
+ console.log('Available profiles:');
1348
+ printProfiles();
1349
+ options.profiles = await terminal.question(
1350
+ 'Profiles separated by commas, or press Enter for all: ',
1351
+ );
1352
+ }
1353
+ } finally {
1354
+ terminal.close();
1355
+ }
1356
+
1357
+ return options;
1358
+ }
1359
+
1360
+ async function main() {
1361
+ let options = parseArguments();
1362
+
1363
+ if (options.help) {
1364
+ printHelp();
1365
+ return;
1366
+ }
1367
+
1368
+ if (options.list) {
1369
+ printProfiles();
1370
+ return;
1371
+ }
1372
+
1373
+ options = await getInteractiveOptions(options);
1374
+
1375
+ const selectedProfiles = selectProfiles(options.profiles);
1376
+
1377
+ if (options.frameExisting) {
1378
+ await frameExistingScreenshots(selectedProfiles);
1379
+ return;
1380
+ }
1381
+
1382
+ const interactiveMode = process.stdin.isTTY && !options.prefix && !options.dryRun;
1383
+ const deviceId = getConnectedDevice();
1384
+ const appId = getAppId();
1385
+ const socketName = getWebViewSocket(deviceId, appId);
1386
+ const localPort = runAdb([
1387
+ '-s',
1388
+ deviceId,
1389
+ 'forward',
1390
+ 'tcp:0',
1391
+ `localabstract:${socketName}`,
1392
+ ]);
1393
+
1394
+ let deviceClient;
1395
+ let replayBrowser;
1396
+ let replayClient;
1397
+
1398
+ try {
1399
+ const target = await getWebViewTarget(localPort);
1400
+ deviceClient = new CdpClient(target.webSocketDebuggerUrl);
1401
+ await deviceClient.connect();
1402
+ await deviceClient.send('Page.enable');
1403
+ await deviceClient.send('Runtime.enable');
1404
+
1405
+ const pageDetails = await getPageDetails(deviceClient);
1406
+ console.log(`Connected device: ${deviceId}`);
1407
+ console.log(`App: ${appId}`);
1408
+ console.log(`Current page: ${pageDetails.title || '(untitled)'}`);
1409
+ console.log(`Current URL: ${pageDetails.url}`);
1410
+ console.log(
1411
+ `Current viewport: ${pageDetails.width}x${pageDetails.height} `
1412
+ + `at ${pageDetails.devicePixelRatio}x (${pageDetails.readyState})`,
1413
+ );
1414
+
1415
+ if (options.dryRun) {
1416
+ console.log('Dry run completed. No screenshots were created.');
1417
+ return;
1418
+ }
1419
+
1420
+ fs.mkdirSync(screenshotDirectory, { recursive: true });
1421
+ replayBrowser = await launchReplayBrowser();
1422
+ replayClient = await createReplayPage(replayBrowser);
1423
+
1424
+ console.log(
1425
+ 'Apple, TV, Chromebook, Mac, and XR profiles are viewport approximations of the live Android WebView.',
1426
+ );
1427
+
1428
+ if (interactiveMode) {
1429
+ await runInteractiveCaptureLoop(
1430
+ deviceClient,
1431
+ replayClient,
1432
+ selectedProfiles,
1433
+ );
1434
+ } else {
1435
+ await captureScreenshotSet(
1436
+ deviceClient,
1437
+ replayClient,
1438
+ selectedProfiles,
1439
+ options.prefix,
1440
+ );
1441
+ }
1442
+ } finally {
1443
+ if (replayClient) {
1444
+ replayClient.close();
1445
+ }
1446
+
1447
+ if (replayBrowser) {
1448
+ await closeReplayBrowser(replayBrowser);
1449
+ }
1450
+
1451
+ if (deviceClient) {
1452
+ deviceClient.close();
1453
+ }
1454
+
1455
+ if (localPort) {
1456
+ try {
1457
+ runAdb(['-s', deviceId, 'forward', '--remove', `tcp:${localPort}`]);
1458
+ } catch {
1459
+ // ADB may already have removed the temporary forwarding rule.
1460
+ }
1461
+ }
1462
+ }
1463
+ }
1464
+
1465
+ main().catch((error) => {
1466
+ console.error(`Responsive screenshot failed: ${error.message}`);
1467
+ process.exitCode = 1;
1468
+ });