@orkestrel/test 0.0.30 → 0.0.32

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.
@@ -1,7 +1,7 @@
1
- import { STATECHART_ATTRIBUTES, STATECHART_STATUSES, buildRefusal, checkBounds, collectSelectorClasses, executeScenario, invokeUnchecked, readProperty, requireValue, waitForAbort, waitForCondition, waitForDelay } from "../core/index.js";
1
+ import { STATECHART_ATTRIBUTES, STATECHART_STATUSES, buildRefusal, captureProduction, checkBounds, collectSelectorClasses, executeScenario, invokeUnchecked, readProperty, requireValue, waitForAbort, waitForCondition, waitForDelay } from "../core/index.js";
2
2
  import { cdp, commands, page, server, userEvent } from "vitest/browser";
3
- import { isArray, isError, isNumber, isRecord, isString, resolveField } from "@orkestrel/contract";
4
- //#region src/browser/helpers.ts
3
+ import { attempt, isArray, isError, isNumber, isRecord, isString, resolveField } from "@orkestrel/contract";
4
+ // src/browser/helpers.ts
5
5
  /**
6
6
  * Sends one DevTools protocol command through the browser provider.
7
7
  *
@@ -20,16 +20,26 @@ import { isArray, isError, isNumber, isRecord, isString, resolveField } from "@o
20
20
  * ```
21
21
  */
22
22
  async function sendProtocol(method, params) {
23
- let session;
24
- let send;
23
+ const [session, send] = readProtocolSession();
24
+ if (typeof send !== "function") throw new Error("Browser provider exposes no DevTools session");
25
+ return await invokeUnchecked(session, send, [method, params]);
26
+ }
27
+ /**
28
+ * Reads the browser provider's DevTools session and its send member.
29
+ *
30
+ * @throws Thrown when the provider or member read fails.
31
+ * @example
32
+ * ```ts
33
+ * const [session, send] = readProtocolSession()
34
+ * ```
35
+ */
36
+ function readProtocolSession() {
25
37
  try {
26
- session = cdp();
27
- send = readProperty(session, "send");
38
+ const session = cdp();
39
+ return [session, readProperty(session, "send")];
28
40
  } catch (cause) {
29
41
  throw new Error("Browser provider exposes no DevTools session", { cause });
30
42
  }
31
- if (typeof send !== "function") throw new Error("Browser provider exposes no DevTools session");
32
- return await invokeUnchecked(session, send, [method, params]);
33
43
  }
34
44
  /**
35
45
  * Waits for one animation frame to settle pending browser paint work.
@@ -128,8 +138,7 @@ function readStyle(element, property, pseudo) {
128
138
  }
129
139
  return getComputedStyle(element, pseudo).getPropertyValue(property).trim();
130
140
  }
131
- //#endregion
132
- //#region src/browser/journeys/constants.ts
141
+ // src/browser/journeys/constants.ts
133
142
  /**
134
143
  * Names the interactive ARIA roles a bare accessible name is searched across.
135
144
  *
@@ -303,8 +312,7 @@ var IMPLICIT_ROLES = Object.freeze({
303
312
  * so a rejected send keeps the marker for a retry.
304
313
  */
305
314
  var POINTER_HOLD = "data-pointer-hold";
306
- //#endregion
307
- //#region src/browser/captures/constants.ts
315
+ // src/browser/captures/constants.ts
308
316
  /**
309
317
  * Names the attribute marking the runner's tester pane, and the rule that sizes it, while a frame
310
318
  * is staged.
@@ -343,8 +351,7 @@ var CAPTURE_STAGE_LIMIT = 4;
343
351
  * the marker stays four bits and release leaves touch emulation alone.
344
352
  */
345
353
  var MEDIA_STAGE = "data-media-stage";
346
- //#endregion
347
- //#region src/browser/captures/helpers.ts
354
+ // src/browser/captures/helpers.ts
348
355
  /**
349
356
  * Reads one resolved CSS length as a number of pixels.
350
357
  *
@@ -573,15 +580,14 @@ function clipsOverflow(element) {
573
580
  * ```
574
581
  */
575
582
  function measureContent() {
576
- let edge = 0;
577
- for (const element of document.body.querySelectorAll("*")) {
583
+ const edge = Array.from(document.body.querySelectorAll("*")).reduce((greatest, element) => {
578
584
  const limits = collectClippingAncestors(element).filter((frame) => frame !== document.body && frame !== document.documentElement).flatMap((frame) => {
579
585
  const limit = readClipEdge(frame);
580
586
  return limit === void 0 ? [] : [limit];
581
587
  });
582
588
  const bottom = Math.min(element.getBoundingClientRect().bottom + window.scrollY + readPixels(element, "margin-bottom"), ...limits);
583
- if (bottom > edge) edge = bottom;
584
- }
589
+ return bottom > greatest ? bottom : greatest;
590
+ }, 0);
585
591
  return Math.ceil(edge + readPixels(document.body, "padding-bottom") + readPixels(document.body, "margin-bottom") + readPixels(document.documentElement, "padding-bottom") + readPixels(document.documentElement, "margin-bottom"));
586
592
  }
587
593
  /**
@@ -1067,120 +1073,8 @@ async function captureFrame(options) {
1067
1073
  const prepared = window.innerWidth === options.width && window.innerHeight === options.height;
1068
1074
  try {
1069
1075
  if (!prepared) await stagePane(options.width, options.height);
1070
- let pane = options.height;
1071
- let covered;
1072
- let growth = 0;
1073
- for (let stage = 0;; stage += 1) {
1074
- let height = element?.getBoundingClientRect().height;
1075
- if (element !== void 0 && height !== void 0 && height > options.height) {
1076
- element.scrollIntoView({
1077
- block: "start",
1078
- inline: "nearest",
1079
- behavior: "instant"
1080
- });
1081
- const aligned = element.getBoundingClientRect();
1082
- height = aligned.height + Math.max(0, aligned.top);
1083
- } else if (element !== void 0 && height !== void 0) {
1084
- const padding = readStyle(document.documentElement, "scroll-padding-top");
1085
- const margin = readStyle(element, "scroll-margin-top");
1086
- if (padding !== "auto" && padding !== "0px" || margin !== "0px") {
1087
- element.scrollIntoView({
1088
- block: "nearest",
1089
- inline: "nearest",
1090
- behavior: "instant"
1091
- });
1092
- if (element.getBoundingClientRect().bottom >= options.height) {
1093
- let placement = {
1094
- left: window.scrollX,
1095
- top: window.scrollY
1096
- };
1097
- element.scrollIntoView({
1098
- block: "start",
1099
- inline: "nearest",
1100
- behavior: "instant"
1101
- });
1102
- const aligned = element.getBoundingClientRect();
1103
- if (aligned.bottom > options.height) {
1104
- element.scrollIntoView({
1105
- block: "end",
1106
- inline: "nearest",
1107
- behavior: "instant"
1108
- });
1109
- const end = element.getBoundingClientRect();
1110
- const sticky = readStyle(element, "position") === "sticky" && readStyle(element, "top") !== "auto" && end.top >= 0 && end.bottom <= pane;
1111
- if (sticky) placement = {
1112
- left: window.scrollX,
1113
- top: window.scrollY
1114
- };
1115
- if (!sticky && (pane > options.height || end.top !== aligned.top)) {
1116
- height = aligned.height + Math.max(0, aligned.top);
1117
- element.scrollIntoView({
1118
- block: "start",
1119
- inline: "nearest",
1120
- behavior: "instant"
1121
- });
1122
- }
1123
- }
1124
- if (height <= options.height) window.scrollTo({
1125
- ...placement,
1126
- behavior: "instant"
1127
- });
1128
- }
1129
- }
1130
- }
1131
- const extent = Math.max(height === void 0 ? measureContent() : Math.ceil(height), options.height);
1132
- if (covered !== void 0) growth = Math.max(0, extent - covered);
1133
- covered = extent;
1134
- if (pane === covered) {
1135
- if (prepared && stage === 0) {
1136
- await stagePane(options.width, pane);
1137
- continue;
1138
- }
1139
- break;
1140
- }
1141
- if (stage === 4) throw new Error(`Capture frame at ${options.path} never settled after ${String(4)} restagings: ${String(covered)} over a ${String(pane)} pane`);
1142
- pane = covered + growth;
1143
- await stagePane(options.width, pane);
1144
- }
1145
- let shot;
1146
- if (element === void 0) shot = await page.screenshot({
1147
- path: options.path,
1148
- base64: true
1149
- });
1150
- else {
1151
- const box = element.getBoundingClientRect();
1152
- const down = box.top < 0 ? box.top : Math.max(0, box.bottom - window.innerHeight);
1153
- const across = box.left < 0 ? box.left : Math.max(0, box.right - window.innerWidth);
1154
- if (down !== 0 || across !== 0) window.scrollBy({
1155
- top: down,
1156
- left: across,
1157
- behavior: "instant"
1158
- });
1159
- const frame = window.frameElement;
1160
- const view = window.top;
1161
- const placed = element.getBoundingClientRect();
1162
- const move = view === null ? {
1163
- top: 0,
1164
- left: 0
1165
- } : computeOffset(placed, view.innerWidth, view.innerHeight);
1166
- const style = frame?.getAttribute("style") ?? null;
1167
- const offset = frame !== null && (move.top !== 0 || move.left !== 0);
1168
- try {
1169
- if (offset) {
1170
- frame.setAttribute("style", `${style ?? ""};top:${String(move.top)}px !important;left:${String(move.left)}px !important;will-change:transform`);
1171
- await waitForFrame();
1172
- await waitForFrame();
1173
- }
1174
- shot = await page.screenshot({
1175
- element,
1176
- path: options.path,
1177
- base64: true
1178
- });
1179
- } finally {
1180
- if (offset && style === null) frame.removeAttribute("style");
1181
- else if (offset && style !== null) frame.setAttribute("style", style);
1182
- }
1183
- }
1076
+ await settleFrame(options, element, prepared);
1077
+ const shot = await takeFrameShot(options, element);
1184
1078
  await verifyFrame(shot, options.path, readCaptureReader());
1185
1079
  return shot.path;
1186
1080
  } finally {
@@ -1314,13 +1208,10 @@ async function readFrame(path) {
1314
1208
  const red = row[0];
1315
1209
  const green = row[1];
1316
1210
  const blue = row[2];
1317
- const alpha = row[3];
1318
- let single = red !== void 0 && green !== void 0 && blue !== void 0;
1319
- for (let pixel = 4; single && pixel < row.length; pixel += 4) single = row[pixel] === red && row[pixel + 1] === green && row[pixel + 2] === blue && row[pixel + 3] === alpha;
1320
1211
  return {
1321
1212
  width,
1322
1213
  height,
1323
- floor: single ? `rgb(${String(red)}, ${String(green)}, ${String(blue)})` : void 0
1214
+ floor: red !== void 0 && green !== void 0 && blue !== void 0 && row.subarray(4).every((channel, index) => channel === row[index % 4]) ? `rgb(${String(red)}, ${String(green)}, ${String(blue)})` : void 0
1324
1215
  };
1325
1216
  }
1326
1217
  /**
@@ -1360,12 +1251,13 @@ async function readShotPixel(element, x, y) {
1360
1251
  if (context === void 0) throw new Error("Shot cannot be measured without a 2D canvas");
1361
1252
  const { width, height } = context.canvas;
1362
1253
  const [red = 0, green = 0, blue = 0, alpha = 0] = context.getImageData(Math.min(width - 1, Math.floor(width * x)), Math.min(height - 1, Math.floor(height * y)), 1, 1).data;
1363
- return Object.freeze([
1254
+ const pixel = [
1364
1255
  red,
1365
1256
  green,
1366
1257
  blue,
1367
1258
  alpha / 255
1368
- ]);
1259
+ ];
1260
+ return Object.freeze(pixel);
1369
1261
  }
1370
1262
  /**
1371
1263
  * Expands a capture registry across every variant into the filenames a complete portfolio holds.
@@ -1390,8 +1282,155 @@ function expandCaptures(states, variants) {
1390
1282
  for (const state of states) for (const variant of variants) files.push(`${state}--${variant.name}.png`);
1391
1283
  return files;
1392
1284
  }
1393
- //#endregion
1394
- //#region src/browser/journeys/helpers.ts
1285
+ /**
1286
+ * Restages a capture until its content extent equals the pane height.
1287
+ *
1288
+ * @remarks The stage limit bounds the recursion; a prepared pane is staged before accepting it.
1289
+ * @example
1290
+ * ```ts
1291
+ * await settleFrame({ path: 'frame.png', width: 390, height: 844 }, undefined, false)
1292
+ * ```
1293
+ */
1294
+ async function settleFrame(options, element, prepared, pane = options.height, covered, stage = 0) {
1295
+ const height = readFrameHeight(options, element, pane);
1296
+ const measured = height === void 0 ? measureContent() : Math.ceil(height);
1297
+ const extent = Math.max(measured, options.height);
1298
+ const growth = covered === void 0 ? 0 : Math.max(0, extent - covered);
1299
+ if (pane === extent) {
1300
+ if (prepared && stage === 0) {
1301
+ await stagePane(options.width, pane);
1302
+ return settleFrame(options, element, prepared, pane, extent, stage + 1);
1303
+ }
1304
+ return;
1305
+ }
1306
+ if (stage === 4) throw new Error(`Capture frame at ${options.path} never settled after ${String(4)} restagings: ${String(extent)} over a ${String(pane)} pane`);
1307
+ const next = extent + growth;
1308
+ await stagePane(options.width, next);
1309
+ return settleFrame(options, element, prepared, next, extent, stage + 1);
1310
+ }
1311
+ /**
1312
+ * Reads a capture subject's height after applying its native scroll clearance.
1313
+ *
1314
+ * @example
1315
+ * ```ts
1316
+ * readFrameHeight({ path: 'frame.png', width: 390, height: 844 }, undefined, 844)
1317
+ * ```
1318
+ */
1319
+ function readFrameHeight(options, element, pane) {
1320
+ const height = element?.getBoundingClientRect().height;
1321
+ if (element === void 0 || height === void 0) return height;
1322
+ if (height > options.height) {
1323
+ element.scrollIntoView({
1324
+ block: "start",
1325
+ inline: "nearest",
1326
+ behavior: "instant"
1327
+ });
1328
+ const aligned = element.getBoundingClientRect();
1329
+ return aligned.height + Math.max(0, aligned.top);
1330
+ }
1331
+ const padding = readStyle(document.documentElement, "scroll-padding-top");
1332
+ const margin = readStyle(element, "scroll-margin-top");
1333
+ if ((padding === "auto" || padding === "0px") && margin === "0px") return height;
1334
+ element.scrollIntoView({
1335
+ block: "nearest",
1336
+ inline: "nearest",
1337
+ behavior: "instant"
1338
+ });
1339
+ if (!(element.getBoundingClientRect().bottom >= options.height)) return height;
1340
+ const placement = {
1341
+ left: window.scrollX,
1342
+ top: window.scrollY
1343
+ };
1344
+ element.scrollIntoView({
1345
+ block: "start",
1346
+ inline: "nearest",
1347
+ behavior: "instant"
1348
+ });
1349
+ const aligned = element.getBoundingClientRect();
1350
+ if (aligned.bottom > options.height) {
1351
+ element.scrollIntoView({
1352
+ block: "end",
1353
+ inline: "nearest",
1354
+ behavior: "instant"
1355
+ });
1356
+ const end = element.getBoundingClientRect();
1357
+ if (readStyle(element, "position") === "sticky" && readStyle(element, "top") !== "auto" && end.top >= 0 && end.bottom <= pane) {
1358
+ if (height <= options.height) window.scrollTo({
1359
+ left: window.scrollX,
1360
+ top: window.scrollY,
1361
+ behavior: "instant"
1362
+ });
1363
+ return height;
1364
+ }
1365
+ if (pane > options.height || end.top !== aligned.top) {
1366
+ const extended = aligned.height + Math.max(0, aligned.top);
1367
+ element.scrollIntoView({
1368
+ block: "start",
1369
+ inline: "nearest",
1370
+ behavior: "instant"
1371
+ });
1372
+ if (extended <= options.height) window.scrollTo({
1373
+ ...placement,
1374
+ behavior: "instant"
1375
+ });
1376
+ return extended;
1377
+ }
1378
+ }
1379
+ if (height <= options.height) window.scrollTo({
1380
+ ...placement,
1381
+ behavior: "instant"
1382
+ });
1383
+ return height;
1384
+ }
1385
+ /**
1386
+ * Takes a screenshot while temporarily positioning the runner frame around its subject.
1387
+ *
1388
+ * @example
1389
+ * ```ts
1390
+ * const shot = await takeFrameShot({ path: 'frame.png', width: 390, height: 844 }, undefined)
1391
+ * ```
1392
+ */
1393
+ async function takeFrameShot(options, element) {
1394
+ if (element === void 0) return await page.screenshot({
1395
+ path: options.path,
1396
+ base64: true
1397
+ });
1398
+ else {
1399
+ const box = element.getBoundingClientRect();
1400
+ const down = box.top < 0 ? box.top : Math.max(0, box.bottom - window.innerHeight);
1401
+ const across = box.left < 0 ? box.left : Math.max(0, box.right - window.innerWidth);
1402
+ if (down !== 0 || across !== 0) window.scrollBy({
1403
+ top: down,
1404
+ left: across,
1405
+ behavior: "instant"
1406
+ });
1407
+ const frame = window.frameElement;
1408
+ const view = window.top;
1409
+ const placed = element.getBoundingClientRect();
1410
+ const move = view === null ? {
1411
+ top: 0,
1412
+ left: 0
1413
+ } : computeOffset(placed, view.innerWidth, view.innerHeight);
1414
+ const style = frame?.getAttribute("style") ?? null;
1415
+ const offset = frame !== null && (move.top !== 0 || move.left !== 0);
1416
+ try {
1417
+ if (offset) {
1418
+ frame.setAttribute("style", `${style ?? ""};top:${String(move.top)}px !important;left:${String(move.left)}px !important;will-change:transform`);
1419
+ await waitForFrame();
1420
+ await waitForFrame();
1421
+ }
1422
+ return await page.screenshot({
1423
+ element,
1424
+ path: options.path,
1425
+ base64: true
1426
+ });
1427
+ } finally {
1428
+ if (offset && style === null) frame.removeAttribute("style");
1429
+ else if (offset && style !== null) frame.setAttribute("style", style);
1430
+ }
1431
+ }
1432
+ }
1433
+ // src/browser/journeys/helpers.ts
1395
1434
  /**
1396
1435
  * Sends one emulated touch event through the browser protocol.
1397
1436
  *
@@ -1556,6 +1595,36 @@ async function sendFileDrag(type, role, name, names) {
1556
1595
  });
1557
1596
  }
1558
1597
  /**
1598
+ * Records every call one console channel receives and hands that call on unchanged.
1599
+ *
1600
+ * @param name - The channel's name, which prefixes each line it records.
1601
+ * @param output - The list each call is recorded into, appended to in place.
1602
+ * @param forward - The channel every call is passed on to after it is recorded.
1603
+ * @returns A channel carrying the console's own call signature.
1604
+ *
1605
+ * @remarks
1606
+ * One call becomes one line. Every argument of that call is put through `String` and joined with a
1607
+ * space, so a call carrying several values reads as the one line the page printed rather than as
1608
+ * several entries.
1609
+ *
1610
+ * Nothing is swallowed. The record happens first and `forward` receives the arguments it would have
1611
+ * received, so a page recorded through this prints exactly what it printed without it. The list
1612
+ * belongs to the caller, so a channel writes into whatever it was handed and holds no state of its
1613
+ * own. {@link createJournal} builds one channel per console method over one list.
1614
+ *
1615
+ * @example
1616
+ * ```ts
1617
+ * const output: string[] = []
1618
+ * console.log = recordConsole('log', output, console.log)
1619
+ * ```
1620
+ */
1621
+ function recordConsole(name, output, forward) {
1622
+ return (...data) => {
1623
+ output.push(`${name}: ${data.map((value) => String(value)).join(" ")}`);
1624
+ forward(...data);
1625
+ };
1626
+ }
1627
+ /**
1559
1628
  * Determines whether a rectangle lies wholly outside the browser viewport.
1560
1629
  *
1561
1630
  * @param rectangle - The measured client rectangle to inspect.
@@ -1618,12 +1687,7 @@ function isOutsideViewport(rectangle) {
1618
1687
  */
1619
1688
  function isReachable(element) {
1620
1689
  if (!(element instanceof HTMLElement) && !(element instanceof SVGElement)) return false;
1621
- const chain = [element];
1622
- let root = element.getRootNode();
1623
- while (root instanceof ShadowRoot) {
1624
- chain.push(root.host);
1625
- root = root.host.getRootNode();
1626
- }
1690
+ const chain = collectShadowHosts(element);
1627
1691
  const rectangle = element.getBoundingClientRect();
1628
1692
  return element.isConnected && element.checkVisibility({
1629
1693
  checkOpacity: true,
@@ -1631,6 +1695,21 @@ function isReachable(element) {
1631
1695
  }) && rectangle.width > 0 && rectangle.height > 0 && element.tabIndex >= 0 && !element.matches(":disabled, [aria-disabled=\"true\"]") && element.closest("[inert]") === null && [...element.ownerDocument.querySelectorAll("[aria-modal=\"true\"]")].every((dialog) => !isRendered(dialog) || chain.some((node) => dialog.contains(node)));
1632
1696
  }
1633
1697
  /**
1698
+ * Collects an element and the successive hosts of its containing shadow roots.
1699
+ *
1700
+ * @param element - The element that opens the collected chain.
1701
+ * @param root - The root already read by an outer traversal step, or the element's current root.
1702
+ * @example
1703
+ * ```ts
1704
+ * collectShadowHosts(document.body) // [document.body]
1705
+ * ```
1706
+ */
1707
+ function collectShadowHosts(element, root = element.getRootNode()) {
1708
+ if (!(root instanceof ShadowRoot)) return [element];
1709
+ const host = root.host;
1710
+ return [element, ...collectShadowHosts(host, root.host.getRootNode())];
1711
+ }
1712
+ /**
1634
1713
  * Determines whether the accessibility tree presents one element at all.
1635
1714
  *
1636
1715
  * @param element - The element to judge.
@@ -1814,15 +1893,13 @@ function resolveRendered(first, second) {
1814
1893
  }
1815
1894
  function resolveAccessible(first, second) {
1816
1895
  const target = resolveRendered(first, second);
1817
- let rectangle = target.getBoundingClientRect();
1818
- if (isOutsideViewport(rectangle)) {
1896
+ if (isOutsideViewport(target.getBoundingClientRect())) {
1819
1897
  target.scrollIntoView({
1820
1898
  block: "nearest",
1821
1899
  behavior: "instant"
1822
1900
  });
1823
- rectangle = target.getBoundingClientRect();
1901
+ if (isOutsideViewport(target.getBoundingClientRect())) throw new Error(`Interactive target "${second ?? first}" is unreachable after scrolling`);
1824
1902
  }
1825
- if (isOutsideViewport(rectangle)) throw new Error(`Interactive target "${second ?? first}" is unreachable after scrolling`);
1826
1903
  return target;
1827
1904
  }
1828
1905
  async function clickAccessible(first, second) {
@@ -1908,10 +1985,10 @@ async function clickAccessibleWithin(region, role, name) {
1908
1985
  * @throws When the named control is absent, unreachable, or ambiguous inside the region.
1909
1986
  *
1910
1987
  * @remarks
1911
- * The region's name is matched exactly and the control's name loosely, over a computed name that
1912
- * includes hidden subtrees, so a glyph joins the text rather than displacing it. One pass answers
1913
- * this: a control the region cannot reach is refused whether it is absent or hidden. This is the
1914
- * resolver the region-scoped verbs share.
1988
+ * The region's name is matched exactly. The control first matches the case-sensitive pattern
1989
+ * from `computeNamePattern`, with hidden subtrees included. Any exact candidates own the result,
1990
+ * including unreachable or ambiguous candidates. Only an empty exact tier selects the loose query.
1991
+ * Both tiers refuse zero reachable candidates and several reachable candidates.
1915
1992
  *
1916
1993
  * @example
1917
1994
  * ```ts
@@ -1919,14 +1996,20 @@ async function clickAccessibleWithin(region, role, name) {
1919
1996
  * ```
1920
1997
  */
1921
1998
  function resolveAccessibleWithin(region, role, name) {
1922
- const reachable = page.getByRole("region", {
1999
+ const scope = page.getByRole("region", {
1923
2000
  name: region,
1924
2001
  exact: true
1925
- }).getByRole(role, {
2002
+ });
2003
+ const exact = scope.getByRole(role, {
2004
+ name: computeNamePattern(name),
2005
+ exact: true,
2006
+ includeHidden: true
2007
+ }).elements();
2008
+ const reachable = (exact.length > 0 ? exact : scope.getByRole(role, {
1926
2009
  name,
1927
2010
  exact: false,
1928
2011
  includeHidden: true
1929
- }).elements().filter((element) => element instanceof HTMLElement && isReachable(element));
2012
+ }).elements()).filter((element) => element instanceof HTMLElement && isReachable(element));
1930
2013
  if (reachable.length === 0) throw new Error(`Interactive target "${name}" is not reachable inside "${region}"`);
1931
2014
  if (reachable.length > 1) throw new Error(`Interactive target "${name}" is ambiguous across ${reachable.length} elements inside "${region}"`);
1932
2015
  const [target] = reachable;
@@ -2106,24 +2189,18 @@ async function parkPointer() {
2106
2189
  */
2107
2190
  async function releasePointer() {
2108
2191
  const held = document.documentElement.getAttribute(POINTER_HOLD);
2109
- let released = held === null;
2110
- let rejection;
2111
- try {
2112
- if (held !== null) {
2113
- const [x, y] = held.split("x").map(Number);
2114
- await sendProtocol("Input.dispatchMouseEvent", {
2115
- type: "mouseReleased",
2116
- x,
2117
- y,
2118
- button: "left",
2119
- buttons: 0,
2120
- clickCount: 1
2121
- });
2122
- released = true;
2123
- }
2124
- } catch (cause) {
2125
- rejection = cause;
2126
- }
2192
+ const [x, y] = held === null ? [] : held.split("x").map(Number);
2193
+ const request = {
2194
+ type: "mouseReleased",
2195
+ x,
2196
+ y,
2197
+ button: "left",
2198
+ buttons: 0,
2199
+ clickCount: 1
2200
+ };
2201
+ const release = held === null ? void 0 : await captureProduction(() => sendProtocol("Input.dispatchMouseEvent", request));
2202
+ const released = release === void 0 || release.status === "fulfilled";
2203
+ const rejection = release?.status === "rejected" ? release.reason : void 0;
2127
2204
  if (released) document.documentElement.removeAttribute(POINTER_HOLD);
2128
2205
  try {
2129
2206
  await parkPointer();
@@ -2804,10 +2881,10 @@ function readFocus() {
2804
2881
  *
2805
2882
  * @example
2806
2883
  * ```ts
2807
- * readValue('spinbutton', 'Runs') // '3'
2884
+ * readControlValue('spinbutton', 'Runs') // '3'
2808
2885
  * ```
2809
2886
  */
2810
- function readValue(role, name) {
2887
+ function readControlValue(role, name) {
2811
2888
  const control = resolveAccessible(role, name);
2812
2889
  if (!(control instanceof HTMLInputElement) && !(control instanceof HTMLTextAreaElement) && !(control instanceof HTMLSelectElement)) throw new Error(`Interactive target "${name}" does not carry a value`);
2813
2890
  return control.value;
@@ -2840,7 +2917,9 @@ function readRefusal(first, second) {
2840
2917
  function readText(element) {
2841
2918
  const parts = [];
2842
2919
  const walker = element.ownerDocument.createTreeWalker(element, NodeFilter.SHOW_TEXT);
2843
- for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
2920
+ while (true) {
2921
+ const node = walker.nextNode();
2922
+ if (node === null) break;
2844
2923
  const owner = node.parentElement;
2845
2924
  if (owner === null || owner.closest("[aria-hidden=\"true\"]") !== null) continue;
2846
2925
  parts.push(node.textContent ?? "");
@@ -3007,14 +3086,14 @@ function describeTree(element) {
3007
3086
  if (entry === void 0) break;
3008
3087
  if (!isRendered(entry.node)) continue;
3009
3088
  const role = readRole(entry.node);
3010
- let depth = entry.depth;
3011
3089
  if (role !== void 0) {
3012
3090
  const name = readName(entry.node);
3013
3091
  const states = readStates(entry.node);
3014
- lines.push(`${" ".repeat(depth)}${role}${name.length > 0 ? ` "${name}"` : ""}${states.length > 0 ? ` [${states.join(", ")}]` : ""}`);
3015
- depth += 1;
3092
+ lines.push(`${" ".repeat(entry.depth)}${role}${name.length > 0 ? ` "${name}"` : ""}${states.length > 0 ? ` [${states.join(", ")}]` : ""}`);
3016
3093
  }
3017
- for (let index = entry.node.children.length - 1; index >= 0; index -= 1) {
3094
+ const depth = entry.depth + (role === void 0 ? 0 : 1);
3095
+ const length = entry.node.children.length;
3096
+ for (const index of Array.from({ length }, (_, offset) => length - offset - 1)) {
3018
3097
  const child = entry.node.children[index];
3019
3098
  if (child !== void 0) pending.push({
3020
3099
  node: child,
@@ -3066,24 +3145,22 @@ async function waitForState(first, second, third, fourth) {
3066
3145
  const options = keyed ? fourth : third;
3067
3146
  const absent = options?.absent ?? false;
3068
3147
  const description = `"${name}" to ${absent ? "stop announcing" : "announce"} "${state}"`;
3069
- let observed = [];
3070
- let count = 0;
3071
- let refused;
3072
- try {
3148
+ const observations = [];
3149
+ const waited = await captureProduction(async () => {
3073
3150
  await waitForCondition(description, () => {
3074
- count += 1;
3075
- try {
3076
- observed = readStates(role === void 0 ? resolveRendered(name) : resolveRendered(role, name));
3077
- } catch (thrown) {
3078
- refused = { thrown };
3079
- throw thrown;
3080
- }
3081
- return observed.includes(state) !== absent;
3151
+ const observation = attempt(() => readStates(role === void 0 ? resolveRendered(name) : resolveRendered(role, name)));
3152
+ observations.push(observation);
3153
+ if (!observation.success) throw observation.error;
3154
+ return observation.value.includes(state) !== absent;
3082
3155
  }, options);
3083
- } catch (cause) {
3084
- if (refused !== void 0 && cause === refused.thrown) throw cause;
3156
+ });
3157
+ const observed = observations.reduce((states, observation) => observation.success ? observation.value : states, []);
3158
+ const refused = observations.find((observation) => !observation.success);
3159
+ if (waited.status === "rejected") {
3160
+ const cause = waited.reason;
3161
+ if (refused?.success === false && cause === refused.error) throw cause;
3085
3162
  if (cause === options?.signal?.reason) throw cause;
3086
- if (count === 0) throw cause;
3163
+ if (observations.length === 0) throw cause;
3087
3164
  if (!isError(cause)) throw cause;
3088
3165
  throw new Error(`${cause.message} (last states: ${JSON.stringify(observed)})`, { cause });
3089
3166
  }
@@ -3133,22 +3210,20 @@ async function waitForAnimations(element, options) {
3133
3210
  const label = readName(element);
3134
3211
  const subject = `${readRole(element) ?? element.localName}${label.length > 0 ? ` "${label}"` : ""}`;
3135
3212
  const start = performance.now();
3136
- let expired = false;
3137
- let aborted;
3138
- let timer;
3139
- const expiry = new Promise((resolve) => {
3140
- timer = setTimeout(() => {
3141
- expired = true;
3142
- resolve();
3143
- }, budget);
3144
- });
3213
+ const deadline = new AbortController();
3214
+ const aborts = /* @__PURE__ */ new Map();
3215
+ const expiry = Promise.withResolvers();
3216
+ const timer = setTimeout(() => {
3217
+ deadline.abort();
3218
+ expiry.resolve();
3219
+ }, budget);
3145
3220
  try {
3146
3221
  while (true) {
3147
3222
  signal?.throwIfAborted();
3148
3223
  const running = readAnimations(element).finite;
3149
3224
  if (running.length === 0) return;
3150
3225
  const elapsed = performance.now() - start;
3151
- if (expired || elapsed >= budget) {
3226
+ if (deadline.signal.aborted || elapsed >= budget) {
3152
3227
  const names = running.map((animation) => {
3153
3228
  if (animation instanceof CSSAnimation) return animation.animationName;
3154
3229
  if (animation instanceof CSSTransition) return animation.transitionProperty;
@@ -3157,15 +3232,16 @@ async function waitForAnimations(element, options) {
3157
3232
  throw new Error(`Animation "${subject}" did not settle within ${budget}ms (waited ${elapsed}ms): ${names.join(", ")}`);
3158
3233
  }
3159
3234
  const pending = running.map((animation) => animation.finished.catch(() => void 0));
3160
- pending.push(expiry);
3235
+ pending.push(expiry.promise);
3161
3236
  if (signal !== void 0) {
3162
- aborted ??= waitForAbort(signal);
3237
+ const aborted = aborts.get(signal) ?? waitForAbort(signal);
3238
+ if (!aborts.has(signal)) aborts.set(signal, aborted);
3163
3239
  pending.push(aborted);
3164
3240
  }
3165
3241
  await Promise.race(pending);
3166
3242
  }
3167
3243
  } finally {
3168
- if (timer !== void 0) clearTimeout(timer);
3244
+ clearTimeout(timer);
3169
3245
  }
3170
3246
  }
3171
3247
  /**
@@ -3453,38 +3529,110 @@ function readRows(root, selector) {
3453
3529
  function buildDenial(operation, key) {
3454
3530
  return new DOMException(`Access is denied for ${operation}${key === void 0 ? "" : ` "${key}"`}`, "SecurityError");
3455
3531
  }
3456
- //#endregion
3457
- //#region src/browser/journeys/factories.ts
3458
- /**
3459
- * Creates one console channel that records every call it receives and hands that call on unchanged.
3460
- *
3461
- * @param name - The channel's name, which prefixes each line it records.
3462
- * @param output - The list each call is recorded into, appended to in place.
3463
- * @param forward - The channel every call is passed on to after it is recorded.
3464
- * @returns A channel carrying the console's own call signature.
3465
- *
3466
- * @remarks
3467
- * One call becomes one line. Every argument of that call is put through `String` and joined with a
3468
- * space, so a call carrying several values reads as the one line the page printed rather than as
3469
- * several entries.
3470
- *
3471
- * Nothing is swallowed. The record happens first and `forward` receives the arguments it would have
3472
- * received, so a page recorded through this prints exactly what it printed without it. The list
3473
- * belongs to the caller, so a channel writes into whatever it was handed and holds no state of its
3474
- * own. {@link createJournal} builds one channel per console method over one list.
3475
- *
3476
- * @example
3477
- * ```ts
3478
- * const output: string[] = []
3479
- * console.log = createChannel('log', output, console.log)
3480
- * ```
3481
- */
3482
- function createChannel(name, output, forward) {
3483
- return (...data) => {
3484
- output.push(`${name}: ${data.map((value) => String(value)).join(" ")}`);
3485
- forward(...data);
3486
- };
3487
- }
3532
+ // src/browser/journeys/Journal.ts
3533
+ /** Owns the state and console subscriptions behind a journal projection. */
3534
+ var Journal = class {
3535
+ #steps = [];
3536
+ #output = [];
3537
+ #intercepted;
3538
+ #listeners;
3539
+ get steps() {
3540
+ return [...this.#steps];
3541
+ }
3542
+ get output() {
3543
+ return [...this.#output];
3544
+ }
3545
+ start() {
3546
+ this.#steps.length = 0;
3547
+ this.#output.length = 0;
3548
+ if (this.#intercepted !== void 0) return;
3549
+ const forwarded = {
3550
+ debug: console.debug,
3551
+ error: console.error,
3552
+ info: console.info,
3553
+ log: console.log,
3554
+ warn: console.warn
3555
+ };
3556
+ this.#intercepted = forwarded;
3557
+ for (const channel of [
3558
+ "debug",
3559
+ "error",
3560
+ "info",
3561
+ "log",
3562
+ "warn"
3563
+ ]) console[channel] = recordConsole(channel, this.#output, forwarded[channel]);
3564
+ const dropped = new AbortController();
3565
+ this.#listeners = dropped;
3566
+ window.addEventListener("error", (event) => {
3567
+ this.#output.push(`error: ${event.message}`);
3568
+ }, { signal: dropped.signal });
3569
+ window.addEventListener("unhandledrejection", (event) => {
3570
+ this.#output.push(`rejection: ${String(event.reason)}`);
3571
+ }, { signal: dropped.signal });
3572
+ }
3573
+ stop() {
3574
+ if (this.#intercepted === void 0) return;
3575
+ Object.assign(console, this.#intercepted);
3576
+ this.#intercepted = void 0;
3577
+ this.#listeners?.abort();
3578
+ this.#listeners = void 0;
3579
+ }
3580
+ record(action, trigger, result) {
3581
+ if (this.#intercepted === void 0) return;
3582
+ this.#steps.push(Object.freeze({
3583
+ action,
3584
+ trigger,
3585
+ result
3586
+ }));
3587
+ }
3588
+ };
3589
+ // src/browser/journeys/WebStorage.ts
3590
+ /** Owns permissions, values, and quota behind a Web Storage projection. */
3591
+ var WebStorage = class {
3592
+ #values;
3593
+ #reads;
3594
+ #writes;
3595
+ #room;
3596
+ constructor(options, quota) {
3597
+ this.#values = new Map(Object.entries(options?.values ?? {}));
3598
+ this.#reads = options?.reads ?? true;
3599
+ this.#writes = options?.writes ?? true;
3600
+ this.#room = quota;
3601
+ }
3602
+ get length() {
3603
+ if (!this.#reads) throw buildDenial("length");
3604
+ return this.#values.size;
3605
+ }
3606
+ permit() {
3607
+ this.#reads = true;
3608
+ this.#writes = true;
3609
+ }
3610
+ clear() {
3611
+ if (!this.#writes) throw buildDenial("clear");
3612
+ this.#values.clear();
3613
+ }
3614
+ getItem(key) {
3615
+ if (!this.#reads) throw buildDenial("getItem", key);
3616
+ return this.#values.get(key) ?? null;
3617
+ }
3618
+ key(index) {
3619
+ if (!this.#reads) throw buildDenial("key");
3620
+ return [...this.#values.keys()][index] ?? null;
3621
+ }
3622
+ removeItem(key) {
3623
+ if (!this.#writes) throw buildDenial("removeItem", key);
3624
+ this.#values.delete(key);
3625
+ }
3626
+ setItem(key, value) {
3627
+ if (!this.#writes) throw buildDenial("setItem", key);
3628
+ if (this.#room !== void 0) {
3629
+ if (this.#room === 0) throw new DOMException(`No room is left for ${key}`, "QuotaExceededError");
3630
+ this.#room -= 1;
3631
+ }
3632
+ this.#values.set(key, value);
3633
+ }
3634
+ };
3635
+ // src/browser/journeys/factories.ts
3488
3636
  /**
3489
3637
  * Creates the journal one scenario records its steps and the page's own output into.
3490
3638
  *
@@ -3510,60 +3658,17 @@ function createChannel(name, output, forward) {
3510
3658
  * ```
3511
3659
  */
3512
3660
  function createJournal() {
3513
- const steps = [];
3514
- const output = [];
3515
- let intercepted;
3516
- let listeners;
3661
+ const journal = new Journal();
3517
3662
  return {
3518
3663
  get steps() {
3519
- return [...steps];
3664
+ return journal.steps;
3520
3665
  },
3521
3666
  get output() {
3522
- return [...output];
3523
- },
3524
- start() {
3525
- steps.length = 0;
3526
- output.length = 0;
3527
- if (intercepted !== void 0) return;
3528
- const forwarded = {
3529
- debug: console.debug,
3530
- error: console.error,
3531
- info: console.info,
3532
- log: console.log,
3533
- warn: console.warn
3534
- };
3535
- intercepted = forwarded;
3536
- for (const channel of [
3537
- "debug",
3538
- "error",
3539
- "info",
3540
- "log",
3541
- "warn"
3542
- ]) console[channel] = createChannel(channel, output, forwarded[channel]);
3543
- const dropped = new AbortController();
3544
- listeners = dropped;
3545
- window.addEventListener("error", (event) => {
3546
- output.push(`error: ${event.message}`);
3547
- }, { signal: dropped.signal });
3548
- window.addEventListener("unhandledrejection", (event) => {
3549
- output.push(`rejection: ${String(event.reason)}`);
3550
- }, { signal: dropped.signal });
3551
- },
3552
- stop() {
3553
- if (intercepted === void 0) return;
3554
- Object.assign(console, intercepted);
3555
- intercepted = void 0;
3556
- listeners?.abort();
3557
- listeners = void 0;
3667
+ return journal.output;
3558
3668
  },
3559
- record(action, trigger, result) {
3560
- if (intercepted === void 0) return;
3561
- steps.push(Object.freeze({
3562
- action,
3563
- trigger,
3564
- result
3565
- }));
3566
- }
3669
+ start: journal.start.bind(journal),
3670
+ stop: journal.stop.bind(journal),
3671
+ record: journal.record.bind(journal)
3567
3672
  };
3568
3673
  }
3569
3674
  /**
@@ -3611,43 +3716,17 @@ function createJournal() {
3611
3716
  function createStorage(options) {
3612
3717
  const quota = options?.quota;
3613
3718
  if (quota !== void 0 && (!Number.isSafeInteger(quota) || quota < 0)) throw new Error("Storage quota must be a non-negative integer");
3614
- const values = new Map(Object.entries(options?.values ?? {}));
3615
- let reads = options?.reads ?? true;
3616
- let writes = options?.writes ?? true;
3617
- let room = quota;
3719
+ const storage = new WebStorage(options, quota);
3618
3720
  return {
3619
3721
  get length() {
3620
- if (!reads) throw buildDenial("length");
3621
- return values.size;
3622
- },
3623
- permit() {
3624
- reads = true;
3625
- writes = true;
3626
- },
3627
- clear() {
3628
- if (!writes) throw buildDenial("clear");
3629
- values.clear();
3722
+ return storage.length;
3630
3723
  },
3631
- getItem(key) {
3632
- if (!reads) throw buildDenial("getItem", key);
3633
- return values.get(key) ?? null;
3634
- },
3635
- key(index) {
3636
- if (!reads) throw buildDenial("key");
3637
- return [...values.keys()][index] ?? null;
3638
- },
3639
- removeItem(key) {
3640
- if (!writes) throw buildDenial("removeItem", key);
3641
- values.delete(key);
3642
- },
3643
- setItem(key, value) {
3644
- if (!writes) throw buildDenial("setItem", key);
3645
- if (room !== void 0) {
3646
- if (room === 0) throw new DOMException(`No room is left for ${key}`, "QuotaExceededError");
3647
- room -= 1;
3648
- }
3649
- values.set(key, value);
3650
- }
3724
+ permit: storage.permit.bind(storage),
3725
+ clear: storage.clear.bind(storage),
3726
+ getItem: storage.getItem.bind(storage),
3727
+ key: storage.key.bind(storage),
3728
+ removeItem: storage.removeItem.bind(storage),
3729
+ setItem: storage.setItem.bind(storage)
3651
3730
  };
3652
3731
  }
3653
3732
  /**
@@ -3750,34 +3829,25 @@ function createHarness(options) {
3750
3829
  for (const row of table) row.element.removeAttribute(STATECHART_ATTRIBUTES.result);
3751
3830
  state.removeAttribute(STATECHART_ATTRIBUTES.state);
3752
3831
  state.textContent = "";
3753
- let passed = 0;
3754
- let failed = 0;
3832
+ const outcomes = [];
3755
3833
  root.setAttribute(STATECHART_ATTRIBUTES.passed, "0");
3756
3834
  root.setAttribute(STATECHART_ATTRIBUTES.failed, "0");
3757
3835
  root.setAttribute(STATECHART_ATTRIBUTES.status, "running");
3758
3836
  announcer.textContent = `Statechart harness is running, 0 passed and 0 failed of ${table.length}.`;
3759
3837
  try {
3760
3838
  for (const [index, row] of table.entries()) {
3761
- let built;
3762
- let refusal;
3763
- try {
3764
- built = { context: await options.build(row.scenario) };
3765
- } catch (cause) {
3766
- refusal = buildRefusal(row.scenario.transition.name, cause).message;
3767
- }
3768
- if (built !== void 0) {
3769
- try {
3770
- await executeScenario(row.scenario, built.context);
3771
- } catch (cause) {
3772
- if (!isError(cause)) throw cause;
3773
- refusal = cause.message;
3774
- }
3775
- const current = options.state(built.context);
3839
+ const built = await captureProduction(() => options.build(row.scenario));
3840
+ const executed = built.status === "fulfilled" ? await captureProduction(() => executeScenario(row.scenario, built.value)) : void 0;
3841
+ if (executed?.status === "rejected" && !isError(executed.reason)) throw executed.reason;
3842
+ const refusal = built.status === "rejected" ? buildRefusal(row.scenario.transition.name, built.reason).message : executed?.status === "rejected" && isError(executed.reason) ? executed.reason.message : void 0;
3843
+ if (built.status === "fulfilled") {
3844
+ const current = options.state(built.value);
3776
3845
  state.setAttribute(STATECHART_ATTRIBUTES.state, current);
3777
3846
  state.textContent = current;
3778
3847
  }
3779
- if (refusal === void 0) passed += 1;
3780
- else failed += 1;
3848
+ outcomes.push(refusal === void 0);
3849
+ const passed = outcomes.filter((outcome) => outcome).length;
3850
+ const failed = outcomes.length - passed;
3781
3851
  row.element.setAttribute(STATECHART_ATTRIBUTES.result, refusal === void 0 ? "passed" : "failed");
3782
3852
  root.setAttribute(STATECHART_ATTRIBUTES.passed, String(passed));
3783
3853
  root.setAttribute(STATECHART_ATTRIBUTES.failed, String(failed));
@@ -3785,10 +3855,14 @@ function createHarness(options) {
3785
3855
  if (options.pause !== void 0 && index < table.length - 1) await waitForDelay(options.pause);
3786
3856
  }
3787
3857
  } catch (cause) {
3858
+ const passed = outcomes.filter((outcome) => outcome).length;
3859
+ const failed = outcomes.length - passed;
3788
3860
  root.setAttribute(STATECHART_ATTRIBUTES.status, "failed");
3789
3861
  announcer.textContent = `Statechart harness failed, ${passed} passed and ${failed} failed of ${table.length}.`;
3790
3862
  throw cause;
3791
3863
  }
3864
+ const passed = outcomes.filter((result) => result).length;
3865
+ const failed = outcomes.length - passed;
3792
3866
  const outcome = failed === 0 ? "passed" : "failed";
3793
3867
  root.setAttribute(STATECHART_ATTRIBUTES.status, outcome);
3794
3868
  announcer.textContent = `Statechart harness ${outcome}, ${passed} passed and ${failed} failed of ${table.length}.`;
@@ -3905,8 +3979,7 @@ function createKeyboardEvent(name, options) {
3905
3979
  ...options
3906
3980
  });
3907
3981
  }
3908
- //#endregion
3909
- //#region src/browser/captures/factories.ts
3982
+ // src/browser/captures/factories.ts
3910
3983
  /**
3911
3984
  * Creates the capture portfolio one run places its screenshots through; a disabled run still refuses.
3912
3985
  *
@@ -3977,8 +4050,7 @@ function createPortfolio(options) {
3977
4050
  }
3978
4051
  };
3979
4052
  }
3980
- //#endregion
3981
- //#region src/browser/colors/constants.ts
4053
+ // src/browser/colors/constants.ts
3982
4054
  /**
3983
4055
  * Names the color a browser paints an unstyled document with: opaque white.
3984
4056
  *
@@ -3993,8 +4065,7 @@ var CANVAS_COLOR = Object.freeze([
3993
4065
  255,
3994
4066
  1
3995
4067
  ]);
3996
- //#endregion
3997
- //#region src/browser/colors/helpers.ts
4068
+ // src/browser/colors/helpers.ts
3998
4069
  /**
3999
4070
  * Converts normalized encoded sRGB channels to the clipped paint scale.
4000
4071
  *
@@ -4507,20 +4578,12 @@ function measureContrast(front, back) {
4507
4578
  * ```
4508
4579
  */
4509
4580
  function readLayers(element) {
4510
- const layers = [];
4511
- for (let node = element; node !== null; node = node.parentElement) {
4512
- const computed = getComputedStyle(node).backgroundColor;
4513
- if (computed === "") continue;
4514
- const layer = parseColor(computed);
4515
- if (layer === void 0) {
4516
- if (/\/\s*(?:0(?:\.0*)?|none)\s*\)$/u.test(computed)) continue;
4517
- throw new Error(`Computed background color is unreadable on ${node.localName}${node.id === "" ? "" : `#${node.id}`}: ${computed}`);
4518
- }
4519
- if (layer[3] === 0) continue;
4520
- layers.push(layer);
4521
- if (layer[3] >= 1) break;
4522
- }
4523
- return Object.freeze(layers);
4581
+ const computed = getComputedStyle(element).backgroundColor;
4582
+ const layer = computed === "" ? void 0 : parseColor(computed);
4583
+ if (layer === void 0 && computed !== "" && !/\/\s*(?:0(?:\.0*)?|none)\s*\)$/u.test(computed)) throw new Error(`Computed background color is unreadable on ${element.localName}${element.id === "" ? "" : `#${element.id}`}: ${computed}`);
4584
+ if (layer !== void 0 && layer[3] >= 1) return Object.freeze([layer]);
4585
+ const parent = element.parentElement;
4586
+ return Object.freeze([...layer === void 0 || layer[3] === 0 ? [] : [layer], ...parent === null ? [] : readLayers(parent)]);
4524
4587
  }
4525
4588
  /**
4526
4589
  * Resolves the opaque color standing behind one element.
@@ -4760,20 +4823,21 @@ function buildContrast(bar) {
4760
4823
  tint[2],
4761
4824
  1
4762
4825
  ];
4763
- let refusedChannel;
4764
- let acceptedChannel;
4765
- for (let channel = 0; channel <= 255; channel += 1) {
4826
+ const channels = Array.from({ length: 256 }, (_, channel) => {
4766
4827
  const front = [
4767
4828
  channel,
4768
4829
  channel,
4769
4830
  channel,
4770
4831
  1
4771
4832
  ];
4772
- const composited = measureContrast(front, backdrop);
4773
- const flat = measureContrast(front, flattened);
4774
- if (refusedChannel === void 0 && composited < bar && flat >= bar) refusedChannel = channel;
4775
- if (acceptedChannel === void 0 && composited >= bar && flat < bar) acceptedChannel = channel;
4776
- }
4833
+ return {
4834
+ channel,
4835
+ composited: measureContrast(front, backdrop),
4836
+ flat: measureContrast(front, flattened)
4837
+ };
4838
+ });
4839
+ const refusedChannel = channels.find(({ composited, flat }) => composited < bar && flat >= bar)?.channel;
4840
+ const acceptedChannel = channels.find(({ composited, flat }) => composited >= bar && flat < bar)?.channel;
4777
4841
  if (refusedChannel === void 0 || acceptedChannel === void 0) throw new Error(`Contrast control cannot straddle the bar ${bar}`);
4778
4842
  const root = build("div", { attributes: { style: `background-color: rgb(${CANVAS_COLOR[0]}, ${CANVAS_COLOR[1]}, ${CANVAS_COLOR[2]})` } });
4779
4843
  const tinted = build("div", { attributes: { style: `background-color: rgba(${tint[0]}, ${tint[1]}, ${tint[2]}, ${tint[3]})` } });
@@ -4793,8 +4857,7 @@ function buildContrast(bar) {
4793
4857
  accepted
4794
4858
  });
4795
4859
  }
4796
- //#endregion
4797
- //#region src/browser/sheets/helpers.ts
4860
+ // src/browser/sheets/helpers.ts
4798
4861
  /**
4799
4862
  * Adopts CSS text into the document with an idempotent release operation.
4800
4863
  *
@@ -4953,7 +5016,7 @@ function readCensus(root) {
4953
5016
  * The walk is iterative and reads the list it is still appending to, which is what expands a media
4954
5017
  * query, a supports block, a layer, and a nested style rule without recursion. Expanding by level
4955
5018
  * rather than by depth is why a top-level rule is always met before a rule nested inside an earlier
4956
- * one; {@link findRule} returns the first match in exactly this order.
5019
+ * one; {@link findStyleRule} returns the first match in exactly this order.
4957
5020
  *
4958
5021
  * The descent reaches a `CSSGroupingRule` and nothing else, and a `@keyframes` rule is not one. The
4959
5022
  * `@keyframes` rule itself is collected wherever it sits, and the keyframe rules inside it are not;
@@ -4976,10 +5039,7 @@ function readRules() {
4976
5039
  } catch {
4977
5040
  continue;
4978
5041
  }
4979
- for (let index = 0; index < rules.length; index += 1) {
4980
- const rule = rules[index];
4981
- if (rule instanceof CSSGroupingRule) rules.push(...rule.cssRules);
4982
- }
5042
+ for (const rule of rules) if (rule instanceof CSSGroupingRule) rules.push(...rule.cssRules);
4983
5043
  return rules;
4984
5044
  }
4985
5045
  /**
@@ -4996,15 +5056,15 @@ function readRules() {
4996
5056
  * another. Assert on this where the subject is the stylesheet, and on `readStyle` where the subject is
4997
5057
  * the rendered result.
4998
5058
  *
4999
- * The match is a substring, so `findRule('.card')` finds `.card`, `.card:hover`, and
5059
+ * The match is a substring, so `findStyleRule('.card')` finds `.card`, `.card:hover`, and
5000
5060
  * `.panel > .card` alike. Pass more of the selector to narrow it.
5001
5061
  *
5002
5062
  * @example
5003
5063
  * ```ts
5004
- * findRule('.card')?.style.getPropertyValue('padding')
5064
+ * findStyleRule('.card')?.style.getPropertyValue('padding')
5005
5065
  * ```
5006
5066
  */
5007
- function findRule(selector) {
5067
+ function findStyleRule(selector) {
5008
5068
  for (const rule of readRules()) if (rule instanceof CSSStyleRule && rule.selectorText.includes(selector)) return rule;
5009
5069
  }
5010
5070
  /**
@@ -5015,7 +5075,7 @@ function findRule(selector) {
5015
5075
  * declares no animation under that name.
5016
5076
  *
5017
5077
  * @remarks
5018
- * The name is matched exactly, which is where this parts from {@link findRule}: a selector is
5078
+ * The name is matched exactly, which is where this parts from {@link findStyleRule}: a selector is
5019
5079
  * compound and a fragment of one is a useful question, and an animation name is one atom that either
5020
5080
  * is or is not the one an `animation` declaration references.
5021
5081
  *
@@ -5219,7 +5279,6 @@ function buildCensus() {
5219
5279
  mark
5220
5280
  });
5221
5281
  }
5222
- //#endregion
5223
- export { ACCESSIBLE_ROLES, CANVAS_COLOR, CAPTURE_PANE, CAPTURE_STAGE_LIMIT, CONTENT_ROLES, FIELD_ROLES, FOCUSABLE_SELECTOR, FOCUS_SEGMENT_LIMIT, HEADER_ROLES, IMPLICIT_ROLES, MEDIA_STAGE, POINTER_HOLD, SEGMENTED_INPUT_TYPES, adoptSheet, blendColor, build, buildCensus, buildContrast, buildDenial, buildEscapes, captureFrame, chooseAccessible, clearStorage, clickAccessible, clickAccessibleWithin, clickDisclosure, clipsOverflow, collectClippingAncestors, collectScrollRegions, collectTabStops, commitInput, computeNamePattern, computeOffset, containsNode, convertA98RGB, convertDisplayP3, convertLab, convertLinearSRGB, convertOKLab, convertProPhotoRGB, convertRec2020, convertSRGB, convertXYZD50, convertXYZD65, countElements, createChannel, createDragEvent, createHarness, createJournal, createKeyboardEvent, createPointerEvent, createPortfolio, createStorage, describeFocus, describeScrollRegions, describeTree, driveHold, driveTraversal, expandCaptures, extractOrphans, extractStyles, fillAccessible, findKeyframes, findRule, holdAccessible, holdAccessibleWithin, hoverAccessible, isOutsideViewport, isReachable, isRendered, matchesColor, matchesTraversalName, measureContent, measureContrast, measureLuminance, mount, paintImage, parkPointer, parseCSSColor, parseColor, pressKeys, readAccessibilityNode, readActiveElement, readAnimations, readBackdrop, readCaptureReader, readCascade, readCensus, readClasses, readClipEdge, readClipMargin, readClippedBlock, readColorContrast, readContrast, readFocus, readFrame, readHit, readLayerNames, readLayers, readName, readPage, readPerception, readPixels, readProtocolNode, readProtocolPoint, readRefusal, readRing, readRole, readRootToken, readRows, readRules, readShotPixel, readStates, readStyle, readText, readToken, readValue, releaseMedia, releasePane, releasePointer, releaseTouch, removeDatabase, render, resolveAccessible, resolveAccessibleWithin, resolveFileInput, resolveRendered, sendFileDrag, sendProtocol, sendTouch, settleCapture, stageMedia, stagePane, stepFocus, supportsSegmentedFocus, tapTouch, traverseAccessible, traverseAccessibleWithin, typeAccessible, typeInput, verifyFrame, waitForAnimations, waitForFrame, waitForStability, waitForState, walkFocus };
5282
+ export { ACCESSIBLE_ROLES, CANVAS_COLOR, CAPTURE_PANE, CAPTURE_STAGE_LIMIT, CONTENT_ROLES, FIELD_ROLES, FOCUSABLE_SELECTOR, FOCUS_SEGMENT_LIMIT, HEADER_ROLES, IMPLICIT_ROLES, MEDIA_STAGE, POINTER_HOLD, SEGMENTED_INPUT_TYPES, adoptSheet, blendColor, build, buildCensus, buildContrast, buildDenial, buildEscapes, captureFrame, chooseAccessible, clearStorage, clickAccessible, clickAccessibleWithin, clickDisclosure, clipsOverflow, collectClippingAncestors, collectScrollRegions, collectShadowHosts, collectTabStops, commitInput, computeNamePattern, computeOffset, containsNode, convertA98RGB, convertDisplayP3, convertLab, convertLinearSRGB, convertOKLab, convertProPhotoRGB, convertRec2020, convertSRGB, convertXYZD50, convertXYZD65, countElements, createDragEvent, createHarness, createJournal, createKeyboardEvent, createPointerEvent, createPortfolio, createStorage, describeFocus, describeScrollRegions, describeTree, driveHold, driveTraversal, expandCaptures, extractOrphans, extractStyles, fillAccessible, findKeyframes, findStyleRule, holdAccessible, holdAccessibleWithin, hoverAccessible, isOutsideViewport, isReachable, isRendered, matchesColor, matchesTraversalName, measureContent, measureContrast, measureLuminance, mount, paintImage, parkPointer, parseCSSColor, parseColor, pressKeys, readAccessibilityNode, readActiveElement, readAnimations, readBackdrop, readCaptureReader, readCascade, readCensus, readClasses, readClipEdge, readClipMargin, readClippedBlock, readColorContrast, readContrast, readControlValue, readFocus, readFrame, readFrameHeight, readHit, readLayerNames, readLayers, readName, readPage, readPerception, readPixels, readProtocolNode, readProtocolPoint, readProtocolSession, readRefusal, readRing, readRole, readRootToken, readRows, readRules, readShotPixel, readStates, readStyle, readText, readToken, recordConsole, releaseMedia, releasePane, releasePointer, releaseTouch, removeDatabase, render, resolveAccessible, resolveAccessibleWithin, resolveFileInput, resolveRendered, sendFileDrag, sendProtocol, sendTouch, settleCapture, settleFrame, stageMedia, stagePane, stepFocus, supportsSegmentedFocus, takeFrameShot, tapTouch, traverseAccessible, traverseAccessibleWithin, typeAccessible, typeInput, verifyFrame, waitForAnimations, waitForFrame, waitForStability, waitForState, walkFocus };
5224
5283
 
5225
5284
  //# sourceMappingURL=index.js.map