@buffcore/cli 0.8.45 → 0.8.46

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/CHANGELOG.md CHANGED
@@ -4,6 +4,13 @@ One section per release (a git tag). **Upgrade notes** list anything that breaks
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## v0.8.46 (2026-12-03)
8
+
9
+ - Prototype snapshots draw a scene's later looks in place, on the same page. Each scene starts in a fresh browser context and then checks its last look against a fresh load; when the picture or findings differ, the scene is drawn again with full loads. The terminal counts full-page fallbacks of looks and scenes. Every load now blurs a field that autofocuses late before the picture, so a scene's focus ring no longer depends on timing; this changes earlier pictures only where that ring came and went. A view that takes the focus back after the blur keeps it, as a plain load shows it. Limits: code above the scene page that reads the look or storage once at boot is not rechecked per look, and scenes whose pictures vary between loads always redraw fresh.
10
+ - On Linux (and likely macOS), the app's first page after its Metro server starts (in `ape dev` and in a prototype snapshot's warm-up) no longer fails with HTTP 500 "Failed to collapse": a new product's `apps/app/app.json` turns off Expo's tsconfig `paths` resolver (`"experiments": { "tsconfigPaths": false }`), which tripped on the app's tsconfig extending the root one. No product tsconfig declares `paths`.
11
+
12
+ **Upgrade notes** (every product): on Linux (and likely macOS), add `"experiments": { "tsconfigPaths": false }` under `expo` in `apps/app/app.json`. Leave it out if your app relies on tsconfig `paths`.
13
+
7
14
  ## v0.8.45 (2026-12-03)
8
15
 
9
16
  - The studio's Prototype is a workspace: along the top, the change and its version (Compare, Approve), **Customer app | Console**, **Mobile | Tablet | Desktop** (Rotate for a tablet) and the tools **Select | Comment | Draw | Area**; on the left, **Journeys** (from `plan/journeys.md`, by who does them and in which app, joined to the journeys the running app plays; the open one lists its steps to jump to) and **Screens**, with the sample data at the foot; in the middle, the app in its device, zoomed to fit, with a line saying what you see and the step bar (Back, the step, Play, Next) under it. The console is a second frame at the stack's admin address: switching keeps each one's step and never reloads the other. The rail folds to its icons on this page. At phone width a phone's app takes the page (a tablet or a desktop is drawn in its bezel, zoomed to fit), the device choice shows as icons, and a bar sits at the app's foot (Journeys, Back, the step, Next, Changes); on a touch screen the Comment hint says tap. The preview's Try a journey and Preview options menus, the canvas's Full screen button and the drawn-only full-screen scenes are gone.
@@ -1,5 +1,7 @@
1
- import { type Browser, type BrowserContextOptions, type Frame, type Page } from 'playwright-core';
1
+ import { type Browser, type BrowserContextOptions, type Page } from 'playwright-core';
2
2
  import type { Size } from './checks.ts';
3
+ import type { MediaState } from './media-ready.ts';
4
+ export { animationsDone, sceneFrames, waitForScene } from './scene-ready.ts';
3
5
  /**
4
6
  * The one command that installs the browser, anywhere (a product has no playwright-core of its
5
7
  * own): the version this CLI runs, since each version drives its own Chromium build.
@@ -30,32 +32,10 @@ export declare const pageGone: (error: unknown) => boolean;
30
32
  export declare function pageOptions(frame: Size): BrowserContextOptions;
31
33
  /** A page for one scene, opened as `pageOptions` says. */
32
34
  export declare function openPage(browser: Browser, frame: Size, timeout?: number): Promise<Page>;
33
- /**
34
- * Runs inside the page (Playwright sends its source): paints two frames, then resolves when the
35
- * animations have finished, so a sheet fading in is not caught half way, or after `timeout` ms.
36
- * An animation that never ends (a spinner) is not waited for. Chromium paints no frame in a framed
37
- * page from another origin while it is off screen, so the wait for a paint ends after a second.
38
- */
39
- export declare function animationsDone(timeout: number): Promise<void>;
40
- /** The console can show an app scene in an iframe of its own. */
41
- export declare function sceneFrames(page: Page, locale: string): Promise<{
42
- frame: Frame;
43
- index: number;
44
- locale: string;
45
- }[]>;
46
- /**
47
- * Wait for the current scene and its framed scenes to finish drawing. True when a font or picture
48
- * was still loading as its allowance ran out: the page is shot as it is.
49
- */
50
- export declare function waitForScene(page: Page, locale: string, { live, animationWait, mediaWait, }?: {
51
- live?: () => boolean;
52
- animationWait?: number;
53
- mediaWait?: number;
54
- }): Promise<boolean>;
55
35
  /**
56
36
  * Show a scene page and wait until it has drawn. A scene that frames a scene page (a console
57
37
  * scene with the app's `/_scene` inside, e.g. a `DeviceFrame`) waits for that page too. A page
58
38
  * whose module fails to load (a busy dev server drops requests under load) is loaded again once.
59
39
  * True when a font or picture was still loading after `mediaWait` (`MEDIA_WAIT` unset).
60
40
  */
61
- export declare function openScene(page: Page, url: string, locale: string, mediaWait?: number): Promise<boolean>;
41
+ export declare function openScene(page: Page, url: string, locale: string, mediaWait?: number, onMedia?: (media: MediaState) => void): Promise<boolean>;
@@ -5,8 +5,10 @@
5
5
  import { createRequire } from 'node:module';
6
6
  import { chromium, } from 'playwright-core';
7
7
  import { accessDenied } from './access-denied.js';
8
- import { MEDIA_WAIT, mediaReady } from './media-ready.js';
8
+ import { collectLoadedGarbage } from './loaded-garbage.js';
9
+ import { waitForScene } from './scene-ready.js';
9
10
  import { SnapshotAccessRefused } from './snapshot-refused.js';
11
+ export { animationsDone, sceneFrames, waitForScene } from './scene-ready.js';
10
12
  /**
11
13
  * The one command that installs the browser, anywhere (a product has no playwright-core of its
12
14
  * own): the version this CLI runs, since each version drives its own Chromium build.
@@ -94,84 +96,14 @@ export async function openPage(browser, frame, timeout = 120_000) {
94
96
  throw new PageLoadError(String(error), { cause: error });
95
97
  }
96
98
  }
97
- /**
98
- * Runs inside the page (Playwright sends its source): paints two frames, then resolves when the
99
- * animations have finished, so a sheet fading in is not caught half way, or after `timeout` ms.
100
- * An animation that never ends (a spinner) is not waited for. Chromium paints no frame in a framed
101
- * page from another origin while it is off screen, so the wait for a paint ends after a second.
102
- */
103
- export async function animationsDone(timeout) {
104
- const frames = () => new Promise((done) => {
105
- requestAnimationFrame(() => requestAnimationFrame(done));
106
- setTimeout(done, 1_000);
107
- });
108
- const end = performance.now() + timeout;
109
- await frames();
110
- while (performance.now() < end) {
111
- const running = document
112
- .getAnimations()
113
- .filter((a) => a.playState === 'running' && a.effect?.getComputedTiming().endTime !== Infinity);
114
- if (running.length === 0)
115
- return;
116
- const wait = Math.max(end - performance.now(), 0);
117
- await Promise.race([
118
- Promise.allSettled(running.map((a) => a.finished)),
119
- new Promise((done) => setTimeout(done, wait)),
120
- ]);
121
- await frames();
122
- }
123
- }
124
- /** The longest `openScene` waits for animations to finish. */
125
- const ANIMATION_WAIT = 2_000;
126
- /**
127
- * Wait until a scene page in this frame has drawn: the view rendered in the asked language, the
128
- * fonts and pictures loaded (`mediaReady`), two frames painted, and animations finished within
129
- * their allowance. The focused element is blurred first, so a field that autofocuses shows no
130
- * focus ring. True when fonts or pictures were still loading as their allowance ran out.
131
- */
132
- async function drawn(frame, locale, live, { animationWait, mediaWait }) {
133
- await frame.waitForFunction((lang) => document.documentElement.lang === lang &&
134
- (document.getElementById('root')?.childElementCount ?? 0) > 0, locale);
135
- // An attempt that lost its page (a module failed, the page loaded again) does nothing more.
136
- if (!live())
137
- return false;
138
- await frame.evaluate(() => document.activeElement?.blur());
139
- const ready = await frame.evaluate(mediaReady, mediaWait);
140
- await frame.evaluate(animationsDone, animationWait);
141
- return !ready;
142
- }
143
99
  /** A script or module of the page failed to load: a busy dev server dropping a request. */
144
100
  class ModuleLost extends Error {
145
101
  }
146
- /** The console can show an app scene in an iframe of its own. */
147
- export async function sceneFrames(page, locale) {
148
- const frames = await Promise.all((await page.$$('iframe')).map(async (iframe, index) => {
149
- const src = new URL((await iframe.getAttribute('src')) ?? '', page.url());
150
- if (src.pathname !== '/_scene')
151
- return;
152
- const frame = await iframe.contentFrame();
153
- if (frame)
154
- return { frame, index, locale: src.searchParams.get('locale') ?? locale };
155
- }));
156
- return frames.filter((entry) => entry !== undefined);
157
- }
158
- /**
159
- * Wait for the current scene and its framed scenes to finish drawing. True when a font or picture
160
- * was still loading as its allowance ran out: the page is shot as it is.
161
- */
162
- export async function waitForScene(page, locale, { live = () => true, animationWait = ANIMATION_WAIT, mediaWait = MEDIA_WAIT, } = {}) {
163
- const waits = { animationWait, mediaWait };
164
- let late = await drawn(page.mainFrame(), locale, live, waits);
165
- for (const entry of await sceneFrames(page, locale))
166
- if (await drawn(entry.frame, entry.locale, live, waits))
167
- late = true;
168
- return late;
169
- }
170
102
  /**
171
103
  * Open the page (or load it again) and wait until it has drawn. A page whose script or module
172
104
  * fails to load never draws, so that ends the wait at once, not at the timeout.
173
105
  */
174
- async function show(page, url, locale, again, mediaWait) {
106
+ async function show(page, url, locale, again, mediaWait, onMedia) {
175
107
  let lose = (_) => { };
176
108
  const lost = new Promise((_, reject) => {
177
109
  lose = reject;
@@ -191,6 +123,7 @@ async function show(page, url, locale, again, mediaWait) {
191
123
  page.on('requestfailed', watch);
192
124
  const drawing = (async () => {
193
125
  try {
126
+ await collectLoadedGarbage(page);
194
127
  await (again ? page.reload({ waitUntil: 'load' }) : page.goto(url, { waitUntil: 'load' }));
195
128
  }
196
129
  catch (error) {
@@ -199,7 +132,11 @@ async function show(page, url, locale, again, mediaWait) {
199
132
  throw new ConnectionRefused(url);
200
133
  throw error;
201
134
  }
202
- return waitForScene(page, locale, { live, ...(mediaWait === undefined ? {} : { mediaWait }) });
135
+ return waitForScene(page, locale, {
136
+ live,
137
+ onMedia,
138
+ ...(mediaWait === undefined ? {} : { mediaWait }),
139
+ });
203
140
  })();
204
141
  // Whichever loses the race must not end the run as an unhandled rejection.
205
142
  drawing.catch(() => { });
@@ -218,15 +155,15 @@ async function show(page, url, locale, again, mediaWait) {
218
155
  * whose module fails to load (a busy dev server drops requests under load) is loaded again once.
219
156
  * True when a font or picture was still loading after `mediaWait` (`MEDIA_WAIT` unset).
220
157
  */
221
- export async function openScene(page, url, locale, mediaWait) {
158
+ export async function openScene(page, url, locale, mediaWait, onMedia) {
222
159
  try {
223
160
  try {
224
- return await show(page, url, locale, false, mediaWait);
161
+ return await show(page, url, locale, false, mediaWait, onMedia);
225
162
  }
226
163
  catch (error) {
227
164
  if (!(error instanceof ModuleLost))
228
165
  throw error;
229
- return await show(page, url, locale, true, mediaWait);
166
+ return await show(page, url, locale, true, mediaWait, onMedia);
230
167
  }
231
168
  }
232
169
  catch (error) {
@@ -0,0 +1,10 @@
1
+ import type { Page } from 'playwright-core';
2
+ /**
3
+ * On Linux, Chromium keeps each loaded response in a shared-memory file of about 2 MB, which it
4
+ * reserves on disk (Playwright moves it from /dev/shm to /tmp), until the page's garbage is
5
+ * collected. Its scripts' heap stays small, so no collection comes: a console page served as
6
+ * about 1,250 separate modules held about 1.2 GB per full load, in the renderer that every
7
+ * context shares, until the disk was full and loads failed with net::ERR_INSUFFICIENT_RESOURCES.
8
+ * Collecting before each full load (about 60 ms) keeps that to the page being replaced.
9
+ */
10
+ export declare function collectLoadedGarbage(page: Page, platform?: NodeJS.Platform): Promise<void>;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * On Linux, Chromium keeps each loaded response in a shared-memory file of about 2 MB, which it
3
+ * reserves on disk (Playwright moves it from /dev/shm to /tmp), until the page's garbage is
4
+ * collected. Its scripts' heap stays small, so no collection comes: a console page served as
5
+ * about 1,250 separate modules held about 1.2 GB per full load, in the renderer that every
6
+ * context shares, until the disk was full and loads failed with net::ERR_INSUFFICIENT_RESOURCES.
7
+ * Collecting before each full load (about 60 ms) keeps that to the page being replaced.
8
+ */
9
+ export async function collectLoadedGarbage(page, platform = process.platform) {
10
+ if (platform !== 'linux')
11
+ return;
12
+ // Only an aid: a page that cannot collect still loads.
13
+ try {
14
+ const session = await page.context().newCDPSession(page);
15
+ await session
16
+ .send('HeapProfiler.collectGarbage')
17
+ .finally(() => session.detach().catch(() => { }));
18
+ }
19
+ catch { }
20
+ }
@@ -1,8 +1,14 @@
1
1
  /** The longest a scene page waits for its fonts and pictures; then it is shot anyway, with a hint. */
2
2
  export declare const MEDIA_WAIT = 10000;
3
+ /** `ready`: all loaded in time. `failed`: a picture or font failed. `elapsed`: ms spent waiting. */
4
+ export interface MediaState {
5
+ ready: boolean;
6
+ failed: boolean;
7
+ elapsed: number;
8
+ }
3
9
  /**
4
10
  * Runs in the page: wait until its fonts are ready and every picture has finished, loaded or
5
- * failed (a lazy picture loads now: the shot is of the whole page). False when `timeout` ran out
6
- * first. Self-contained, since Playwright sends it to the page as text.
11
+ * failed (a lazy picture loads now: the shot is of the whole page). Also say whether any failed
12
+ * and how long the wait took. Self-contained, since Playwright sends it to the page as text.
7
13
  */
8
- export declare function mediaReady(timeout: number): Promise<boolean>;
14
+ export declare function mediaReady(timeout: number): Promise<MediaState>;
@@ -4,13 +4,15 @@
4
4
  export const MEDIA_WAIT = 10_000;
5
5
  /**
6
6
  * Runs in the page: wait until its fonts are ready and every picture has finished, loaded or
7
- * failed (a lazy picture loads now: the shot is of the whole page). False when `timeout` ran out
8
- * first. Self-contained, since Playwright sends it to the page as text.
7
+ * failed (a lazy picture loads now: the shot is of the whole page). Also say whether any failed
8
+ * and how long the wait took. Self-contained, since Playwright sends it to the page as text.
9
9
  */
10
10
  export async function mediaReady(timeout) {
11
11
  // Layout first, so the fonts the text needs have started loading before `fonts.ready` is read.
12
+ const start = performance.now();
12
13
  document.body?.getBoundingClientRect();
13
- const pictures = [...document.images].flatMap((image) => {
14
+ const images = [...document.images];
15
+ const pictures = images.flatMap((image) => {
14
16
  if (image.loading === 'lazy')
15
17
  image.loading = 'eager';
16
18
  if (image.complete)
@@ -28,7 +30,10 @@ export async function mediaReady(timeout) {
28
30
  });
29
31
  const ready = Promise.all([document.fonts.ready, ...pictures]).then(() => true);
30
32
  try {
31
- return await Promise.race([ready, late]);
33
+ const finished = await Promise.race([ready, late]);
34
+ const failed = images.some((image) => image.naturalWidth === 0) ||
35
+ [...document.fonts].some((font) => font.status === 'error');
36
+ return { ready: finished, failed, elapsed: performance.now() - start };
32
37
  }
33
38
  finally {
34
39
  clearTimeout(timer);
@@ -42,6 +42,7 @@ export declare const en: {
42
42
  'prototype.remade': string;
43
43
  'prototype.problems': string;
44
44
  'prototype.sceneResult': string;
45
+ 'prototype.drawFallbacks': string;
45
46
  'prototype.sceneFailed': string;
46
47
  'prototype.serverUnavailable': string;
47
48
  'prototype.serverExitCode': string;
@@ -43,6 +43,7 @@ export const en = {
43
43
  'prototype.remade': 'remade',
44
44
  'prototype.problems': '{count} problem(s)',
45
45
  'prototype.sceneResult': ' {title}: {result}{retry}',
46
+ 'prototype.drawFallbacks': 'Full-page fallbacks: {looks} looks, {scenes} scenes.',
46
47
  'prototype.sceneFailed': 'Scene "{scene}" failed{retry}: {detail}',
47
48
  'prototype.serverUnavailable': 'Server "{server}" is not answering for scene "{scene}". {status}.',
48
49
  'prototype.serverExitCode': 'Last exit code was {code}',
@@ -44,6 +44,7 @@ const es = {
44
44
  'prototype.remade': 'regenerada',
45
45
  'prototype.problems': '{count} problema(s)',
46
46
  'prototype.sceneResult': ' {title}: {result}{retry}',
47
+ 'prototype.drawFallbacks': 'Recargas completas: {looks} apariencias, {scenes} escenas.',
47
48
  'prototype.sceneFailed': 'La escena "{scene}" falló{retry}: {detail}',
48
49
  'prototype.serverUnavailable': 'El servidor "{server}" no responde para la escena "{scene}". {status}.',
49
50
  'prototype.serverExitCode': 'El último código de salida fue {code}',
@@ -0,0 +1,37 @@
1
+ import type { Scene } from '@buffcore/config';
2
+ import type { PrototypeProblem } from '@buffcore/contracts/prototype';
3
+ import type { Browser, Page } from 'playwright-core';
4
+ import type { checkLook, Run } from './scene.ts';
5
+ type Look = {
6
+ theme: string;
7
+ mode: string;
8
+ locale: string;
9
+ };
10
+ /** The scene's last look as drawn: where it is and whether its media was late. */
11
+ export interface LastLook {
12
+ look: Look;
13
+ url: string;
14
+ mediaWait: number | undefined;
15
+ late: boolean;
16
+ }
17
+ /** One look's picture and findings, from a found list of its own. */
18
+ export interface LookEvidence {
19
+ picture: Buffer;
20
+ problems: PrototypeProblem[];
21
+ late: boolean;
22
+ }
23
+ /** The page as it shows `last` now: its picture and the findings `check` gives on it. */
24
+ export declare function lookEvidence(page: Page, last: LastLook, run: Run, scene: Scene, check: typeof checkLook): Promise<LookEvidence>;
25
+ /** True when a fresh load of the last look, in a new context, matches the in-place evidence. */
26
+ export declare function freshLoadAgrees(browser: Browser, scene: Scene, run: Run, signal: AbortSignal, last: LastLook, inPlace: LookEvidence, check: typeof checkLook): Promise<boolean>;
27
+ /** A look drawn in place and its evidence, to be compared with a fresh load. */
28
+ export type SceneCheck = {
29
+ last: LastLook;
30
+ evidence: LookEvidence;
31
+ };
32
+ /**
33
+ * Every check agrees with its fresh load, within the time the draw left of the scene timeout.
34
+ * An error other than an abort (a timeout, a page that failed) counts as a disagreement.
35
+ */
36
+ export declare function freshLoadsAgree(browser: Browser, scene: Scene, run: Run, signal: AbortSignal, checks: readonly SceneCheck[], started: number, check: typeof checkLook): Promise<boolean>;
37
+ export {};
@@ -0,0 +1,68 @@
1
+ // The check a scene drawn with in-place looks must pass: its last look, which carries the most
2
+ // state left by earlier looks, drawn again by a fresh load in a new context must give the same
3
+ // picture and the same findings. Otherwise the scene is drawn again with full loads.
4
+ import { mkdtemp, readFile, rm } from 'node:fs/promises';
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { isDeepStrictEqual } from 'node:util';
8
+ import { openScene } from './browser.js';
9
+ import { dataWords } from './checks.js';
10
+ import { fullShot } from './full-shot.js';
11
+ import { renderScene, SCENE_TIMEOUT_MS } from './scene-render.js';
12
+ import { sceneRequests } from './snapshot-requests.js';
13
+ /** The page as it shows `last` now: its picture and the findings `check` gives on it. */
14
+ export async function lookEvidence(page, last, run, scene, check) {
15
+ const out = await mkdtemp(join(tmpdir(), 'ape-look-check-'));
16
+ try {
17
+ const found = {
18
+ scene,
19
+ data: dataWords(scene.props),
20
+ screenshots: {},
21
+ cut: [],
22
+ problems: [],
23
+ hints: [],
24
+ pairs: new Set(),
25
+ };
26
+ await check(page, last.look, { ...run, out }, found);
27
+ const path = join(out, 'look.png');
28
+ await fullShot(page, path);
29
+ return { picture: await readFile(path), problems: found.problems, late: last.late };
30
+ }
31
+ finally {
32
+ await rm(out, { recursive: true, force: true });
33
+ }
34
+ }
35
+ /** True when a fresh load of the last look, in a new context, matches the in-place evidence. */
36
+ export async function freshLoadAgrees(browser, scene, run, signal, last, inPlace, check) {
37
+ const fresh = await renderScene(browser, run.frames[scene.frame], scene.key, run.sceneTimeout, async (page) => {
38
+ // Requests this load makes count too: the scene's facts stay a union over every load.
39
+ sceneRequests(page, run, scene);
40
+ const late = await openScene(page, last.url, last.look.locale, last.mediaWait);
41
+ return lookEvidence(page, { ...last, late }, run, scene, check);
42
+ }, signal, run);
43
+ return (fresh.late === inPlace.late &&
44
+ fresh.picture.equals(inPlace.picture) &&
45
+ isDeepStrictEqual(fresh.problems, inPlace.problems));
46
+ }
47
+ /**
48
+ * Every check agrees with its fresh load, within the time the draw left of the scene timeout.
49
+ * An error other than an abort (a timeout, a page that failed) counts as a disagreement.
50
+ */
51
+ export async function freshLoadsAgree(browser, scene, run, signal, checks, started, check) {
52
+ const deadline = started + (run.sceneTimeout ?? SCENE_TIMEOUT_MS);
53
+ for (const { last, evidence } of checks) {
54
+ const left = deadline - performance.now();
55
+ if (left <= 0)
56
+ return false;
57
+ try {
58
+ const fresh = { ...run, sceneTimeout: left };
59
+ if (!(await freshLoadAgrees(browser, scene, fresh, signal, last, evidence, check)))
60
+ return false;
61
+ }
62
+ catch {
63
+ signal.throwIfAborted();
64
+ return false;
65
+ }
66
+ }
67
+ return true;
68
+ }
@@ -0,0 +1,14 @@
1
+ import type { Page } from 'playwright-core';
2
+ /** Counts a look drawn by a full load instead of in place, or a scene drawn again fresh. */
3
+ export type FallbackCounter = (kind: 'look' | 'scene') => void;
4
+ /** The attempt may have had side effects. Discard its context before replaying the scene. */
5
+ export declare class LookMoveFailed extends Error {
6
+ }
7
+ /**
8
+ * A fresh navigation starts the scene; its later looks move in place. A picture is shot only once
9
+ * `mediaReady` says all is ready, so warm media draws the same picture; only a media finding could
10
+ * differ. So a later look loads fresh when the first look got one (late or failed), or when its
11
+ * wait used more than half the later look's allowance (a cold load near the limit). A cold load
12
+ * well within the allowance means a warm one is too, so the findings are equal.
13
+ */
14
+ export declare function sceneLookLoader(page: Page, onFallback?: FallbackCounter, inPlace?: boolean, onMove?: () => void): (url: string, locale: string, mediaWait?: number) => Promise<boolean>;
@@ -0,0 +1,89 @@
1
+ /// <reference lib="dom" />
2
+ import { SCENE_LOOK_ATTR, SCENE_LOOK_CHANGE, SCENE_LOOK_REUSABLE, } from '@buffcore/contracts/prototype';
3
+ import { openScene, sceneFrames, waitForScene } from './browser.js';
4
+ import { MEDIA_WAIT } from './media-ready.js';
5
+ import { SCENE_FOCUS_KEPT } from './scene-ready.js';
6
+ const LOOK_WAIT = 5_000;
7
+ /** The attempt may have had side effects. Discard its context before replaying the scene. */
8
+ export class LookMoveFailed extends Error {
9
+ }
10
+ /**
11
+ * The head's stylesheets, by element: one added or removed by a look would stay on the kept page.
12
+ * A sheet's text may change, since a styling library (Unistyles) rewrites its one sheet for the
13
+ * look on screen; the proof's equal pictures cover that.
14
+ */
15
+ function headStyles() {
16
+ return [...document.head.querySelectorAll('style, link[rel="stylesheet"]')]
17
+ .map((node) => node.cloneNode(false).outerHTML)
18
+ .join('\n');
19
+ }
20
+ /** False means the current document was left untouched. */
21
+ async function moveLook(page, url, locale, mediaWait, onMove) {
22
+ try {
23
+ if ((await sceneFrames(page, locale)).length)
24
+ return false;
25
+ const eligible = await page.evaluate(({ url, attr, reusable, kept }) => {
26
+ const html = document.documentElement;
27
+ const current = new URL(location.href);
28
+ const next = new URL(url);
29
+ return (current.origin === next.origin &&
30
+ current.pathname === next.pathname &&
31
+ current.searchParams.get('key') === next.searchParams.get('key') &&
32
+ html.getAttribute(attr) === location.search &&
33
+ html.hasAttribute(reusable) &&
34
+ (document.activeElement === document.body ||
35
+ document.activeElement === html ||
36
+ html.hasAttribute(kept)));
37
+ }, { url, attr: SCENE_LOOK_ATTR, reusable: SCENE_LOOK_REUSABLE, kept: SCENE_FOCUS_KEPT });
38
+ if (!eligible)
39
+ return false;
40
+ const styles = await page.evaluate(headStyles);
41
+ onMove?.();
42
+ await page.evaluate(({ url, event, attr }) => {
43
+ document.documentElement.removeAttribute(attr);
44
+ history.replaceState(history.state, '', url);
45
+ window.dispatchEvent(new Event(event));
46
+ }, { url, event: SCENE_LOOK_CHANGE, attr: SCENE_LOOK_ATTR });
47
+ await page.waitForFunction(({ attr, search }) => location.search === search && document.documentElement.getAttribute(attr) === search, { attr: SCENE_LOOK_ATTR, search: new URL(url).search }, { timeout: LOOK_WAIT });
48
+ const late = await waitForScene(page, locale, {
49
+ unframed: true,
50
+ readyWait: LOOK_WAIT,
51
+ ...(mediaWait === undefined ? {} : { mediaWait }),
52
+ });
53
+ if (late)
54
+ throw new LookMoveFailed('Media was late after the move');
55
+ if (styles !== (await page.evaluate(headStyles)))
56
+ throw new LookMoveFailed('The move added or removed a stylesheet');
57
+ return true;
58
+ }
59
+ catch (cause) {
60
+ throw new LookMoveFailed(undefined, { cause });
61
+ }
62
+ }
63
+ /**
64
+ * A fresh navigation starts the scene; its later looks move in place. A picture is shot only once
65
+ * `mediaReady` says all is ready, so warm media draws the same picture; only a media finding could
66
+ * differ. So a later look loads fresh when the first look got one (late or failed), or when its
67
+ * wait used more than half the later look's allowance (a cold load near the limit). A cold load
68
+ * well within the allowance means a warm one is too, so the findings are equal.
69
+ */
70
+ export function sceneLookLoader(page, onFallback, inPlace = true, onMove) {
71
+ let opened = false;
72
+ let found = false;
73
+ let elapsed = 0;
74
+ const observe = (media) => {
75
+ found ||= !media.ready || media.failed;
76
+ elapsed = Math.max(elapsed, media.elapsed);
77
+ };
78
+ return async (url, locale, mediaWait) => {
79
+ if (opened) {
80
+ const warmSafe = !found && elapsed <= (mediaWait ?? MEDIA_WAIT) / 2;
81
+ if (inPlace && warmSafe && (await moveLook(page, url, locale, mediaWait, onMove)))
82
+ return false;
83
+ onFallback?.('look');
84
+ }
85
+ const late = await openScene(page, url, locale, mediaWait, inPlace ? observe : undefined);
86
+ opened = true;
87
+ return late;
88
+ };
89
+ }
@@ -0,0 +1,46 @@
1
+ import type { Frame, Page } from 'playwright-core';
2
+ import { type MediaState } from './media-ready.ts';
3
+ /**
4
+ * Runs inside the page (Playwright sends its source): paints two frames, then resolves when the
5
+ * animations have finished, so a sheet fading in is not caught half way, or after `timeout` ms.
6
+ * An animation that never ends (a spinner) is not waited for. Chromium paints no frame in a framed
7
+ * page from another origin while it is off screen, so the wait for a paint ends after a second.
8
+ */
9
+ export declare function animationsDone(timeout: number): Promise<void>;
10
+ /** Set on `<html>` when the view took the focus back on purpose (`unfocused`). */
11
+ export declare const SCENE_FOCUS_KEPT = "data-scene-focus-kept";
12
+ /**
13
+ * Runs inside the page, after `animationsDone` has painted two frames (so the view's mount effects
14
+ * and autofocus have had their chance): blur whatever has focus, and again after each frame until
15
+ * nothing does, for up to `timeout` ms. A field that autofocuses late (Expo's router can commit the
16
+ * root before the view) then shows no focus ring on any path. An element that takes the focus back
17
+ * after its blur does so on purpose (a sheet that focuses its field): it keeps the focus, as a plain
18
+ * load shows it, and `<html>` is marked with `data-scene-focus-kept`. True when nothing has focus.
19
+ */
20
+ export declare function unfocused(timeout: number): Promise<boolean>;
21
+ /** How long a scene page waits: for its animations, and for its fonts and pictures. */
22
+ type Waits = {
23
+ animationWait: number;
24
+ mediaWait: number;
25
+ readyWait?: number | undefined;
26
+ onMedia?: ((media: MediaState) => void) | undefined;
27
+ };
28
+ /** The console can show an app scene in an iframe of its own. */
29
+ export declare function sceneFrames(page: Page, locale: string): Promise<{
30
+ frame: Frame;
31
+ index: number;
32
+ locale: string;
33
+ }[]>;
34
+ /**
35
+ * Wait for the current scene and its framed scenes to finish drawing. True when a font or picture
36
+ * was still loading as its allowance ran out: the page is shot as it is.
37
+ */
38
+ export declare function waitForScene(page: Page, locale: string, { live, animationWait, mediaWait, readyWait, unframed, onMedia, }?: {
39
+ live?: () => boolean;
40
+ animationWait?: number;
41
+ mediaWait?: number;
42
+ readyWait?: number;
43
+ unframed?: boolean;
44
+ onMedia?: Waits['onMedia'];
45
+ }): Promise<boolean>;
46
+ export {};