@cevek/screentest 0.4.0 → 0.6.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/dist/index.js CHANGED
@@ -14560,9 +14560,24 @@ var projectInfoSchema = external_exports.object({
14560
14560
  /** Current git branch, or `null` if not a git repo (or `git` not on PATH). */
14561
14561
  branch: external_exports.string().nullable()
14562
14562
  });
14563
+ var rendererSchema = external_exports.object({
14564
+ fingerprint: external_exports.string().min(1),
14565
+ label: external_exports.string()
14566
+ });
14563
14567
  var docSchema = external_exports.object({
14564
14568
  /** Optional for backward compatibility with pre-0.3 doc.json files. */
14565
14569
  project: projectInfoSchema.optional(),
14570
+ /**
14571
+ * `current` shot this run's actuals; `baseline` is what snapshot.json
14572
+ * records for its hashes (null when it records none). `mismatch`: the
14573
+ * renderers differ AND the diffs look like it (see generateDoc). Optional
14574
+ * for pre-0.5 doc.json files.
14575
+ */
14576
+ renderer: external_exports.object({
14577
+ current: rendererSchema,
14578
+ baseline: rendererSchema.nullable(),
14579
+ mismatch: external_exports.boolean()
14580
+ }).optional(),
14566
14581
  groups: external_exports.array(groupItemSchema)
14567
14582
  });
14568
14583
  var snapshotTestSchema = external_exports.object({
@@ -14576,6 +14591,7 @@ var snapshotGroupSchema = external_exports.lazy(
14576
14591
  })
14577
14592
  );
14578
14593
  var snapshotDocSchema = external_exports.object({
14594
+ renderer: rendererSchema.optional(),
14579
14595
  groups: external_exports.array(snapshotGroupSchema)
14580
14596
  });
14581
14597
  var apiDocResponseSchema = external_exports.object({
@@ -14859,6 +14875,9 @@ async function withFileLock(absPath, fn) {
14859
14875
  function isSnapshotGroup(x) {
14860
14876
  return Array.isArray(x.items);
14861
14877
  }
14878
+ function hasAnyHash(items) {
14879
+ return items.some((n) => isSnapshotGroup(n) ? hasAnyHash(n.items) : n.hash !== null);
14880
+ }
14862
14881
  function upsertHash(doc, path, hash2) {
14863
14882
  if (path.length === 0) throw new Error("Empty path for upsertHash");
14864
14883
  const testName = path[path.length - 1];
@@ -14950,7 +14969,9 @@ async function patchSnapshot(args) {
14950
14969
  throw err;
14951
14970
  }
14952
14971
  }
14972
+ const fresh = !doc.renderer && !hasAnyHash(doc.groups);
14953
14973
  upsertHash(doc, args.path, args.hash);
14974
+ if (args.renderer && fresh) doc = { renderer: args.renderer, groups: doc.groups };
14954
14975
  await atomicWriteJson(abs, doc);
14955
14976
  });
14956
14977
  }
@@ -14990,7 +15011,8 @@ function acceptRoute(state) {
14990
15011
  docDir: state.docDir,
14991
15012
  patchSnapshotJsonFile: entry.item.patchSnapshotJsonFile,
14992
15013
  path: [...entry.parents, entry.name],
14993
- hash: hash2
15014
+ hash: hash2,
15015
+ renderer: state.doc.renderer?.current
14994
15016
  });
14995
15017
  res.json({
14996
15018
  hash: hash2,
@@ -15256,6 +15278,27 @@ function detectBranch(projectRoot) {
15256
15278
  const branch = r.stdout.trim();
15257
15279
  return branch || null;
15258
15280
  }
15281
+ async function readRunRenderer(runFile) {
15282
+ try {
15283
+ const run3 = JSON.parse(await fs4.readFile(runFile, "utf8"));
15284
+ const parsed = rendererSchema.safeParse(run3.renderer);
15285
+ return parsed.success ? parsed.data : null;
15286
+ } catch {
15287
+ return null;
15288
+ }
15289
+ }
15290
+ function baselineRenderer(snap) {
15291
+ const parsed = rendererSchema.safeParse(snap.renderer);
15292
+ return parsed.success ? parsed.data : null;
15293
+ }
15294
+ async function writeSnapshotRenderer(snapshotFile, renderer) {
15295
+ const raw = JSON.parse(await fs4.readFile(snapshotFile, "utf8"));
15296
+ const { renderer: _old, ...rest } = raw;
15297
+ await fs4.writeFile(snapshotFile, JSON.stringify({ renderer, ...rest }, null, 2) + "\n");
15298
+ }
15299
+ function describeRenderer(r) {
15300
+ return `${r.label} [${r.fingerprint}]`;
15301
+ }
15259
15302
  function isGroup(node) {
15260
15303
  return Array.isArray(node.items);
15261
15304
  }
@@ -15319,8 +15362,9 @@ function countLeaves(doc) {
15319
15362
  for (const g of doc.groups) walk(g.items);
15320
15363
  return n;
15321
15364
  }
15322
- async function generateDoc(projectRoot, snapshotFile, actualDir, docFile, cacheDir, opts = {}) {
15323
- const detectDeletions = opts.detectDeletions ?? true;
15365
+ async function generateDoc(paths, opts = {}) {
15366
+ const { projectRoot, snapshotFile, actualDir, docFile, cacheDir } = paths;
15367
+ const fullRun = opts.fullRun ?? true;
15324
15368
  const snap = await readSnapshot(snapshotFile);
15325
15369
  const expectedByPath = indexSnapshot(snap);
15326
15370
  const actuals = await walkActual(actualDir);
@@ -15358,7 +15402,7 @@ async function generateDoc(projectRoot, snapshotFile, actualDir, docFile, cacheD
15358
15402
  });
15359
15403
  summary.change++;
15360
15404
  }
15361
- if (detectDeletions) {
15405
+ if (fullRun) {
15362
15406
  for (const [key, hash2] of expectedByPath) {
15363
15407
  if (seen.has(key) || !hash2) continue;
15364
15408
  insertLeaf(doc, key.split("/"), {
@@ -15369,13 +15413,47 @@ async function generateDoc(projectRoot, snapshotFile, actualDir, docFile, cacheD
15369
15413
  summary.deleted++;
15370
15414
  }
15371
15415
  }
15416
+ const current = await readRunRenderer(paths.runFile);
15417
+ let baseline = baselineRenderer(snap);
15418
+ const allMatched = fullRun && summary.change === 0 && summary.unchanged > 0;
15419
+ if (current && allMatched && baseline?.fingerprint !== current.fingerprint && !process.env.CI) {
15420
+ await writeSnapshotRenderer(snapshotFile, current);
15421
+ process.stdout.write(
15422
+ `[screentest] recorded renderer ${describeRenderer(current)} in ${relative(projectRoot, snapshotFile)}` + (baseline ? ` (was ${describeRenderer(baseline)})` : "") + ` \u2014 every screenshot matched under it. Commit it with the baselines.
15423
+ `
15424
+ );
15425
+ baseline = current;
15426
+ }
15427
+ const mismatch = !!current && !!baseline && baseline.fingerprint !== current.fingerprint && summary.change > 0 && summary.change >= summary.unchanged;
15428
+ if (current) doc.renderer = { current, baseline, mismatch };
15372
15429
  await fs4.mkdir(cacheDir, { recursive: true });
15373
15430
  await fs4.writeFile(docFile, JSON.stringify(doc, null, 2));
15374
15431
  const total = countLeaves(doc);
15375
- const deletedSummary = detectDeletions ? `deleted: ${summary.deleted}, ` : "";
15432
+ if (mismatch && current && baseline) {
15433
+ process.stderr.write(
15434
+ `
15435
+ [screentest] RENDERER CHANGED \u2014 the diffs below are likely not app changes.
15436
+ [screentest] baselines: ${describeRenderer(baseline)}
15437
+ [screentest] this run: ${describeRenderer(current)}
15438
+ [screentest] Re-run with the baseline renderer, or accept everything to
15439
+ [screentest] move the baselines to this one.
15440
+
15441
+ `
15442
+ );
15443
+ } else if (current && !baseline && summary.change > 0 && summary.unchanged === 0) {
15444
+ process.stderr.write(
15445
+ `
15446
+ [screentest] Every screenshot changed, and ${relative(projectRoot, snapshotFile)}
15447
+ [screentest] records no renderer to compare with. Make sure this run used
15448
+ [screentest] the same renderer as the baselines before accepting.
15449
+
15450
+ `
15451
+ );
15452
+ }
15453
+ const deletedSummary = fullRun ? `deleted: ${summary.deleted}, ` : "";
15376
15454
  process.stdout.write(
15377
15455
  `Wrote ${docFile}
15378
- ${total} diff${total === 1 ? "" : "s"} to review (new: ${summary.new}, change: ${summary.change}, ${deletedSummary}unchanged: ${summary.unchanged}${detectDeletions ? "" : "; deletion detection disabled \u2014 subset run"})
15456
+ ${total} diff${total === 1 ? "" : "s"} to review (new: ${summary.new}, change: ${summary.change}, ${deletedSummary}unchanged: ${summary.unchanged}${fullRun ? "" : "; deletion detection disabled \u2014 subset run"})
15379
15457
  `
15380
15458
  );
15381
15459
  return total;
@@ -15392,7 +15470,8 @@ function resolveRunnerPaths(cwd = process.cwd()) {
15392
15470
  snapshotFile: resolveSnapshotFile(projectRoot),
15393
15471
  cacheDir,
15394
15472
  actualDir: join4(cacheDir, "actual"),
15395
- docFile: join4(cacheDir, "doc.json")
15473
+ docFile: join4(cacheDir, "doc.json"),
15474
+ runFile: join4(cacheDir, "run.json")
15396
15475
  };
15397
15476
  }
15398
15477
  function resolveSnapshotFile(projectRoot) {
@@ -15415,13 +15494,7 @@ function run(cmd, argv) {
15415
15494
  }
15416
15495
  async function runReview() {
15417
15496
  const paths = resolveRunnerPaths();
15418
- const total = await generateDoc(
15419
- paths.projectRoot,
15420
- paths.snapshotFile,
15421
- paths.actualDir,
15422
- paths.docFile,
15423
- paths.cacheDir
15424
- );
15497
+ const total = await generateDoc(paths);
15425
15498
  if (total === 0) {
15426
15499
  process.stdout.write("Nothing to review \u2014 all snapshots match.\n");
15427
15500
  return 0;
@@ -15477,37 +15550,56 @@ Tip: add a script to package.json so you can just \`npm run screentest\`:
15477
15550
  // src/daemon.ts
15478
15551
  import { spawn as spawn2, spawnSync as spawnSync2 } from "child_process";
15479
15552
  import { existsSync as existsSync4 } from "fs";
15553
+ import { request } from "http";
15480
15554
  import { dirname as dirname6, resolve as resolve8 } from "path";
15481
15555
  import { fileURLToPath as fileURLToPath4 } from "url";
15482
- import { createConnection } from "net";
15483
15556
  var IMAGE_NAME = "cevek/screentest-firefox";
15484
- var IMAGE_TAG = "pw-1.60.0";
15557
+ var IMAGE_TAG = "pw-1.60.0-r2";
15558
+ var PRE_IDLE_STOP_IMAGE = `${IMAGE_NAME}:pw-1.60.0`;
15485
15559
  var FULL_IMAGE = `${IMAGE_NAME}:${IMAGE_TAG}`;
15486
15560
  var CONTAINER_NAME = "screentest-firefox";
15487
15561
  var PORT = 5180;
15488
15562
  var WS_PATH = "screentest-firefox";
15489
15563
  var WS_ENDPOINT = `ws://localhost:${PORT}/${WS_PATH}`;
15564
+ var START_TIMEOUT_MS = 3e4;
15565
+ var READY_TIMEOUT_MS = 15e3;
15566
+ var IDLE_ENV = "SCREENTEST_DAEMON_IDLE_SECONDS";
15490
15567
  function run2(cmd, argv) {
15491
15568
  return new Promise((resolveExit) => {
15492
15569
  const p = spawn2(cmd, argv, { stdio: "inherit" });
15570
+ p.on("error", () => resolveExit(127));
15493
15571
  p.on("exit", (code) => resolveExit(code ?? 0));
15494
15572
  });
15495
15573
  }
15496
15574
  function daemonState() {
15497
15575
  const ps = spawnSync2(
15498
15576
  "docker",
15499
- ["ps", "-a", "-f", `name=^${CONTAINER_NAME}$`, "--format", "{{.Status}} {{.Image}}"],
15577
+ ["ps", "-a", "-f", `name=^${CONTAINER_NAME}$`, "--format", "{{.State}} {{.Image}} {{.ID}}"],
15500
15578
  { stdio: "pipe", encoding: "utf8" }
15501
15579
  );
15502
- const line = ps.stdout.trim();
15503
- if (line.startsWith("Up")) {
15504
- const tab = line.indexOf(" ");
15505
- const image = tab === -1 ? "" : line.slice(tab + 1).trim();
15506
- return { state: "running", image };
15507
- }
15580
+ if (ps.error) return { state: "no-docker", reason: ps.error.message };
15581
+ if (ps.status !== 0) return { state: "no-docker", reason: ps.stderr.trim() };
15582
+ const [status = "", image = "", id = ""] = ps.stdout.trim().split(" ");
15583
+ if (status === "running") return { state: "running", image: image.trim(), id: id.trim() };
15584
+ if (status === "paused") return { state: "paused", id: id.trim() };
15585
+ if (status === "created" || status === "restarting" || status === "removing") {
15586
+ return { state: "transitional", status };
15587
+ }
15588
+ const staleId = id.trim();
15508
15589
  const img = spawnSync2("docker", ["image", "inspect", FULL_IMAGE], { stdio: "pipe" });
15509
- if (img.status !== 0) return { state: "missing-image" };
15510
- return { state: "stopped" };
15590
+ if (img.status !== 0) return { state: "missing-image", staleId };
15591
+ return { state: "stopped", staleId };
15592
+ }
15593
+ function sameRunningContainer(id) {
15594
+ const s = daemonState();
15595
+ return s.state === "running" && s.id === id;
15596
+ }
15597
+ function containerExists(id) {
15598
+ const r = spawnSync2("docker", ["ps", "-aq", "--no-trunc", "-f", `id=${id}`], {
15599
+ stdio: "pipe",
15600
+ encoding: "utf8"
15601
+ });
15602
+ return r.status !== 0 || r.stdout.trim() !== "";
15511
15603
  }
15512
15604
  function resolveTemplatesDir() {
15513
15605
  const here = dirname6(fileURLToPath4(import.meta.url));
@@ -15540,84 +15632,166 @@ async function buildImage() {
15540
15632
  }
15541
15633
  return true;
15542
15634
  }
15543
- function probePort() {
15635
+ function probeServer() {
15544
15636
  return new Promise((resolveProbe) => {
15545
- const s = createConnection({ host: "127.0.0.1", port: PORT });
15546
- s.once("connect", () => {
15547
- s.end();
15637
+ const req = request({
15638
+ host: "127.0.0.1",
15639
+ port: PORT,
15640
+ path: `/${WS_PATH}`,
15641
+ timeout: 1e3,
15642
+ agent: false
15643
+ });
15644
+ req.once("response", (res) => {
15645
+ res.resume();
15548
15646
  resolveProbe(true);
15549
15647
  });
15550
- s.once("error", () => resolveProbe(false));
15648
+ req.once("timeout", () => req.destroy());
15649
+ req.once("error", () => resolveProbe(false));
15650
+ req.end();
15551
15651
  });
15552
15652
  }
15553
- async function waitForReady(timeoutMs = 1e4) {
15554
- const start = Date.now();
15555
- while (Date.now() - start < timeoutMs) {
15556
- if (await probePort()) return true;
15557
- await new Promise((r) => setTimeout(r, 150));
15558
- }
15559
- return false;
15653
+ function sleep(ms) {
15654
+ return new Promise((r) => setTimeout(r, ms));
15560
15655
  }
15561
- async function startDaemon() {
15562
- const s = daemonState();
15563
- if (s.state === "running") {
15564
- if (s.image !== FULL_IMAGE) {
15565
- process.stderr.write(
15566
- `screentest-firefox daemon is running, but on a different image:
15656
+ function assertUsable(s) {
15657
+ if (s.state === "no-docker") {
15658
+ throw new Error(
15659
+ `docker is not available \u2014 screentest renders only in the pinned Firefox
15660
+ container (${FULL_IMAGE}). Start Docker, then re-run.
15661
+ docker said: ${s.reason}
15662
+ `
15663
+ );
15664
+ }
15665
+ if (s.state === "paused") {
15666
+ throw new Error(`screentest-firefox daemon is paused.
15667
+ \u2192 docker unpause ${CONTAINER_NAME}
15668
+ `);
15669
+ }
15670
+ if (s.state === "running" && s.image !== FULL_IMAGE) {
15671
+ throw new Error(
15672
+ `screentest-firefox daemon is running, but on a different image:
15567
15673
  running: ${s.image}
15568
15674
  this @cevek/screentest wants: ${FULL_IMAGE}
15569
- \u2192 stop it first: screentest stop
15675
+ ` + (s.image === PRE_IDLE_STOP_IMAGE ? ` (daemons from @cevek/screentest < 0.6 never stop on their own)
15676
+ ` : "") + ` \u2192 stop it first: screentest stop
15570
15677
  \u2192 then re-run: screentest serve
15678
+ `
15679
+ );
15680
+ }
15681
+ }
15682
+ function startContainer(staleId) {
15683
+ if (staleId) spawnSync2("docker", ["rm", staleId], { stdio: "pipe" });
15684
+ const idle = process.env[IDLE_ENV];
15685
+ const r = spawnSync2(
15686
+ "docker",
15687
+ [
15688
+ "run",
15689
+ "-d",
15690
+ "--rm",
15691
+ "--name",
15692
+ CONTAINER_NAME,
15693
+ "--network=host",
15694
+ ...idle ? ["-e", `${IDLE_ENV}=${idle}`] : [],
15695
+ FULL_IMAGE
15696
+ ],
15697
+ { stdio: "pipe", encoding: "utf8" }
15698
+ );
15699
+ return { ok: !r.error && r.status === 0, stderr: r.stderr?.trim() ?? String(r.error) };
15700
+ }
15701
+ async function ensureDaemon() {
15702
+ let deadline = Date.now() + START_TIMEOUT_MS;
15703
+ let started = false;
15704
+ let lastError = "";
15705
+ let deafId = "";
15706
+ let deafSince = 0;
15707
+ for (; ; ) {
15708
+ const s = daemonState();
15709
+ assertUsable(s);
15710
+ if (s.state === "running") {
15711
+ if (await probeServer() && sameRunningContainer(s.id)) return { started };
15712
+ if (deafId !== s.id) {
15713
+ deafId = s.id;
15714
+ deafSince = Date.now();
15715
+ }
15716
+ const now = Date.now();
15717
+ if (now - deafSince > READY_TIMEOUT_MS || now > deadline + READY_TIMEOUT_MS) {
15718
+ spawnSync2("docker", ["logs", CONTAINER_NAME], { stdio: "inherit" });
15719
+ throw new Error(
15720
+ `screentest-firefox daemon container is up but never answered on port ${PORT}.
15721
+ `
15722
+ );
15723
+ }
15724
+ await sleep(150);
15725
+ continue;
15726
+ }
15727
+ if (Date.now() > deadline) {
15728
+ throw new Error(
15729
+ `screentest-firefox daemon did not come up within ${START_TIMEOUT_MS / 1e3}s` + (s.state === "transitional" ? ` (container stuck in "${s.status}")` : "") + (lastError ? `:
15730
+ ${lastError}` : "") + `
15571
15731
  `
15572
15732
  );
15573
- return 1;
15574
15733
  }
15575
- process.stdout.write(`screentest-firefox daemon already running at ${WS_ENDPOINT}
15576
- `);
15577
- return 0;
15578
- }
15579
- if (s.state === "missing-image") {
15580
- if (!await buildImage()) return 1;
15581
- }
15582
- spawnSync2("docker", ["rm", "-f", CONTAINER_NAME], { stdio: "pipe" });
15583
- process.stderr.write(`Starting screentest-firefox daemon (port ${PORT})\u2026
15734
+ if (s.state === "missing-image") {
15735
+ if (!await buildImage()) throw new Error(`could not build ${FULL_IMAGE}
15584
15736
  `);
15585
- const code = await run2("docker", [
15586
- "run",
15587
- "-d",
15588
- "--rm",
15589
- "--name",
15590
- CONTAINER_NAME,
15591
- "--network=host",
15592
- FULL_IMAGE
15593
- ]);
15594
- if (code !== 0) {
15595
- process.stderr.write(`docker run failed (exit ${code})
15737
+ deadline = Date.now() + START_TIMEOUT_MS;
15738
+ }
15739
+ if (s.state === "stopped" || s.state === "missing-image") {
15740
+ if (!started) process.stderr.write(`Starting screentest-firefox daemon (port ${PORT})\u2026
15596
15741
  `);
15597
- return code;
15742
+ const r = startContainer(s.staleId);
15743
+ if (r.ok) started = true;
15744
+ else lastError = r.stderr;
15745
+ }
15746
+ await sleep(300);
15598
15747
  }
15599
- if (!await waitForReady()) {
15600
- process.stderr.write(`Daemon container started but port ${PORT} never opened. Logs:
15601
- `);
15602
- spawnSync2("docker", ["logs", CONTAINER_NAME], { stdio: "inherit" });
15748
+ }
15749
+ async function startDaemon() {
15750
+ try {
15751
+ const { started } = await ensureDaemon();
15752
+ process.stdout.write(
15753
+ `screentest-firefox daemon ${started ? "ready" : "already running"} at ${WS_ENDPOINT}
15754
+ `
15755
+ );
15756
+ return 0;
15757
+ } catch (err) {
15758
+ process.stderr.write(err instanceof Error ? err.message : String(err));
15603
15759
  return 1;
15604
15760
  }
15605
- process.stdout.write(`screentest-firefox daemon ready at ${WS_ENDPOINT}
15606
- `);
15607
- return 0;
15608
15761
  }
15609
15762
  async function stopDaemon() {
15610
15763
  const s = daemonState();
15611
- if (s.state !== "running") {
15764
+ if (s.state !== "running" && s.state !== "paused") {
15612
15765
  process.stdout.write("screentest-firefox daemon is not running\n");
15613
15766
  return 0;
15614
15767
  }
15615
- const code = await run2("docker", ["stop", CONTAINER_NAME]);
15616
- if (code === 0) process.stdout.write("screentest-firefox daemon stopped\n");
15617
- return code;
15768
+ const code = await run2("docker", ["stop", s.id]);
15769
+ const gone = code === 0 || !containerExists(s.id);
15770
+ if (gone) process.stdout.write("screentest-firefox daemon stopped\n");
15771
+ return gone ? 0 : code;
15618
15772
  }
15619
15773
  async function printStatus() {
15620
15774
  const s = daemonState();
15775
+ if (s.state === "no-docker") {
15776
+ process.stdout.write(
15777
+ `screentest-firefox daemon: unknown (docker is not available: ${s.reason})
15778
+ `
15779
+ );
15780
+ return 1;
15781
+ }
15782
+ if (s.state === "paused") {
15783
+ process.stdout.write(
15784
+ `screentest-firefox daemon: paused
15785
+ \u2192 docker unpause ${CONTAINER_NAME}
15786
+ `
15787
+ );
15788
+ return 0;
15789
+ }
15790
+ if (s.state === "transitional") {
15791
+ process.stdout.write(`screentest-firefox daemon: ${s.status}
15792
+ `);
15793
+ return 0;
15794
+ }
15621
15795
  if (s.state === "running") {
15622
15796
  const match = s.image === FULL_IMAGE ? "(matches this @cevek/screentest)" : "(MISMATCH!)";
15623
15797
  process.stdout.write(
@@ -15640,14 +15814,14 @@ async function printStatus() {
15640
15814
  if (s.state === "stopped") {
15641
15815
  process.stdout.write(
15642
15816
  `screentest-firefox daemon: stopped (image ${FULL_IMAGE} exists)
15643
- start it with: screentest serve
15817
+ starts automatically on the next test run, or now with: screentest serve
15644
15818
  `
15645
15819
  );
15646
15820
  return 0;
15647
15821
  }
15648
15822
  process.stdout.write(
15649
15823
  `screentest-firefox daemon: not installed (image ${FULL_IMAGE} missing)
15650
- build + start with: screentest serve
15824
+ built + started automatically on the next test run, or now with: screentest serve
15651
15825
  `
15652
15826
  );
15653
15827
  return 0;
@@ -15940,7 +16114,8 @@ function printHelp() {
15940
16114
  "",
15941
16115
  " screentest serve start the shared Firefox browser-server daemon",
15942
16116
  " (builds the image on first run). One daemon per",
15943
- " machine \u2014 used by every project",
16117
+ " machine \u2014 used by every project. Test runs start",
16118
+ " it on their own; `serve` just does it up front",
15944
16119
  " screentest stop stop the daemon",
15945
16120
  " screentest status show whether the daemon is running",
15946
16121
  "",
@@ -15963,8 +16138,8 @@ function printHelp() {
15963
16138
  "Running screenshot tests:",
15964
16139
  " Add to your package.json scripts (or run directly):",
15965
16140
  ' "screentest": "vitest run --config vitest.screentest.config.ts"',
15966
- " The vitest globalSetup we ship handles pre-flight (wipe actualDir, locate",
15967
- " the daemon) and post-flight (build doc.json, auto-launch the review UI",
16141
+ " The vitest globalSetup we ship handles pre-flight (wipe actualDir, start",
16142
+ " the daemon if needed) and post-flight (build doc.json, auto-launch the review UI",
15968
16143
  " if there are diffs).",
15969
16144
  "",
15970
16145
  "Env vars (UI mode):",
package/dist/runner.js CHANGED
@@ -14,7 +14,8 @@ function resolveRunnerPaths(cwd = process.cwd()) {
14
14
  snapshotFile: resolveSnapshotFile(projectRoot),
15
15
  cacheDir,
16
16
  actualDir: join(cacheDir, "actual"),
17
- docFile: join(cacheDir, "doc.json")
17
+ docFile: join(cacheDir, "doc.json"),
18
+ runFile: join(cacheDir, "run.json")
18
19
  };
19
20
  }
20
21
  function resolveSnapshotFile(projectRoot) {
@@ -198,15 +199,19 @@ async function compareSnapshot(target, name, opts = {}) {
198
199
  // src/runner/browser.ts
199
200
  import { inject } from "vitest";
200
201
  import { firefox } from "playwright";
202
+
203
+ // src/runner/context-defaults.ts
204
+ var CONTEXT_DEFAULTS = {
205
+ viewport: { width: 1280, height: 800 },
206
+ deviceScaleFactor: 1,
207
+ reducedMotion: "reduce"
208
+ };
209
+
210
+ // src/runner/browser.ts
201
211
  async function newPage(opts = {}) {
202
212
  const wsEndpoint = inject("wsEndpoint");
203
213
  const browser = await firefox.connect(wsEndpoint);
204
- const ctx = await browser.newContext({
205
- viewport: { width: 1280, height: 800 },
206
- deviceScaleFactor: 1,
207
- reducedMotion: "reduce",
208
- ...opts
209
- });
214
+ const ctx = await browser.newContext({ ...CONTEXT_DEFAULTS, ...opts });
210
215
  const page = await ctx.newPage();
211
216
  return {
212
217
  ctx,
@@ -18,7 +18,7 @@ WORKDIR /work
18
18
  RUN npm init -y >/dev/null \
19
19
  && npm install --no-audit --no-fund --no-progress playwright@1.60.0
20
20
 
21
- COPY launch-server.mjs ./
21
+ COPY launch-server.mjs idle-proxy.mjs ./
22
22
 
23
23
  EXPOSE 5180
24
24
 
@@ -0,0 +1,88 @@
1
+ import net from 'node:net';
2
+
3
+ export const DEFAULT_IDLE_SECONDS = 180;
4
+ // A cold start must survive until the host's readiness probe and lease
5
+ // connect land (ensureDaemon polls every 150–300 ms; Firefox may be slow).
6
+ export const MIN_IDLE_SECONDS = 10;
7
+ // setTimeout overflows above 2^31-1 ms and fires after 1 ms instead.
8
+ const MAX_TIMER_MS = 2 ** 31 - 1;
9
+
10
+ /**
11
+ * `SCREENTEST_DAEMON_IDLE_SECONDS`: a non-negative number, `0` = never stop,
12
+ * raised to MIN_IDLE_SECONDS. Anything else falls back to the default rather
13
+ * than disabling the stop.
14
+ *
15
+ * @param {string | undefined} raw
16
+ * @returns {number}
17
+ */
18
+ export function parseIdleSeconds(raw) {
19
+ const s = raw?.trim() ?? '';
20
+ if (!/^\d+(\.\d+)?$/.test(s)) return DEFAULT_IDLE_SECONDS;
21
+ const n = Number(s);
22
+ return n === 0 ? 0 : Math.max(n, MIN_IDLE_SECONDS);
23
+ }
24
+
25
+ /**
26
+ * TCP proxy in front of the Playwright browser-server that counts open client
27
+ * connections; Playwright's BrowserServer exposes no such count. Calls
28
+ * `onIdle` once after `idleMs` with no connection open (counted from start
29
+ * and from every drop to zero), after it has already stopped accepting.
30
+ * `idleMs <= 0` never fires; `close()` stops it for good.
31
+ *
32
+ * @param {{ host: string; port: number; upstreamPort: number; idleMs: number; onIdle: () => void }} opts
33
+ * @returns {Promise<{ port: number; close: () => void }>}
34
+ */
35
+ export function startIdleProxy({ host, port, upstreamPort, idleMs, onIdle }) {
36
+ let open = 0;
37
+ let stopped = false;
38
+ let timer;
39
+ const stop = () => {
40
+ stopped = true;
41
+ clearTimeout(timer);
42
+ proxy.close();
43
+ };
44
+ const wait = (until) => {
45
+ timer = setTimeout(
46
+ () => {
47
+ if (Date.now() < until) return wait(until);
48
+ stop();
49
+ onIdle();
50
+ },
51
+ Math.min(until - Date.now(), MAX_TIMER_MS),
52
+ );
53
+ };
54
+ const arm = () => {
55
+ if (stopped || idleMs <= 0) return;
56
+ wait(Date.now() + idleMs);
57
+ };
58
+
59
+ // Half-open on both legs: a client's FIN must not cut off the reply still
60
+ // coming back. `pipe` forwards each FIN; 'close' fires once both are done.
61
+ const proxy = net.createServer({ allowHalfOpen: true }, (client) => {
62
+ clearTimeout(timer);
63
+ open += 1;
64
+ const upstream = net.connect({ port: upstreamPort, host: '127.0.0.1', allowHalfOpen: true });
65
+ client.pipe(upstream);
66
+ upstream.pipe(client);
67
+ client.on('error', () => upstream.destroy());
68
+ upstream.on('error', () => client.destroy());
69
+ client.on('close', () => {
70
+ upstream.destroy();
71
+ open -= 1;
72
+ if (open === 0) arm();
73
+ });
74
+ upstream.on('close', () => client.destroy());
75
+ });
76
+
77
+ return new Promise((resolveStart, rejectStart) => {
78
+ proxy.once('error', rejectStart);
79
+ proxy.listen(port, host, () => {
80
+ proxy.off('error', rejectStart);
81
+ arm();
82
+ resolveStart({
83
+ port: /** @type {net.AddressInfo} */ (proxy.address()).port,
84
+ close: stop,
85
+ });
86
+ });
87
+ });
88
+ }