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.
- package/LICENSE +21 -0
- package/README.md +612 -2
- package/dist/android.d.ts +26 -0
- package/dist/android.js +113 -0
- package/dist/chromium/clock.d.ts +12 -0
- package/dist/chromium/clock.js +45 -0
- package/dist/chromium/gestures.d.ts +56 -0
- package/dist/chromium/gestures.js +500 -0
- package/dist/chromium/steady.d.ts +16 -0
- package/dist/chromium/steady.js +38 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +459 -0
- package/dist/index.d.ts +111 -0
- package/dist/index.js +149 -0
- package/dist/ios/bplist.d.ts +8 -0
- package/dist/ios/bplist.js +150 -0
- package/dist/ios/device.d.ts +30 -0
- package/dist/ios/device.js +48 -0
- package/dist/ios/inspector.d.ts +61 -0
- package/dist/ios/inspector.js +342 -0
- package/dist/ios/iphone.d.ts +27 -0
- package/dist/ios/iphone.js +141 -0
- package/dist/ios/page.d.ts +90 -0
- package/dist/ios/page.js +338 -0
- package/dist/ios/paths.d.ts +17 -0
- package/dist/ios/paths.js +77 -0
- package/dist/ios/simulator.d.ts +24 -0
- package/dist/ios/simulator.js +69 -0
- package/dist/ios/tab.d.ts +41 -0
- package/dist/ios/tab.js +171 -0
- package/dist/ios/tools.d.ts +4 -0
- package/dist/ios/tools.js +17 -0
- package/dist/ios/touch.d.ts +31 -0
- package/dist/ios/touch.js +178 -0
- package/dist/ios/usbmux.d.ts +34 -0
- package/dist/ios/usbmux.js +346 -0
- package/dist/layout.d.ts +35 -0
- package/dist/layout.js +164 -0
- package/dist/measure.d.ts +86 -0
- package/dist/measure.js +173 -0
- package/dist/own-tabs.d.ts +8 -0
- package/dist/own-tabs.js +242 -0
- package/dist/playwright-test.d.ts +66 -0
- package/dist/playwright-test.js +64 -0
- package/dist/polyline.d.ts +10 -0
- package/dist/polyline.js +38 -0
- package/dist/recipes.d.ts +57 -0
- package/dist/recipes.js +135 -0
- package/dist/report.d.ts +46 -0
- package/dist/report.js +118 -0
- package/dist/session.d.ts +35 -0
- package/dist/session.js +23 -0
- package/dist/show.d.ts +13 -0
- package/dist/show.js +51 -0
- package/dist/synthetic.d.ts +17 -0
- package/dist/synthetic.js +117 -0
- package/dist/types.d.ts +58 -0
- package/dist/types.js +2 -0
- package/package.json +83 -4
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
// A real iPhone on the cable. macOS runs a service, usbmuxd, that carries connections to the phone
|
|
2
|
+
// over USB. The phone's own front door, lockdown, hands out its services to a Mac the owner has
|
|
3
|
+
// trusted. Both speak property lists written as XML.
|
|
4
|
+
import { connect, createServer } from 'node:net';
|
|
5
|
+
import { connect as secureConnect } from 'node:tls';
|
|
6
|
+
import { decode } from './bplist.js';
|
|
7
|
+
const escaped = (text) => text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
8
|
+
const unescaped = (text) => text
|
|
9
|
+
.replace(/</g, '<')
|
|
10
|
+
.replace(/>/g, '>')
|
|
11
|
+
.replace(/"/g, '"')
|
|
12
|
+
.replace(/'/g, "'")
|
|
13
|
+
.replace(/&/g, '&');
|
|
14
|
+
function element(value) {
|
|
15
|
+
if (Buffer.isBuffer(value))
|
|
16
|
+
return `<data>${value.toString('base64')}</data>`;
|
|
17
|
+
if (typeof value === 'string')
|
|
18
|
+
return `<string>${escaped(value)}</string>`;
|
|
19
|
+
if (typeof value === 'number')
|
|
20
|
+
return Number.isInteger(value) ? `<integer>${value}</integer>` : `<real>${value}</real>`;
|
|
21
|
+
if (typeof value === 'boolean')
|
|
22
|
+
return value ? '<true/>' : '<false/>';
|
|
23
|
+
if (value === null)
|
|
24
|
+
return '<string></string>';
|
|
25
|
+
if (Array.isArray(value))
|
|
26
|
+
return `<array>${value.map(element).join('')}</array>`;
|
|
27
|
+
return `<dict>${Object.entries(value)
|
|
28
|
+
.map(([key, one]) => `<key>${escaped(key)}</key>${element(one)}`)
|
|
29
|
+
.join('')}</dict>`;
|
|
30
|
+
}
|
|
31
|
+
/** Writes a property list as XML. */
|
|
32
|
+
export function toXml(value) {
|
|
33
|
+
return Buffer.from(`<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0">${element(value)}</plist>\n`);
|
|
34
|
+
}
|
|
35
|
+
/** Reads a property list written as XML. Dates are kept as text. */
|
|
36
|
+
export function fromXml(text) {
|
|
37
|
+
const tags = /<(\/?)(dict|array|key|string|integer|real|data|date|true|false)\s*(\/?)>/g;
|
|
38
|
+
const early = () => new Error('playwright-touch: a property list from the iPhone ends too early.');
|
|
39
|
+
const next = () => {
|
|
40
|
+
const found = tags.exec(text);
|
|
41
|
+
if (!found)
|
|
42
|
+
throw early();
|
|
43
|
+
return found;
|
|
44
|
+
};
|
|
45
|
+
/** Where the closing tag starts. A missing one must not send the reader back to the beginning. */
|
|
46
|
+
const closing = (tag) => {
|
|
47
|
+
const end = text.indexOf(`</${tag}>`, tags.lastIndex);
|
|
48
|
+
if (end < 0)
|
|
49
|
+
throw early();
|
|
50
|
+
return end;
|
|
51
|
+
};
|
|
52
|
+
const value = (opening) => {
|
|
53
|
+
const tag = opening[2];
|
|
54
|
+
const empty = opening[3] === '/';
|
|
55
|
+
if (tag === 'true')
|
|
56
|
+
return true;
|
|
57
|
+
if (tag === 'false')
|
|
58
|
+
return false;
|
|
59
|
+
if (tag === 'dict') {
|
|
60
|
+
const dict = {};
|
|
61
|
+
if (empty)
|
|
62
|
+
return dict;
|
|
63
|
+
for (let key = next(); key[1] !== '/'; key = next()) {
|
|
64
|
+
if (key[2] !== 'key')
|
|
65
|
+
throw new Error('playwright-touch: a property list from the iPhone has a value where a key belongs.');
|
|
66
|
+
let name = '';
|
|
67
|
+
// A key may be written empty, as <key/>.
|
|
68
|
+
if (key[3] !== '/') {
|
|
69
|
+
const end = closing('key');
|
|
70
|
+
name = unescaped(text.slice(tags.lastIndex, end));
|
|
71
|
+
tags.lastIndex = end + '</key>'.length;
|
|
72
|
+
}
|
|
73
|
+
dict[name] = value(next());
|
|
74
|
+
}
|
|
75
|
+
return dict;
|
|
76
|
+
}
|
|
77
|
+
if (tag === 'array') {
|
|
78
|
+
const list = [];
|
|
79
|
+
if (empty)
|
|
80
|
+
return list;
|
|
81
|
+
for (let item = next(); !(item[1] === '/' && item[2] === 'array'); item = next())
|
|
82
|
+
list.push(value(item));
|
|
83
|
+
return list;
|
|
84
|
+
}
|
|
85
|
+
if (empty)
|
|
86
|
+
return tag === 'data' ? Buffer.alloc(0) : '';
|
|
87
|
+
const end = closing(tag);
|
|
88
|
+
const body = text.slice(tags.lastIndex, end);
|
|
89
|
+
tags.lastIndex = end + tag.length + 3;
|
|
90
|
+
if (tag === 'integer' || tag === 'real')
|
|
91
|
+
return Number(body);
|
|
92
|
+
if (tag === 'data')
|
|
93
|
+
return Buffer.from(body, 'base64');
|
|
94
|
+
return unescaped(body);
|
|
95
|
+
};
|
|
96
|
+
tags.lastIndex = Math.max(0, text.indexOf('<plist'));
|
|
97
|
+
return value(next());
|
|
98
|
+
}
|
|
99
|
+
const read = (bytes) => bytes.subarray(0, 6).toString('latin1') === 'bplist' ? decode(bytes) : fromXml(bytes.toString('utf8'));
|
|
100
|
+
/** Hands out exactly as many bytes as asked for, as they arrive. */
|
|
101
|
+
class Bytes {
|
|
102
|
+
#stream;
|
|
103
|
+
#pending = Buffer.alloc(0);
|
|
104
|
+
#ended = false;
|
|
105
|
+
#wake = null;
|
|
106
|
+
#onData = (chunk) => {
|
|
107
|
+
this.#pending = Buffer.concat([this.#pending, chunk]);
|
|
108
|
+
this.#wake?.();
|
|
109
|
+
};
|
|
110
|
+
#onEnd = () => {
|
|
111
|
+
this.#ended = true;
|
|
112
|
+
this.#wake?.();
|
|
113
|
+
};
|
|
114
|
+
constructor(stream) {
|
|
115
|
+
this.#stream = stream;
|
|
116
|
+
stream.on('data', this.#onData);
|
|
117
|
+
stream.on('close', this.#onEnd);
|
|
118
|
+
stream.on('error', this.#onEnd);
|
|
119
|
+
}
|
|
120
|
+
async take(count, timeout = 10_000) {
|
|
121
|
+
for (const deadline = Date.now() + timeout; this.#pending.length < count;) {
|
|
122
|
+
if (this.#ended)
|
|
123
|
+
throw new Error('playwright-touch: the connection to the iPhone was closed.');
|
|
124
|
+
if (Date.now() > deadline)
|
|
125
|
+
throw new Error('playwright-touch: the iPhone did not answer in time.');
|
|
126
|
+
await new Promise((resolve) => {
|
|
127
|
+
this.#wake = resolve;
|
|
128
|
+
setTimeout(resolve, 250);
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
const out = this.#pending.subarray(0, count);
|
|
132
|
+
this.#pending = this.#pending.subarray(count);
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
135
|
+
/** Stops reading, so that the stream can be handed to someone else. What was read ahead is given back. */
|
|
136
|
+
release() {
|
|
137
|
+
if (this.#pending.length)
|
|
138
|
+
this.#stream.unshift(this.#pending);
|
|
139
|
+
this.#pending = Buffer.alloc(0);
|
|
140
|
+
this.#stream.off('data', this.#onData);
|
|
141
|
+
this.#stream.off('close', this.#onEnd);
|
|
142
|
+
this.#stream.off('error', this.#onEnd);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
const MUX = '/var/run/usbmuxd';
|
|
146
|
+
/** One question to usbmuxd and its answer. The connection is left open for what follows. */
|
|
147
|
+
async function mux() {
|
|
148
|
+
const socket = connect(MUX);
|
|
149
|
+
await new Promise((resolve, reject) => {
|
|
150
|
+
socket.once('connect', resolve);
|
|
151
|
+
socket.once('error', () => reject(new Error('playwright-touch: could not reach usbmuxd, the macOS service that talks to iPhones.')));
|
|
152
|
+
});
|
|
153
|
+
const bytes = new Bytes(socket);
|
|
154
|
+
let tag = 0;
|
|
155
|
+
return {
|
|
156
|
+
socket,
|
|
157
|
+
bytes,
|
|
158
|
+
async ask(message) {
|
|
159
|
+
const body = toXml({ ClientVersionString: 'playwright-touch', ProgName: 'playwright-touch', ...message });
|
|
160
|
+
// Sixteen bytes go first: the whole length, the protocol version, the kind (8 is a property list) and a tag.
|
|
161
|
+
const head = Buffer.alloc(16);
|
|
162
|
+
head.writeUInt32LE(16 + body.length, 0);
|
|
163
|
+
head.writeUInt32LE(1, 4);
|
|
164
|
+
head.writeUInt32LE(8, 8);
|
|
165
|
+
head.writeUInt32LE(++tag, 12);
|
|
166
|
+
socket.write(Buffer.concat([head, body]));
|
|
167
|
+
const answer = await bytes.take(16);
|
|
168
|
+
return read(await bytes.take(answer.readUInt32LE(0) - 16));
|
|
169
|
+
},
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
/** The iPhones connected by cable. */
|
|
173
|
+
export async function iphones() {
|
|
174
|
+
const { socket, ask } = await mux();
|
|
175
|
+
try {
|
|
176
|
+
const listed = ((await ask({ MessageType: 'ListDevices' })).DeviceList ?? []);
|
|
177
|
+
return listed
|
|
178
|
+
.map((one) => ({ id: Number(one.DeviceID), properties: (one.Properties ?? {}) }))
|
|
179
|
+
.filter((one) => one.properties.ConnectionType === 'USB')
|
|
180
|
+
.map((one) => ({ udid: String(one.properties.SerialNumber), id: one.id }));
|
|
181
|
+
}
|
|
182
|
+
finally {
|
|
183
|
+
socket.destroy();
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
/** A connection to a port on the phone, carried over the cable. */
|
|
187
|
+
export async function tunnel(phone, port) {
|
|
188
|
+
const { socket, bytes, ask } = await mux();
|
|
189
|
+
let answer;
|
|
190
|
+
try {
|
|
191
|
+
// usbmuxd wants the port with its two bytes swapped.
|
|
192
|
+
answer = await ask({
|
|
193
|
+
MessageType: 'Connect',
|
|
194
|
+
DeviceID: phone.id,
|
|
195
|
+
PortNumber: ((port & 0xff) << 8) | (port >> 8),
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
catch (error) {
|
|
199
|
+
socket.destroy();
|
|
200
|
+
throw error;
|
|
201
|
+
}
|
|
202
|
+
if (answer.Number !== 0) {
|
|
203
|
+
socket.destroy();
|
|
204
|
+
// usbmuxd answers 2 when the device is gone and 3 when nothing listens on the port.
|
|
205
|
+
throw new Error(answer.Number === 2
|
|
206
|
+
? 'playwright-touch: the iPhone is no longer on the cable.'
|
|
207
|
+
: `playwright-touch: nothing answers on port ${port} of the iPhone.`);
|
|
208
|
+
}
|
|
209
|
+
bytes.release();
|
|
210
|
+
return socket;
|
|
211
|
+
}
|
|
212
|
+
/** Offers a port of the phone on this computer. Returns the local port and a way to stop. */
|
|
213
|
+
export async function forward(phone, port) {
|
|
214
|
+
const open = new Set();
|
|
215
|
+
let closed = false;
|
|
216
|
+
const server = createServer((local) => {
|
|
217
|
+
open.add(local);
|
|
218
|
+
local.on('close', () => open.delete(local));
|
|
219
|
+
local.on('error', () => local.destroy());
|
|
220
|
+
tunnel(phone, port).then((remote) => {
|
|
221
|
+
// The local side may have gone, or everything been closed, while the tunnel was being made.
|
|
222
|
+
if (closed || local.destroyed)
|
|
223
|
+
return void remote.destroy();
|
|
224
|
+
open.add(remote);
|
|
225
|
+
remote.on('close', () => (open.delete(remote), local.destroy()));
|
|
226
|
+
remote.on('error', () => remote.destroy());
|
|
227
|
+
local.on('close', () => remote.destroy());
|
|
228
|
+
local.pipe(remote).pipe(local);
|
|
229
|
+
}, () => local.destroy());
|
|
230
|
+
});
|
|
231
|
+
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
232
|
+
// A script that forgets to disconnect is not kept alive by the open port.
|
|
233
|
+
server.unref();
|
|
234
|
+
return {
|
|
235
|
+
port: server.address().port,
|
|
236
|
+
close() {
|
|
237
|
+
closed = true;
|
|
238
|
+
server.close();
|
|
239
|
+
for (const socket of open)
|
|
240
|
+
socket.destroy();
|
|
241
|
+
},
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Opens a session with the phone's lockdown service, as the Mac the owner trusted. The proof is
|
|
246
|
+
* the pairing record macOS keeps for the phone, which usbmuxd hands over.
|
|
247
|
+
*/
|
|
248
|
+
export async function lockdown(phone) {
|
|
249
|
+
const asked = await mux();
|
|
250
|
+
let record;
|
|
251
|
+
try {
|
|
252
|
+
const answer = await asked.ask({ MessageType: 'ReadPairRecord', PairRecordID: phone.udid });
|
|
253
|
+
if (!Buffer.isBuffer(answer.PairRecordData)) {
|
|
254
|
+
throw new Error('playwright-touch: this Mac has never been paired with the iPhone. Unlock the phone, open it in Finder and choose Trust.');
|
|
255
|
+
}
|
|
256
|
+
record = read(answer.PairRecordData);
|
|
257
|
+
}
|
|
258
|
+
finally {
|
|
259
|
+
asked.socket.destroy();
|
|
260
|
+
}
|
|
261
|
+
// The phone asks for a certificate from the pairing record. Phones sign theirs in ways newer
|
|
262
|
+
// TLS libraries call too weak, hence the lowered security level; the phone is on a cable.
|
|
263
|
+
const secured = (plain) => new Promise((resolve, reject) => {
|
|
264
|
+
const secure = secureConnect({
|
|
265
|
+
socket: plain,
|
|
266
|
+
cert: record.HostCertificate,
|
|
267
|
+
key: record.HostPrivateKey,
|
|
268
|
+
rejectUnauthorized: false,
|
|
269
|
+
ciphers: 'DEFAULT@SECLEVEL=0',
|
|
270
|
+
}, () => resolve(secure));
|
|
271
|
+
// A phone that takes the connection and then says nothing would otherwise be waited for forever.
|
|
272
|
+
const patience = setTimeout(() => {
|
|
273
|
+
plain.destroy();
|
|
274
|
+
reject(new Error('playwright-touch: the iPhone did not finish the encrypted connection in time.'));
|
|
275
|
+
}, 10_000);
|
|
276
|
+
secure.once('secureConnect', () => clearTimeout(patience));
|
|
277
|
+
secure.once('error', () => {
|
|
278
|
+
clearTimeout(patience);
|
|
279
|
+
reject(new Error('playwright-touch: the iPhone refused the encrypted connection.'));
|
|
280
|
+
});
|
|
281
|
+
});
|
|
282
|
+
let stream = await tunnel(phone, 62078);
|
|
283
|
+
let bytes = new Bytes(stream);
|
|
284
|
+
const ask = async (message) => {
|
|
285
|
+
const body = toXml({ Label: 'playwright-touch', ...message });
|
|
286
|
+
const head = Buffer.alloc(4);
|
|
287
|
+
head.writeUInt32BE(body.length);
|
|
288
|
+
stream.write(Buffer.concat([head, body]));
|
|
289
|
+
return read(await bytes.take((await bytes.take(4)).readUInt32BE(0)));
|
|
290
|
+
};
|
|
291
|
+
const close = () => stream.destroy();
|
|
292
|
+
try {
|
|
293
|
+
const begin = () => ask({ Request: 'StartSession', HostID: record.HostID, SystemBUID: record.SystemBUID });
|
|
294
|
+
let session = await begin();
|
|
295
|
+
if (session.Error === 'InvalidHostID') {
|
|
296
|
+
// The phone no longer knows this Mac. Asking it to pair with the record the Mac already has
|
|
297
|
+
// puts the Trust question on its screen, or completes a pairing its owner has just allowed.
|
|
298
|
+
const paired = await ask({
|
|
299
|
+
Request: 'Pair',
|
|
300
|
+
PairRecord: {
|
|
301
|
+
DeviceCertificate: record.DeviceCertificate,
|
|
302
|
+
HostCertificate: record.HostCertificate,
|
|
303
|
+
HostID: record.HostID,
|
|
304
|
+
RootCertificate: record.RootCertificate,
|
|
305
|
+
SystemBUID: record.SystemBUID,
|
|
306
|
+
},
|
|
307
|
+
PairingOptions: { ExtendedPairingErrors: true },
|
|
308
|
+
ProtocolVersion: '2',
|
|
309
|
+
}).catch(() => ({ Error: 'no answer' }));
|
|
310
|
+
if (paired.Error) {
|
|
311
|
+
throw new Error(paired.Error === 'PasswordProtected'
|
|
312
|
+
? 'playwright-touch: the iPhone does not trust this Mac and is locked. Unlock it, choose Trust on its screen and try again.'
|
|
313
|
+
: 'playwright-touch: the iPhone does not trust this Mac. Choose Trust on its screen and try again.');
|
|
314
|
+
}
|
|
315
|
+
session = await begin();
|
|
316
|
+
}
|
|
317
|
+
if (session.Error === 'PasswordProtected')
|
|
318
|
+
throw new Error('playwright-touch: the iPhone is locked. Unlock it and try again.');
|
|
319
|
+
if (session.Error)
|
|
320
|
+
throw new Error(`playwright-touch: the iPhone refused the session: ${String(session.Error)}`);
|
|
321
|
+
if (session.EnableSessionSSL) {
|
|
322
|
+
bytes.release();
|
|
323
|
+
stream = await secured(stream);
|
|
324
|
+
bytes = new Bytes(stream);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
catch (error) {
|
|
328
|
+
close();
|
|
329
|
+
throw error;
|
|
330
|
+
}
|
|
331
|
+
return {
|
|
332
|
+
async value(key) {
|
|
333
|
+
return (await ask({ Request: 'GetValue', Key: key })).Value ?? null;
|
|
334
|
+
},
|
|
335
|
+
async service(name) {
|
|
336
|
+
const started = await ask({ Request: 'StartService', Service: name });
|
|
337
|
+
if (started.Error === 'PasswordProtected')
|
|
338
|
+
throw new Error('playwright-touch: the iPhone is locked. Unlock it and try again.');
|
|
339
|
+
if (typeof started.Port !== 'number')
|
|
340
|
+
throw new Error(`playwright-touch: the iPhone did not start ${name}: ${String(started.Error ?? 'no reason given')}`);
|
|
341
|
+
const plain = await tunnel(phone, started.Port);
|
|
342
|
+
return started.EnableServiceSSL ? secured(plain) : plain;
|
|
343
|
+
},
|
|
344
|
+
close,
|
|
345
|
+
};
|
|
346
|
+
}
|
package/dist/layout.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { SharedPage } from './index.js';
|
|
2
|
+
/** An element that sticks out of the page sideways. */
|
|
3
|
+
export interface Overflow {
|
|
4
|
+
/** A short description of the element: its tag, id and classes. */
|
|
5
|
+
element: string;
|
|
6
|
+
/** How far past the right edge of the viewport it reaches, in CSS pixels. Negative values reach past the left edge. */
|
|
7
|
+
by: number;
|
|
8
|
+
/** Its own width, in CSS pixels. */
|
|
9
|
+
width: number;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Finds what makes the page wider than the screen, the cause of sideways scrolling on a phone.
|
|
13
|
+
* Returns nothing when the page fits. Content inside its own scrolling or clipping box, like a
|
|
14
|
+
* carousel, is not counted: it does not widen the page.
|
|
15
|
+
*/
|
|
16
|
+
export declare function findOverflow(page: SharedPage): Promise<Overflow[]>;
|
|
17
|
+
/** Something to tap that is too small for a finger, with too little room around it. */
|
|
18
|
+
export interface SmallTarget {
|
|
19
|
+
/** A short description of the element: its tag, id and classes. */
|
|
20
|
+
element: string;
|
|
21
|
+
/** What it says, or how it is labelled, as far as the first forty characters. */
|
|
22
|
+
text: string;
|
|
23
|
+
/** Its size in CSS pixels, with its label where a checkbox or a radio button has one. */
|
|
24
|
+
width: number;
|
|
25
|
+
height: number;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Finds the links, buttons and form controls that are too small to hit with a finger. The measure
|
|
29
|
+
* is the one in WCAG 2.2 (target size, minimum): 24 CSS pixels either way, and a smaller target
|
|
30
|
+
* passes when it has that much room to itself. Links inside a sentence are left out. Pass `min: 44`
|
|
31
|
+
* for the size Apple recommends, or 48 for Google's.
|
|
32
|
+
*/
|
|
33
|
+
export declare function findSmallTargets(page: SharedPage, options?: {
|
|
34
|
+
min?: number;
|
|
35
|
+
}): Promise<SmallTarget[]>;
|
package/dist/layout.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Finds what makes the page wider than the screen, the cause of sideways scrolling on a phone.
|
|
3
|
+
* Returns nothing when the page fits. Content inside its own scrolling or clipping box, like a
|
|
4
|
+
* carousel, is not counted: it does not widen the page.
|
|
5
|
+
*/
|
|
6
|
+
export async function findOverflow(page) {
|
|
7
|
+
return page.evaluate(() => {
|
|
8
|
+
const viewport = document.documentElement.clientWidth;
|
|
9
|
+
if (document.documentElement.scrollWidth <= viewport + 1)
|
|
10
|
+
return [];
|
|
11
|
+
const clipped = (element) => {
|
|
12
|
+
for (let parent = element.parentElement; parent && parent !== document.documentElement; parent = parent.parentElement) {
|
|
13
|
+
if (parent === document.body)
|
|
14
|
+
continue;
|
|
15
|
+
const style = getComputedStyle(parent);
|
|
16
|
+
if (style.overflowX !== 'visible') {
|
|
17
|
+
const box = parent.getBoundingClientRect();
|
|
18
|
+
if (box.right <= viewport + 1 && box.left >= -1)
|
|
19
|
+
return true;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return false;
|
|
23
|
+
};
|
|
24
|
+
const found = [];
|
|
25
|
+
for (const element of Array.from(document.body.querySelectorAll('*'))) {
|
|
26
|
+
const box = element.getBoundingClientRect();
|
|
27
|
+
if (box.width === 0 || box.height === 0)
|
|
28
|
+
continue;
|
|
29
|
+
const style = getComputedStyle(element);
|
|
30
|
+
if (style.position === 'fixed' && (box.right <= 0 || box.left >= viewport))
|
|
31
|
+
continue;
|
|
32
|
+
// Text that cannot wrap spills out of a box that itself fits; the box then holds more than it is wide.
|
|
33
|
+
const spill = style.overflowX === 'visible' ? Math.max(0, box.left + element.scrollWidth - viewport) : 0;
|
|
34
|
+
const past = box.right > viewport + 1
|
|
35
|
+
? box.right - viewport
|
|
36
|
+
: box.left + scrollX < -1
|
|
37
|
+
? box.left + scrollX
|
|
38
|
+
: spill > 1 && element.scrollWidth > element.clientWidth + 1
|
|
39
|
+
? spill
|
|
40
|
+
: 0;
|
|
41
|
+
if (!past || clipped(element))
|
|
42
|
+
continue;
|
|
43
|
+
const classes = typeof element.className === 'string' && element.className.trim()
|
|
44
|
+
? '.' + element.className.trim().split(/\s+/).slice(0, 3).join('.')
|
|
45
|
+
: '';
|
|
46
|
+
found.push({
|
|
47
|
+
element: element.tagName.toLowerCase() + (element.id ? '#' + element.id : '') + classes,
|
|
48
|
+
by: Math.round(past),
|
|
49
|
+
width: Math.round(box.width),
|
|
50
|
+
node: element,
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
// The outermost offenders say enough; what is inside them sticks out for the same reason.
|
|
54
|
+
// A spill is reported at the innermost box that holds it; a box that is too wide, at the outermost.
|
|
55
|
+
const spilling = (one) => one.node.getBoundingClientRect().right <= viewport + 1;
|
|
56
|
+
return found
|
|
57
|
+
.filter((one) => spilling(one)
|
|
58
|
+
? !found.some((other) => other !== one && one.node.contains(other.node))
|
|
59
|
+
: !found.some((other) => other !== one && !spilling(other) && other.node.contains(one.node)))
|
|
60
|
+
.map(({ element, by, width }) => ({ element, by, width }));
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/** Runs in the page. Kept free of anything from outside, because it travels there as text. */
|
|
64
|
+
function smallTargets(min) {
|
|
65
|
+
const SELECTOR = 'a[href], button, input:not([type="hidden"]), select, textarea, summary, [onclick], [role="button"], [role="link"], [role="checkbox"], [role="radio"], [role="switch"], [role="tab"], [role="menuitem"]';
|
|
66
|
+
const shown = (element) => {
|
|
67
|
+
const style = getComputedStyle(element);
|
|
68
|
+
if (style.visibility !== 'visible' || style.pointerEvents === 'none')
|
|
69
|
+
return false;
|
|
70
|
+
if (element.disabled)
|
|
71
|
+
return false;
|
|
72
|
+
const box = element.getBoundingClientRect();
|
|
73
|
+
// One pixel or less is how text meant only for screen readers is hidden.
|
|
74
|
+
return box.width > 1 && box.height > 1;
|
|
75
|
+
};
|
|
76
|
+
const all = Array.from(document.querySelectorAll(SELECTOR)).filter(shown);
|
|
77
|
+
// A button inside a link is one thing to tap, the outer one. A plain box that listens for
|
|
78
|
+
// clicks is the other way round: what is inside it is what gets tapped, and the box, a card
|
|
79
|
+
// or the whole page, is left out.
|
|
80
|
+
const control = (element) => element.matches('a[href], button, input, select, textarea, summary, [role]');
|
|
81
|
+
const targets = all.filter((one) => {
|
|
82
|
+
if (!control(one) && all.some((other) => other !== one && one.contains(other)))
|
|
83
|
+
return false;
|
|
84
|
+
return !all.some((other) => other !== one && control(other) && other.contains(one));
|
|
85
|
+
});
|
|
86
|
+
const boxOf = (element) => {
|
|
87
|
+
const own = element.getBoundingClientRect();
|
|
88
|
+
const box = { left: own.left, top: own.top, right: own.right, bottom: own.bottom };
|
|
89
|
+
// A checkbox is also ticked by tapping its label, so the two count together.
|
|
90
|
+
const labels = element.labels;
|
|
91
|
+
for (const label of labels ? Array.from(labels) : []) {
|
|
92
|
+
const more = label.getBoundingClientRect();
|
|
93
|
+
if (more.width === 0)
|
|
94
|
+
continue;
|
|
95
|
+
box.left = Math.min(box.left, more.left);
|
|
96
|
+
box.top = Math.min(box.top, more.top);
|
|
97
|
+
box.right = Math.max(box.right, more.right);
|
|
98
|
+
box.bottom = Math.max(box.bottom, more.bottom);
|
|
99
|
+
}
|
|
100
|
+
return box;
|
|
101
|
+
};
|
|
102
|
+
// A link in the middle of a sentence is as tall as the line, and nobody can make it taller. The
|
|
103
|
+
// sentence is whatever block the link sits in, also when the link is wrapped, as a footnote
|
|
104
|
+
// mark is in its raised brackets.
|
|
105
|
+
const inSentence = (element) => {
|
|
106
|
+
if (element.tagName !== 'A' || !getComputedStyle(element).display.startsWith('inline'))
|
|
107
|
+
return false;
|
|
108
|
+
let block = element.parentElement;
|
|
109
|
+
while (block && getComputedStyle(block).display.startsWith('inline'))
|
|
110
|
+
block = block.parentElement;
|
|
111
|
+
if (!block)
|
|
112
|
+
return false;
|
|
113
|
+
// Only words that are not links themselves make a sentence; a row of links is a menu.
|
|
114
|
+
const linked = Array.from(block.querySelectorAll('a')).reduce((sum, link) => sum + (link.textContent ?? '').trim().length, 0);
|
|
115
|
+
return ((block.textContent ?? '').replace(/\s+/g, ' ').trim().length - linked > 8 + block.querySelectorAll('a').length);
|
|
116
|
+
};
|
|
117
|
+
const boxes = targets.map(boxOf);
|
|
118
|
+
const small = boxes.map((box) => Math.min(box.right - box.left, box.bottom - box.top) < min - 0.5);
|
|
119
|
+
const middle = (box) => ({ x: (box.left + box.right) / 2, y: (box.top + box.bottom) / 2 });
|
|
120
|
+
const away = (point, box) => Math.hypot(Math.max(box.left - point.x, 0, point.x - box.right), Math.max(box.top - point.y, 0, point.y - box.bottom));
|
|
121
|
+
const found = [];
|
|
122
|
+
targets.forEach((element, index) => {
|
|
123
|
+
if (!small[index] || inSentence(element))
|
|
124
|
+
return;
|
|
125
|
+
const centre = middle(boxes[index]);
|
|
126
|
+
// A small target with room around it is fine: a circle of the wanted size on its middle must
|
|
127
|
+
// not reach another target, nor the circle of another small one.
|
|
128
|
+
const crowded = boxes.some((other, at) => {
|
|
129
|
+
if (at === index)
|
|
130
|
+
return false;
|
|
131
|
+
if (away(centre, other) < min / 2)
|
|
132
|
+
return true;
|
|
133
|
+
const there = middle(other);
|
|
134
|
+
return small[at] && Math.hypot(there.x - centre.x, there.y - centre.y) < min;
|
|
135
|
+
});
|
|
136
|
+
if (!crowded)
|
|
137
|
+
return;
|
|
138
|
+
const classes = typeof element.className === 'string' && element.className.trim()
|
|
139
|
+
? '.' + element.className.trim().split(/\s+/).slice(0, 3).join('.')
|
|
140
|
+
: '';
|
|
141
|
+
const said = element.getAttribute('aria-label') ||
|
|
142
|
+
element.innerText ||
|
|
143
|
+
element.value ||
|
|
144
|
+
element.getAttribute('title') ||
|
|
145
|
+
element.querySelector('img')?.getAttribute('alt') ||
|
|
146
|
+
'';
|
|
147
|
+
found.push({
|
|
148
|
+
element: element.tagName.toLowerCase() + (element.id ? '#' + element.id : '') + classes,
|
|
149
|
+
text: said.trim().replace(/\s+/g, ' ').slice(0, 40),
|
|
150
|
+
width: Math.round(boxes[index].right - boxes[index].left),
|
|
151
|
+
height: Math.round(boxes[index].bottom - boxes[index].top),
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
return found.sort((a, b) => Math.min(a.width, a.height) - Math.min(b.width, b.height));
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Finds the links, buttons and form controls that are too small to hit with a finger. The measure
|
|
158
|
+
* is the one in WCAG 2.2 (target size, minimum): 24 CSS pixels either way, and a smaller target
|
|
159
|
+
* passes when it has that much room to itself. Links inside a sentence are left out. Pass `min: 44`
|
|
160
|
+
* for the size Apple recommends, or 48 for Google's.
|
|
161
|
+
*/
|
|
162
|
+
export async function findSmallTargets(page, options = {}) {
|
|
163
|
+
return page.evaluate(`(${smallTargets})(${Number(options.min ?? 24)})`);
|
|
164
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { type Page } from './session.js';
|
|
2
|
+
/** What a page that can be measured adds to the gestures' page. Any Playwright `Page` fits. */
|
|
3
|
+
export interface MeasuredPage extends Page {
|
|
4
|
+
addInitScript(script: {
|
|
5
|
+
content: string;
|
|
6
|
+
}): Promise<unknown>;
|
|
7
|
+
goto(url: string, options?: {
|
|
8
|
+
waitUntil?: 'load' | 'domcontentloaded' | 'networkidle' | 'commit';
|
|
9
|
+
timeout?: number;
|
|
10
|
+
}): Promise<unknown>;
|
|
11
|
+
waitForTimeout(ms: number): Promise<void>;
|
|
12
|
+
}
|
|
13
|
+
/** Field-style metrics read in the page itself, in milliseconds unless said otherwise. A metric the page has not produced is null. */
|
|
14
|
+
export interface Vitals {
|
|
15
|
+
/** Time to first byte of the document. */
|
|
16
|
+
ttfb: number | null;
|
|
17
|
+
/** First contentful paint. */
|
|
18
|
+
fcp: number | null;
|
|
19
|
+
/** Largest contentful paint so far. */
|
|
20
|
+
lcp: number | null;
|
|
21
|
+
/** Cumulative layout shift: the worst burst of shifts, as a unitless score. Null where the browser does not report shifts, as in Safari. */
|
|
22
|
+
cls: number | null;
|
|
23
|
+
/** The slowest interaction so far, from input to the next paint. With few interactions this is the page's INP. Null with `interactions` above zero means every one was answered in under 16 ms, too fast for the browser to list. */
|
|
24
|
+
inp: number | null;
|
|
25
|
+
/** How many interactions were seen. */
|
|
26
|
+
interactions: number;
|
|
27
|
+
/** Main-thread tasks longer than 50 ms. Null where the browser does not report them, as in Safari. */
|
|
28
|
+
longTasks: number | null;
|
|
29
|
+
/** Time those tasks spent over 50 ms, summed. */
|
|
30
|
+
blocked: number | null;
|
|
31
|
+
}
|
|
32
|
+
export declare const COLLECTOR = "(() => {\n if (window.__playwrightTouchVitals) return;\n const can = (type) => (PerformanceObserver.supportedEntryTypes || []).includes(type);\n const v = (window.__playwrightTouchVitals = { fcp: null, lcp: null, cls: can('layout-shift') ? 0 : null, longTasks: can('longtask') ? 0 : null, blocked: can('longtask') ? 0 : null, slow: {} });\n const watch = (type, each, extra) => {\n try { new PerformanceObserver((list) => list.getEntries().forEach(each)).observe(Object.assign({ type, buffered: true }, extra)); } catch (_) {}\n };\n watch('paint', (e) => { if (e.name === 'first-contentful-paint') v.fcp = e.startTime; });\n watch('largest-contentful-paint', (e) => { v.lcp = e.startTime; });\n // Shifts are counted in bursts: a burst ends after a second of calm or five seconds in all, and\n // the score is the worst burst. Shifts right after input are the user's own doing and are left out.\n let burst = 0, first = 0, last = 0;\n watch('layout-shift', (e) => {\n if (e.hadRecentInput) return;\n if (burst && e.startTime - last < 1000 && e.startTime - first < 5000) burst += e.value;\n else { burst = e.value; first = e.startTime; }\n last = e.startTime;\n if (burst > v.cls) v.cls = burst;\n });\n // Safari gives a click no interaction of its own, so a slow click handler would go unseen there;\n // such a click counts as an interaction by itself.\n watch('event', (e) => { const id = e.interactionId || (e.name === 'click' ? 'click' + Math.round(e.startTime) : 0); if (id) v.slow[id] = Math.max(v.slow[id] || 0, e.duration); }, { durationThreshold: 16 });\n watch('longtask', (e) => { v.longTasks++; v.blocked += e.duration - 50; });\n})();";
|
|
33
|
+
export declare const READ = "(() => {\n const v = window.__playwrightTouchVitals;\n if (!v) return null;\n const nav = performance.getEntriesByType('navigation')[0];\n const slow = Object.values(v.slow);\n // The browser's own count also includes touches answered too fast to be listed one by one.\n return { ttfb: nav ? nav.responseStart : null, fcp: v.fcp, lcp: v.lcp, cls: v.cls, inp: slow.length ? Math.max(...slow) : null, interactions: Math.max(slow.length, performance.interactionCount || 0), longTasks: v.longTasks, blocked: v.blocked };\n})()";
|
|
34
|
+
export declare const tidy: (vitals: Vitals) => Vitals;
|
|
35
|
+
/**
|
|
36
|
+
* Starts collecting metrics on the page and on every page it navigates to. Call it before the
|
|
37
|
+
* navigation that should be measured, then read at any time: after the load, after a gesture.
|
|
38
|
+
*/
|
|
39
|
+
export declare function watchVitals(page: MeasuredPage): Promise<{
|
|
40
|
+
read(): Promise<Vitals>;
|
|
41
|
+
}>;
|
|
42
|
+
/**
|
|
43
|
+
* Opens the address the way a first-time visitor gets it: nothing from the HTTP cache and no
|
|
44
|
+
* service worker in between. Nothing is deleted, so on a real phone the owner's cache, cookies and
|
|
45
|
+
* sign-ins stay as they were. Connections the browser already holds open may be reused.
|
|
46
|
+
*/
|
|
47
|
+
export declare function coldLoad(page: MeasuredPage, url: string, options?: {
|
|
48
|
+
settle?: number;
|
|
49
|
+
timeout?: number;
|
|
50
|
+
}): Promise<Vitals>;
|
|
51
|
+
/**
|
|
52
|
+
* The longest time between two pictures in a row while the page was moving. The wait before the
|
|
53
|
+
* motion starts is not a pause in it, and neither is what happens after the page has come to
|
|
54
|
+
* rest, such as a scroll bar fading out a third of a second later. `until` is when the page last
|
|
55
|
+
* scrolled, on the frames' clock; without it every frame after the first counts.
|
|
56
|
+
*/
|
|
57
|
+
export declare function longestPauseOf(frames: Frame[], until?: number | null): number;
|
|
58
|
+
/** Runs in the page: notes the wall-clock time of every scroll, of the document or of anything inside it. */
|
|
59
|
+
export declare const SCROLL_WATCH = "(() => {\n window.__playwrightTouchScrolled = null;\n window.__playwrightTouchTouched = false;\n if (window.__playwrightTouchScrollWatch) return;\n window.__playwrightTouchScrollWatch = true;\n // Bringing an element into view before a gesture scrolls the page as well. Only what scrolls\n // after the first touch, wheel turn, click or key belongs to the action.\n for (const type of ['touchstart', 'wheel', 'pointerdown', 'keydown']) addEventListener(type, () => { window.__playwrightTouchTouched = true; }, { capture: true, passive: true });\n addEventListener('scroll', () => { if (window.__playwrightTouchTouched) window.__playwrightTouchScrolled = performance.timeOrigin + performance.now(); }, { capture: true, passive: true });\n})()";
|
|
60
|
+
export declare const SCROLL_READ = "window.__playwrightTouchScrolled ?? null";
|
|
61
|
+
/** One picture of the screen from a film. */
|
|
62
|
+
export interface Frame {
|
|
63
|
+
/** Milliseconds since the recording started. */
|
|
64
|
+
at: number;
|
|
65
|
+
jpeg: Buffer;
|
|
66
|
+
}
|
|
67
|
+
/** What the screen showed while an action ran. */
|
|
68
|
+
export interface Film {
|
|
69
|
+
frames: Frame[];
|
|
70
|
+
/** How long the recording ran, in milliseconds. */
|
|
71
|
+
duration: number;
|
|
72
|
+
/** The longest time between two frames in a row while the page was moving, in milliseconds. */
|
|
73
|
+
longestPause: number;
|
|
74
|
+
/** For how long the page kept scrolling after the first touch, wheel turn, click or key, counted from the first frame, in milliseconds. Null when no such scrolling was seen: nothing scrolled, a script did the scrolling, or it happened inside a frame. `longestPause` then covers the whole film. */
|
|
75
|
+
scrolledFor: number | null;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Records what the screen shows while `action` runs, and for `settle` milliseconds after, so that
|
|
79
|
+
* momentum and late paints are in the picture. The browser sends a frame whenever the picture
|
|
80
|
+
* changes, each with the time it was drawn.
|
|
81
|
+
*/
|
|
82
|
+
export declare function film(page: MeasuredPage, action: () => Promise<unknown>, options?: {
|
|
83
|
+
settle?: number;
|
|
84
|
+
width?: number;
|
|
85
|
+
quality?: number;
|
|
86
|
+
}): Promise<Film>;
|