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.
Files changed (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +495 -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 +485 -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 +108 -0
  14. package/dist/index.js +147 -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/polyline.d.ts +10 -0
  44. package/dist/polyline.js +38 -0
  45. package/dist/report.d.ts +46 -0
  46. package/dist/report.js +118 -0
  47. package/dist/session.d.ts +35 -0
  48. package/dist/session.js +23 -0
  49. package/dist/show.d.ts +13 -0
  50. package/dist/show.js +51 -0
  51. package/dist/types.d.ts +58 -0
  52. package/dist/types.js +2 -0
  53. package/package.json +68 -4
@@ -0,0 +1,173 @@
1
+ import { sessionOf } from './session.js';
2
+ // Runs in the page before any of its own scripts. Kept as text so it is the same on every page and
3
+ // survives navigations.
4
+ export const COLLECTOR = `(() => {
5
+ if (window.__playwrightTouchVitals) return;
6
+ const can = (type) => (PerformanceObserver.supportedEntryTypes || []).includes(type);
7
+ 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: {} });
8
+ const watch = (type, each, extra) => {
9
+ try { new PerformanceObserver((list) => list.getEntries().forEach(each)).observe(Object.assign({ type, buffered: true }, extra)); } catch (_) {}
10
+ };
11
+ watch('paint', (e) => { if (e.name === 'first-contentful-paint') v.fcp = e.startTime; });
12
+ watch('largest-contentful-paint', (e) => { v.lcp = e.startTime; });
13
+ // Shifts are counted in bursts: a burst ends after a second of calm or five seconds in all, and
14
+ // the score is the worst burst. Shifts right after input are the user's own doing and are left out.
15
+ let burst = 0, first = 0, last = 0;
16
+ watch('layout-shift', (e) => {
17
+ if (e.hadRecentInput) return;
18
+ if (burst && e.startTime - last < 1000 && e.startTime - first < 5000) burst += e.value;
19
+ else { burst = e.value; first = e.startTime; }
20
+ last = e.startTime;
21
+ if (burst > v.cls) v.cls = burst;
22
+ });
23
+ // Safari gives a click no interaction of its own, so a slow click handler would go unseen there;
24
+ // such a click counts as an interaction by itself.
25
+ 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 });
26
+ watch('longtask', (e) => { v.longTasks++; v.blocked += e.duration - 50; });
27
+ })();`;
28
+ export const READ = `(() => {
29
+ const v = window.__playwrightTouchVitals;
30
+ if (!v) return null;
31
+ const nav = performance.getEntriesByType('navigation')[0];
32
+ const slow = Object.values(v.slow);
33
+ // The browser's own count also includes touches answered too fast to be listed one by one.
34
+ 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 };
35
+ })()`;
36
+ export const tidy = (vitals) => {
37
+ // Everything here comes out of the measured page, so nothing is trusted to be the number it should be.
38
+ const number = (value) => (typeof value === 'number' && Number.isFinite(value) ? value : null);
39
+ const ms = (value) => (number(value) === null ? null : Math.round(number(value)));
40
+ const cls = number(vitals.cls);
41
+ return {
42
+ ttfb: ms(vitals.ttfb),
43
+ fcp: ms(vitals.fcp),
44
+ lcp: ms(vitals.lcp),
45
+ inp: ms(vitals.inp),
46
+ interactions: ms(vitals.interactions) ?? 0,
47
+ longTasks: ms(vitals.longTasks),
48
+ blocked: ms(vitals.blocked),
49
+ cls: cls === null ? null : Math.round(cls * 1000) / 1000,
50
+ };
51
+ };
52
+ /**
53
+ * Starts collecting metrics on the page and on every page it navigates to. Call it before the
54
+ * navigation that should be measured, then read at any time: after the load, after a gesture.
55
+ */
56
+ export async function watchVitals(page) {
57
+ await page.addInitScript({ content: COLLECTOR });
58
+ return {
59
+ async read() {
60
+ const vitals = await page.evaluate(READ);
61
+ if (!vitals)
62
+ throw new Error('playwright-touch: nothing was measured on this page. Call watchVitals() before the navigation.');
63
+ return tidy(vitals);
64
+ },
65
+ };
66
+ }
67
+ /**
68
+ * Opens the address the way a first-time visitor gets it: nothing from the HTTP cache and no
69
+ * service worker in between. Nothing is deleted, so on a real phone the owner's cache, cookies and
70
+ * sign-ins stay as they were. Connections the browser already holds open may be reused.
71
+ */
72
+ export async function coldLoad(page, url, options = {}) {
73
+ const cdp = await sessionOf(page);
74
+ await cdp.send('Network.enable');
75
+ await cdp.send('Network.setCacheDisabled', { cacheDisabled: true });
76
+ await cdp.send('Network.setBypassServiceWorker', { bypass: true });
77
+ const vitals = await watchVitals(page);
78
+ try {
79
+ await page.goto(url, { waitUntil: 'load', timeout: options.timeout ?? 60_000 });
80
+ // The largest paint and late shifts often land after the load event.
81
+ await page.waitForTimeout(options.settle ?? 2000);
82
+ return await vitals.read();
83
+ }
84
+ finally {
85
+ await cdp.send('Network.setCacheDisabled', { cacheDisabled: false }).catch(() => { });
86
+ await cdp.send('Network.setBypassServiceWorker', { bypass: false }).catch(() => { });
87
+ }
88
+ }
89
+ /**
90
+ * The longest time between two pictures in a row while the page was moving. The wait before the
91
+ * motion starts is not a pause in it, and neither is what happens after the page has come to
92
+ * rest, such as a scroll bar fading out a third of a second later. `until` is when the page last
93
+ * scrolled, on the frames' clock; without it every frame after the first counts.
94
+ */
95
+ export function longestPauseOf(frames, until = null) {
96
+ let longest = 0;
97
+ for (let i = 2; i < frames.length; i++) {
98
+ const [before, now] = [frames[i - 1].at, frames[i].at];
99
+ if (until !== null && before >= until)
100
+ break;
101
+ // A pause that begins while the page moves and ends after it stopped counts up to the stop:
102
+ // a freeze at the very end of a fling is still a freeze.
103
+ longest = Math.max(longest, (until === null ? now : Math.min(now, until)) - before);
104
+ }
105
+ return longest;
106
+ }
107
+ /** Runs in the page: notes the wall-clock time of every scroll, of the document or of anything inside it. */
108
+ export const SCROLL_WATCH = `(() => {
109
+ window.__playwrightTouchScrolled = null;
110
+ window.__playwrightTouchTouched = false;
111
+ if (window.__playwrightTouchScrollWatch) return;
112
+ window.__playwrightTouchScrollWatch = true;
113
+ // Bringing an element into view before a gesture scrolls the page as well. Only what scrolls
114
+ // after the first touch, wheel turn, click or key belongs to the action.
115
+ for (const type of ['touchstart', 'wheel', 'pointerdown', 'keydown']) addEventListener(type, () => { window.__playwrightTouchTouched = true; }, { capture: true, passive: true });
116
+ addEventListener('scroll', () => { if (window.__playwrightTouchTouched) window.__playwrightTouchScrolled = performance.timeOrigin + performance.now(); }, { capture: true, passive: true });
117
+ })()`;
118
+ export const SCROLL_READ = 'window.__playwrightTouchScrolled ?? null';
119
+ const watched = new WeakSet();
120
+ /**
121
+ * Records what the screen shows while `action` runs, and for `settle` milliseconds after, so that
122
+ * momentum and late paints are in the picture. The browser sends a frame whenever the picture
123
+ * changes, each with the time it was drawn.
124
+ */
125
+ export async function film(page, action, options = {}) {
126
+ const cdp = await sessionOf(page);
127
+ const frames = [];
128
+ let origin = null;
129
+ const onFrame = (frame) => {
130
+ const stamp = (frame.metadata.timestamp ?? Date.now() / 1000) * 1000;
131
+ origin ??= stamp;
132
+ frames.push({ at: Math.round(stamp - origin), jpeg: Buffer.from(frame.data, 'base64') });
133
+ void cdp.send('Page.screencastFrameAck', { sessionId: frame.sessionId }).catch(() => { });
134
+ };
135
+ cdp.on('Page.screencastFrame', onFrame);
136
+ const started = Date.now();
137
+ let scrolled = null;
138
+ try {
139
+ // The scroll bar fades out a third of a second after the page has come to rest, which would
140
+ // show up as one long pause at the end of every film. Without it the last frame is the last motion.
141
+ await cdp.send('Emulation.setScrollbarsHidden', { hidden: true }).catch(() => undefined);
142
+ // Also for every page the action goes on to, so a film across a navigation still knows what
143
+ // scrolled. Once per page: an init script cannot be taken back.
144
+ if (!watched.has(page)) {
145
+ watched.add(page);
146
+ await page.addInitScript({ content: SCROLL_WATCH }).catch(() => undefined);
147
+ }
148
+ await page.evaluate(SCROLL_WATCH).catch(() => undefined);
149
+ await cdp.send('Page.startScreencast', {
150
+ format: 'jpeg',
151
+ quality: options.quality ?? 60,
152
+ maxWidth: options.width ?? 360,
153
+ maxHeight: 4000,
154
+ everyNthFrame: 1,
155
+ });
156
+ await action();
157
+ await page.waitForTimeout(options.settle ?? 1500);
158
+ scrolled = await page.evaluate(SCROLL_READ).catch(() => null);
159
+ }
160
+ finally {
161
+ await cdp.send('Page.stopScreencast').catch(() => { });
162
+ await cdp.send('Emulation.setScrollbarsHidden', { hidden: false }).catch(() => undefined);
163
+ cdp.off('Page.screencastFrame', onFrame);
164
+ }
165
+ // The frames and the page's own clock both count from 1970, so they can be compared directly.
166
+ const scrolledFor = scrolled !== null && origin !== null ? Math.max(0, Math.round(scrolled - origin)) : null;
167
+ return {
168
+ frames,
169
+ duration: Date.now() - started,
170
+ longestPause: longestPauseOf(frames, scrolledFor === null ? null : scrolledFor + 34),
171
+ scrolledFor,
172
+ };
173
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Listens on a local port and relays to the browser at `browserPort`, hiding every tab that was
3
+ * already open. Returns the port to connect to and a way to shut the relay down.
4
+ */
5
+ export declare function ownTabsOnly(browserPort: number): Promise<{
6
+ port: number;
7
+ close(): void;
8
+ }>;
@@ -0,0 +1,242 @@
1
+ // A small stand-in for Chrome's debugging address that shows a client only the tabs it opens itself.
2
+ //
3
+ // Playwright attaches to every tab it is shown. On somebody's phone that means their tabs, and a
4
+ // single tab that has not loaded yet (Android keeps background tabs unloaded) makes the connection
5
+ // wait for ever. Here the owner's tabs are never attached to and never listed, so they can neither
6
+ // be read nor get in the way.
7
+ import { createHash } from 'node:crypto';
8
+ import { createServer } from 'node:http';
9
+ const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
10
+ /** Writes one unfragmented WebSocket text frame, as a server (unmasked). */
11
+ function frame(text, opcode = 1) {
12
+ const body = Buffer.from(text);
13
+ const head = body.length < 126
14
+ ? Buffer.from([0x80 | opcode, body.length])
15
+ : body.length < 65536
16
+ ? Buffer.from([0x80 | opcode, 126, body.length >> 8, body.length & 255])
17
+ : Buffer.concat([Buffer.from([0x80 | opcode, 127]), bigLength(body.length)]);
18
+ return Buffer.concat([head, body]);
19
+ }
20
+ function bigLength(length) {
21
+ const out = Buffer.alloc(8);
22
+ out.writeBigUInt64BE(BigInt(length));
23
+ return out;
24
+ }
25
+ /** Reads the client's (masked) frames from a socket and hands over whole text messages. */
26
+ function reader(socket, onText, onClose) {
27
+ let pending = Buffer.alloc(0);
28
+ let parts = [];
29
+ socket.on('data', (chunk) => {
30
+ pending = Buffer.concat([pending, chunk]);
31
+ for (;;) {
32
+ if (pending.length < 2)
33
+ return;
34
+ const opcode = pending[0] & 15;
35
+ const final = (pending[0] & 0x80) !== 0;
36
+ const masked = (pending[1] & 0x80) !== 0;
37
+ let length = pending[1] & 127;
38
+ let offset = 2;
39
+ if (length === 126) {
40
+ if (pending.length < 4)
41
+ return;
42
+ length = pending.readUInt16BE(2);
43
+ offset = 4;
44
+ }
45
+ else if (length === 127) {
46
+ if (pending.length < 10)
47
+ return;
48
+ length = Number(pending.readBigUInt64BE(2));
49
+ offset = 10;
50
+ }
51
+ const start = offset + (masked ? 4 : 0);
52
+ if (pending.length < start + length)
53
+ return;
54
+ const body = Buffer.from(pending.subarray(start, start + length));
55
+ if (masked)
56
+ for (let i = 0; i < body.length; i++)
57
+ body[i] ^= pending[offset + (i & 3)];
58
+ pending = pending.subarray(start + length);
59
+ if (opcode === 8)
60
+ return onClose();
61
+ if (opcode === 9)
62
+ socket.write(frame(body.toString(), 10));
63
+ if (opcode <= 2) {
64
+ parts.push(body);
65
+ if (final) {
66
+ onText(Buffer.concat(parts).toString());
67
+ parts = [];
68
+ }
69
+ }
70
+ }
71
+ });
72
+ socket.on('close', onClose);
73
+ socket.on('error', onClose);
74
+ }
75
+ /**
76
+ * Listens on a local port and relays to the browser at `browserPort`, hiding every tab that was
77
+ * already open. Returns the port to connect to and a way to shut the relay down.
78
+ */
79
+ export async function ownTabsOnly(browserPort) {
80
+ if (typeof WebSocket !== 'function')
81
+ throw new Error('playwright-touch: connecting to a phone needs Node.js 22 or newer.');
82
+ const version = (await (await fetch(`http://127.0.0.1:${browserPort}/json/version`, { signal: AbortSignal.timeout(3000) })).json());
83
+ const browserUrl = version.webSocketDebuggerUrl.replace(/^ws:\/\/[^/]+/, `ws://127.0.0.1:${browserPort}`);
84
+ const sockets = new Set();
85
+ const upstreams = new Set();
86
+ const server = createServer((_request, response) => {
87
+ // Playwright asks here for the address of the socket; it gets ours.
88
+ const address = server.address();
89
+ const port = typeof address === 'object' && address ? address.port : 0;
90
+ response
91
+ .writeHead(200, { 'content-type': 'application/json' })
92
+ .end(JSON.stringify({ ...version, webSocketDebuggerUrl: `ws://127.0.0.1:${port}/devtools/browser` }));
93
+ });
94
+ server.on('upgrade', (request, socket) => {
95
+ const key = request.headers['sec-websocket-key'];
96
+ if (!key) {
97
+ socket.destroy();
98
+ return;
99
+ }
100
+ sockets.add(socket);
101
+ const upstream = new WebSocket(browserUrl);
102
+ upstreams.add(upstream);
103
+ // Tabs are told apart by where they come from. A tab is the client's when the client asked the
104
+ // browser for it, or when one of the client's tabs opened it. Every other tab is the owner's,
105
+ // whether it was open before we arrived or appears later.
106
+ const ours = new Set();
107
+ const creating = new Set();
108
+ /** Sessions on the browser itself, as opposed to on a tab. What they report about tabs is filtered like the main connection. */
109
+ const browserSessions = new Set();
110
+ const attachingToBrowser = new Set();
111
+ /** News about tabs that arrived while the client was waiting for a tab it asked for: it may be that tab, or the owner's. */
112
+ let held = [];
113
+ const early = [];
114
+ let ready = false;
115
+ // Requests of our own use ids far below anything a client sends, so the answers can be told apart.
116
+ let own = -1;
117
+ const overBrowser = (sessionId) => !sessionId || browserSessions.has(sessionId);
118
+ const fromClient = (text) => {
119
+ const message = JSON.parse(text);
120
+ if (typeof message.id === 'number') {
121
+ if (message.method === 'Target.createTarget')
122
+ creating.add(message.id);
123
+ if (message.method === 'Target.attachToBrowserTarget')
124
+ attachingToBrowser.add(message.id);
125
+ }
126
+ // A client that names a tab which is not its own is told there is no such tab.
127
+ if (overBrowser(message.sessionId) &&
128
+ message.method?.startsWith('Target.') &&
129
+ message.params?.targetId &&
130
+ !ours.has(message.params.targetId)) {
131
+ socket.write(frame(JSON.stringify({
132
+ id: message.id,
133
+ sessionId: message.sessionId,
134
+ error: { code: -32602, message: 'No target with given id found' },
135
+ })));
136
+ return;
137
+ }
138
+ upstream.send(text);
139
+ };
140
+ const toBrowser = (text) => (ready ? fromClient(text) : early.push(text));
141
+ const done = () => {
142
+ sockets.delete(socket);
143
+ upstreams.delete(upstream);
144
+ socket.destroy();
145
+ if (upstream.readyState <= 1)
146
+ upstream.close();
147
+ };
148
+ /** Lets go of an owner's tab the browser attached us to, without leaving it waiting for a debugger. */
149
+ const letGo = (message) => {
150
+ if (message.method !== 'Target.attachedToTarget' || !message.params?.sessionId)
151
+ return;
152
+ // A new tab is held until its debugger says go. Nobody else will, so say it before leaving,
153
+ // or the owner's new tab would stay blank for as long as we are connected.
154
+ upstream.send(JSON.stringify({ id: own--, method: 'Runtime.runIfWaitingForDebugger', sessionId: message.params.sessionId }));
155
+ upstream.send(JSON.stringify({
156
+ id: own--,
157
+ method: 'Target.detachFromTarget',
158
+ params: { sessionId: message.params.sessionId },
159
+ }));
160
+ };
161
+ upstream.addEventListener('open', () => upstream.send(JSON.stringify({ id: own--, method: 'Target.getTargets' })));
162
+ upstream.addEventListener('close', done);
163
+ upstream.addEventListener('error', done);
164
+ upstream.addEventListener('message', (event) => {
165
+ let text = String(event.data);
166
+ const message = JSON.parse(text);
167
+ if (typeof message.id === 'number' && message.id < 0) {
168
+ // The answer to our opening question marks the moment from which requests are passed on.
169
+ // Any answer will do, an error included: what matters is that the browser is listening.
170
+ if (!ready) {
171
+ ready = true;
172
+ for (const waiting of early.splice(0))
173
+ fromClient(waiting);
174
+ }
175
+ return;
176
+ }
177
+ if (typeof message.id === 'number') {
178
+ if (attachingToBrowser.delete(message.id) && message.result?.sessionId)
179
+ browserSessions.add(message.result.sessionId);
180
+ if (creating.delete(message.id)) {
181
+ if (message.result?.targetId)
182
+ ours.add(message.result.targetId);
183
+ // What was held back is now known for what it is. The client's own tab is announced
184
+ // before the answer, the order a client expects; with no request left open, the rest is the owner's.
185
+ const waiting = held;
186
+ held = [];
187
+ for (const one of waiting) {
188
+ if (ours.has(one.targetId))
189
+ socket.write(frame(one.text));
190
+ else if (creating.size > 0)
191
+ held.push(one);
192
+ else
193
+ letGo(one.message);
194
+ }
195
+ }
196
+ // A list of tabs is passed on with the client's own tabs only.
197
+ if (message.result?.targetInfos) {
198
+ message.result.targetInfos = message.result.targetInfos.filter((info) => ours.has(info.targetId) || info.type === 'browser');
199
+ text = JSON.stringify(message);
200
+ }
201
+ }
202
+ const info = message.params?.targetInfo;
203
+ const targetId = info?.targetId ?? message.params?.targetId;
204
+ // The browser itself is a target too, the one a client attaches to for a session of its own.
205
+ if (overBrowser(message.sessionId) &&
206
+ message.method?.startsWith('Target.') &&
207
+ targetId &&
208
+ info?.type !== 'browser' &&
209
+ !ours.has(targetId)) {
210
+ if (info?.openerId && ours.has(info.openerId)) {
211
+ ours.add(targetId);
212
+ }
213
+ else if (creating.size > 0) {
214
+ held.push({ text, message, targetId });
215
+ return;
216
+ }
217
+ else {
218
+ letGo(message);
219
+ return;
220
+ }
221
+ }
222
+ socket.write(frame(text));
223
+ });
224
+ socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${createHash('sha1')
225
+ .update(key + GUID)
226
+ .digest('base64')}\r\n\r\n`);
227
+ reader(socket, toBrowser, done);
228
+ });
229
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
230
+ const address = server.address();
231
+ return {
232
+ port: typeof address === 'object' && address ? address.port : 0,
233
+ close() {
234
+ for (const upstream of upstreams)
235
+ if (upstream.readyState <= 1)
236
+ upstream.close();
237
+ for (const socket of sockets)
238
+ socket.destroy();
239
+ server.close();
240
+ },
241
+ };
242
+ }
@@ -0,0 +1,10 @@
1
+ import type { Point } from './types.js';
2
+ /** The length of the way through the points. */
3
+ export declare function lengthOf(points: Point[]): number;
4
+ /**
5
+ * The way through the points as a function of progress: 0 is the first point, 1 the last, and
6
+ * equal steps of progress are equal lengths of the way, however unevenly the points are spaced.
7
+ */
8
+ export declare function along(points: Point[]): (k: number) => Point;
9
+ /** Points on a circle around `centre`, from one angle to another, one about every four degrees. Angles in degrees, clockwise from the right. */
10
+ export declare function arc(centre: Point, radius: number, from: number, to: number): Point[];
@@ -0,0 +1,38 @@
1
+ /** The length of the way through the points. */
2
+ export function lengthOf(points) {
3
+ let length = 0;
4
+ for (let i = 1; i < points.length; i++)
5
+ length += Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y);
6
+ return length;
7
+ }
8
+ /**
9
+ * The way through the points as a function of progress: 0 is the first point, 1 the last, and
10
+ * equal steps of progress are equal lengths of the way, however unevenly the points are spaced.
11
+ */
12
+ export function along(points) {
13
+ if (points.length === 0)
14
+ throw new Error('playwright-touch: a finger needs at least one point to be at.');
15
+ const total = lengthOf(points);
16
+ if (total === 0)
17
+ return () => points[0];
18
+ return (k) => {
19
+ let left = Math.min(1, Math.max(0, k)) * total;
20
+ for (let i = 1; i < points.length; i++) {
21
+ const [from, to] = [points[i - 1], points[i]];
22
+ const piece = Math.hypot(to.x - from.x, to.y - from.y);
23
+ if (left <= piece && piece > 0) {
24
+ return { x: from.x + ((to.x - from.x) * left) / piece, y: from.y + ((to.y - from.y) * left) / piece };
25
+ }
26
+ left -= piece;
27
+ }
28
+ return points.at(-1);
29
+ };
30
+ }
31
+ /** Points on a circle around `centre`, from one angle to another, one about every four degrees. Angles in degrees, clockwise from the right. */
32
+ export function arc(centre, radius, from, to) {
33
+ const steps = Math.max(1, Math.ceil(Math.abs(to - from) / 4));
34
+ return Array.from({ length: steps + 1 }, (_, step) => {
35
+ const angle = ((from + ((to - from) * step) / steps) * Math.PI) / 180;
36
+ return { x: centre.x + radius * Math.cos(angle), y: centre.y + radius * Math.sin(angle) };
37
+ });
38
+ }
@@ -0,0 +1,46 @@
1
+ import type { Film, Vitals } from './measure.js';
2
+ /** How a metric stands against the published thresholds. */
3
+ export type Rating = 'good' | 'needs improvement' | 'poor';
4
+ declare const LIMITS: {
5
+ readonly ttfb: readonly [800, 1800];
6
+ readonly fcp: readonly [1800, 3000];
7
+ readonly lcp: readonly [2500, 4000];
8
+ readonly inp: readonly [200, 500];
9
+ readonly cls: readonly [0.1, 0.25];
10
+ };
11
+ /** Rates one metric against the published thresholds. A metric the page did not produce has no rating. */
12
+ export declare function rate(metric: keyof typeof LIMITS, value: number | null): Rating | null;
13
+ /** One visit on one device. */
14
+ export interface Run {
15
+ /** What it was measured on, for example the phone's model and browser. */
16
+ device: string;
17
+ vitals: Vitals;
18
+ /** Recordings to show as film strips, in order. */
19
+ films?: {
20
+ label: string;
21
+ film: Film;
22
+ }[];
23
+ }
24
+ /** One visit on one device, with what the report should say about it. */
25
+ export interface Report extends Run {
26
+ title: string;
27
+ /** The address that was measured. */
28
+ url: string;
29
+ /** How many frames of each recording to show. Default 8. */
30
+ framesPerFilm?: number;
31
+ }
32
+ /** The same visit on several devices. */
33
+ export interface Comparison {
34
+ title: string;
35
+ /** The address that was measured. */
36
+ url: string;
37
+ /** The same visit on several devices, shown side by side in this order. */
38
+ runs: Run[];
39
+ /** How many frames of each recording to show. Default 8. */
40
+ framesPerFilm?: number;
41
+ }
42
+ /** Writes the same visit on several devices as one self-contained HTML file: no network, no other files. */
43
+ export declare function writeComparison(path: string, report: Comparison): void;
44
+ /** Writes one visit as one self-contained HTML file. */
45
+ export declare function writeReport(path: string, report: Report): void;
46
+ export {};
package/dist/report.js ADDED
@@ -0,0 +1,118 @@
1
+ import { writeFileSync } from 'node:fs';
2
+ // The thresholds Google publishes for each metric: up to the first is good, past the second is poor.
3
+ const LIMITS = { ttfb: [800, 1800], fcp: [1800, 3000], lcp: [2500, 4000], inp: [200, 500], cls: [0.1, 0.25] };
4
+ /** Rates one metric against the published thresholds. A metric the page did not produce has no rating. */
5
+ export function rate(metric, value) {
6
+ if (value === null)
7
+ return null;
8
+ const [good, poor] = LIMITS[metric];
9
+ return value <= good ? 'good' : value <= poor ? 'needs improvement' : 'poor';
10
+ }
11
+ const escape = (text) => text.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
12
+ /** Evenly spaced items, always with the first and the last. */
13
+ function pick(items, count) {
14
+ if (items.length <= count)
15
+ return items;
16
+ if (count <= 1)
17
+ return items.slice(0, Math.max(0, count));
18
+ return Array.from({ length: count }, (_, i) => items[Math.round((i * (items.length - 1)) / (count - 1))]);
19
+ }
20
+ const METRICS = [
21
+ {
22
+ name: 'Largest contentful paint',
23
+ meaning: 'When the biggest thing on the first screen was drawn.',
24
+ key: 'lcp',
25
+ unit: 'ms',
26
+ },
27
+ {
28
+ name: 'Interaction to next paint',
29
+ meaning: 'The slowest interaction, from touch to the next picture.',
30
+ key: 'inp',
31
+ unit: 'ms',
32
+ },
33
+ { name: 'Cumulative layout shift', meaning: 'How much the page jumped around on its own.', key: 'cls', unit: '' },
34
+ { name: 'First contentful paint', meaning: 'When the first text or image appeared.', key: 'fcp', unit: 'ms' },
35
+ { name: 'Time to first byte', meaning: 'How long the server took to start answering.', key: 'ttfb', unit: 'ms' },
36
+ ];
37
+ const number = (value) => value.toLocaleString('en-GB');
38
+ /** One table cell: the value and, under it, how it rates. A value the browser did not report says so. */
39
+ function cell(key, value, unit) {
40
+ if (value === null)
41
+ return '<td class="value none">not measured</td>';
42
+ const rating = rate(key, value);
43
+ return `<td class="value">${number(value)}${unit ? ' ' + unit : ''}<span class="rating ${rating.replace(/ /g, '-')}">${rating}</span></td>`;
44
+ }
45
+ /** Writes the same visit on several devices as one self-contained HTML file: no network, no other files. */
46
+ export function writeComparison(path, report) {
47
+ const { runs } = report;
48
+ const head = runs.length > 1
49
+ ? `<thead><tr><th></th>${runs.map((run) => `<th scope="col">${escape(run.device)}</th>`).join('')}</tr></thead>`
50
+ : '';
51
+ // No slowest interaction although there were some: each was answered in under 16 ms, which the browser does not list.
52
+ const quick = (run, key) => key === 'inp' && run.vitals.inp === null && run.vitals.interactions > 0;
53
+ const rows = METRICS.map(({ name, meaning, key, unit }) => `<tr><th scope="row">${name}<small>${meaning}</small></th>${runs.map((run) => (quick(run, key) ? '<td class="value">under 16 ms<span class="rating good">good</span></td>' : cell(key, run.vitals[key], unit))).join('')}</tr>`);
54
+ rows.push(`<tr><th scope="row">Interactions seen<small>How many touches the page had to answer.</small></th>${runs.map((run) => `<td class="value">${run.vitals.interactions}</td>`).join('')}</tr>`, `<tr><th scope="row">Long tasks<small>Stretches over 50 ms in which the page could not react.</small></th>${runs
55
+ .map((run) => run.vitals.longTasks === null
56
+ ? '<td class="value none">not measured</td>'
57
+ : `<td class="value">${run.vitals.longTasks}<span class="note">${number(run.vitals.blocked ?? 0)} ms over the limit</span></td>`)
58
+ .join('')}</tr>`);
59
+ const films = runs.flatMap((run) => (run.films ?? []).map(({ label, film }) => {
60
+ const frames = pick(film.frames, report.framesPerFilm ?? 8);
61
+ const strip = frames
62
+ .map((frame) => `<figure><img alt="" src="data:image/jpeg;base64,${frame.jpeg.toString('base64')}"><figcaption>${(frame.at / 1000).toFixed(2)} s</figcaption></figure>`)
63
+ .join('');
64
+ const where = runs.length > 1 ? `${escape(run.device)}: ` : '';
65
+ return `<section><h2>${where}${escape(label)}</h2><p>${film.frames.length} frames in ${(film.duration / 1000).toFixed(1)} s, ${film.scrolledFor === null ? `the longest pause between two of them ${film.longestPause} ms` : `the page scrolled for ${(film.scrolledFor / 1000).toFixed(1)} s with a longest pause of ${film.longestPause} ms`}. ${frames.length} shown.</p><div class="strip">${strip}</div></section>`;
66
+ }));
67
+ const measuredOn = runs.length > 1 ? `${runs.length} devices` : escape(runs[0]?.device ?? '');
68
+ const html = `<!doctype html>
69
+ <html lang="en">
70
+ <head>
71
+ <meta charset="utf-8">
72
+ <meta name="viewport" content="width=device-width, initial-scale=1">
73
+ <title>${escape(report.title)}</title>
74
+ <style>
75
+ :root { color-scheme: light dark; --ink: #1c1c1c; --soft: #666; --line: #ddd; --paper: #fff; }
76
+ @media (prefers-color-scheme: dark) { :root { --ink: #eee; --soft: #aaa; --line: #3a3a3a; --paper: #161616; } }
77
+ body { margin: 0 auto; max-width: 1040px; padding: 24px 16px 64px; font: 16px/1.5 system-ui, sans-serif; color: var(--ink); background: var(--paper); }
78
+ h1 { font-size: 1.5rem; margin: 0 0 4px; } h2 { font-size: 1.1rem; margin: 40px 0 4px; }
79
+ p { margin: 0 0 12px; color: var(--soft); overflow-wrap: anywhere; }
80
+ .table { overflow-x: auto; }
81
+ table { width: 100%; border-collapse: collapse; margin-top: 16px; }
82
+ th, td { text-align: left; padding: 10px 16px 10px 0; border-top: 1px solid var(--line); vertical-align: top; }
83
+ thead th { border-top: 0; font-size: .9rem; color: var(--soft); font-weight: 600; }
84
+ th { font-weight: 600; } th small { display: block; font-weight: 400; color: var(--soft); }
85
+ .value { white-space: nowrap; font-variant-numeric: tabular-nums; } .none { color: var(--soft); }
86
+ .rating, .note { display: block; width: fit-content; margin-top: 4px; font-size: .8rem; }
87
+ .rating { padding: 1px 8px; border-radius: 999px; border: 1px solid currentColor; } .note { color: var(--soft); }
88
+ .good { color: #1a7f37; } .needs-improvement { color: #9a6700; } .poor { color: #cf222e; }
89
+ @media (prefers-color-scheme: dark) { .good { color: #4ac26b; } .needs-improvement { color: #d4a72c; } .poor { color: #ff8182; } }
90
+ .strip { display: flex; gap: 8px; overflow-x: auto; padding-bottom: 8px; }
91
+ figure { margin: 0; flex: 0 0 150px; } img { width: 100%; display: block; border: 1px solid var(--line); border-radius: 6px; }
92
+ figcaption { font-size: .8rem; color: var(--soft); text-align: center; font-variant-numeric: tabular-nums; }
93
+ </style>
94
+ </head>
95
+ <body>
96
+ <h1>${escape(report.title)}</h1>
97
+ <p>${escape(report.url)}<br>Measured on ${measuredOn}, ${new Date().toISOString().slice(0, 16).replace('T', ' ')} UTC.</p>
98
+ <div class="table"><table>
99
+ ${head}
100
+ <tbody>
101
+ ${rows.join('\n')}
102
+ </tbody>
103
+ </table></div>
104
+ ${films.join('\n')}
105
+ </body>
106
+ </html>
107
+ `;
108
+ writeFileSync(path, html);
109
+ }
110
+ /** Writes one visit as one self-contained HTML file. */
111
+ export function writeReport(path, report) {
112
+ writeComparison(path, {
113
+ title: report.title,
114
+ url: report.url,
115
+ runs: [{ device: report.device, vitals: report.vitals, films: report.films }],
116
+ framesPerFilm: report.framesPerFilm,
117
+ });
118
+ }