playwright-touch 0.0.0-stage → 0.1.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 +495 -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 +485 -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 +108 -0
- package/dist/index.js +147 -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/polyline.d.ts +10 -0
- package/dist/polyline.js +38 -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/types.d.ts +58 -0
- package/dist/types.js +2 -0
- package/package.json +68 -4
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
// A client for Safari's Web Inspector, the channel Safari's own developer tools use. It lists the
|
|
2
|
+
// pages open in Safari and runs commands on one of them. Unlike a WebDriver session it does not
|
|
3
|
+
// take the page over, so real touches still reach it.
|
|
4
|
+
import { connect } from 'node:net';
|
|
5
|
+
import { randomUUID } from 'node:crypto';
|
|
6
|
+
import { decode, encode } from './bplist.js';
|
|
7
|
+
/** Told to listeners in place of a message when the connection has ended. */
|
|
8
|
+
const CLOSED = '__closed';
|
|
9
|
+
/** A connection to Safari's Web Inspector in a simulator: it knows the open pages and opens command channels to them. */
|
|
10
|
+
export class WebInspector {
|
|
11
|
+
#socket;
|
|
12
|
+
#connection = randomUUID().toUpperCase();
|
|
13
|
+
#pending = Buffer.alloc(0);
|
|
14
|
+
#listeners = new Set();
|
|
15
|
+
#apps = new Set();
|
|
16
|
+
#bundles = new Map();
|
|
17
|
+
#pages = new Map();
|
|
18
|
+
constructor(socket) {
|
|
19
|
+
this.#socket = socket;
|
|
20
|
+
socket.on('data', (chunk) => {
|
|
21
|
+
this.#pending = Buffer.concat([this.#pending, chunk]);
|
|
22
|
+
// Each message is a four-byte length followed by a binary property list.
|
|
23
|
+
while (this.#pending.length >= 4 && this.#pending.length >= 4 + this.#pending.readUInt32BE(0)) {
|
|
24
|
+
const size = this.#pending.readUInt32BE(0);
|
|
25
|
+
const body = this.#pending.subarray(4, 4 + size);
|
|
26
|
+
this.#pending = this.#pending.subarray(4 + size);
|
|
27
|
+
try {
|
|
28
|
+
const message = decode(body);
|
|
29
|
+
this.#track(message.__selector, message.__argument ?? {});
|
|
30
|
+
for (const listener of [...this.#listeners])
|
|
31
|
+
listener(message.__selector, message.__argument ?? {});
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
// One message that cannot be read is skipped; the ones after it still count.
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
// When the simulator goes away, everyone waiting for an answer is told at once.
|
|
39
|
+
const gone = () => {
|
|
40
|
+
for (const listener of [...this.#listeners])
|
|
41
|
+
listener(CLOSED, {});
|
|
42
|
+
};
|
|
43
|
+
socket.on('close', gone);
|
|
44
|
+
socket.on('error', gone);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Connects to the inspector and introduces itself. A simulator offers its inspector as a socket
|
|
48
|
+
* at a path; for a real iPhone, `dial` makes the connection and `silent` says what to tell the
|
|
49
|
+
* user when the inspector does not answer, which on a phone means it is switched off.
|
|
50
|
+
*
|
|
51
|
+
* The simulator's inspector goes quiet for a while when a client that stayed only a few seconds
|
|
52
|
+
* leaves, and a connection made in that time is never answered. Such a connection is held until
|
|
53
|
+
* the quiet time has passed and then replaced, which takes about a quarter of a minute.
|
|
54
|
+
*/
|
|
55
|
+
static async open(dial, silent) {
|
|
56
|
+
const fromPath = async (path) => {
|
|
57
|
+
const socket = connect(path);
|
|
58
|
+
await new Promise((resolve, reject) => {
|
|
59
|
+
socket.once('connect', resolve);
|
|
60
|
+
socket.once('error', () => reject(new Error('playwright-touch: could not reach the Web Inspector of the simulator. Is it booted?')));
|
|
61
|
+
});
|
|
62
|
+
return socket;
|
|
63
|
+
};
|
|
64
|
+
const attempt = async (patience) => {
|
|
65
|
+
const socket = typeof dial === 'string' ? await fromPath(dial) : await dial();
|
|
66
|
+
const inspector = new WebInspector(socket);
|
|
67
|
+
let answered = false;
|
|
68
|
+
const stop = inspector.on(() => (answered = true));
|
|
69
|
+
inspector.send('_rpc_reportIdentifier:', {});
|
|
70
|
+
for (const deadline = Date.now() + patience; !answered && Date.now() < deadline;)
|
|
71
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
72
|
+
stop();
|
|
73
|
+
return { inspector, answered };
|
|
74
|
+
};
|
|
75
|
+
let tried = await attempt(silent ? 4000 : 1500);
|
|
76
|
+
for (let recovery = 0; !silent && !tried.answered && recovery < 2; recovery++) {
|
|
77
|
+
// Hold the unanswered connection through the quiet time, let go, and give the inspector a moment.
|
|
78
|
+
await new Promise((resolve) => setTimeout(resolve, 11_000));
|
|
79
|
+
await tried.inspector.close();
|
|
80
|
+
await new Promise((resolve) => setTimeout(resolve, 3000));
|
|
81
|
+
tried = await attempt(4000);
|
|
82
|
+
}
|
|
83
|
+
if (tried.answered)
|
|
84
|
+
return tried.inspector;
|
|
85
|
+
await tried.inspector.close();
|
|
86
|
+
throw new Error(silent ??
|
|
87
|
+
'playwright-touch: the Web Inspector of the simulator does not answer. Wait a quarter of a minute and try again.');
|
|
88
|
+
}
|
|
89
|
+
send(selector, argument) {
|
|
90
|
+
const body = encode({
|
|
91
|
+
__selector: selector,
|
|
92
|
+
__argument: { WIRConnectionIdentifierKey: this.#connection, ...argument },
|
|
93
|
+
});
|
|
94
|
+
const head = Buffer.alloc(4);
|
|
95
|
+
head.writeUInt32BE(body.length);
|
|
96
|
+
this.#socket.write(Buffer.concat([head, body]));
|
|
97
|
+
}
|
|
98
|
+
on(listener) {
|
|
99
|
+
this.#listeners.add(listener);
|
|
100
|
+
return () => this.#listeners.delete(listener);
|
|
101
|
+
}
|
|
102
|
+
/** Keeps the list of applications and their pages up to date from what the inspector announces. */
|
|
103
|
+
#track(selector, argument) {
|
|
104
|
+
const learn = (app, bundle) => {
|
|
105
|
+
if (typeof app !== 'string')
|
|
106
|
+
return;
|
|
107
|
+
if (typeof bundle === 'string')
|
|
108
|
+
this.#bundles.set(app, bundle);
|
|
109
|
+
if (this.#apps.has(app))
|
|
110
|
+
return;
|
|
111
|
+
this.#apps.add(app);
|
|
112
|
+
this.send('_rpc_forwardGetListing:', { WIRApplicationIdentifierKey: app });
|
|
113
|
+
};
|
|
114
|
+
if (selector === '_rpc_reportConnectedApplicationList:')
|
|
115
|
+
for (const app of Object.values((argument.WIRApplicationDictionaryKey ?? {})))
|
|
116
|
+
learn(app.WIRApplicationIdentifierKey, app.WIRApplicationBundleIdentifierKey);
|
|
117
|
+
if (selector === '_rpc_applicationConnected:' || selector === '_rpc_applicationUpdated:')
|
|
118
|
+
learn(argument.WIRApplicationIdentifierKey, argument.WIRApplicationBundleIdentifierKey);
|
|
119
|
+
if (selector === '_rpc_applicationDisconnected:') {
|
|
120
|
+
const app = String(argument.WIRApplicationIdentifierKey);
|
|
121
|
+
this.#apps.delete(app);
|
|
122
|
+
for (const key of [...this.#pages.keys()])
|
|
123
|
+
if (key.startsWith(app + '/'))
|
|
124
|
+
this.#pages.delete(key);
|
|
125
|
+
}
|
|
126
|
+
if (selector === '_rpc_applicationSentListing:') {
|
|
127
|
+
const app = String(argument.WIRApplicationIdentifierKey);
|
|
128
|
+
for (const key of [...this.#pages.keys()])
|
|
129
|
+
if (key.startsWith(app + '/'))
|
|
130
|
+
this.#pages.delete(key);
|
|
131
|
+
for (const page of Object.values((argument.WIRListingKey ?? {}))) {
|
|
132
|
+
if (page.WIRTypeKey !== 'WIRTypeWebPage' && page.WIRTypeKey !== 'WIRTypePage')
|
|
133
|
+
continue;
|
|
134
|
+
const id = Number(page.WIRPageIdentifierKey);
|
|
135
|
+
this.#pages.set(`${app}/${id}`, {
|
|
136
|
+
app,
|
|
137
|
+
bundle: this.#bundles.get(app) ?? '',
|
|
138
|
+
id,
|
|
139
|
+
title: String(page.WIRTitleKey ?? ''),
|
|
140
|
+
url: String(page.WIRURLKey ?? ''),
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/** Asks every known application for its pages again. */
|
|
146
|
+
refresh() {
|
|
147
|
+
this.send('_rpc_getConnectedApplications:', {});
|
|
148
|
+
for (const app of this.#apps)
|
|
149
|
+
this.send('_rpc_forwardGetListing:', { WIRApplicationIdentifierKey: app });
|
|
150
|
+
}
|
|
151
|
+
/** Whether an application with this bundle identifier has announced itself to the inspector. */
|
|
152
|
+
knows(bundle) {
|
|
153
|
+
return [...this.#bundles.values()].includes(bundle);
|
|
154
|
+
}
|
|
155
|
+
pages() {
|
|
156
|
+
return [...this.#pages.values()];
|
|
157
|
+
}
|
|
158
|
+
/** Waits until a page matching the test is listed. */
|
|
159
|
+
async waitForPage(matches, timeout = 15_000) {
|
|
160
|
+
for (let round = 0, deadline = Date.now() + timeout; Date.now() < deadline; round++) {
|
|
161
|
+
const found = this.pages().find(matches);
|
|
162
|
+
if (found)
|
|
163
|
+
return found;
|
|
164
|
+
// Safari does not always announce a new tab or a changed address, so ask again now and then.
|
|
165
|
+
if (round % 5 === 4)
|
|
166
|
+
this.refresh();
|
|
167
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
168
|
+
}
|
|
169
|
+
throw new Error('playwright-touch: the page did not show up in the Web Inspector. Is it open in Safari?');
|
|
170
|
+
}
|
|
171
|
+
/** Opens a command channel to one page. */
|
|
172
|
+
async attach(page) {
|
|
173
|
+
const session = new InspectorSession(this, page);
|
|
174
|
+
try {
|
|
175
|
+
await session.ready;
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
session.close();
|
|
179
|
+
throw error;
|
|
180
|
+
}
|
|
181
|
+
return session;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Hangs up after everything already sent has gone out. Cutting the socket with a message still
|
|
185
|
+
* on its way leaves the simulator's inspector deaf to the next connection.
|
|
186
|
+
*/
|
|
187
|
+
close() {
|
|
188
|
+
return new Promise((resolve) => {
|
|
189
|
+
this.#socket.once('close', () => resolve());
|
|
190
|
+
this.#socket.end();
|
|
191
|
+
setTimeout(() => {
|
|
192
|
+
this.#socket.destroy();
|
|
193
|
+
resolve();
|
|
194
|
+
}, 500);
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Commands for one page. Safari wraps each page in a "target" and expects commands to be passed on
|
|
200
|
+
* to it; a navigation to another site swaps the target, and the session follows.
|
|
201
|
+
*/
|
|
202
|
+
export class InspectorSession {
|
|
203
|
+
ready;
|
|
204
|
+
#inspector;
|
|
205
|
+
#page;
|
|
206
|
+
#sender = randomUUID().toUpperCase();
|
|
207
|
+
#target = '';
|
|
208
|
+
#next = 1;
|
|
209
|
+
#waiting = new Map();
|
|
210
|
+
#events = new Set();
|
|
211
|
+
#stop;
|
|
212
|
+
#abandon = () => { };
|
|
213
|
+
/** Why no further command can be answered, once that is so. */
|
|
214
|
+
#over = null;
|
|
215
|
+
constructor(inspector, page) {
|
|
216
|
+
this.#inspector = inspector;
|
|
217
|
+
this.#page = page;
|
|
218
|
+
let announce;
|
|
219
|
+
this.ready = new Promise((resolve, reject) => {
|
|
220
|
+
const timer = setTimeout(() => reject(new Error('playwright-touch: the page did not accept the Web Inspector.')), 10_000);
|
|
221
|
+
announce = () => {
|
|
222
|
+
clearTimeout(timer);
|
|
223
|
+
resolve();
|
|
224
|
+
};
|
|
225
|
+
});
|
|
226
|
+
/** Ends every command still waiting: its answer will not come any more. */
|
|
227
|
+
const abandon = (this.#abandon = (why) => {
|
|
228
|
+
const waiting = [...this.#waiting.values()];
|
|
229
|
+
this.#waiting.clear();
|
|
230
|
+
for (const waiter of waiting)
|
|
231
|
+
waiter.reject(new Error(`playwright-touch: ${why}`));
|
|
232
|
+
});
|
|
233
|
+
this.#stop = inspector.on((selector, argument) => {
|
|
234
|
+
if (selector === CLOSED) {
|
|
235
|
+
this.#over = 'the connection to Safari ended.';
|
|
236
|
+
return abandon(this.#over);
|
|
237
|
+
}
|
|
238
|
+
if (selector !== '_rpc_applicationSentData:' || argument.WIRDestinationKey !== this.#sender)
|
|
239
|
+
return;
|
|
240
|
+
const outer = JSON.parse(argument.WIRMessageDataKey.toString());
|
|
241
|
+
if (outer.method === 'Target.targetCreated' &&
|
|
242
|
+
outer.params?.targetInfo?.type === 'page' &&
|
|
243
|
+
!outer.params.targetInfo.isProvisional) {
|
|
244
|
+
this.#target = outer.params.targetInfo.targetId;
|
|
245
|
+
announce();
|
|
246
|
+
}
|
|
247
|
+
// A navigation to another site swaps the page for a new one. Commands sent to the old one get no answer.
|
|
248
|
+
if (outer.method === 'Target.didCommitProvisionalTarget' && outer.params?.newTargetId) {
|
|
249
|
+
this.#target = outer.params.newTargetId;
|
|
250
|
+
abandon('the page went somewhere else before it answered.');
|
|
251
|
+
}
|
|
252
|
+
if (outer.method === 'Target.targetDestroyed' && outer.params?.targetId === this.#target)
|
|
253
|
+
abandon('the page was closed before it answered.');
|
|
254
|
+
// Safari itself can refuse to pass a command on, for instance to a page that is gone.
|
|
255
|
+
if (outer.id !== undefined && outer.error) {
|
|
256
|
+
const waiter = this.#waiting.get(outer.id);
|
|
257
|
+
this.#waiting.delete(outer.id);
|
|
258
|
+
waiter?.reject(new Error(`playwright-touch: Safari refused the command: ${outer.error.message}`));
|
|
259
|
+
}
|
|
260
|
+
if (outer.method !== 'Target.dispatchMessageFromTarget' || !outer.params?.message)
|
|
261
|
+
return;
|
|
262
|
+
const inner = JSON.parse(outer.params.message);
|
|
263
|
+
if (inner.id !== undefined) {
|
|
264
|
+
const waiter = this.#waiting.get(inner.id);
|
|
265
|
+
this.#waiting.delete(inner.id);
|
|
266
|
+
if (inner.error)
|
|
267
|
+
waiter?.reject(new Error(`playwright-touch: Safari refused the command: ${inner.error.message}`));
|
|
268
|
+
else
|
|
269
|
+
waiter?.resolve(inner.result);
|
|
270
|
+
}
|
|
271
|
+
else if (inner.method)
|
|
272
|
+
for (const listener of [...this.#events])
|
|
273
|
+
listener(inner.method, (inner.params ?? {}));
|
|
274
|
+
});
|
|
275
|
+
inspector.send('_rpc_forwardSocketSetup:', {
|
|
276
|
+
WIRApplicationIdentifierKey: page.app,
|
|
277
|
+
WIRPageIdentifierKey: page.id,
|
|
278
|
+
WIRSenderKey: this.#sender,
|
|
279
|
+
WIRAutomaticallyPause: false,
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
#raw(message) {
|
|
283
|
+
this.#inspector.send('_rpc_forwardSocketData:', {
|
|
284
|
+
WIRApplicationIdentifierKey: this.#page.app,
|
|
285
|
+
WIRPageIdentifierKey: this.#page.id,
|
|
286
|
+
WIRSenderKey: this.#sender,
|
|
287
|
+
WIRSocketDataKey: Buffer.from(JSON.stringify(message)),
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
/** Sends one inspector command to the page and waits for its answer. */
|
|
291
|
+
command(method, params = {}, timeout = 15_000) {
|
|
292
|
+
// After the end nothing is sent: waiting fifteen seconds for an answer that cannot come helps nobody.
|
|
293
|
+
if (this.#over)
|
|
294
|
+
return Promise.reject(new Error(`playwright-touch: ${this.#over}`));
|
|
295
|
+
const id = this.#next++;
|
|
296
|
+
return new Promise((resolve, reject) => {
|
|
297
|
+
const timer = setTimeout(() => {
|
|
298
|
+
this.#waiting.delete(id);
|
|
299
|
+
reject(new Error(`playwright-touch: Safari did not answer ${method}.`));
|
|
300
|
+
}, timeout);
|
|
301
|
+
this.#waiting.set(id, {
|
|
302
|
+
resolve: (value) => (clearTimeout(timer), resolve(value)),
|
|
303
|
+
reject: (error) => (clearTimeout(timer), reject(error)),
|
|
304
|
+
});
|
|
305
|
+
this.#raw({
|
|
306
|
+
id,
|
|
307
|
+
method: 'Target.sendMessageToTarget',
|
|
308
|
+
params: { targetId: this.#target, message: JSON.stringify({ id, method, params }) },
|
|
309
|
+
});
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
onEvent(listener) {
|
|
313
|
+
this.#events.add(listener);
|
|
314
|
+
return () => this.#events.delete(listener);
|
|
315
|
+
}
|
|
316
|
+
/** Runs an expression in the page and returns its value. A promise is waited for. */
|
|
317
|
+
async evaluate(expression) {
|
|
318
|
+
// Safari evaluates first and waits for the promise as a second step.
|
|
319
|
+
const started = await this.command('Runtime.evaluate', {
|
|
320
|
+
expression: `(async () => (${expression}))()`,
|
|
321
|
+
returnByValue: false,
|
|
322
|
+
});
|
|
323
|
+
if (started.wasThrown || !started.result.objectId)
|
|
324
|
+
throw new Error(`playwright-touch: the page threw: ${started.result.description ?? 'an error'}`);
|
|
325
|
+
const answer = await this.command('Runtime.awaitPromise', { promiseObjectId: started.result.objectId, returnByValue: true }, 60_000);
|
|
326
|
+
// The page keeps the promise alive for us until told otherwise.
|
|
327
|
+
void this.command('Runtime.releaseObject', { objectId: started.result.objectId }).catch(() => undefined);
|
|
328
|
+
if (answer.wasThrown)
|
|
329
|
+
throw new Error(`playwright-touch: the page threw: ${answer.result.description ?? 'an error'}`);
|
|
330
|
+
return answer.result.value;
|
|
331
|
+
}
|
|
332
|
+
close() {
|
|
333
|
+
this.#over = 'the session was closed.';
|
|
334
|
+
this.#abandon(this.#over);
|
|
335
|
+
this.#stop();
|
|
336
|
+
this.#inspector.send('_rpc_forwardDidClose:', {
|
|
337
|
+
WIRApplicationIdentifierKey: this.#page.app,
|
|
338
|
+
WIRPageIdentifierKey: this.#page.id,
|
|
339
|
+
WIRSenderKey: this.#sender,
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type IosPage } from './page.js';
|
|
2
|
+
/** Safari on an iPhone on the cable, joined through `connectIphone()`. */
|
|
3
|
+
export interface IosPhone {
|
|
4
|
+
/** The model, as Apple numbers it ("iPhone13,3"). The name its owner gave the phone is not read. */
|
|
5
|
+
model: string;
|
|
6
|
+
/** The iOS version it runs. */
|
|
7
|
+
system: string;
|
|
8
|
+
touch: 'WebDriverAgent';
|
|
9
|
+
/** Whether Safari had to be started again to get the tab, which only happens when `restartSafari` allows it. */
|
|
10
|
+
restartedSafari: boolean;
|
|
11
|
+
page: IosPage;
|
|
12
|
+
/** Disconnects. Safari keeps running and the tab goes back to its start page, to be taken over next time. */
|
|
13
|
+
close(): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Joins Safari on an iPhone connected by cable. The phone has to be unlocked, trust this Mac, have
|
|
17
|
+
* Web Inspector switched on (Settings, Safari, Advanced) and have WebDriverAgent running on it.
|
|
18
|
+
*
|
|
19
|
+
* Only a tab this opens itself is worked in. The owner's other tabs are not attached to, read or
|
|
20
|
+
* touched. Safari does not always announce a new tab while it is running; with `restartSafari` it
|
|
21
|
+
* is then closed and opened again once, which reloads the owner's pages. Without it the connection
|
|
22
|
+
* fails with a message that says so.
|
|
23
|
+
*/
|
|
24
|
+
export declare function connectIphone(options?: {
|
|
25
|
+
udid?: string;
|
|
26
|
+
restartSafari?: boolean;
|
|
27
|
+
}): Promise<IosPhone>;
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// Safari on a real iPhone on the cable: pages are read through the Web Inspector, which the phone
|
|
2
|
+
// offers to a Mac its owner trusted, and touched through WebDriverAgent running on the phone.
|
|
3
|
+
import { WebInspector } from './inspector.js';
|
|
4
|
+
import { createPage } from './page.js';
|
|
5
|
+
import { openTab } from './tab.js';
|
|
6
|
+
import { sleep } from './tools.js';
|
|
7
|
+
import { webDriverAgent } from './touch.js';
|
|
8
|
+
import { forward, iphones, lockdown } from './usbmux.js';
|
|
9
|
+
const SAFARI = 'com.apple.mobilesafari';
|
|
10
|
+
/**
|
|
11
|
+
* Joins Safari on an iPhone connected by cable. The phone has to be unlocked, trust this Mac, have
|
|
12
|
+
* Web Inspector switched on (Settings, Safari, Advanced) and have WebDriverAgent running on it.
|
|
13
|
+
*
|
|
14
|
+
* Only a tab this opens itself is worked in. The owner's other tabs are not attached to, read or
|
|
15
|
+
* touched. Safari does not always announce a new tab while it is running; with `restartSafari` it
|
|
16
|
+
* is then closed and opened again once, which reloads the owner's pages. Without it the connection
|
|
17
|
+
* fails with a message that says so.
|
|
18
|
+
*/
|
|
19
|
+
export async function connectIphone(options = {}) {
|
|
20
|
+
const connected = await iphones();
|
|
21
|
+
if (!options.udid && connected.length > 1) {
|
|
22
|
+
throw new Error(`playwright-touch: ${connected.length} devices are on the cable. Say which one with udid: ${connected.map((one) => one.udid).join(', ')}`);
|
|
23
|
+
}
|
|
24
|
+
const phone = options.udid ? connected.find((one) => one.udid === options.udid) : connected[0];
|
|
25
|
+
if (!phone) {
|
|
26
|
+
throw new Error(options.udid
|
|
27
|
+
? `playwright-touch: no iPhone with the identifier ${options.udid} is on the cable.`
|
|
28
|
+
: 'playwright-touch: no iPhone is on the cable. Connect one and unlock it.');
|
|
29
|
+
}
|
|
30
|
+
const door = await lockdown(phone);
|
|
31
|
+
const closing = [() => door.close()];
|
|
32
|
+
const undo = () => closing.reverse().forEach((close) => close());
|
|
33
|
+
try {
|
|
34
|
+
const model = String(await door.value('ProductType'));
|
|
35
|
+
const system = String(await door.value('ProductVersion'));
|
|
36
|
+
// WebDriverAgent listens on the phone itself; its two ports are brought over the cable.
|
|
37
|
+
const commands = await forward(phone, 8100);
|
|
38
|
+
const pictures = await forward(phone, 9100);
|
|
39
|
+
closing.push(commands.close, pictures.close);
|
|
40
|
+
const agent = `http://127.0.0.1:${commands.port}`;
|
|
41
|
+
// The agent is told the name the owner gave the phone only on old systems, so the phone is
|
|
42
|
+
// recognised by the system it runs and not by a name.
|
|
43
|
+
const touch = await webDriverAgent(agent, { name: '', system }, `http://127.0.0.1:${pictures.port}`);
|
|
44
|
+
if (!touch) {
|
|
45
|
+
throw new Error('playwright-touch: WebDriverAgent is not running on the iPhone. Start it with: playwright-touch iphone --wda <folder>');
|
|
46
|
+
}
|
|
47
|
+
const ask = async (method, path, body) => {
|
|
48
|
+
const response = await fetch(agent + path, {
|
|
49
|
+
method,
|
|
50
|
+
signal: AbortSignal.timeout(30_000),
|
|
51
|
+
headers: { 'content-type': 'application/json' },
|
|
52
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
53
|
+
});
|
|
54
|
+
return (await response.json());
|
|
55
|
+
};
|
|
56
|
+
const inSession = async (path, body) => {
|
|
57
|
+
const session = (await ask('GET', '/status')).sessionId;
|
|
58
|
+
if (!session)
|
|
59
|
+
throw new Error('playwright-touch: WebDriverAgent on the iPhone lost its session.');
|
|
60
|
+
const said = await ask('POST', `/session/${session}${path}`, body);
|
|
61
|
+
if (said.value?.error)
|
|
62
|
+
throw new Error(`playwright-touch: the iPhone refused: ${said.value.message ?? said.value.error}`);
|
|
63
|
+
};
|
|
64
|
+
const safariInFront = async () => (await touch.front?.()) === SAFARI;
|
|
65
|
+
const inspector = await WebInspector.open(() => door.service('com.apple.webinspector'), 'playwright-touch: the Web Inspector of the iPhone does not answer. Switch it on in Settings, Safari, Advanced, and keep the phone unlocked.');
|
|
66
|
+
closing.push(() => void inspector.close());
|
|
67
|
+
// The phone cannot reach a page served by this computer without a network, but it can reach
|
|
68
|
+
// WebDriverAgent on itself. The tab opens on that, and the page is then written into it.
|
|
69
|
+
const startUrl = 'http://127.0.0.1:8100/status';
|
|
70
|
+
let restartedSafari = false;
|
|
71
|
+
const opener = {
|
|
72
|
+
url: startUrl,
|
|
73
|
+
ownOnly: true,
|
|
74
|
+
inFront: safariInFront,
|
|
75
|
+
async open() {
|
|
76
|
+
// Safari goes back to a tab that already shows an address instead of opening another, so
|
|
77
|
+
// the address is made new each time. Safari is named, or the phone's default browser,
|
|
78
|
+
// which may be another one, would be given the address.
|
|
79
|
+
await inSession('/url', { url: `${startUrl}?${Date.now()}`, bundleId: SAFARI });
|
|
80
|
+
},
|
|
81
|
+
async expect() {
|
|
82
|
+
// With Web Inspector switched off the service still answers; Safari is just not in it.
|
|
83
|
+
for (let waited = 0; waited < 40 && !inspector.knows(SAFARI); waited++) {
|
|
84
|
+
if (waited % 10 === 9)
|
|
85
|
+
inspector.refresh();
|
|
86
|
+
await sleep(100);
|
|
87
|
+
}
|
|
88
|
+
if (!inspector.knows(SAFARI)) {
|
|
89
|
+
throw new Error('playwright-touch: Safari on the iPhone is not offered for inspection. Switch on Settings, Safari, Advanced, Web Inspector, then close Safari and open it again.');
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
async prepare(session) {
|
|
93
|
+
await session.evaluate(`(document.open(), document.write('<!doctype html><meta name="viewport" content="width=device-width, initial-scale=1"><title>playwright-touch</title><body style="margin:0;height:100vh">'), document.close(), addEventListener('touchstart', (e) => { window.__touch = { x: e.touches[0].clientX, y: e.touches[0].clientY }; }, { passive: true }), true)`);
|
|
94
|
+
},
|
|
95
|
+
async revive() {
|
|
96
|
+
if (!options.restartSafari) {
|
|
97
|
+
throw new Error('playwright-touch: Safari on the iPhone opened the tab but does not announce it to the Web Inspector, which happens when Safari was already running. Close Safari on the phone and try again, or pass restartSafari: true to have it closed and opened again (its pages reload).');
|
|
98
|
+
}
|
|
99
|
+
await inSession('/wda/apps/terminate', { bundleId: SAFARI });
|
|
100
|
+
await sleep(1000);
|
|
101
|
+
await inSession('/wda/apps/launch', { bundleId: SAFARI });
|
|
102
|
+
restartedSafari = true;
|
|
103
|
+
},
|
|
104
|
+
close() { },
|
|
105
|
+
};
|
|
106
|
+
const { session, origin } = await openTab(inspector, touch, phone.udid, 'the iPhone', opener);
|
|
107
|
+
// Before every gesture: a finger that misses the page would land on the owner's home screen
|
|
108
|
+
// or in another app.
|
|
109
|
+
const guard = async () => {
|
|
110
|
+
if (!(await safariInFront())) {
|
|
111
|
+
throw new Error('playwright-touch: Safari is not the app in front on the iPhone, so nothing is touched. Bring Safari back to the tab this opened.');
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
return {
|
|
115
|
+
model,
|
|
116
|
+
system,
|
|
117
|
+
touch: 'WebDriverAgent',
|
|
118
|
+
restartedSafari,
|
|
119
|
+
page: createPage(session, touch, origin, undefined, guard),
|
|
120
|
+
async close() {
|
|
121
|
+
try {
|
|
122
|
+
// The tab goes back to its start page. A tab there is known to be ours next time, and
|
|
123
|
+
// no address that was visited has to be written down to find it again.
|
|
124
|
+
await session.evaluate(`void (location.href = ${JSON.stringify(startUrl)})`).catch(() => undefined);
|
|
125
|
+
await touch.close();
|
|
126
|
+
session.close();
|
|
127
|
+
await inspector.close();
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
commands.close();
|
|
131
|
+
pictures.close();
|
|
132
|
+
door.close();
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
undo();
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { type Film, type Vitals } from '../measure.js';
|
|
2
|
+
import type { Direction, GestureOptions, Point, RotateOptions } from '../types.js';
|
|
3
|
+
import type { InspectorSession } from './inspector.js';
|
|
4
|
+
import type { Touch } from './touch.js';
|
|
5
|
+
/** Something a finger can land on: a CSS selector, or a point in CSS pixels of the viewport. */
|
|
6
|
+
type Target = string | Point;
|
|
7
|
+
/** An element in Safari, named by a CSS selector. Pass it to the gestures the way a Playwright locator is passed. */
|
|
8
|
+
export interface IosLocator {
|
|
9
|
+
readonly ios: true;
|
|
10
|
+
readonly selector: string;
|
|
11
|
+
readonly page: IosPage;
|
|
12
|
+
}
|
|
13
|
+
/** The page in Safari's front tab. It is read through the Web Inspector and touched through the simulator. */
|
|
14
|
+
export interface IosPage {
|
|
15
|
+
readonly ios: true;
|
|
16
|
+
/** Names an element by a CSS selector, for the gestures. */
|
|
17
|
+
locator(selector: string): IosLocator;
|
|
18
|
+
/** Goes to the address in the same tab and waits for the page to finish loading. */
|
|
19
|
+
goto(url: string, options?: {
|
|
20
|
+
timeout?: number;
|
|
21
|
+
}): Promise<void>;
|
|
22
|
+
/** Runs a function or an expression in the page and returns its value. */
|
|
23
|
+
evaluate<T>(code: string | (() => T | Promise<T>)): Promise<T>;
|
|
24
|
+
/**
|
|
25
|
+
* Opens the address without the HTTP cache and returns the metrics. Nothing is deleted.
|
|
26
|
+
* Safari reports the paints and interactions, but not layout shift or long tasks.
|
|
27
|
+
*/
|
|
28
|
+
coldLoad(url: string, options?: {
|
|
29
|
+
settle?: number;
|
|
30
|
+
timeout?: number;
|
|
31
|
+
}): Promise<Vitals>;
|
|
32
|
+
/** The metrics of the current page so far. */
|
|
33
|
+
vitals(): Promise<Vitals>;
|
|
34
|
+
/**
|
|
35
|
+
* Records the simulator's screen while `action` runs and for `settle` milliseconds after. The
|
|
36
|
+
* frames show the whole screen, Safari's bars included, each with the time it arrived.
|
|
37
|
+
*/
|
|
38
|
+
film(action: () => Promise<unknown>, options?: {
|
|
39
|
+
settle?: number;
|
|
40
|
+
}): Promise<Film>;
|
|
41
|
+
tap(target: Target): Promise<void>;
|
|
42
|
+
/** Two quick taps on the same place. */
|
|
43
|
+
doubleTap(target: Target): Promise<void>;
|
|
44
|
+
longPress(target: Target, options?: {
|
|
45
|
+
duration?: number;
|
|
46
|
+
}): Promise<void>;
|
|
47
|
+
/** A controlled swipe: the finger slows to a stop before it lifts. Through idb it cannot slow down, so the content coasts a little. */
|
|
48
|
+
swipe(options: Stroke | Directed): Promise<void>;
|
|
49
|
+
/** A hard flick; the content carries on by momentum. */
|
|
50
|
+
fling(options: Stroke | Directed): Promise<void>;
|
|
51
|
+
/** With `hold`, the finger rests first, for lists that pick an item up on a long press. */
|
|
52
|
+
drag(source: Target, destination: Target, options?: {
|
|
53
|
+
hold?: number;
|
|
54
|
+
duration?: number;
|
|
55
|
+
}): Promise<void>;
|
|
56
|
+
/** Two fingers spreading (scale above 1) or closing on an element, or on the whole page with `null`, which zooms it. Needs WebDriverAgent. */
|
|
57
|
+
pinch(target: string | null, options: {
|
|
58
|
+
scale: number;
|
|
59
|
+
duration?: number;
|
|
60
|
+
}): Promise<void>;
|
|
61
|
+
/** Two fingers turning around the middle of an element. Needs WebDriverAgent. */
|
|
62
|
+
rotate(selector: string, options: RotateOptions): Promise<void>;
|
|
63
|
+
/** Any gesture, finger by finger. More than one finger, or a way that is not straight, needs WebDriverAgent. */
|
|
64
|
+
gesture(options: GestureOptions): Promise<void>;
|
|
65
|
+
/** Draws a dot under every finger from now on, also on the pages the tab goes to. */
|
|
66
|
+
showTouches(): Promise<void>;
|
|
67
|
+
}
|
|
68
|
+
interface Stroke {
|
|
69
|
+
from: Point;
|
|
70
|
+
to: Point;
|
|
71
|
+
duration?: number;
|
|
72
|
+
}
|
|
73
|
+
interface Directed {
|
|
74
|
+
direction: Direction;
|
|
75
|
+
/** A selector to stroke across; the whole viewport without one. */
|
|
76
|
+
on?: string;
|
|
77
|
+
distance?: number;
|
|
78
|
+
duration?: number;
|
|
79
|
+
}
|
|
80
|
+
/** The page behind `session`. `origin` is where the page starts on the screen, in screen points. */
|
|
81
|
+
export declare function createPage(session: InspectorSession, touch: Touch, origin: Point,
|
|
82
|
+
/** Called whenever the tab shows a new document. */
|
|
83
|
+
arrived?: () => Promise<void>,
|
|
84
|
+
/**
|
|
85
|
+
* On a person's own phone a finger that misses the page lands on their home screen or in another
|
|
86
|
+
* app. With this, every gesture first asks whether Safari is in front, and a page that does not
|
|
87
|
+
* answer is taken for one that cannot be touched.
|
|
88
|
+
*/
|
|
89
|
+
guard?: () => Promise<void>): IosPage;
|
|
90
|
+
export {};
|