@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.
@@ -0,0 +1,116 @@
1
+ import { MEDIA_WAIT, mediaReady } from './media-ready.js';
2
+ /**
3
+ * Runs inside the page (Playwright sends its source): paints two frames, then resolves when the
4
+ * animations have finished, so a sheet fading in is not caught half way, or after `timeout` ms.
5
+ * An animation that never ends (a spinner) is not waited for. Chromium paints no frame in a framed
6
+ * page from another origin while it is off screen, so the wait for a paint ends after a second.
7
+ */
8
+ export async function animationsDone(timeout) {
9
+ const frames = () => new Promise((done) => {
10
+ requestAnimationFrame(() => requestAnimationFrame(done));
11
+ setTimeout(done, 1_000);
12
+ });
13
+ const end = performance.now() + timeout;
14
+ await frames();
15
+ while (performance.now() < end) {
16
+ const running = document
17
+ .getAnimations()
18
+ .filter((a) => a.playState === 'running' && a.effect?.getComputedTiming().endTime !== Infinity);
19
+ if (running.length === 0)
20
+ return;
21
+ const wait = Math.max(end - performance.now(), 0);
22
+ await Promise.race([
23
+ Promise.allSettled(running.map((a) => a.finished)),
24
+ new Promise((done) => setTimeout(done, wait)),
25
+ ]);
26
+ await frames();
27
+ }
28
+ }
29
+ /** Set on `<html>` when the view took the focus back on purpose (`unfocused`). */
30
+ export const SCENE_FOCUS_KEPT = 'data-scene-focus-kept';
31
+ /**
32
+ * Runs inside the page, after `animationsDone` has painted two frames (so the view's mount effects
33
+ * and autofocus have had their chance): blur whatever has focus, and again after each frame until
34
+ * nothing does, for up to `timeout` ms. A field that autofocuses late (Expo's router can commit the
35
+ * root before the view) then shows no focus ring on any path. An element that takes the focus back
36
+ * after its blur does so on purpose (a sheet that focuses its field): it keeps the focus, as a plain
37
+ * load shows it, and `<html>` is marked with `data-scene-focus-kept`. True when nothing has focus.
38
+ */
39
+ export async function unfocused(timeout) {
40
+ const frames = () => new Promise((done) => {
41
+ requestAnimationFrame(() => requestAnimationFrame(done));
42
+ setTimeout(done, 1_000);
43
+ });
44
+ const end = performance.now() + timeout;
45
+ const focused = () => {
46
+ const active = document.activeElement;
47
+ return active && active !== document.body && active !== document.documentElement
48
+ ? active
49
+ : undefined;
50
+ };
51
+ // The same name as SCENE_FOCUS_KEPT: Playwright sends this function as text.
52
+ document.documentElement.removeAttribute('data-scene-focus-kept');
53
+ let blurred;
54
+ for (let active = focused(); active; active = focused()) {
55
+ if (active === blurred) {
56
+ document.documentElement.setAttribute('data-scene-focus-kept', '');
57
+ return false;
58
+ }
59
+ if (performance.now() > end)
60
+ return false;
61
+ active.blur();
62
+ blurred = active;
63
+ await frames();
64
+ }
65
+ return true;
66
+ }
67
+ /** How long `unfocused` keeps blurring a field that takes the focus back. */
68
+ const FOCUS_WAIT = 1_000;
69
+ /** The longest `openScene` waits for animations to finish. */
70
+ const ANIMATION_WAIT = 2_000;
71
+ /**
72
+ * Wait until a scene page in this frame has drawn: the view rendered in the asked language, the
73
+ * fonts and pictures loaded (`mediaReady`), two frames painted, and animations finished within
74
+ * their allowance, and then nothing focused (`unfocused`), so a field that autofocuses shows no
75
+ * focus ring. True when fonts or pictures were still loading as their allowance ran out.
76
+ */
77
+ async function drawn(frame, locale, live, { animationWait, mediaWait, readyWait, onMedia }) {
78
+ await frame.waitForFunction((lang) => document.documentElement.lang === lang &&
79
+ (document.getElementById('root')?.childElementCount ?? 0) > 0, locale, readyWait === undefined ? undefined : { timeout: readyWait });
80
+ // An attempt that lost its page (a module failed, the page loaded again) does nothing more.
81
+ if (!live())
82
+ return false;
83
+ await frame.evaluate(() => document.activeElement?.blur());
84
+ const media = await frame.evaluate(mediaReady, mediaWait);
85
+ onMedia?.(media);
86
+ await frame.evaluate(animationsDone, animationWait);
87
+ await frame.evaluate(unfocused, FOCUS_WAIT);
88
+ return !media.ready;
89
+ }
90
+ /** The console can show an app scene in an iframe of its own. */
91
+ export async function sceneFrames(page, locale) {
92
+ const frames = await Promise.all((await page.$$('iframe')).map(async (iframe, index) => {
93
+ const src = new URL((await iframe.getAttribute('src')) ?? '', page.url());
94
+ if (src.pathname !== '/_scene')
95
+ return;
96
+ const frame = await iframe.contentFrame();
97
+ if (frame)
98
+ return { frame, index, locale: src.searchParams.get('locale') ?? locale };
99
+ }));
100
+ return frames.filter((entry) => entry !== undefined);
101
+ }
102
+ /**
103
+ * Wait for the current scene and its framed scenes to finish drawing. True when a font or picture
104
+ * was still loading as its allowance ran out: the page is shot as it is.
105
+ */
106
+ export async function waitForScene(page, locale, { live = () => true, animationWait = ANIMATION_WAIT, mediaWait = MEDIA_WAIT, readyWait, unframed = false, onMedia, } = {}) {
107
+ const waits = { animationWait, mediaWait, readyWait, onMedia };
108
+ let late = await drawn(page.mainFrame(), locale, live, waits);
109
+ const children = await sceneFrames(page, locale);
110
+ if (unframed && children.length)
111
+ throw new Error('Framed scene appeared while settling a look');
112
+ for (const entry of children)
113
+ if (await drawn(entry.frame, entry.locale, live, waits))
114
+ late = true;
115
+ return late;
116
+ }
@@ -1,9 +1,11 @@
1
1
  import { type Frame, type FrameSize, type Scene, type Surface } from '@buffcore/config';
2
+ import type { PrototypeProblem } from '@buffcore/contracts/prototype';
2
3
  import { type Theme } from '@buffcore/tokens';
3
- import type { Browser } from 'playwright-core';
4
+ import type { Browser, Page } from 'playwright-core';
4
5
  import { type browserSession } from './browser.ts';
5
6
  import type { SnapshotHint } from './report.ts';
6
7
  import type { LoadFailure } from './scene-errors.ts';
8
+ import { type FallbackCounter } from './scene-look.ts';
7
9
  import type { SnapshotProgress } from './snapshot-progress.ts';
8
10
  import { type SceneRequestFacts } from './snapshot-requests.ts';
9
11
  import { lookKey, photographed } from './snapshot-themes.ts';
@@ -30,6 +32,7 @@ export interface Run {
30
32
  out: string;
31
33
  session?: ReturnType<typeof browserSession> | undefined;
32
34
  requests?: SceneRequestFacts;
35
+ onFallback?: FallbackCounter | undefined;
33
36
  hasAsset?: ((scene: Scene, url: URL) => boolean) | undefined;
34
37
  saveScene?: SnapshotProgress['draw'] | undefined;
35
38
  /** The first full-run scene on each surface, even when that scene has already finished. */
@@ -51,6 +54,18 @@ export type SceneResult = Awaited<ReturnType<typeof snapScene>> & {
51
54
  /** A page exception's source and first line; it is not evidence of a load failure. */
52
55
  scriptError?: LoadFailure;
53
56
  };
57
+ /** What one scene gathers as it goes. */
58
+ interface Found {
59
+ scene: Scene;
60
+ data: Set<string>;
61
+ screenshots: Record<string, string>;
62
+ /** The looks whose shot was cut at the height cap. */
63
+ cut: string[];
64
+ problems: PrototypeProblem[];
65
+ hints: SnapshotHint[];
66
+ /** The color pairs already reported, by theme and mode. */
67
+ pairs: Set<string>;
68
+ }
54
69
  /** Open the first look so the surface can finish its cold build. */
55
70
  export declare function warmSurface(browser: Browser, scene: Scene, run: Run, signal: AbortSignal): Promise<void>;
56
71
  /** One scene in every theme, mode and language: its screenshots and its problems. */
@@ -69,3 +84,9 @@ export declare function snapScene(browser: Browser, scene: Scene, run: Run, sign
69
84
  }[];
70
85
  hints: SnapshotHint[];
71
86
  }>;
87
+ /** The scene page as it shows one look: photographed when it is reviewed, and checked. */
88
+ export declare function checkLook(page: Page, look: {
89
+ theme: string;
90
+ mode: string;
91
+ locale: string;
92
+ }, run: Run, found: Found): Promise<void>;
@@ -11,7 +11,9 @@ import { measure } from './measure.js';
11
11
  import { MEDIA_WAIT } from './media-ready.js';
12
12
  import { t } from './messages.js';
13
13
  import { describe, readText } from './readable.js';
14
- import { renderScene, requireNoErrorOverlay } from './scene-render.js';
14
+ import { freshLoadsAgree, lookEvidence } from './scene-check.js';
15
+ import { LookMoveFailed, sceneLookLoader } from './scene-look.js';
16
+ import { renderScene, requireNoErrorOverlay, SceneTimeoutError } from './scene-render.js';
15
17
  import { sceneRequests } from './snapshot-requests.js';
16
18
  import { shotName } from './snapshot-shots.js';
17
19
  import { lookKey, photographed } from './snapshot-themes.js';
@@ -29,8 +31,46 @@ export async function warmSurface(browser, scene, run, signal) {
29
31
  }
30
32
  /** One scene in every theme, mode and language: its screenshots and its problems. */
31
33
  export async function snapScene(browser, scene, run, signal) {
34
+ const requests = run.requests ?? { apiCalls: false, untrackedRequests: false };
35
+ const attempt = { ...run, requests };
36
+ let moved = false;
37
+ let started = performance.now();
38
+ let result;
39
+ try {
40
+ result = await drawScene(browser, scene, attempt, signal, () => {
41
+ moved = true;
42
+ });
43
+ }
44
+ catch (error) {
45
+ signal.throwIfAborted();
46
+ if (!(error instanceof LookMoveFailed) && (!moved || error instanceof SceneTimeoutError))
47
+ throw error;
48
+ // The failed document may have changed storage or cookies. Replay the scene in a new
49
+ // context so its earlier full loads establish the same state as a run using only goto.
50
+ run.onFallback?.('scene');
51
+ started = performance.now();
52
+ result = await drawScene(browser, scene, attempt, signal);
53
+ }
54
+ const { checks, ...drawn } = result;
55
+ if (!(await freshLoadsAgree(browser, scene, attempt, signal, checks, started, checkLook))) {
56
+ // Something an earlier look left behind changed a checked one: draw every look fresh.
57
+ run.onFallback?.('scene');
58
+ const { checks: _, ...fresh } = await drawScene(browser, scene, attempt, signal);
59
+ return { ...fresh, ...requests };
60
+ }
61
+ return { ...drawn, ...requests };
62
+ }
63
+ function drawScene(browser, scene, run, signal, onMove) {
32
64
  return renderScene(browser, run.frames[scene.frame], scene.key, run.sceneTimeout, async (page, advise) => {
33
- const requests = sceneRequests(page, run, scene);
65
+ sceneRequests(page, run, scene);
66
+ let moves = 0;
67
+ const show = sceneLookLoader(page, onMove && run.onFallback, Boolean(onMove), () => {
68
+ moves++;
69
+ onMove?.();
70
+ });
71
+ let last;
72
+ // The last photographed look drawn in place: its saved picture is checked as well.
73
+ let photo;
34
74
  const found = {
35
75
  scene,
36
76
  data: dataWords(scene.props),
@@ -53,7 +93,12 @@ export async function snapScene(browser, scene, run, signal) {
53
93
  !(locale === run.first && photographed(theme.key, mode, run.product)))
54
94
  continue;
55
95
  const url = sceneUrl(run.urls[scene.surface], scene.key, look);
56
- if (await openScene(page, url, locale, late.length ? LATE_WAIT : undefined))
96
+ const mediaWait = late.length ? LATE_WAIT : undefined;
97
+ const before = moves;
98
+ const lateNow = await show(url, locale, mediaWait);
99
+ last = { look, url, mediaWait, late: lateNow };
100
+ const photoMoved = moves > before && locale === run.first && photographed(theme.key, mode, run.product);
101
+ if (lateNow)
57
102
  if (!late.length)
58
103
  late.push({
59
104
  scene: scene.key,
@@ -66,6 +111,8 @@ export async function snapScene(browser, scene, run, signal) {
66
111
  await checkLook(page, look, run, found).catch((error) => {
67
112
  throw pageGone(error) ? new PageLoadError(String(error), { cause: error }) : error;
68
113
  });
114
+ if (photoMoved)
115
+ photo = { last, evidence: await lookEvidence(page, last, run, scene, checkLook) };
69
116
  if (theme === declared) {
70
117
  const details = await advise(async (timeLeft) => (await watchFonts(page, scene.key, theme)?.(timeLeft)) ?? []);
71
118
  if (!details)
@@ -79,11 +126,19 @@ export async function snapScene(browser, scene, run, signal) {
79
126
  }
80
127
  }
81
128
  const { screenshots, cut, problems } = found;
82
- return { screenshots, cut, problems, hints: [...found.hints, ...late], ...requests };
129
+ // A scene with a look moved in place proves its last look against a fresh load, and its
130
+ // last photographed moved look when that is another one.
131
+ const checks = [];
132
+ if (moves > 0 && last) {
133
+ checks.push({ last, evidence: await lookEvidence(page, last, run, scene, checkLook) });
134
+ if (photo && photo.last !== last)
135
+ checks.push(photo);
136
+ }
137
+ return { screenshots, cut, problems, hints: [...found.hints, ...late], checks };
83
138
  }, signal, run);
84
139
  }
85
140
  /** The scene page as it shows one look: photographed when it is reviewed, and checked. */
86
- async function checkLook(page, look, run, found) {
141
+ export async function checkLook(page, look, run, found) {
87
142
  await requireNoErrorOverlay(page);
88
143
  const { theme, mode, locale } = look;
89
144
  const scene = found.scene.key;
@@ -8,7 +8,7 @@ import { configuredSnapshotRedact } from '../ui/snapshot-redaction.js';
8
8
  import { accessDenied } from './access-denied.js';
9
9
  import { readModel } from './data.js';
10
10
  import { MAX_SHOT_HEIGHT } from './full-shot.js';
11
- import { t } from './messages.js';
11
+ import { number, t } from './messages.js';
12
12
  import { newestReport, renderRetries, requireCommitted, shortCommit, unsavedWork, } from './report.js';
13
13
  import { remakeScreenshots, takeSnapshot } from './snapshot.js';
14
14
  import { SnapshotAccessRefused } from './snapshot-refused.js';
@@ -17,7 +17,7 @@ import { shareShots } from './snapshot-shared-shots.js';
17
17
  import { exitOnSignals } from './snapshot-signals.js';
18
18
  export { loadScenes } from './snapshot-setup.js';
19
19
  /** Snapshot (or remake) as the flags say; the screenshots, report and data model on disk. */
20
- async function snapshotted(flags, hints) {
20
+ async function snapshotted(flags, hints, onFallback) {
21
21
  const servers = {};
22
22
  // A signal takes the run's servers down and frees its locks, then ends the process.
23
23
  const unhook = exitOnSignals(() => {
@@ -25,7 +25,7 @@ async function snapshotted(flags, hints) {
25
25
  servers.locks?.release();
26
26
  });
27
27
  try {
28
- return await drawn(flags, hints, servers);
28
+ return await drawn(flags, hints, servers, onFallback);
29
29
  }
30
30
  finally {
31
31
  unhook();
@@ -34,14 +34,14 @@ async function snapshotted(flags, hints) {
34
34
  }
35
35
  }
36
36
  /** `--remake`: the last committed snapshot's screenshots, drawn again. */
37
- async function remade(run) {
37
+ async function remade(run, onFallback) {
38
38
  const { root, dir, scene, options } = run;
39
39
  requireCommitted(root, 'the screenshots are made again from the commit checked out');
40
40
  const report = await newestReport(root);
41
41
  if (!report)
42
42
  throw new Error('No snapshot here to make again: run ape prototype snapshot.');
43
43
  console.log(`Making the screenshots of snapshot ${report.commit} again:`);
44
- const made = await remakeScreenshots({ ...options, commit: report.commit, report });
44
+ const made = await remakeScreenshots({ ...options, commit: report.commit, report, onFallback });
45
45
  const folder = relative(root, join(dir, report.commit)).replaceAll('\\', '/');
46
46
  const base = { folder, commit: report.commit, scene: scene ?? null, remade: true };
47
47
  return {
@@ -58,7 +58,7 @@ async function remade(run) {
58
58
  };
59
59
  }
60
60
  /** The snapshot itself: every scene (or the ones asked for), then its report. */
61
- async function taken(run, commit) {
61
+ async function taken(run, commit, onFallback) {
62
62
  const { root, own, servers, scene, checkout, urls } = run;
63
63
  const unsaved = unsavedWork(root);
64
64
  const design = await designState(root);
@@ -71,6 +71,7 @@ async function taken(run, commit) {
71
71
  return takeSnapshot({
72
72
  ...run.options,
73
73
  commit,
74
+ onFallback,
74
75
  checkCheckout: servers.own
75
76
  ? () => {
76
77
  checkout?.check();
@@ -93,17 +94,17 @@ async function taken(run, commit) {
93
94
  artifacts: { 'data.json': model, ...(design ? { 'design.json': design } : {}) },
94
95
  });
95
96
  }
96
- async function drawn(flags, hints, servers) {
97
+ async function drawn(flags, hints, servers, onFallback) {
97
98
  const run = await setup(flags, servers);
98
99
  if (flags.remake)
99
- return remade(run);
100
+ return remade(run, onFallback);
100
101
  const { root, own, scene, picked, dir } = run;
101
102
  const commit = shortCommit(root, run.checkout?.head);
102
103
  const count = scene
103
104
  ? `scene ${Array.isArray(scene) ? scene.join(', ') : scene}`
104
105
  : `${run.scenes.scenes.length} scenes`;
105
106
  console.log(`Snapshot of ${count}:`);
106
- const report = await taken(run, commit);
107
+ const report = await taken(run, commit, onFallback);
107
108
  if (own && !run.comp && report.scene === undefined && !report.problems.length)
108
109
  await shareShots(root, join(dir, commit), report);
109
110
  const selected = new Set(picked.map((scene) => scene.key));
@@ -167,7 +168,16 @@ function printNotes(result) {
167
168
  /** `ape prototype snapshot`: needs `ape dev` running. Fails (exit 1) when a check fails. */
168
169
  export async function snapshot(flags = {}) {
169
170
  const hints = new Set();
170
- const captured = await captureSnapshotCommand(() => snapshotted(flags, hints), findRoot);
171
+ const fallbacks = { look: 0, scene: 0 };
172
+ const countFallback = (kind) => {
173
+ fallbacks[kind]++;
174
+ };
175
+ const captured = await captureSnapshotCommand(() => snapshotted(flags, hints, countFallback), findRoot);
176
+ if (!flags.json && fallbacks.look + fallbacks.scene > 0)
177
+ console.log(t('prototype.drawFallbacks', {
178
+ looks: number(fallbacks.look),
179
+ scenes: number(fallbacks.scene),
180
+ }));
171
181
  if (captured.kind !== 'passed') {
172
182
  printCommandFailure(captured, flags.json, console.log);
173
183
  const note = captured.kind === 'failed' && !flags.json ? cutNote(captured.metadata?.cut) : '';
@@ -17,9 +17,16 @@ const CHECKS = [
17
17
  'font-samples',
18
18
  'full-shot',
19
19
  'measure',
20
+ 'media-ready',
21
+ 'module-errors',
20
22
  'readable',
21
23
  'scene',
24
+ 'scene-check',
25
+ 'scene-load',
26
+ 'scene-look',
27
+ 'scene-ready',
22
28
  'scene-render',
29
+ 'snapshot-recovery',
23
30
  'snapshot-requests',
24
31
  'snapshot-themes',
25
32
  ];
@@ -6,4 +6,4 @@ export interface SceneRequestFacts {
6
6
  untrackedRequests: boolean;
7
7
  }
8
8
  /** Context requests include iframes, workers and requests that fail before receiving a response. */
9
- export declare function sceneRequests(page: Page, { urls, hasAsset, requests: found }: Run, scene: Scene): SceneRequestFacts;
9
+ export declare function sceneRequests(page: Page, { urls, hasAsset, requests: found, }: Pick<Run, 'urls' | 'hasAsset' | 'requests'>, scene: Scene): SceneRequestFacts;
@@ -7,7 +7,7 @@ const origin = (url) => {
7
7
  };
8
8
  const apiPath = (url) => /^\/api(?:\/|$)/i.test(url.pathname);
9
9
  /** Context requests include iframes, workers and requests that fail before receiving a response. */
10
- export function sceneRequests(page, { urls, hasAsset, requests: found = { apiCalls: false, untrackedRequests: false } }, scene) {
10
+ export function sceneRequests(page, { urls, hasAsset, requests: found = { apiCalls: false, untrackedRequests: false }, }, scene) {
11
11
  const api = urls.api ? origin(new URL(urls.api)) : undefined;
12
12
  const surfaces = new Set();
13
13
  for (const address of [urls.app, urls.admin])
@@ -180,8 +180,10 @@ export function snapshotServers(root, environment, urls, { owners = systemOwners
180
180
  throw new SnapshotRefused(t('prototype.installChanged'));
181
181
  },
182
182
  async verify() {
183
- for (const [surface, child] of children)
184
- await owned(surface, child);
183
+ const checks = await Promise.allSettled([...children].map(([surface, child]) => owned(surface, child)));
184
+ for (const check of checks)
185
+ if (check.status === 'rejected')
186
+ throw check.reason;
185
187
  },
186
188
  kill,
187
189
  exit: (server) => exits.get(server),
@@ -40,6 +40,7 @@ export interface SnapshotOptions {
40
40
  /** A linked worktree's run draws against a stand-in API: the report says so. */
41
41
  api?: 'stand-in' | undefined;
42
42
  serverExit?: Run['serverExit'];
43
+ onFallback?: Run['onFallback'];
43
44
  /** Scene pages open at once (`--pages`); undefined is `pagesFor` the cores and the free memory. */
44
45
  pages?: number | undefined;
45
46
  /** Keys of the scenes drawn before the others (the change's own); the report keeps its order. */
@@ -39,6 +39,7 @@ function runOf(options) {
39
39
  commit,
40
40
  out: join(options.dir, commit),
41
41
  serverExit: options.serverExit,
42
+ onFallback: options.onFallback,
42
43
  };
43
44
  }
44
45
  /**