playwright-touch 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +612 -2
  3. package/dist/android.d.ts +26 -0
  4. package/dist/android.js +113 -0
  5. package/dist/chromium/clock.d.ts +12 -0
  6. package/dist/chromium/clock.js +45 -0
  7. package/dist/chromium/gestures.d.ts +56 -0
  8. package/dist/chromium/gestures.js +500 -0
  9. package/dist/chromium/steady.d.ts +16 -0
  10. package/dist/chromium/steady.js +38 -0
  11. package/dist/cli.d.ts +2 -0
  12. package/dist/cli.js +459 -0
  13. package/dist/index.d.ts +111 -0
  14. package/dist/index.js +149 -0
  15. package/dist/ios/bplist.d.ts +8 -0
  16. package/dist/ios/bplist.js +150 -0
  17. package/dist/ios/device.d.ts +30 -0
  18. package/dist/ios/device.js +48 -0
  19. package/dist/ios/inspector.d.ts +61 -0
  20. package/dist/ios/inspector.js +342 -0
  21. package/dist/ios/iphone.d.ts +27 -0
  22. package/dist/ios/iphone.js +141 -0
  23. package/dist/ios/page.d.ts +90 -0
  24. package/dist/ios/page.js +338 -0
  25. package/dist/ios/paths.d.ts +17 -0
  26. package/dist/ios/paths.js +77 -0
  27. package/dist/ios/simulator.d.ts +24 -0
  28. package/dist/ios/simulator.js +69 -0
  29. package/dist/ios/tab.d.ts +41 -0
  30. package/dist/ios/tab.js +171 -0
  31. package/dist/ios/tools.d.ts +4 -0
  32. package/dist/ios/tools.js +17 -0
  33. package/dist/ios/touch.d.ts +31 -0
  34. package/dist/ios/touch.js +178 -0
  35. package/dist/ios/usbmux.d.ts +34 -0
  36. package/dist/ios/usbmux.js +346 -0
  37. package/dist/layout.d.ts +35 -0
  38. package/dist/layout.js +164 -0
  39. package/dist/measure.d.ts +86 -0
  40. package/dist/measure.js +173 -0
  41. package/dist/own-tabs.d.ts +8 -0
  42. package/dist/own-tabs.js +242 -0
  43. package/dist/playwright-test.d.ts +66 -0
  44. package/dist/playwright-test.js +64 -0
  45. package/dist/polyline.d.ts +10 -0
  46. package/dist/polyline.js +38 -0
  47. package/dist/recipes.d.ts +57 -0
  48. package/dist/recipes.js +135 -0
  49. package/dist/report.d.ts +46 -0
  50. package/dist/report.js +118 -0
  51. package/dist/session.d.ts +35 -0
  52. package/dist/session.js +23 -0
  53. package/dist/show.d.ts +13 -0
  54. package/dist/show.js +51 -0
  55. package/dist/synthetic.d.ts +17 -0
  56. package/dist/synthetic.js +117 -0
  57. package/dist/types.d.ts +58 -0
  58. package/dist/types.js +2 -0
  59. package/package.json +83 -4
package/dist/cli.js ADDED
@@ -0,0 +1,459 @@
1
+ #!/usr/bin/env node
2
+ // The phone from the desk, as commands:
3
+ // playwright-touch report <url> [--tap <selector>] [--fingers] [--iphone] [--out <file>] [--json <file>]
4
+ // playwright-touch fits <url> [<url> ...] [--targets]
5
+ // playwright-touch simulator --wda <folder> [--udid <udid>]
6
+ // playwright-touch iphone --wda <folder> [--team <team>] [--udid <udid>]
7
+ import { execFile, spawn } from 'node:child_process';
8
+ import { existsSync, readdirSync, writeFileSync } from 'node:fs';
9
+ import { join, resolve } from 'node:path';
10
+ import { parseArgs } from 'node:util';
11
+ import { anotherDevice, boot, describe, servedBy, simulators } from './ios/device.js';
12
+ import { iphones } from './ios/usbmux.js';
13
+ import { coldLoad, connectAndroid, connectIphone, connectSimulator, film, findOverflow, findSmallTargets, fling, showTouches, steadyScrollArgs, tap, watchVitals, writeComparison, } from './index.js';
14
+ const HELP = `playwright-touch: the phone from the desk
15
+
16
+ playwright-touch report <url> [--tap <selector>] [--fingers] [--iphone] [--out <file>] [--json <file>]
17
+ Visits the address cold on every device at hand, flings the page, taps the selector if one
18
+ is given, and writes one report with a column per device (default report.html).
19
+ Devices: an emulated phone in Chrome, the Android phone on the cable, a booted iPhone simulator.
20
+ With --fingers the film strips show a dot where each finger was.
21
+ With --iphone the iPhone on the cable is visited too. It is only touched when asked for,
22
+ because it is somebody's own phone: Safari on it may be closed and opened again, and the
23
+ film strips show its whole screen, a notification that arrives included.
24
+ With --json the numbers are also written as JSON, for scripts.
25
+
26
+ playwright-touch fits <url> [<url> ...] [--targets]
27
+ Opens each address cold at 320, 360 and 393 px in an emulated phone, flings it three times
28
+ and names whatever makes the page wider than the screen. Exits with 1 if anything does, and with 2 if a page
29
+ could not be opened. It also counts the links and buttons too small for a finger (under 24 px
30
+ without room around them, as in WCAG 2.2); with --targets those fail the check as well.
31
+
32
+ playwright-touch steady-args
33
+ Prints the browser switch that makes scroll distances exact, for the Playwright installed
34
+ here. Paste it into launchOptions.args.
35
+
36
+ playwright-touch simulator --wda <folder> [--udid <udid>]
37
+ Gets an iPhone simulator ready for report and for connectSimulator(): boots it without
38
+ opening its window, builds WebDriverAgent from the given checkout if it is not built yet,
39
+ and keeps it running until Ctrl-C. Without --udid it takes the booted iPhone, or the newest
40
+ one there is.
41
+
42
+ playwright-touch iphone --wda <folder> [--team <team>] [--udid <udid>]
43
+ Gets the iPhone on the cable ready for connectIphone() and for report --iphone: builds
44
+ WebDriverAgent from the given checkout, signs it for the phone and keeps it running until
45
+ Ctrl-C. Xcode needs an Apple Account; without --team the team of the Apple Development
46
+ certificate in the keychain is used.
47
+ `;
48
+ async function emulatedBrowser() {
49
+ let playwright;
50
+ try {
51
+ playwright = await import('playwright-core');
52
+ }
53
+ catch {
54
+ throw new Error('playwright-touch: Playwright is not installed here. Add playwright, @playwright/test or playwright-core to the project.');
55
+ }
56
+ // The Chrome that is installed, or the Chromium that Playwright downloaded.
57
+ return playwright.chromium.launch({ channel: 'chrome' }).catch(() => playwright.chromium.launch());
58
+ }
59
+ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
60
+ async function report(url, options) {
61
+ const visit = async (device, page) => {
62
+ if (options.fingers)
63
+ await showTouches(page);
64
+ await coldLoad(page, url);
65
+ const vitals = await watchVitals(page);
66
+ const flung = await film(page, () => fling(page, { direction: 'up' }), { settle: 2500 });
67
+ if (options.tap) {
68
+ await tap(page.locator(options.tap));
69
+ await pause(1200);
70
+ }
71
+ const after = await vitals.read();
72
+ console.log(`${device}: first paint ${after.fcp ?? '?'} ms, largest paint ${after.lcp ?? '?'} ms, slowest interaction ${after.inp === null ? 'none seen' : after.inp + ' ms'}`);
73
+ return { device, vitals: after, films: [{ label: 'A hard fling', film: flung }] };
74
+ };
75
+ const runs = [];
76
+ const attempt = async (name, run) => {
77
+ try {
78
+ await run();
79
+ }
80
+ catch (error) {
81
+ console.log(`${name} skipped: ${error.message.replace(/^playwright-touch: /, '').split('\n')[0]}`);
82
+ }
83
+ };
84
+ await attempt('Emulated phone', async () => {
85
+ const browser = await emulatedBrowser();
86
+ try {
87
+ const context = await browser.newContext({
88
+ viewport: { width: 393, height: 851 },
89
+ deviceScaleFactor: 2.75,
90
+ isMobile: true,
91
+ hasTouch: true,
92
+ });
93
+ runs.push(await visit('Chrome, emulated phone on this computer', await context.newPage()));
94
+ }
95
+ finally {
96
+ await browser.close();
97
+ }
98
+ });
99
+ await attempt('Android phone', async () => {
100
+ const phone = await connectAndroid();
101
+ try {
102
+ runs.push(await visit(`Chrome ${phone.browser.version().split('.')[0]}, ${phone.model}`, await phone.newPage()));
103
+ }
104
+ finally {
105
+ await phone.close();
106
+ }
107
+ });
108
+ await attempt('iPhone simulator', async () => {
109
+ const simulator = await connectSimulator();
110
+ try {
111
+ runs.push(await visit(`Safari, ${simulator.model} simulator`, simulator.page));
112
+ }
113
+ finally {
114
+ await simulator.close();
115
+ }
116
+ });
117
+ if (options.iphone) {
118
+ await attempt('iPhone', async () => {
119
+ // Asking for the phone's column is also the say-so for starting Safari again when it has to be.
120
+ const phone = await connectIphone({ restartSafari: true });
121
+ try {
122
+ if (phone.restartedSafari)
123
+ console.log('Safari on the iPhone was closed and opened again to get a tab.');
124
+ runs.push(await visit(`Safari, ${phone.model} on the cable with iOS ${phone.system}`, phone.page));
125
+ }
126
+ finally {
127
+ await phone.close();
128
+ }
129
+ });
130
+ }
131
+ if (runs.length === 0) {
132
+ console.error('Nothing could be measured.');
133
+ return 1;
134
+ }
135
+ writeComparison(options.out, { title: 'One visit, side by side', url, runs, framesPerFilm: 6 });
136
+ console.log(`${options.out} written with ${runs.length} device${runs.length === 1 ? '' : 's'}`);
137
+ if (options.json) {
138
+ // The numbers alone, for a script that wants to compare them with a budget or with last week.
139
+ const devices = runs.map((run) => ({
140
+ device: run.device,
141
+ vitals: run.vitals,
142
+ films: (run.films ?? []).map(({ label, film: shot }) => ({
143
+ label,
144
+ frames: shot.frames.length,
145
+ duration: shot.duration,
146
+ scrolledFor: shot.scrolledFor,
147
+ longestPause: shot.longestPause,
148
+ })),
149
+ }));
150
+ writeFileSync(options.json, JSON.stringify({ url, measuredAt: new Date().toISOString(), devices }, null, 2) + '\n');
151
+ console.log(`${options.json} written`);
152
+ }
153
+ return 0;
154
+ }
155
+ async function fits(urls, options = {}) {
156
+ const browser = await emulatedBrowser();
157
+ let failures = 0;
158
+ let broken = false;
159
+ try {
160
+ for (const url of urls) {
161
+ for (const width of [320, 360, 393]) {
162
+ const context = await browser.newContext({
163
+ viewport: { width, height: 700 },
164
+ deviceScaleFactor: 2,
165
+ isMobile: true,
166
+ hasTouch: true,
167
+ });
168
+ const page = await context.newPage();
169
+ try {
170
+ await coldLoad(page, url, { settle: 1200 });
171
+ }
172
+ catch (error) {
173
+ console.log(`${url} at ${width} px: could not be opened: ${error.message.split('\n')[0]}`);
174
+ broken = true;
175
+ await context.close();
176
+ break;
177
+ }
178
+ const vitals = await watchVitals(page);
179
+ const wide = await findOverflow(page);
180
+ for (let i = 0; i < 3; i++) {
181
+ await fling(page, { direction: 'up' });
182
+ await pause(900);
183
+ }
184
+ for (const late of await findOverflow(page))
185
+ if (!wide.some((early) => early.element === late.element))
186
+ wide.push(late);
187
+ const end = await vitals.read();
188
+ // Counted once the page has been flung through, so that what loads late is there too.
189
+ const small = await findSmallTargets(page);
190
+ if (wide.length || (options.targets && small.length))
191
+ failures++;
192
+ const verdict = wide.length === 0 ? 'fits' : `too wide: ${wide.map((one) => `${one.element} by ${one.by} px`).join(', ')}`;
193
+ // Load times are left out on purpose: the first visit pays for the connection, which would read as a slow width.
194
+ const named = small
195
+ .slice(0, 3)
196
+ .map((one) => `${one.element} ${one.width}x${one.height}`)
197
+ .join(', ');
198
+ const targets = small.length === 0 ? 'none' : `${small.length} (${named}${small.length > 3 ? ', ...' : ''})`;
199
+ console.log(`${url} at ${width} px: ${verdict} | targets too small for a finger: ${targets} | layout shift after three flings ${end.cls ?? '?'}`);
200
+ await context.close();
201
+ }
202
+ }
203
+ }
204
+ finally {
205
+ await browser.close();
206
+ }
207
+ // 1: something is too wide. 2: a page could not be opened, so nothing is known about it.
208
+ return broken ? 2 : failures ? 1 : 0;
209
+ }
210
+ const sh = (command, args) => new Promise((done, fail) => {
211
+ execFile(command, args, { maxBuffer: 32 * 1024 * 1024 }, (error, stdout, stderr) => error
212
+ ? fail(new Error(`${command} ${args[0]} failed: ${(stderr || error.message).trim().split('\n').pop()}`))
213
+ : done(stdout));
214
+ });
215
+ const WDA = 'http://127.0.0.1:8100';
216
+ async function simulator(options) {
217
+ if (!options.wda)
218
+ throw new Error('Say where WebDriverAgent is: --wda <folder>. Get it with: git clone --depth 1 https://github.com/appium/WebDriverAgent.git');
219
+ const folder = resolve(options.wda);
220
+ if (!existsSync(join(folder, 'WebDriverAgent.xcodeproj')))
221
+ throw new Error(`${folder} is not a WebDriverAgent checkout: there is no WebDriverAgent.xcodeproj in it.`);
222
+ const iphones = (await simulators()).filter((one) => one.name.startsWith('iPhone'));
223
+ // Without a choice, the one that is running, or else the one with the newest system.
224
+ const device = options.udid
225
+ ? iphones.find((one) => one.udid === options.udid)
226
+ : (iphones.find((one) => one.state === 'Booted') ?? iphones.at(-1));
227
+ if (!device) {
228
+ throw new Error(options.udid
229
+ ? `No iPhone simulator with the identifier ${options.udid}.`
230
+ : 'No iPhone simulator is installed. Add one in Xcode.');
231
+ }
232
+ // Asked before anything is booted, so that a refusal leaves the machine as it was.
233
+ const served = await servedBy(WDA);
234
+ const other = served && anotherDevice(served, device);
235
+ if (other) {
236
+ throw new Error(`WebDriverAgent already answers on port 8100, but for ${other}, not for ${describe(device)}. Stop that one first.`);
237
+ }
238
+ if (device.state !== 'Booted')
239
+ console.log(`Booting ${device.name}...`);
240
+ await boot(device);
241
+ if (served) {
242
+ console.log(`WebDriverAgent already answers on port 8100. ${device.name} is ready.`);
243
+ return 0;
244
+ }
245
+ const answering = async () => (await servedBy(WDA)) !== null;
246
+ const destination = `platform=iOS Simulator,id=${device.udid}`;
247
+ const products = join(folder, 'build', 'Build', 'Products');
248
+ const testRun = () => existsSync(products)
249
+ ? readdirSync(products).find((file) => file.endsWith('.xctestrun') && file.includes('iphonesimulator'))
250
+ : undefined;
251
+ if (!testRun()) {
252
+ console.log('Building WebDriverAgent, which takes a few minutes the first time...');
253
+ await sh('xcodebuild', [
254
+ 'build-for-testing',
255
+ '-project',
256
+ join(folder, 'WebDriverAgent.xcodeproj'),
257
+ '-scheme',
258
+ 'WebDriverAgentRunner',
259
+ '-destination',
260
+ destination,
261
+ '-derivedDataPath',
262
+ join(folder, 'build'),
263
+ 'CODE_SIGNING_ALLOWED=NO',
264
+ ]);
265
+ }
266
+ const runner = spawn('xcodebuild', ['test-without-building', '-xctestrun', join(products, testRun()), '-destination', destination], { stdio: 'ignore' });
267
+ const gone = new Promise((done) => runner.once('exit', (exit) => done(exit ?? 1)));
268
+ // Ctrl-C is the normal way to stop this, also before WebDriverAgent has come up.
269
+ let stopped = false;
270
+ for (const signal of ['SIGINT', 'SIGTERM'])
271
+ process.once(signal, () => {
272
+ stopped = true;
273
+ runner.kill();
274
+ });
275
+ let ended = false;
276
+ void gone.then(() => (ended = true));
277
+ // A child stopped by a signal has no exit code, so the exit itself is what ends the wait.
278
+ for (let waited = 0; waited < 120 && !ended; waited++) {
279
+ if (await answering()) {
280
+ console.log(`${device.name} is ready, with WebDriverAgent on port 8100. Leave this running; Ctrl-C stops it.`);
281
+ // Stopped by Ctrl-C is the normal way out; WebDriverAgent ending by itself is not.
282
+ await gone;
283
+ if (!stopped)
284
+ console.error('WebDriverAgent stopped by itself.');
285
+ return stopped ? 0 : 1;
286
+ }
287
+ await pause(1000);
288
+ }
289
+ runner.kill();
290
+ if (stopped)
291
+ return 0;
292
+ throw new Error('WebDriverAgent did not start. Run the xcodebuild commands from the README by hand to see why.');
293
+ }
294
+ /** The teams of the Apple Development certificates in the keychain, which is what Xcode signs with. */
295
+ async function signingTeams() {
296
+ try {
297
+ const certificates = await sh('security', ['find-certificate', '-a', '-c', 'Apple Development', '-p']);
298
+ const teams = new Set();
299
+ for (const certificate of certificates.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g) ??
300
+ []) {
301
+ const subject = await new Promise((done) => {
302
+ const openssl = execFile('openssl', ['x509', '-noout', '-subject', '-checkend', '0'], (_error, stdout) => done(stdout));
303
+ openssl.stdin?.end(certificate);
304
+ });
305
+ // A certificate that has run out is of no use for signing.
306
+ if (/will expire/.test(subject))
307
+ continue;
308
+ const team = /OU\s*=\s*([A-Z0-9]{10})/.exec(subject)?.[1];
309
+ if (team)
310
+ teams.add(team);
311
+ }
312
+ return [...teams];
313
+ }
314
+ catch {
315
+ return [];
316
+ }
317
+ }
318
+ async function iphone(options) {
319
+ if (!options.wda)
320
+ throw new Error('Say where WebDriverAgent is: --wda <folder>. Get it with: git clone --depth 1 https://github.com/appium/WebDriverAgent.git');
321
+ const folder = resolve(options.wda);
322
+ if (!existsSync(join(folder, 'WebDriverAgent.xcodeproj')))
323
+ throw new Error(`${folder} is not a WebDriverAgent checkout: there is no WebDriverAgent.xcodeproj in it.`);
324
+ const connected = await iphones();
325
+ if (!options.udid && connected.length > 1)
326
+ throw new Error(`${connected.length} devices are on the cable. Say which one with --udid: ${connected.map((one) => one.udid).join(', ')}`);
327
+ const phone = options.udid ? connected.find((one) => one.udid === options.udid) : connected[0];
328
+ if (!phone)
329
+ throw new Error(options.udid
330
+ ? `No iPhone with the identifier ${options.udid} is on the cable.`
331
+ : 'No iPhone is on the cable. Connect one and unlock it.');
332
+ if (options.team && !/^[A-Z0-9]{10}$/.test(options.team))
333
+ throw new Error('--team takes the ten letters and digits of an Apple developer team, as in ABCDE12345.');
334
+ const teams = options.team ? [options.team] : await signingTeams();
335
+ if (teams.length === 0)
336
+ throw new Error('No signing team. Add an Apple Account in Xcode (Settings, Apple Accounts), create an Apple Development certificate there, and try again or pass --team.');
337
+ // Signing registers the phone with the team, so with several teams the choice is not made here.
338
+ if (teams.length > 1)
339
+ throw new Error(`The keychain has Apple Development certificates of ${teams.length} teams: ${teams.join(', ')}. Say which one with --team.`);
340
+ const team = teams[0];
341
+ console.log(`Signing with team ${team}. The phone is registered with that team if it is not yet.`);
342
+ console.log('Building WebDriverAgent for the iPhone and starting it, which takes a few minutes the first time...');
343
+ const runner = spawn('xcodebuild', [
344
+ 'test',
345
+ '-project',
346
+ join(folder, 'WebDriverAgent.xcodeproj'),
347
+ '-scheme',
348
+ 'WebDriverAgentRunner',
349
+ '-destination',
350
+ `id=${phone.udid}`,
351
+ '-derivedDataPath',
352
+ join(folder, 'build-iphone'),
353
+ '-allowProvisioningUpdates',
354
+ `DEVELOPMENT_TEAM=${team}`,
355
+ 'CODE_SIGN_STYLE=Automatic',
356
+ `PRODUCT_BUNDLE_IDENTIFIER=dev.playwright-touch.wda.${team.toLowerCase()}`,
357
+ ], {
358
+ // WebDriverAgent listens on every network the phone is on unless told otherwise. On the
359
+ // phone's own loopback address it is reached over the cable and by nothing on its Wi-Fi.
360
+ env: { ...process.env, TEST_RUNNER_USE_IP: '127.0.0.1' },
361
+ });
362
+ let stopped = false;
363
+ for (const signal of ['SIGINT', 'SIGTERM'])
364
+ process.once(signal, () => {
365
+ stopped = true;
366
+ runner.kill();
367
+ });
368
+ // xcodebuild says what went wrong among thousands of lines; the ones that matter are picked out.
369
+ let why = '';
370
+ const examine = (line) => {
371
+ if (line.includes('ServerURLHere'))
372
+ console.log('The iPhone is ready, with WebDriverAgent running on it. Leave this running; Ctrl-C stops it.');
373
+ else if (/not been explicitly trusted|Developer App Certificate is not trusted/.test(line))
374
+ why =
375
+ 'The iPhone does not trust the developer yet. On the phone open Settings, General, VPN & Device Management, choose the developer app entry and trust it. Then run this again.';
376
+ else if (/errSecInternalComponent/.test(line))
377
+ why =
378
+ 'macOS did not let codesign use the signing key. Answer the keychain question with Always Allow, or unlock the login keychain, and run this again.';
379
+ else if (/device is locked|Unlock .* to Continue/i.test(line))
380
+ why = 'The iPhone is locked. Unlock it and run this again.';
381
+ else if (/Developer Mode disabled/i.test(line))
382
+ why = 'Developer Mode is off on the iPhone. Switch it on in Settings, Privacy & Security, and run this again.';
383
+ else if (!why && /error: /.test(line))
384
+ why = line.slice(line.indexOf('error: ') + 7).trim();
385
+ };
386
+ // Each stream keeps its own unfinished line, or half a line of one would be glued to the other.
387
+ const lines = () => {
388
+ let pending = '';
389
+ return {
390
+ read(chunk) {
391
+ const parts = (pending + chunk.toString('utf8')).split('\n');
392
+ pending = parts.pop() ?? '';
393
+ parts.forEach(examine);
394
+ },
395
+ flush: () => examine(pending),
396
+ };
397
+ };
398
+ const [out, err] = [lines(), lines()];
399
+ runner.stdout.on('data', out.read);
400
+ runner.stderr.on('data', err.read);
401
+ // 'close' comes after the last output has been read, which is where xcodebuild says why it failed.
402
+ const exit = await new Promise((done, fail) => {
403
+ runner.once('error', () => fail(new Error('xcodebuild was not found. Install Xcode and its command line tools.')));
404
+ runner.once('close', (status) => done(status ?? 1));
405
+ });
406
+ out.flush();
407
+ err.flush();
408
+ if (stopped)
409
+ return 0;
410
+ throw new Error(why || `xcodebuild ended with ${exit}. Run the xcodebuild command from the README by hand to see why.`);
411
+ }
412
+ let code = 0;
413
+ try {
414
+ const { positionals, values } = parseArgs({
415
+ allowPositionals: true,
416
+ options: {
417
+ tap: { type: 'string' },
418
+ out: { type: 'string', default: 'report.html' },
419
+ json: { type: 'string' },
420
+ fingers: { type: 'boolean' },
421
+ iphone: { type: 'boolean' },
422
+ team: { type: 'string' },
423
+ targets: { type: 'boolean' },
424
+ wda: { type: 'string' },
425
+ udid: { type: 'string' },
426
+ help: { type: 'boolean', short: 'h' },
427
+ },
428
+ });
429
+ const [command, ...rest] = positionals;
430
+ if (values.help || !command)
431
+ console.log(HELP);
432
+ else if (command === 'report' && rest[0])
433
+ code = await report(rest[0], {
434
+ tap: values.tap,
435
+ out: values.out,
436
+ json: values.json,
437
+ fingers: values.fingers,
438
+ iphone: values.iphone,
439
+ });
440
+ else if (command === 'fits' && rest.length)
441
+ code = await fits(rest, { targets: values.targets });
442
+ else if (command === 'simulator')
443
+ code = await simulator({ wda: values.wda, udid: values.udid });
444
+ else if (command === 'iphone')
445
+ code = await iphone({ wda: values.wda, team: values.team, udid: values.udid });
446
+ else if (command === 'steady-args')
447
+ console.log((await steadyScrollArgs()).join(' '));
448
+ else {
449
+ console.error(HELP);
450
+ code = 2;
451
+ }
452
+ }
453
+ catch (error) {
454
+ // Something went wrong before there was a verdict, a mistyped option included. That is 2 for
455
+ // every command, so that 1 always means the command ran and the answer was no.
456
+ console.error(error.message);
457
+ code = 2;
458
+ }
459
+ process.exit(code);
@@ -0,0 +1,111 @@
1
+ import type { Locator, Page } from './session.js';
2
+ import type { IosLocator, IosPage } from './ios/simulator.js';
3
+ import type { Target } from './chromium/gestures.js';
4
+ import type { Film, MeasuredPage, Vitals } from './measure.js';
5
+ import type { DirectedOptions, DragOptions, GestureOptions, PinchOptions, RotateOptions, StrokeOptions } from './types.js';
6
+ export type { Direction, DirectedOptions, DragOptions, GestureOptions, PinchOptions, Point, RotateOptions, StrokeOptions, } from './types.js';
7
+ export type { Target } from './chromium/gestures.js';
8
+ export { steadyScrollArgs } from './chromium/steady.js';
9
+ export { isSynthetic } from './synthetic.js';
10
+ export { edgeSwipe, pullToRefresh, swipeUntilVisible, twoFingerSwipe } from './recipes.js';
11
+ export type { SwipeUntilOptions } from './recipes.js';
12
+ /**
13
+ * What Chrome's and Safari's pages have in common. A script whose page is typed like this runs on
14
+ * both: an emulated or real Android phone through Playwright, and Safari in an iPhone simulator.
15
+ */
16
+ export interface SharedPage {
17
+ goto(url: string): Promise<unknown>;
18
+ evaluate<T>(pageFunction: () => T | Promise<T>): Promise<T>;
19
+ /** A script given as text, for code that must be the same in every browser. */
20
+ evaluate<T>(script: string): Promise<T>;
21
+ locator(selector: string): Locator | IosLocator;
22
+ }
23
+ /** Anything a stroke can go across: a page or an element, in either browser. */
24
+ type Surface = Page | Locator | IosPage | IosLocator | SharedPage;
25
+ /** A page given alongside a bare point, to say which page the point is on. */
26
+ type AnyPage = Page | IosPage | SharedPage;
27
+ /**
28
+ * A hard flick: the finger is still moving at full speed when it lifts, so the content keeps
29
+ * scrolling on its own momentum, as it does under a thumb.
30
+ */
31
+ export declare function fling(target: Surface, options: StrokeOptions | DirectedOptions): Promise<void>;
32
+ /**
33
+ * A controlled swipe: the finger slows to a stop before it lifts, so the content moves by the
34
+ * length of the stroke and no further.
35
+ */
36
+ export declare function swipe(target: Surface, options: StrokeOptions | DirectedOptions): Promise<void>;
37
+ /**
38
+ * A quick touch that the browser turns into a click. Playwright's own `tap` needs a context created
39
+ * with `hasTouch`, which the browser on a real phone is not; this one works in both.
40
+ */
41
+ export declare function tap(target: Target | IosLocator, options?: {
42
+ page?: AnyPage;
43
+ }): Promise<void>;
44
+ /**
45
+ * Two quick taps on the same place, which browsers report as a `dblclick` and some pages answer by
46
+ * zooming in.
47
+ */
48
+ export declare function doubleTap(target: Target | IosLocator, options?: {
49
+ page?: AnyPage;
50
+ }): Promise<void>;
51
+ /** Rests one finger on the target without moving, long enough for a long-press menu or a pick-up. */
52
+ export declare function longPress(target: Target | IosLocator, options?: {
53
+ duration?: number;
54
+ page?: AnyPage;
55
+ }): Promise<void>;
56
+ /**
57
+ * Carries the source to the destination under one finger and lets go at a standstill. With `hold`,
58
+ * the finger rests first, for lists that pick an item up on a long press.
59
+ */
60
+ export declare function drag(source: Target | IosLocator, destination: Target | IosLocator, options?: DragOptions & {
61
+ page?: AnyPage;
62
+ }): Promise<void>;
63
+ /**
64
+ * Two fingers spreading (scale above 1) or closing (below 1).
65
+ *
66
+ * On a page, the browser zooms by `scale`, where the page allows zooming. On an element, two
67
+ * fingers travel around its centre, for maps and canvases that read the touches themselves.
68
+ */
69
+ export declare function pinch(target: Surface, options: PinchOptions): Promise<void>;
70
+ /**
71
+ * Two fingers turning around the middle of an element, for maps and pictures that follow the
72
+ * angle between the touches. Positive degrees turn clockwise.
73
+ */
74
+ export declare function rotate(target: Locator | IosLocator, options: RotateOptions): Promise<void>;
75
+ /**
76
+ * Any gesture, finger by finger: each finger lands on its first point, passes through the others
77
+ * at an even pace and lifts on the last. For what the named gestures do not cover, a signature or
78
+ * a drawing.
79
+ */
80
+ export declare function gesture(page: AnyPage, options: GestureOptions): Promise<void>;
81
+ /**
82
+ * Draws a dot under every finger from now on, also on the pages gone to later. The dots follow the
83
+ * touches the page really gets, so they show in a film and tell where a gesture landed.
84
+ */
85
+ export declare function showTouches(page: AnyPage): Promise<void>;
86
+ export { connectAndroid, type AndroidPhone } from './android.js';
87
+ export type { Film, Frame, Vitals } from './measure.js';
88
+ export { longestPauseOf } from './measure.js';
89
+ /**
90
+ * Starts collecting metrics on the page. Call it before the navigation that should be measured,
91
+ * then read at any time. In Safari the collector can start late, so the order does not matter.
92
+ */
93
+ export declare function watchVitals(page: MeasuredPage | IosPage | SharedPage): Promise<{
94
+ read(): Promise<Vitals>;
95
+ }>;
96
+ /**
97
+ * Opens the address the way a first-time visitor gets it, without the HTTP cache, and returns the
98
+ * metrics. Nothing is deleted, so on a real phone the owner's cache, cookies and sign-ins stay.
99
+ */
100
+ export declare function coldLoad(page: MeasuredPage | IosPage | SharedPage, url: string, options?: {
101
+ settle?: number;
102
+ timeout?: number;
103
+ }): Promise<Vitals>;
104
+ /** Records what the screen shows while `action` runs, and for `settle` milliseconds after. */
105
+ export declare function film(page: MeasuredPage | IosPage | SharedPage, action: () => Promise<unknown>, options?: {
106
+ settle?: number;
107
+ }): Promise<Film>;
108
+ export { rate, writeComparison, writeReport, type Comparison, type Rating, type Report, type Run } from './report.js';
109
+ export { connectSimulator, type IosLocator, type IosPage, type IosSimulator } from './ios/simulator.js';
110
+ export { connectIphone, type IosPhone } from './ios/iphone.js';
111
+ export { findOverflow, findSmallTargets, type Overflow, type SmallTarget } from './layout.js';